function SearchResultsCacheManager()
{
	this.cookieName = 'searchResults';
	this.cookieValue = getCookieFromCache(this.cookieName);
	this.searchResultsCookie = null;
	this.MAX_SEARCHRESULTS = 3;
	
	if(this.cookieValue == null)
	{
		this.searchResultsCookie = new Array(0);
	}
	else
	{
		this.searchResultsCookie = eval(this.cookieValue);
	}
	
	this.addSearchResult = addSearchResult;
	this.render = renderSearchResults;
}

function addSearchResult(searchResult)
{
	for(var j=0;j<this.searchResultsCookie.length;j++)
	{
		if(searchResult.searchURL==this.searchResultsCookie[j].searchURL)
		{
			for(var k=j;k<this.searchResultsCookie.length - 1;k++)
			{
				this.searchResultsCookie[k] = this.searchResultsCookie[k+1];
			}
			
			this.searchResultsCookie[this.searchResultsCookie.length - 1] = searchResult;
			
			this.cookieValue = serializeSearchResultsCookie(this.searchResultsCookie);
			
			return;
		}
	}
	
	if(this.searchResultsCookie.length == this.MAX_SEARCHRESULTS)
	{
		this.searchResultsCookie.shift();
	}
	
	this.searchResultsCookie.length += 1;
	
	this.searchResultsCookie[this.searchResultsCookie.length - 1] = searchResult;
	
	this.cookieValue = serializeSearchResultsCookie(this.searchResultsCookie);
	
	//Temporary Fix for the case when new search criteria is not cached when cookie value is exhaustively long:
	var tempSearchResults = getCookieFromCache(this.cookieName);
	if(tempSearchResults!=this.cookieValue)
	{
		this.searchResultsCookie.length -= 1;
		this.searchResultsCookie.shift();
		this.addSearchResult(searchResult);
	}
}

function renderSearchResults()
{
	var HTMLText = '';
	for(var i=this.searchResultsCookie.length - 1;i>=0;i--)
	{
		HTMLText += this.searchResultsCookie[i].render();
	}
	
	return HTMLText;
}

/**
The SearchResult class is an encapuslation of all the data we would lke to store in a cookie so that the recent
searches can be stored be displayed to the user.
**/
function SearchResult(imgURL, searchURL, departureDate, departureAirport, countryID, countryName, resortID, resortName, accomID, accomName, duration, paxData)
{
	this.imgURL = imgURL;	
	var searchUrlPart1 = searchURL.substring(0,(searchURL.indexOf('?')+1));
	var searchUrlPart2 = searchURL.substring((searchURL.indexOf('?')+1));
	//alert("searchURL--->"+searchURL.substring(0,(searchURL.indexOf('?')+1)));
	//alert("Reamin searchURL--->"+searchURL.substring((searchURL.indexOf('?')+1)));
	//alert("searchURL--->"+(searchUrlPart1 + 'cmp=crystalskirecentsearches&' +searchUrlPart2));
	searchURL = searchUrlPart1 + '_s_icmp=recentsearches&' + searchUrlPart2;
	this.searchURL = searchURL;		
	this.departureDate = departureDate;
	this.departureAirport = departureAirport;
	this.countryID = countryID;
	this.countryName = countryName;
	this.resortID = resortID;
	this.resortName = resortName;
	this.accomID = accomID;
	this.accomName = accomName;
	this.duration = duration;
	this.paxData = paxData;
	
	this.getJSONNotation = getSearchResultJSONNotation;
	this.render = renderSearchResult; 
}

