/* ws/fastSearch/static/js/page_search.js */ /* UTF8-Côôkie */



/******************************************************************************************************/

function	pageSearchClass()
{
	var	self = this;

	this.dateFormat = '%a, %d %b %Y';
	this.currentCalendar = null;

	this.txtMoreLessMore = 'more';
	this.txtMoreLessLess = 'less';

	this.preselectedGuestId = null;

	this.ajax = new fsAjaxRequest(true);
	
	this.ajax.onLoad = function(data)
	{				
		if(data != null)
			self.onLoad(data);
		else
			this.onError();
	}

	this.ajax.onError = this.ajax.onTimeout = function(data)
	{		
		// Sleep a bit then retry		
		window.setTimeout(function() { self.read(); }, 7500);
	}

	vkDom.onLoad(
		function()
		{
			self.read();
		}
	);
}

pageSearchClass.prototype.read = function()
{	
	var po = null;
	
	if (kigo.is_array(PAGETYPE_SEARCHRES_SEARCH_OPTIONS)) {
		po = {'SEARCH_OPTIONS': PAGETYPE_SEARCHRES_SEARCH_OPTIONS};
	}
	
	this.ajax.post(
			WS_ROOT + 'ajax/page_search.xml',
			po
	);
}





pageSearchClass.prototype.onLoad = function(data)
{
	var	self = this;
	var	i, j;
	// If no option at all is available, make the whole search block invisible...

	if(
		data.DATES == null &&
		data.GUEST == null &&
		!data.CAT.length
	)
	{
		vkDom.addClass('searchmenu_1', 'none');
		return;
	}

	if(data.DATES == null)
		vkDom.addClass('search_dates', 'none');
	else
	{
		vkDom.setText('search_dates_name', data.DATES.NAME);
		vkDom.removeClass('search_dates', 'none');

		vkDom.el('search_date_in').value = this.mysql2human(data.DATES.START);
		vkDom.el('search_date_out').value = this.mysql2human(data.DATES.END);

		if(data.DATES.START != null && data.DATES.END != null)
			vkDom.removeClass('search_dates_remove', 'none');
		else
			vkDom.addClass('search_dates_remove', 'none');

		

		/////////////////////////////////////////
		// Setup calendars...

		// Arrival date
		vkDom.el('search_date_in').onclick = function()
		{
			// The departure date is always cleared if there was already an arrival date

			if(vkDom.el('search_date_in').value.length)
				vkDom.el('search_date_out').value = '';

			self.currentCalendar = new Calendar(
				1,										// firstDayOfWeek
				vkDom.el('search_date_in').value,		// dateStr
				function(cal)							// onSelected
				{
					if(cal.dateClicked)
					{
						vkDom.el('search_date_in').value = cal.date.print(cal.dateFormat); 
						self.onDatesChange();
						cal.hide();
					}
				},
				function(cal)							// onClose
				{
					cal.hide();
				}
			);

			self.currentCalendar.setDisabledHandler(
				function(date, year, month, day)
				{
					if(self.compareDates(date, self.today()) < 0)
						return true;

					// Disable all dates that are >= current departure date
					if(vkDom.el('search_date_out').value.length)
						return self.compareDates(date, Date.parseDate(vkDom.el('search_date_out').value, self.dateFormat)) >= 0;
					else
						return false;
				}
			);

			var	year = self.today().getFullYear();

			self.currentCalendar.setDateFormat(self.dateFormat);
			self.currentCalendar.setRange(year, year+6);
			self.currentCalendar.create();
			self.currentCalendar.refresh();
			self.currentCalendar.showAtElement(vkDom.el('search_date_in'));
		}

		// Departure date
		vkDom.el('search_date_out').onclick = function()
		{
			var	defaultDate;

			if(vkDom.el('search_date_out').value.length)
				defaultDate = vkDom.el('search_date_out').value;
			else
			{
				if(vkDom.el('search_date_in').value.length)
				{
					var	tmp = Date.parseDate(vkDom.el('search_date_in').value, self.dateFormat);
					tmp.setDate(tmp.getDate() + 1);
					defaultDate = tmp.print(self.dateFormat);
				}
				else
					defaultDate = '';
			}

			self.currentCalendar = new Calendar(
				1,										// firstDayOfWeek
				defaultDate,							// dateStr
				function(cal)							// onSelected
				{
					if(cal.dateClicked)
					{
						vkDom.el('search_date_out').value = cal.date.print(cal.dateFormat); 
						self.onDatesChange();
						cal.hide(); 
					}
				},
				function(cal)							// onClose
				{
					cal.hide();
				}
			);

			self.currentCalendar.setDisabledHandler(
				function(date, year, month, day)
				{
					if(self.compareDates(date, self.today()) <= 0)
						return true;

					// Disable all dates that are <= current arrival date
					if(vkDom.el('search_date_in').value.length)
						return self.compareDates(date, Date.parseDate(vkDom.el('search_date_in').value, self.dateFormat)) <= 0;
					else
						return false;
				}
			);

			var	year = self.today().getFullYear();

			self.currentCalendar.setDateFormat(self.dateFormat);
			self.currentCalendar.setRange(year, year+6);
			self.currentCalendar.create();
			self.currentCalendar.refresh();
			self.currentCalendar.showAtElement(vkDom.el('search_date_out'));
		}
	}

	// Always empty guests dropdown

	var	guestSel;

	this.selReset(guestSel = vkDom.el('search_guests_sel'));
	this.selAdd(guestSel, 0, '');


	if(data.GUEST == null)
		vkDom.addClass('search_guests', 'none');
	else
	{
		vkDom.setText('search_guests_name', data.GUEST.NAME);
		vkDom.removeClass('search_guests', 'none');


		for(i = 0; i < data.GUEST.OPT.length; i++)
		{
			this.selAdd(guestSel, data.GUEST.OPT[i].ID, data.GUEST.OPT[i].NAME);
			if(data.GUEST.OPT[i].ID == data.GUEST.SEL) {
				guestSel.selectedIndex = i+1;
			} else {
				if (kigo.is_array(PAGETYPE_SEARCHRES_SEARCH_OPTIONS)) {
					// array contains a list provided by a page of type Search Results to properly display the selected search options  08/12/2009
					if (kigo.in_array(data.GUEST.OPT[i].ID, PAGETYPE_SEARCHRES_SEARCH_OPTIONS)) {
						this.preselectedGuestId = data.GUEST.OPT[i].ID; 
						guestSel.selectedIndex = i+1;
					}
				}
			}
		}
	}

	// 24/02/2009
	this.selSetClasses(guestSel);


	// Okay, then render other categories...

	if(data.CAT.length)
	{
		vkDom.removeClass('search_options', 'none');


		var optContainer = vkDom.el('search_options');
		var	CAT, catTitle, catTitleSpan, optBlock, optList, optItem, optItemLink, optIfSel;
		var	morelessP, morelessA, morelessSPAN;
		var	cls, tmp;


		for(i = 0; i < data.CAT.length; i++)
		{
			CAT = data.CAT[i];

			optBlock = document.createElement('div');

			cls = [
				'search_options_block',
				'e-'+(i+1),
				(i%2) ? 'even' : 'odd'
			];

			if(i == 0 && data.CAT.length == 1)
				cls[cls.length] = 'single';
			else if(i == 0)
				cls[cls.length] = 'first';
			else if(i == data.CAT.length - 1)
				cls[cls.length] = 'last';
			else
				cls[cls.length] = 'middle';

			optBlock.className = cls.join(' ');


			// Category title

			catTitle = document.createElement('h3');
				catTitleSpan = document.createElement('span');
				catTitleSpan.appendChild(document.createTextNode(CAT.NAME));
			catTitle.appendChild(catTitleSpan);

			optBlock.appendChild(catTitle);

			// Category options list

			optList = document.createElement('ul');
			optList.id = 'search_category_'+CAT.ID;

			// Remember the number of items to show
			if(CAT.SHOW != null)
			{
				optList.setAttribute('showitems', CAT.SHOW);
				optList.setAttribute('more', '0');
			}

		

			/*

			first/middle/last/single classes are based on number of items *DISPLAYED* in the list in *SHORT* mode
			They are recomputed when the list switches between SHORT and LONG modes

			*/

			var	displayedItems;

			if(CAT.SHOW != null)
				displayedItems = CAT.SHOW;
			else
				displayedItems = CAT.OPT.length;

			// Category options list items
			for(j = 0; j < CAT.OPT.length; j++)
			{

				if(j < displayedItems)
				{
					cls = [
						'e-'+(j+1),
						(j%2) ? 'even' : 'odd'
					];

					if(j == 0 && displayedItems == 1)
						cls[cls.length] = 'single';
					else if(j == 0)
						cls[cls.length] = 'first';
					else if(j == displayedItems - 1)
						cls[cls.length] = 'last';
					else
						cls[cls.length] = 'middle';
				}
				else	// Not displayed
					cls = ['none']; // cls = ['hidden'];

				var selected = '';
				if (kigo.is_array(PAGETYPE_SEARCHRES_SEARCH_OPTIONS)) {
						// array contains a list provided by a page of type Search Results to properly display the selected search options  08/12/2009
						// if it is in this array then it is part of the page's settings
						// therefore we dispaly it as selected
						if (kigo.in_array(CAT.OPT[j].ID, PAGETYPE_SEARCHRES_SEARCH_OPTIONS))
							selected = ' selected ';
					}

				optItem	= document.createElement('li');
				optItem.id = optList.id+'-'+(j+1);
				optItem.className = cls.join(' ') + selected;

					optItemLink = document.createElement('a');
					optItemLink.setAttribute('href', '#');
					optItemLink.setAttribute('optid', CAT.OPT[j].ID);
					optItemLink.setAttribute('title', CAT.OPT[j].NAME);

					optItemLink.appendChild(document.createTextNode(CAT.OPT[j].NAME));

					optItemLink.appendChild(document.createTextNode(' '));
						optIfSel = document.createElement('span');
						optIfSel.appendChild(document.createTextNode('('+CAT.OPT[j].IFSEL+')'));
					optItemLink.appendChild(optIfSel);

					optItemLink.onclick = function()
					{
						// 12/06/2009 - We had problems with people double-clicking on links causing weird behaviour in firefox (firefox used to reload the current page)
						// Therefore, we have to disable (ie - hide) the menu after the first click..
						// Nb: disabling the link or changing the onclick handler did not work...
						if(vkDom.hasClass(document.body, 'ua-firefox'))
							vkDom.visibility(this, false);

						self.goSearch(null, null, this.getAttribute('optid'));
						return false;
					}

				optItem.appendChild(optItemLink);

				optList.appendChild(optItem);
			}

			optBlock.appendChild(optList);

			if(CAT.SHOW != null)
			{
				morelessP = document.createElement('p');
				morelessP.className = 'moreless';

					morelessA = document.createElement('a');
					morelessA.setAttribute('href', '#');
					morelessA.setAttribute('title', this.txtMoreLessMore);
					morelessA.onclick = function(el)
					{
						var	i, cls, li;
						var	ul = this.parentNode.parentNode.getElementsByTagName('ul')[0];

						if(ul.getAttribute('more') == '0')
						{
							// Less -> More

							// -> Display all <li> elements...
							li = ul.childNodes;

							for(i = 0; i < li.length; i++)
							{
								cls = [
									'e-'+(i+1),
									(i%2) ? 'even' : 'odd'
								];

								if(i == 0 && li.length == 1)
									cls[cls.length] = 'single';
								else if(i == 0)
									cls[cls.length] = 'first';
								else if(i == li.length - 1)
									cls[cls.length] = 'last';
								else
									cls[cls.length] = 'middle';

								li[i].className = cls.join(' ');
							}

							ul.setAttribute('more', 1);
							vkDom.setText(this, self.txtMoreLessLess);

						}
						else
						{
							// More -> Less

							var	showItems = ul.getAttribute('showitems');

							li = ul.childNodes;

							for(i = 0; i < li.length; i++)
							{
								if(i < showItems)
								{
									cls = [
										'e-'+(i+1),
										(i%2) ? 'even' : 'odd'
									];

									if(i == 0 && showItems == 1)
										cls[cls.length] = 'single';
									else if(i == 0)
										cls[cls.length] = 'first';
									else if(i == showItems - 1)
										cls[cls.length] = 'last';
									else
										cls[cls.length] = 'middle';

									li[i].className = cls.join(' ');

								}
								else
									li[i].className = 'none';	// li[i].className = 'hidden';
							}

							ul.setAttribute('more', 0);
							vkDom.setText(this, self.txtMoreLessMore);
						}

						return false;
					}

						morelessSPAN = document.createElement('span');
						morelessSPAN.appendChild(document.createTextNode(this.txtMoreLessMore));

					morelessA.appendChild(morelessSPAN);

				morelessP.appendChild(morelessA);

				optBlock.appendChild(morelessP);
			}

			optContainer.appendChild(optBlock);

		}	// Loop on categories
	}
	else	// No categories
		vkDom.addClass('search_options', 'none');
}


