Lib = {};

Lib.Timer = {};
Lib.Timer.data = new Hash();
Lib.Timer.allowed = function (namespace, seconds) {
	time = Lib.Timer.data.get(namespace);
	now = new Date().valueOf();

	if (!time || time < now) {
		time = now + (seconds * 1000);
		Lib.Timer.data.set(namespace, time);
		
		return true;
	}

	return false;
}

Lib.Actions = {};
Lib.Actions.Filter = {};
Lib.Actions.Filter.click = function(event){
	elm = Event.element(event).up('div');
	
	if (elm.hasClassName('close')) {
		elm.removeClassName('close');
		elm.addClassName('open');
	} else {
		elm.removeClassName('open');
		elm.addClassName('close');
	}
};

Lib.Actions.Filter.selectAll = function(event){
	elm = Event.element(event);
	$A($$('.zibb .filter form li input')).each(function(input) {
		input.checked = elm.checked;
	});
};

Lib.Actions.Filter.selectOne = function(event){
	checked = false;
	$A($$('.zibb .filter form li input')).each(function(input) {
		checked = input.checked;
		if (!input.checked) { throw $break; }
	});
	
	$A($$('.zibb .filter .select_all input')).first().checked = checked;
};

/** SEARCH **/

Lib.Actions.Search = {};
Lib.Actions.Search.Ajax = {};

Lib.Actions.Search.Ajax.instance = false;

Lib.Actions.Search.Ajax.config = {
	'method': 'post',
	'requestHeaders': {Accept: 'application/json'},
	'onCreate': function(responder) {
		// check if an other ajax instance if working else we cancel that one first
		if (Lib.Actions.Search.Ajax.instance) {
			Lib.Actions.Search.Ajax.instance.abort();
		}
		
		Lib.Actions.Search.Ajax.instance = responder.transport;

		$$('.zibb .tabset').first().insert({'before': new Element('img', {'src': '/images/loader.gif', 'class': 'loader'})});
	},
	'onSuccess': function (transport) {
		json = transport.responseText.evalJSON(true);

		if (json.tabs != undefined) { $$('.zibb .tabset').first().replace(json.tabs); }

		if (json['head.filter'] != undefined) { // update filters
			filter = $A($$('.zibb .head .filter'));
			
			if (filter.size()) {
				elm = new Element('div').update(json['head.filter']).down().removeClassName('open').removeClassName('close').addClassName(((filter.first().hasClassName('close')) ? 'close' : 'open'))
				filter.first().replace(elm);
			} else if (!json['head.filter'].blank()) {
				$$('.zibb .head .attention').first().insert({'before': json['head.filter']});
			}
		}

		if (json['head.results'] != undefined) { $$('.zibb .head .attention').first().replace(json['head.results']); }

		if (json['head.order'] != undefined) { 
			order = $A($$('.zibb .head .order'));
			
			if (order.size()) {
				order.first().replace(json['head.order']);
			} else if (!json['head.filter'].blank()) {
				$$('.zibb .head .attention').first().insert({'after': json['head.order']});
			}
		}
		
		if (json.results != undefined) {
			$A($$('.zibb .pagination, .zibb .results, .zibb .ads')).invoke('remove');
			$$('.zibb .tab').first().insert(json.pagination).insert(json.results).insert(json.pagination).insert(json.ads);
		}
		
		// register the listners again...
		Lib.Actions.Search.Observe();
	},
	'onComplete': function(transport){
		Lib.Actions.Search.Ajax.instance = false;

		// remove loader
		$$('.zibb .loader').first().remove();
	}
}

Lib.Actions.Search.Click = {};
Lib.Actions.Search.Click.tab = function (event) {
	Event.stop(event); // stop default
	elm = Event.element(event);
	
	if (!Lib.Timer.allowed('search', 1.0) || elm.up('li').hasClassName('active')) { return; } 
	
	ajax = Lib.Actions.Search.Ajax.config;
	ajax['parameters'] = {'action':'tab'};
	
	new Ajax.Request(elm.href, ajax);
}

Lib.Actions.Search.Click.url = function (event) {
	Event.stop(event); // stop default
	
	if (!Lib.Timer.allowed('search', 1.0)) { return; } 

	elm = Event.element(event);
	
	ajax = Lib.Actions.Search.Ajax.config;
	ajax['parameters'] = {};
	
	// check if there is a filter as we got to submit that to
	if (filter = $A($$('.zibb .filter form')).first()) { ajax['parameters'] = filter.serialize(true); }
	
	ajax['parameters']['action'] = 'nav';

	new Ajax.Request(elm.href, ajax);
}

