/*global AjaxHandler*/
/*global handleResponse*/


function SearchMenuHandler()
{
	// this object
	var that = this;
	
	// the calendar object
	this.calendar;
	
	// the ajax handler
	this.ajaxHandler = null;
	// the webservice to call
	this.webservice = 'http://www.jongerenvakanties.com/webservice/searchmenu2.php';
	// the request method for the ajax call
	this.requestMethod = 'GET';
	// the search options like destination, persons etc. with their values (associative array)
	this.searchItems = [];
	// the variables to pass in associative array format
	this.passVars = null;
	
	// the xml handler
	this.xmlHandler = null;
	// the xml document uri
	this.xmlUri = 'http://www.jongerenvakanties.com/xml/catalog.xml';
	
	// the form
	this.form;
	// the formname
	this.formName = 'sm_form';
	
	// searchmenu changed
	this.changed = function()
	{
		that.passVars = [];
		
		that.textFieldChanged();
		that.selectMenuChanged();
		that.hiddenFieldChanged();
		
		that.ajaxHandler.update(that.passVars, that.requestMethod);
	};
	
	// get the textfields
	this.textFieldChanged = function()
	{
		// loop trough the textfields
		for(var item in that.searchItems.text) {
			// get the element
			element = that.searchItems.text[item].element;
			name = that.searchItems.text[item].name;
			
			// set the value
			if(name == 'date') {
				that.passVars[name] = that.reverseDate(element.value);
			}
			else {
				that.passVars[name] = element.value;
			}
		}
	};
	
	// get the selectmenu
	this.selectMenuChanged = function()
	{
		var element;
		var name;
		
		// loop trough the selectboxes
		for(var item in that.searchItems.select) {
			// get the element
			element = that.searchItems.select[item].element;
			name = that.searchItems.select[item].name;
			
			// store the key of the selected item
			that.searchItems.select[item].selectedKey = element.options[element.selectedIndex].value;
			
			// check if the element is the destination_id
			if(name == 'destination_id') {
				that.handleDestinationElement(element);
			}
			else {
				that.passVars[name] = element.value;
			}
		}
	};
	
	// handle the destination element to convert it to a country_id or place_id
	this.handleDestinationElement = function(element)
	{
		that.passVars.country_id = 0;
		that.passVars.place_id = 0;
		
		if(element.value.indexOf('c') != -1) {
			that.passVars.country_id = element.value.substr(1);
		}
		else if(element.value.indexOf('p') != -1) {
			that.passVars.place_id = element.value.substr(1);
		}
	};
	
	// get the hiddenfields
 	this.hiddenFieldChanged = function()
 	{
 		// loop trough the hidden fields
		for(var item in that.searchItems.hidden) {
			// get the element
			element = that.searchItems.hidden[item].element;
			name = that.searchItems.hidden[item].name;
			
			// set the value
			that.passVars[name] = element.value;
		}
 	};
 	
	// get the response of the webrequest
	this.handleResponse = function(responseText, responseStatus)
	{
		//Log(responseText);return;
		
		if(responseStatus == 200 && responseText != 'false') {
			var data = JSON.parse(responseText);
			
			var element = null;
			var options = null;
			
			// * handle the selectboxes
			var selectedKey = null;
			for(var item in that.searchItems.select) {
				element = that.searchItems.select[item].element;
				name = that.searchItems.select[item].name;
				selectedKey = that.searchItems.select[item].selectedKey;
				options = data[name];
				
				if(name == 'destination_id') {
					that.setDestinationOptions(element, options);
					that.paintDestinationOptions();
				}
				else {
					// set the options of the element
					that.setSelectMenuOptions(element, options);
				}
				// set the selected index of the element
				that.setSelectedIndex(element, selectedKey);
			}
			
			// * handle the calendar
			if(that.searchItems.text.__t_date !== null) {
				element = that.searchItems.text.__t_date.element;
				name = that.searchItems.text.__t_date.name;
				
				options = data[name];
				that.calendar.setDates(options);
			}
			
		}
		else {
			alert(responseStatus + ' -- Error Processing Request' + "\n\n" + 'ResponseText is: ' + responseText);
		}
	};
	
	this.setSelectMenuOptions = function(element, options)
	{
		that.deleteOptions(element);
		var value;
		for(var i=0; i<options.length; i++) {
			value = that.searchItems.select[element.name].options[options[i]];
			element[i+1] = new Option(value, options[i]);
		}
	};
	
	this.setDestinationOptions = function(element, options)
	{
		var destinations = [];
		// loop trough the options
		for(var country in options) {
			// add the country
			destinations[destinations.length] = 'c' + country;
			
			// get the places
			places = options[country];
			
			// loop trough the places
			for(var i=0; i<places.length; i++) {
				// add the place
				destinations[destinations.length] = 'p' + places[i];
			}
		}
		that.setSelectMenuOptions(element, destinations);
	};
	
	this.paintDestinationOptions = function()
	{
		var element = that.searchItems.select.__s_destination_id.element;
		
		// loop trought the elements from index = 1
		for(var i=1; i<element.options.length; i++) {
			if(element[i].value.substring(0,1) == 'c') {
				element.options[i].style.color = '#E58C49';
			}
			else {
				element[i].text = '  ' + element[i].text;
				element.options[i].style.color = '#549DC9';
			}
		}
	};
	
	this.deleteOptions = function(element)
	{
		while(element[1] !== null) {
			element[1] = null;
		}
	};
	
	// function to set the selected index to the parameter-key
	this.setSelectedIndex = function(element, selectedKey)
	{
		// loop trough the options of the element
		for(var i=0; i<element.options.length; i++){
			// check if the key is the same as the selected key
			if(element.options[i].value == selectedKey){
				element.selectedIndex = i;
			}
		}
	};
	
	// set the departure date
	this.setDepartureDate = function(date) {
		var element = document.getElementById('date');
		element.value = that.reverseDate(date);
		
		that.calendar.show();
		
		that.changed();
	};
	
	// reverse the date
	this.reverseDate = function(date) {
		var regex = /^[0-9]+-[0-9]+-[0-9]+$/;
		if(regex.test(date)) {
			values = date.split('-');
			return values[2] + '-' + values[1] + '-' + values[0];
		}
		else {
			return date;
		}
	}
	
	// init the form fields
	this.initFormFields = function()
	{
		// the form name
		that.form = document.forms[that.formName];
		
		// init the arrays with input fields		
		that.searchItems.text = [];
		that.searchItems.select = [];
		that.searchItems.hidden = [];
		
		// get the textfields from the form
		that.initInputFields();
	}
	
	// init the selectboxes
	this.initInputFields = function()
	{
	 	var element = null;
	 	var index = 0;
	 	var prfx;
	 	var name;
		for(var i = 0; i < that.form.elements.length; i++) {
			// get the element
			element = that.form.elements[i];
			
			if(element.name.length >= 4) {
				prfx = element.name.substr(0,4);
				name = element.name.substr(4);
				
				if(prfx == '__t_') {
					// the element is a textfield
					that.searchItems.text[element.name] = [];
					that.searchItems.text[element.name].name = name;
					that.searchItems.text[element.name].element = element;
				}
				else if(prfx == '__s_') {
					// the element is a searchmenu
					that.searchItems.select[element.name] = [];
					that.searchItems.select[element.name].name = name;
					that.searchItems.select[element.name].element = element;
				}
				else if(prfx == '__h_') {
					// the element is a hiddenfield
					that.searchItems.hidden[element.name] = [];
					that.searchItems.hidden[element.name].name = name;
					that.searchItems.hidden[element.name].element = element;
				}
			}
		}
	};
	
	// set the options of the xml document in the selectboxes
	this.initSelectMenuOptions = function()
	{
		var name;
		var options = null;
		
		for(var item in that.searchItems.select) {
			name = that.searchItems.select[item].name;
			
			// get the options for this element
			options = that.xmlHandler.getValues(that.xmlUri, name);
			
			// save the options to the specific element-array
			that.searchItems.select[item].options = options;
			
			//Log('***' + element.name + '***');
			//var counter = 1;
			//for(var key in options) {
				//Log(options[key]);
			//	element[counter] = new Option(options[key], key);
			//	counter++;
			//}
		}
	};
	
	// init the searchmenu_handler
	this.init = function()
	{
		// initiate the calendar
		that.calendar = new Calendar('calendar', that.setDepartureDate);
		
		// initiate the ajax_handler
		that.ajaxHandler = new AjaxHandler(that.webservice, that.handleResponse);
		
		// get the field from the form in the document
		that.initFormFields();
		
		// initiate the xml_handler
		that.xmlHandler = new XmlHandler();
		
		// set the xml_options in the selectboxes
		that.initSelectMenuOptions();
		
		that.changed();
		
		// check if the destination element is set
		//if(that.searchItems.select.destination_id !== null) {
		//	that.paintDestinationOptions();
		//}
		
		//that.changed();
	};
	this.init();
}