function getSearchResultJSONNotation()
{
	var jsonText = '';
	jsonText += 'new SearchResult(';
	jsonText += '"' + this.imgURL + '",';
	jsonText += '"' + this.searchURL + '",';
	jsonText += '"' + this.departureDate + '",';
	jsonText += '"' + this.departureAirport + '",';
	jsonText += '"' + this.countryID + '",';
	jsonText += '"' + this.countryName + '",';
	jsonText += '"' + this.resortID + '",';
	jsonText += '"' + this.resortName + '",';
	jsonText += '"' + this.accomID + '",';
	jsonText += '"' + this.accomName + '",';
	jsonText += '"' + this.duration + '",';
	jsonText += 'new PAXData(' + this.paxData.noOfAdults + ',' + this.paxData.noOfChildren + ',' + this.paxData.noOfInfants + ')';
	jsonText += ')';
		/**
		jsonText += 'imgURL:' +  + ',';
		jsonText += 'departureDate:' + this.departureDate + ',';
		jsonText += 'departureAirport:' + this.departureAirport + ',';
		jsonText += 'country:' + this.country + ',';
		jsonText += 'resort:' + this.resort + ',';
		jsonText += 'duration:' + this.duration + ',';
		jsonText += 'paxData:' + this.paxData;
		**/
	
	return jsonText;
}

function renderSearchResult()
{
	var destination = '';
	if(this.accomName != '')
	{
		destination += this.accomName + ', in ' + this.resortName + ', ' + this.countryName; 
	}
	else if(this.resortName != ''){
		destination += this.resortName + ' in ' + this.countryName;
	}
	else{
		destination += 'any resort in ' + this.countryName;
	}
	
	var HTMLText = '';
	HTMLText += '<li>';
	HTMLText +=		'<div class="insideRecentSearch">';
	HTMLText +=			'<div class="image">';
	HTMLText +=				'<a href="' + encodeURI(this.searchURL) + '">';
	HTMLText +=					'<img alt="' + decodeURIComponent(this.accomName) + '" src="/dbimages' + this.imgURL + '" />';
	HTMLText +=				'</a>';
	HTMLText +=			'</div>';				
	HTMLText +=			'<div class="text">';
	HTMLText +=				'<p class="date">' + this.departureDate + '</p>';
	HTMLText +=				'<p class="route">';
	HTMLText +=					'<a href="' + encodeURI(this.searchURL) + '">';
	HTMLText +=						'<span class="flyingFrom">' + this.departureAirport + '</span> to ';
	HTMLText +=						'<span class="goingTo">' + decodeURIComponent(destination) + '</span>';
	HTMLText +=					'</a>';
	HTMLText +=				'</p>';
	HTMLText +=				'<p class="duration">' + this.duration + ' Nights</p>';
	HTMLText +=			'</div>';
	HTMLText +=		'</div>';
	HTMLText +=	'</li>';				

	return HTMLText;
}

function PAXData(noOfAdults, noOfChildren, noOfInfants)
{
	this.noOfAdults = noOfAdults;
	this.noOfChildren = noOfChildren;
	this.noOfInfants = noOfInfants;
}

function serializeSearchResultsCookie(searchResultsCookie)
{
	var cookieValue = '[' + searchResultsCookie[0].getJSONNotation();
	
	for(i=1;i<searchResultsCookie.length;i++)
	{
		cookieValue += ',';
		cookieValue += searchResultsCookie[i].getJSONNotation();
	}
	
	cookieValue += ']';
	
	setCookieToCache('searchResults',cookieValue,'','/');
	
	return cookieValue;
}

function setShowHideCookie(showHideElementId)
{
	if(document.getElementById(showHideElementId).className == "CollapsiblePanelOpen")
	{
		setCookieToCache(showHideElementId,"hide",'','/');
	}
	else
	{
		setCookieToCache(showHideElementId,"show",'','/');
	}
}

function showHideSearchPanel()
{
	if(new SearchResultsCacheManager().cookieValue==null)
	{
		document.getElementById("previousSearches").style.display = "none";
	}
	else
	{
		var showHideSearch = getCookieFromCache("showHideSearches"); 
		if(showHideSearch ==null || showHideSearch == "show")
		{
			document.getElementById("showHideSearches").className = "CollapsiblePanelOpen";
			document.getElementById("recentSearches").style.display = "block";
		}
		else
		{
			document.getElementById("showHideSearches").className = "CollapsiblePanelClosed";
			document.getElementById("recentSearches").style.display = "none";
		}
	}
}

function showHidePanels(id1, id2) {

	if (id1 != null && id2 != null) {

		document.getElementById(id1).style.display = "block";
		document.getElementById(id2).style.display = "none";
	}
}