Lib.Actions.Search.Click.filter = function (event) {
	if (Lib.Actions.Search.timer) { clearTimeout(Lib.Actions.Search.timer) }

	Lib.Actions.Search.timer = setTimeout(function() {
		this.timer = false;

		ajax = Lib.Actions.Search.Ajax.config;

		ajax['parameters'] = $$('.zibb .filter form').first().serialize(true);
		ajax['parameters']['action'] = 'filter';

		new Ajax.Request($$('.zibb .filter form').first().action, ajax);
	}, 800);
}

Lib.Actions.Search.Observe = function () {
	$A($$('.zibb .filter .select_all input')).invoke('observe', 'click', Lib.Actions.Filter.selectAll);
	$A($$('.zibb .filter form li input')).invoke('observe', 'click', Lib.Actions.Filter.selectOne);

	//$$('.zibb .tabset a').invoke('observe', 'click', Lib.Actions.Search.Click.Tab);
	$A($$('.filter .btn')).invoke('observe', 'click', Lib.Actions.Filter.click);
	$A($$('.zibb .pagination a, .zibb .head .order')).invoke('observe', 'click', Lib.Actions.Search.Click.url);
	$A($$('.zibb .filter form input')).invoke('observe', 'click', Lib.Actions.Search.Click.filter);
}

/** SUPPLIERS **/

Lib.Actions.Supplier = {};

Lib.Actions.Supplier.init = function () {
	if ($('select_all')) {
		//$$('.filter_content input').each(function (input) { input.checked = true; }); // default enable all the filters
		$A($$('input[name^="category"]')).invoke('observe', 'click', Lib.Actions.Supplier.Filter.selectOne);
		$A($$('.filter_content .title input')).invoke('observe', 'click', Lib.Actions.Supplier.Filter.selectCat);
		
		$('select_all').observe('click', Lib.Actions.Supplier.Filter.selectAll);
		$A($$('.filter_content input')).invoke('observe', 'click', Lib.Actions.Supplier.Click.filter).invoke('enable');
		
		Lib.Actions.Supplier.observe();
	}
}

Lib.Actions.Supplier.Ajax = {};

Lib.Actions.Supplier.Ajax.instance = false;

Lib.Actions.Supplier.Ajax.config = {
	'method': 'post',
	'requestHeaders': {Accept: 'application/json'},
	'onCreate': function(responder) {
		// check if an other ajax instance if working else we cancel that one first
		if (Lib.Actions.Supplier.Ajax.instance) {
			Lib.Actions.Supplier.Ajax.instance.abort();
		}
		
		Lib.Actions.Supplier.Ajax.instance = responder.transport;
	},
	'onSuccess': function (transport) {
		json = transport.responseText.evalJSON(true);
		
		$$('.leveranciers form').first().action = json.form;
		$('results').update(json.results);
		
		// register the listners again...
		Lib.Actions.Supplier.observe();
	},
	'onComplete': function(transport){
		Lib.Actions.Supplier.Ajax.instance = false;
	}
}

Lib.Actions.Supplier.Click = {};

Lib.Actions.Supplier.Click.filter = function (event) {
	if (Lib.Actions.Supplier.timer) { clearTimeout(Lib.Actions.Supplier.timer) }

	Lib.Actions.Supplier.timer = setTimeout(function() {
		this.timer = false;
		
		ajax = Lib.Actions.Supplier.Ajax.config;

		ajax['parameters'] = $$('.leveranciers form').first().serialize(true);
		ajax['parameters']['action'] = 'filter';

		new Ajax.Request($$('.leveranciers form').first().action, ajax);
	}, 800);
}

Lib.Actions.Supplier.Click.url = function (event) {
	Event.stop(event); // stop default
	
	if (!Lib.Timer.allowed('supplier', 0.8)) { return; } 
	
	elm = Event.element(event);
	
	ajax = Lib.Actions.Supplier.Ajax.config;
	ajax['parameters'] = {};
	
	// check if there is a filter as we got to submit that to
	if (filter = $A($$('.leveranciers form')).first()) { ajax['parameters'] = filter.serialize(true); }

	ajax['parameters']['action'] = 'url';

	new Ajax.Request(elm.href, ajax);
}