function Log(variable)
{
	console.log("- " + variable + "\n");
}

/** GENERAL FUNCTIONS */
	function show_div(div_name)
	{
		var div = document.getElementById(div_name);
		
		if(div != null) {
			if(div.style.display == '')
				div.style.display = 'block';
			else
				div.style.display = '';
		}
	}
	
	function set_image_source(imageId, imageSource)
	{
		var img = document.getElementById(imageId);
		img.src = imageSource;
	}
	
	function get_file_without_extension(file)
	{
		var x = file.indexOf("\.", 0);
		var index = x;
		while(x != -1) {
			index = x;
			x = file.indexOf("\.", x+1);
		}
		
		return file.substring(0, index);
	}
	
	function get_url_without_querystring(url)
	{
		var x = url.indexOf('?');
		if(x>-1)
			url = url.substring(0, x);
		var x = url.indexOf('&');
		if(x>-1)
			url = url.substring(0, x);
		
		return url;
	}
	
	function sm_call_webservice(webserviceUrl, functionName){
		var response = '';
		this.id = new Date().getTime();
	
		try{
			// firefox, opera 8.0+, safari
			xmlHttp = new XMLHttpRequest();
		}
		catch(e){
			// Internet Explorer
			try{
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e){
				// ajax wordt niet ondesteund, laat het zoekmenu niet zien
				//zoek_div = document.getElementById('fastsearch_menu');
				//zoek_div.style.display = "none";
				//return false;
			}
		}
	
		xmlHttp.onreadystatechange = function(){
			// states are:
			// 0 - request not initialized
			// 1 - request has been set up
			// 2 - request has been sent
			// 3 - request is in process
			// 4 - request is complete
			if(xmlHttp.readyState==4){
				// get the data from the server response
				response = xmlHttp.responseText;
				response = response.replace(/"/g, "\\\"");
				response = response.replace(/\n/g, "");
				//functionPointer(response, list);
				eval(functionName + '("' + response + '");');
				//a(response);
				//sm_handle_response(response);
			}
		}
		
		response = xmlHttp.open("GET", webserviceUrl + "&id="+id, true);
		xmlHttp.send(null);
	}
	
