/**
 * Search.js - Live Search
 * 
 * @author  Webstores <info at webstores dot nl>
 *           Copyright (c) Webstores internet totaalbureau <http://www.webstores.nl/>
 */

var fs;

WS.Event.addEvent(window, 'load', function() {
	if($('package-search-filters')) {
		fs = new FilterSet('package-search-filters');
		fs.initialize();
	}
	
	if($('package-sort')) {
		WS.Event.addEvent('package-sort', 'change', function(){
			filterTable(this);
		});
	}
});


/**
 * FilterSet.js - Live search filters
 * 
 * @param {Object} el The element containing all filter buttons
 * @return {Object} Public functions
 */
var FilterSet = function(el) {
	
	var btnWrap;
	var btns;
	var activeFilter;
	var activeCls = arguments[1] || 'active';
	var highlightCls = arguments[2] || 'highlight';
	var defaultMsg = arguments[3] || '(kiezen)';
	
	return {
		initialize: function() {
			btnWrap = $(el);
			btns = WS.DOM.getElementsByClass('button', btnWrap, 'a');
			this.initEvents();
		},
		
		initEvents: function() {
			var self = this;
			
			for(var i = 0; i < btns.length; i++) {
				WS.Event.addEvent(btns[i], 'click', function(e) {
					WS.Event.stopEvent(e);
					WS.hasClass(this.parentNode, activeCls) ? self.hideFilter(this.parentNode) : self.showFilter(this.parentNode);
				});
				
				WS.Event.addEvent($(btns[i].rel + '-submit'), 'click', function(e) {
					WS.Event.stopEvent(e);
					filterTable(WS.DOM.getParent(this, 2));
					self.hideFilter(WS.DOM.getParent(this, 3));
				});
				
				WS.Event.addEvent($(btns[i].rel + '-cancel'), 'click', function(e) {
					WS.Event.stopEvent(e);
					self.hideFilter(WS.DOM.getParent(this, 3));
				});
			}
			
			WS.Event.addEvent(document.body, 'click', function(e) {
				if(activeFilter) {
					var target = WS.Event.getTarget(e);
					while(target) {
						if(WS.hasClass(target, 'filter')) {
							return false;
						}
						target = target.parentNode;
					}
					self.hideFilter(activeFilter);
				}
			});
		},
		
		showFilter: function(el) {
			if(el == activeFilter)
				return;
			
			if(activeFilter)
				WS.removeClass(activeFilter, activeCls);
			
			WS.addClass(el, activeCls);
			activeFilter = el;
		},
		
		hideFilter: function(el) {
			WS.removeClass(el, activeCls);
			activeFilter = null;
		},
		
		setMessage: function(id, msg) {
			$(id + '-selected').innerHTML = msg;
		},
		
		activate: function(id) {
			WS.addClass($(id).parentNode, highlightCls);
		},
		
		deactivate: function(id) {
			if(WS.hasClass($(id).parentNode, highlightCls)) {
				WS.removeClass($(id).parentNode, highlightCls);
				this.setMessage(id, defaultMsg);
			}
		}
	}
}

/**
 * Retrieves filter values and does the actual AJAX request
 * 
 * @param {Object} el The element containing the filter's form controls
 */