Lib.Actions.Supplier.observe = function () {
	$A($$('.pagination a, .abc a, .aThemeList .atitle a')).invoke('observe', 'click', Lib.Actions.Supplier.Click.url);
	
	// resize the ad logos
	$A($$('#results .ads img')).each(function (img) {
		img.observe('load', Lib.Actions.Supplier.Functions.resize.curry(img, 28, 100));

		if (img.complete) {
			Lib.Actions.Supplier.Functions.resize(img, 28, 100);
		}
	});
	// resize the result logos
	$A($$('#results .aThemeList img')).each(function (img) {
		img.observe('load', Lib.Actions.Supplier.Functions.resize.curry(img, 20, 72));

		if (img.complete) {
			Lib.Actions.Supplier.Functions.resize(img, 20, 72);
		}
	});
}

Lib.Actions.Supplier.Filter = {};

Lib.Actions.Supplier.Filter.selectAll = function(event){
	$('select_all').checked = true;

	$A($$('.leveranciers form li input')).each(function(input){
		input.checked = false;
	});
	
	// close all divs except the first one
	$A($$('.filter_content > div.category')).invoke('hide');
	$A($$('.filter_content > div:nth-child(2)')).invoke('show');
};

Lib.Actions.Supplier.Filter.selectCat = function(event){
	$('select_all').checked = false;

	elm = Event.element(event);
	div = elm.up('div.category');

	elm.checked = true;

	$A(div.select('ul input')).each(function(input){
		Lib.Actions.Supplier.Functions.check(input, false);
	});
}

Lib.Actions.Supplier.Filter.selectOne = function(event){
	$('select_all').checked = false;

	elm = Event.element(event);
	div = elm.up('div.category');

	if (title = div.down('.title input')) {
		title.checked = false;
	}
	
	forceone = false;

	// only allow one selection if one or more inputfields got a subcategory
	$A(div.select('ul input')).each(function (input) {
		if ($('filter_parent_' + input.value)) {
			forceone = true;
			throw $break;
		}
	});
	
	if (forceone) {
		$A(div.select('input:not([value="' + elm.value + '"])')).each(function(input){
			Lib.Actions.Supplier.Functions.check(input, false);
		});
		
		Lib.Actions.Supplier.Functions.check(elm, true);
	} else {
		// selecte the title if no other option is selected
		if (title) {
			title.checked = !$A(div.select('ul input')).pluck('checked').sort().last();
		}

		Lib.Actions.Supplier.Functions.check(elm, elm.checked);
	}
};

Lib.Actions.Supplier.Filter.selectCancel = function(event){
	elm = Event.element(event);
	div = elm.up('div.category');

	$A($$('.filter_content > div.category ul input')).each(function (input) {
		console.debug($('filter_parent_' + input.value), div);
		if ($('filter_parent_' + input.value) == div) {
			Lib.Actions.Supplier.Functions.check(input, false);
			input.up('div').show();
		}
	});
};

Lib.Actions.Supplier.Functions = {};

Lib.Actions.Supplier.Functions.check = function(elm, check) {
	$A($$('#filter_parent_' + elm.value + ' input')).each(function(input) { 
		Lib.Actions.Supplier.Functions.check(input, false);
	});
	
	if (div = $('filter_parent_' + elm.value)) {
		if (check) { 
			div.show();
			div.select('ul input').each(function (input) { input.checked = false});
			
			if (title = div.down('div.title input')) {
				title.checked = true;
			}
			
			elm.up('div').hide();
	 	} else { div.hide() }
	}

	elm.checked = check;
}

Lib.Actions.Supplier.Functions.resize = function(elm, maxHeight, maxWidth) {
	dim = elm.getDimensions();

	if (dim.height > maxHeight || dim.width > maxWidth) {
		x = Math.max(dim.height / maxHeight, dim.width / maxWidth);
		elm.setStyle({
			'height': Math.floor((dim.height / x)) + 'px',
			'width': Math.floor((dim.width / x)) + 'px',
			'display': 'inline'
		});
	}
}

/** TABS **/

Event.observe(document, 'dom:loaded', function () {
	$A($$('.panel_tab:not([class~="nojs"])')).each(Lib.Actions.Tab.observe);
});

Lib.Actions.Tab = {};

Lib.Actions.Tab.observe = function(panel) {
	var tabset = $A(panel.select('.tabset li')).invoke('observe', 'click', Lib.Actions.Tab.click);
}

Lib.Actions.Tab.click = function(event) {
	var tabset = Event.element(event);
	tabset = (tabset.tagName == 'LI') ? tabset : tabset.up('li');
	var panel = tabset.up('.panel_tab');
	
	var index = panel.select('.tabset li').invoke('removeClassName', 'active').indexOf(tabset);
	var tab = panel.select('.tab').invoke('removeClassName', 'active');

	tabset.addClassName('active');
	if (tab[index]) { tab[index].addClassName('active')	} 
}

/** ADS **/

var ord = Math.random()*10000000000000000;