pageSearchClass.prototype.onDatesChange = function()
{
	// If both dates are selected, run a search
	if(
		vkDom.el('search_date_in').value.length &&
		vkDom.el('search_date_out').value.length
	)
	{
		this.goSearch(this.human2mysql(vkDom.el('search_date_in').value), this.human2mysql(vkDom.el('search_date_out').value), null);
		return;
	}

	vkDom.removeClass('search_dates_remove', 'none');
}

pageSearchClass.prototype.onDatesClean = function()
{
	vkDom.el('search_date_in').value = '';
	vkDom.el('search_date_out').value = '';
	vkDom.addClass('search_dates_remove', 'none');

	return false;
}


pageSearchClass.prototype.onGuestChange = function(selObj)
{
	this.goSearch(null, null, selObj.options[selObj.selectedIndex].value, this.preselectedGuestId);
}


pageSearchClass.prototype.goSearch = function(arrival, departure, option, excludeOptions)
{
	var	args = '';
	
	if (excludeOptions===undefined) excludeOptions = [];
	if (!kigo.is_array(excludeOptions)) excludeOptions = [excludeOptions];

	if(arrival != null && departure != null)
		args += (args.length?'.':'')+'AD_'+arrival+'.DD_'+departure;

	if (kigo.is_array(PAGETYPE_SEARCHRES_SEARCH_OPTIONS)) {
			// array contains a list provided by a page of type Search Results to properly display the selected search options  08/12/2009
			// if it is in this array then it is part of the page's settings
			// Therefore when the user has clicked on the option it needs to be excluded out of the predefined search or added if it was not in the page's list
			var extraArgs = [];
			if(option != null) {
				if (kigo.in_array(option, PAGETYPE_SEARCHRES_SEARCH_OPTIONS)) {
					for (var i=0; i<PAGETYPE_SEARCHRES_SEARCH_OPTIONS.length; i++) {
						if (PAGETYPE_SEARCHRES_SEARCH_OPTIONS[i]!=option && !kigo.in_array(PAGETYPE_SEARCHRES_SEARCH_OPTIONS[i], excludeOptions))
							extraArgs[extraArgs.length] = PAGETYPE_SEARCHRES_SEARCH_OPTIONS[i];
					}
				} else {
					// else it needs to be added to the predefined search
					for (var i=0; i<PAGETYPE_SEARCHRES_SEARCH_OPTIONS.length; i++) {			
						if (!kigo.in_array(PAGETYPE_SEARCHRES_SEARCH_OPTIONS[i], excludeOptions))
							extraArgs[extraArgs.length]  = PAGETYPE_SEARCHRES_SEARCH_OPTIONS[i];
					}
					if (option > 0) // ignore empty option if any is sent
						extraArgs[extraArgs.length] = option;
				}
				//set the search option to our new set of options
				option = extraArgs.join('-');
			}		
		} 

	if(option != null) {
		if (option == '') { // if no options, request list
			args += (args.length?'.':'')+'DT_LIST';
		} else {
			args += (args.length?'.':'')+'O_'+option;
		}
	}

	window.location = _SEARCH_URL + (args.length ? ('#'+vkDom.uri(args)) : '');
}