function filterTable(el) {
	
	var postBody = '';
	
	switch(el.id) {
		case 'keywds':
			var values = [];
			var inputs = $(el.id).getElementsByTagName('input');
			
			postBody += 'keywords=';
			
			for(var i = 0; i < inputs.length; i++) {
				if(inputs[i].checked) {
					values.push(inputs[i].value);
				}
			}
			
			postBody += values.join(',');
			
			if(values.length > 0) {
				fs.activate(el.id);
				fs.setMessage(el.id, '(' + values.join(', ') + ')');
			}
			else {
				fs.deactivate(el.id);
			}
		break;
		case 'period':
			var fromDay = $('period-day-from').value;
			var fromMonth = $('period-month-from').value;
			var fromYear = $('period-year-from').value;
			var toDay = $('period-day-to').value;
			var toMonth = $('period-month-to').value;
			var toYear = $('period-year-to').value;
			
			if(fromDay != '-1' && fromMonth != '-1' && fromYear != '-1' && toDay != '-1' && toMonth != '-1' && toYear != '-1') {
				fs.setMessage(el.id, '(' + fromDay + '-' + fromMonth + '-' + fromYear + ' tot ' + toDay + '-' + toMonth + '-' + toYear + ')');
			}
			else if(fromDay != '-1' && fromMonth != '-1' && fromYear != '-1') {
				fs.setMessage(el.id, '(vanaf ' + fromDay + '-' + fromMonth + '-' + fromYear + ')');
			}
			else if(toDay != '-1' && toMonth != '-1' && toYear != '-1') {
				fs.setMessage(el.id, '(tot ' + toDay + '-' + toMonth + '-' + toYear + ')');
			}
			
			postBody += 'fromday=' + fromDay + '&frommonth=' + fromMonth + '&fromyear=' + fromYear + '&today=' + toDay + '&tomonth=' + toMonth + '&toyear=' + toYear;
			((fromDay != '-1' && fromMonth != '-1' && fromYear != '-1') || (toDay != '-1' && toMonth != '-1' && toYear != '-1')) ? fs.activate(el.id) : fs.deactivate(el.id);
		break;
		case 'days':
			var daysFrom = $('days-from-field').value;
			var daysTo = $('days-to-field').value;
			
			if(daysFrom || daysTo) {
				fs.setMessage(el.id, '(' + daysFrom + ' - ' + daysTo + ')');
			}
			
			postBody += 'daysmin=' + daysFrom + '&daysmax=' + daysTo;
			(daysFrom || daysTo) ? fs.activate(el.id) : fs.deactivate(el.id);
		break;
		case 'budget':
			var budgetFrom = $('budget-from-field').value;
			var budgetTo = $('budget-to-field').value;
			
			if(budgetFrom || budgetTo) {
				fs.setMessage(el.id, '(&euro; ' + WS.Util.number_format(budgetFrom, 0, ',', '.') + ' - &euro; ' + WS.Util.number_format(budgetTo, 0, ',', '.') + ')');
			}
			
			postBody += 'budgetmin=' + budgetFrom + '&budgetmax=' + budgetTo;
			(budgetFrom || budgetTo) ? fs.activate(el.id) : fs.deactivate(el.id);
		break;
		case 'package-sort':
			postBody += 'sort=' + $('package-sort').value;
		break;
	}
	
	// BEGIN DEBUG, REMOVE FOR PRODUCTION
	var postVars = postBody.split('&');
	for(var i = 0; i < postVars.length; i++) {
		console.log((i + 1) + ': ' + postVars[i]);
	}
	// END DEBUG, REMOVE FOR PRODUCTION
	
	WS.Ajax.request('/filter.json', function(response) {
		parseResponse(response);
	}, postBody);
}

/**
 * Renders the new arrangement list from AJAX response
 * 
 * @param {Object} json The JSON object containing the matching arrangements
 */
function parseResponse(json) {
	var html = [];
	var packages = WS.Util.parseJSON(json);
	
	html.push('<table class="package-table wshover wsclick" cellspacing="0">\n');
	if(packages.length > 0) {
		for(var i = 0; i < packages.length; i++) {
			html.push('<tr>\n');
			html.push('<td><a href="' + packages[i].link + '" title="' + packages[i].title + '">' + packages[i].title + '</a></td>\n');
			html.push('<td class="unit">v.a.</td>\n');
			html.push('<td class="price">&euro; ' + WS.Util.number_format(packages[i].prijs, 2, ',', '.') + '</td>\n');
			html.push('<td class="arrow">&nbsp;</td>\n');
			html.push('</tr>\n');
		}
	}
	html.push('</table>\n');

	$('package-search-table').innerHTML = html.join('');
	$('package-search-count').innerHTML = packages.length;

	RowHover.initialize();
	RowClick.initialize();
}