function encodeParams()
{
	document.forms['frmSearch'].elements['resortName'].value = encodeURIComponent(decodeURIComponent(document.forms['frmSearch'].elements['resortName'].value));
	document.forms['frmSearch'].elements['accommodationName'].value = encodeURIComponent(decodeURIComponent(document.forms['frmSearch'].elements['accommodationName'].value));
}

function restoreSearchOptions(CountryCode,ResortCode,AccomCode) {
	var searchResultsCache = new SearchResultsCacheManager();
	var searhResultsCount = searchResultsCache.searchResultsCookie.length;
	if(searhResultsCount == 0){return;}
	var latestSearch = searchResultsCache.searchResultsCookie[searhResultsCount-1];
	var searchURL = latestSearch.searchURL;
	var departureDate = latestSearch.departureDate;
	var departureAirport = latestSearch.departureAirport;
	var countryID = latestSearch.countryID;
	var countryName = latestSearch.countryName;
	var resortID = latestSearch.resortID;
	var resortName = latestSearch.resortName;
	var accomID = latestSearch.accomID;
	var accomName = latestSearch.accomName;
	var duration = latestSearch.duration;
	var paxData = latestSearch.paxData;
	var noOfAdults = paxData.noOfAdults;
	var noOfChildren = paxData.noOfChildren;
	var noOfInfants = paxData.noOfInfants;
	var departureDateSearchType = splitParameterValueFromURL(searchURL,'DepartureDateSearchType','&','=')[1];
	var boardBasis = new Array();
	var searchParam = 'BasicSearchOption|boardbasis|';
	var inputURL = searchURL;
	var bbIndex = 0;
	while(bbIndex != -1) {
		bbIndex = inputURL.indexOf(searchParam);
		if(splitParameterValueFromURL(inputURL,searchParam,'&','=')!="")
		{
			boardBasis.push(splitParameterValueFromURL(inputURL,searchParam,'&','=')[0]);
		}
		bbIndex = inputURL.indexOf(searchParam,bbIndex+1);
		inputURL = inputURL.substr(bbIndex);
	}
	var priceRange = splitParameterValueFromURL(searchURL,'priceRange','&','=')[1];
	var departureAirportCode;
	var dateString = departureDate.toString();
	var dateStringLength = dateString.length;
	if(dateStringLength==10)
	{
		var dd = departureDate.substr(0,1);
		var mon = departureDate.substr(2,3);
		var yyyy = departureDate.substr(6,4);
	}
	else if (dateStringLength==11)
	{
		var dd = departureDate.substr(0,2);
		var mon = departureDate.substr(3,3);
		var yyyy = departureDate.substr(7,4);
	}
	var monthIndex = -1;
	var mm="";
	var monthNumber;
	var mmyyyy;
	// The yxMonths is used from the Calendar.js
	for(var counter in yxMonths) {
		if(mon==yxMonths[counter].substr(0,3)) {
			monthIndex=counter;	
		}
		else
			continue;
	}
	// monthNumber  : Jan=1, Feb=2, Mar=3 etc.
	monthNumber = (Number(monthIndex)+1).toString();
	// to concatenate '0' before if the monthNumber is in between 1-9
	// 'mm' values  : 01/02/03/04/....12
	if(monthNumber.length==1) {
		mm = "0".concat(monthNumber);
	}
	else {
		mm = monthNumber;
	}
	mmyyyy = mm.concat(yyyy);
	
	// restoreObject is in RestoreFormValues.js
	// It is used to restore the form values 
	 var restoreObj = new restoreObject('frmSearch');
	 restoreObj.optionClear('dd');
	 restoreObj.optionClear('mmyyyy');
	 restoreObj.optionClear('duration');
	 restoreObj.optionClear('countryList');
	 restoreObj.optionClear('resortList');
	 restoreObj.optionClear('accommodationList');
	 restoreObj.optionClear('originAirport');
	 restoreObj.optionClear('adults');
	 restoreObj.optionClear('children');
     restoreObj.optionClear('infants');
	 restoreObj.optionClear('priceRange');
	 restoreObj.optionClear('infants');
	 restoreObj.restoreOption('mmyyyy',mmyyyy);
	 loadDates('dd','mmyyyy','frmSearch');
	 getDepDate();
	 restoreObj.restoreOption('dd',dd);
	// restoreObj.restoreOption('duration',duration); //At present there is no duration option in FCSki
	 restoreObj.restoreOption('adults',noOfAdults);
	 restoreObj.restoreOption('children',noOfChildren);
     restoreObj.restoreOption('infants',noOfInfants);

	 //To get the Code of the departure airport
	if(countryID!="" && resortID == "")
	{
		for(var x in airportCountryList)
		{
			var airportDataSplitted = airportCountryList[x].split(",");
			if(airportDataSplitted[0] == countryID && airportDataSplitted[2] == departureAirport)
			{
				departureAirportCode = airportDataSplitted[1];
			}
		}
	}
	else 
	{
		for(var x in airportResortList)
		{
			var airportDataSplitted = airportResortList[x].split(",");
			if(airportDataSplitted[0] == resortID && airportDataSplitted[2] == departureAirport)
			{
				departureAirportCode = airportDataSplitted[1];
			}
		}
	}
		
	if(departureDateSearchType == 'month') {
		 document.forms['frmSearch'].elements['DepartureDateSearchTypeIn'].checked = true;
	}
	else if (departureDateSearchType == 'exact') {
		 document.forms['frmSearch'].elements['DepartureDateSearchTypeIn'].checked = false;
	}
	// To check if the current page is the Country Page/ Resort Page/Accommodation Page
	if(CountryCode=='' &&ResortCode==''&&AccomCode=='')
	{
		//If it is not the Country Page/ Resort Page/Accommodation Page
		restoreDestinations(countryID,resortID,accomID);
	}
	//If it is the Country Page/ Resort Page/Accommodation Page that is not as per the latest search
	else if(CountryCode!=countryID || ResortCode!=resortID || AccomCode!=accomID){
		// display the error message
		 var destErrorMessageBlock = document.getElementById('destErrorMessage');
		 var spanElement = document.createElement('div');
		 var destMessage =	"<div class='insideInfo'>";
		 destMessage+= "<b>Please note:</b> Your previous search for ";
	  	 destMessage+= destPath(countryID,resortID,accomID);
		 destMessage+= " has been changed as you're looking at the  ";
	  	 destMessage+= destPath(CountryCode,ResortCode,AccomCode);
	  	 destMessage+= " page. </div>";
		 var innerSpan = document.createElement('span');
		 innerSpan.id='restoreLatest';
		 innerSpan.onclick = function(){
			 restoreDestinations(countryID,resortID,accomID);
			 restoreObj.restoreOption('originAirport',departureAirportCode);
			 destErrorMessageBlock.style.display = 'none';
			 var airErrorMessageBlock = document.getElementById('airportErrorMessage');
			 airErrorMessageBlock.style.display = 'none';
			 spanElement.innerHTML = '';
		 }
		 innerSpan.innerHTML = 'Undo';
		 spanElement.innerHTML = destMessage;
		 spanElement.appendChild(innerSpan);	
		 destErrorMessageBlock.appendChild(spanElement);
	}
	//Check if the airport in the cookie is present in the airport dropdown. 	
	var isAirportPresent = isOptionPresent('frmSearch','originAirport',departureAirportCode)
	if(isAirportPresent == true) {
		restoreObj.restoreOption('originAirport',departureAirportCode);
	}
	else {
		//display error message
		var airErrorMessageBlock = document.getElementById('airportErrorMessage');
		var spanElement = document.createElement('div');
		var airportMessage = "<div class='insideInfo'>";
		airportMessage += "<b>Please note:</b> your choice of departure airport has been modified as we dont fly to ";
		airportMessage+=destPath(CountryCode,ResortCode,AccomCode);
		airportMessage+= " from "+departureAirport;
		airportMessage+= "</div>";
		spanElement.innerHTML = airportMessage;
		airErrorMessageBlock.appendChild(spanElement);
		//Check if 'Any London' is present in the airport dropdown.
		var isAnyLondonPresent = isOptionPresent('frmSearch','originAirport','UKLON');
		//restore 'Any London'
		if(isAnyLondonPresent == true) {
			restoreObj.restoreOption('originAirport','UKLON');
		}
		//restore the first one.(i.e. Select...)
		else {
			document.forms['frmSearch'].elements['originAirport'].selectedIndex = 0;
		}
	}
	restoreObj.restoreOption('priceRange',priceRange);

	var boardBasisLength = boardBasis.length;
	if(boardBasisLength != 0)
	{
		showHideBoardBasis.open();
		for(var i=0;i<boardBasisLength;i++) {
			 document.forms['frmSearch'].elements[boardBasis[i]].checked = true;
		}
	}
	else
	{
		showHideBoardBasis.close();
	}
}