/** END GENERAL FUNCTIONS */

/** START MAIL FUNCTIONS */
	// ma = mail_alert
	function ma_send_mail(formId)
	{
		show_div('uo_mail_friend');
		
		var url = get_url_without_querystring(document.URL);
		url = encodeURIComponent(url);
		
		with (document.mail_friend_form)
		{
			var _sender = sender.value;
			var _receiver = receiver.value;
			
			var webserviceurl = 'http://' + window.location.hostname + '/webservice/mail.php?sender=' + _sender + 
								   '&receiver=' + _receiver + '&urltip=' + url + '&formid=' + formId;
   			
			sm_call_webservice(webserviceurl, 'ma_handle_response');
		}
	}
	
	function ma_handle_response(response)
	{
		var values = response.split(';');
		var status = values[0];
		var message = values[1];
		
		var img_name = 'mail_img';
		var img = document.getElementById(img_name);
		var img_src = img.src;
		
		var node = document.getElementById('receiver_text');
		node.style.color = '#464646';
		
		var tmpfile = get_file_without_extension(img_src);
		
		// 1 = mail send
		// 2 = sender incorrect
		// 3 = receiver incorrect
		// 4 = technical problem
		if(status == 1) {
			img.src = tmpfile + "_green.gif";
			window.setTimeout('set_image_source("' + img_name + '", "' + img_src + '")', 5000);
		}
		else if(status == 2) {
			
		}
		else if(status == 3) {
			node.style.color = 'red';
			show_div('uo_mail_friend');
		}
		else {
			img.src = tmpfile + "_red.gif";
			window.setTimeout('set_image_source("' + img_name + '", "' + img_src + '")', 5000);
		}
	}
/** END MAIL FUNCTIONS */