/*************************************************************************/
/* Tools */

pageSearchClass.prototype.today = function()
{
	var	today = new Date();

	today.setHours(0);
	today.setMinutes(0);
	today.setSeconds(0);
	today.setMilliseconds(0);

	return today;
}

pageSearchClass.prototype.compareDates = function(a, b)
{
	if(a.getFullYear() < b.getFullYear())
		return -1;
	if(a.getFullYear() > b.getFullYear())
		return 1;

	if(a.getMonth() < b.getMonth())
		return -1;
	if(a.getMonth() > b.getMonth())
		return 1;

	if(a.getDate() < b.getDate())
		return -1;
	if(a.getDate() > b.getDate())
		return 1;

	return 0;
}

pageSearchClass.prototype.mysql2human = function(input)
{
	if(input == null)
		return '';
	// 31/05/2010 - Bugfix
	return kigoDate.createFromMysql(input).calendar();
}

pageSearchClass.prototype.human2mysql = function(input)
{
	// 31/05/2010
	return kigoDate.createFromCalendar(input).mysql();
}


pageSearchClass.prototype.selReset = function(sel)
{
	var	sel = vkDom.el(sel);
	for(i = sel.options.length; i >=0; i--)
		sel.options[i] = null;

	sel.options.length = 0;
}

pageSearchClass.prototype.selAdd = function(sel, value, text)
{
	var	sel = vkDom.el(sel);
	sel.options[sel.options.length] = new Option(text, value);
}

// 24/02/2009
pageSearchClass.prototype.selSetClasses = function(sel)
{
	var	sel = vkDom.el(sel);
	var	cls;

	for(var i = 0; i < sel.options.length; i++)
	{
		cls = [
			'e-'+(i+1),
			(i%2) ? 'even' : 'odd'
		];

		if(i == 0 && sel.options.length == 1)
			cls[cls.length] = 'single';
		else if(i == 0)
			cls[cls.length] = 'first';
		else if(i == sel.options.length - 1)
			cls[cls.length] = 'last';
		else
			cls[cls.length] = 'middle';

		sel.options[i].className = cls.join(' ');
	}
}


var	pageSearch = new pageSearchClass();