/*
 *This function returns the name & value of the input parameter(param) from the search url (URL)	
 *	In general the search url will be of the form ?name=JOHN&job=Developer&age=37
 * INPUTS:		URL		--> Search URL
 * 					param	--> value of which we want to find
 *					sprt1		--> Seperator (to seperate the required name-value pair from the URL)
 *					spr2		--> Seperator (to seperate the name, value from the name-value pair)	
 * RESULT:     pairSplitted		--> Array with name and value as its elements.
 */
function splitParameterValueFromURL(URL,param,sprt1,sprt2) {
	if(URL.indexOf(param)!=-1)
	{
		var first = URL.indexOf(param);
		var last = URL.indexOf(sprt1,first);
		var pair = URL.substring(first,last);
		var pairSplitted = pair.split(sprt2);
		return pairSplitted;
	}
	else {
		return "";
	}
}

function getAccomName(accomCode) {
	for(var i=0; i<accList.length; i++) 
	{
		var accListMap = accList[i].split(",");
		if(accListMap[1]==accomCode)
		{
			return accListMap[2];
		}
	}
	return "";
}

function getResortName(resortCode) {
	for(var i=0; i<rList.length; i++) 
	{
		var rListMap = rList[i].split(",");
		if(rListMap[1]==resortCode)
		{
			return rListMap[2];
		}
	}
	return "";
}

/** Returns the destination path (string) 
 * E.g. 1. Hotel Des Geneys, in Bardonecchia, Italy		(Country, Resort and Accommodation are present)
 * 		2. Chamonix in France							(If accommodation is absent)
 *		3. Austria										(If only country is present)
 */ 
function destPath(cCode,rCode,aCode) {
	var path ="";
	if(aCode!='')	{
		path+= getAccomName(aCode)+', in '+getResortName(rCode)+', '+getCountry(cCode);
	}
	else {
		if(rCode!='') {
			path+= getResortName(rCode)+' in '+getCountry(cCode);
		}
		else {
			path+= getCountry(cCode);
		}
	}
	return path;
}

function restoreDestinations(cCode,rCode,aCode){
	 var restoreObj = new restoreObject('frmSearch');
	 restoreObj.restoreOption('countryList',cCode);
	 var l1 = new listManager("frmSearch",["countryList","resortList","accommodationList","originAirport"],[cList,rList,accList,airportCountryList,airportResortList],[cCode,rCode,aCode]);
	 if(rCode == "" && aCode == "") {
		l1.drawresort();
		l1.aircountry();
	 }
	 else if (rCode != "" && aCode == "")
	 {
		l1.drawaccom();
		l1.airresort();
	 }
	 else if (rCode != "" && aCode != "")
	 {
		l1.airresort();
	 }
	 restoreObj.restoreOption('resortList',rCode);
	 restoreObj.restoreOption('accommodationList',aCode);
}

/** Checks if the option is present
 * Inputs: 	formName --> Form Name
 *			selectName --> Name of the dropdown list
 *			optionValue --> Value of the option to search for
 */
function isOptionPresent(formName,selectName,optionValue) {
	var restoreObj = new restoreObject(formName);
	var isAnyLondonPresent = false;
		for (i=0;i<restoreObj.form.elements[selectName].options.length;i++) {
			if (restoreObj.form.elements[selectName].options[i].value == optionValue) {
				isAnyLondonPresent = true;
			}
		}
	return isAnyLondonPresent;
}