/* Scripts for the Single Click pages */

/* History:
3-4-2008 Initial Version 
*/

/*Class for loading the data 
This is a rewrite of the old funtion-type handling of the single click page
*/

var SingleClickSelection = {
	intialize: function (p_group, p_id, p_text){
		this.group = p_group;
		this.id = p_id;
		this.text = p_text;
	}
};

var SingleClickOfferClass = 
{	
	LogDebug: function(message) {
    if (this.isDebugging) {
			var div = $('#debug');
			div.append(message + "<br/>");
		}
	},

	SetupDebug: function(){
		if (this.isDebugging) {
			var version = "1.0.20080914.1";
			var div = $('#outerMain');
			div.append("<div id='debug' style='background-color:red;'>Debug window version: " + version + ":<br/></div>");
		}
	},

	hideSelectionlist: function(group, id){
		var gr = $("#"+group); 				//the div holding all the selectable items
		var el = $("#option"+group+id);		//the element that is selected
		
		if (gr!=null){
			//gr.className = 'hidden';
			gr.addClass('hidden');
		}
		if (el!=null){
			//el.className = 'Selected';
			el.addClass('Selected');
		}
	},

	showSelectionlist: function(group, id){
		var gr = $("#"+group); 				//the div holding all the selectable items
		var el = $('#option'+group+id);		//the element that is selected
		
		if (gr!=null){
			//gr.className = '';		
			gr.removeClass("hidden");	
			
			if (el!=null){	
				//el.className = '';
				el.removeClass("Selected");
			}
		}
	},	
	
	/*****************************
	sets the result sort order. field can only be 'price'
	*****************************/
	sort: function(field,direction){
		if (!this.isLoading || this.isInitializing){
			this.pricesort=direction;
			//reset currentpage
			this.currentpage=1;
			if (!this.isLoading) this.loadData();
		}
	},
	
	setPage: function(p_newpage) {
		if (!this.isLoading || this.isInitializing){
		
			this.LogDebug("setPage: start");
		
			//set pagenumber and load the data for that page.
			if (p_newpage=='down') {
				if (this.currentpage>1) { this.currentpage--; }
				else return;
			} else if (p_newpage=='up') {
				if (this.currentpage<(this.pagecount)) { this.currentpage++; }
				else return;
			} else {
				this.currentpage=p_newpage;
			}

			if (!this.isLoading) this.loadData();
			
			this.LogDebug("setPage: done");
		}
	},
			
	//Creates the paging links
	createPagesLinks: function(){
		this.toggleSortLink();
		this.createPagesLinksForDiv('resultsPagination_2');
		this.createPagesLinksForDiv('resultsPaginationBottom_2');
	},

	toggleSortLink: function(){
        if (this.showPriceSort){
			$("#resultsPagination_1").css("display","block");
			$("#resultsPaginationBottom_1").css("display","block");	
		} else{
			$("#resultsPagination_1").css("display","none");
			$("#resultsPaginationBottom_1").css("display","none");
		}
	},

	createPagesLinksForDiv: function(p_divname){
		var div = $('#'+p_divname);
        div.html("");
	
		//create pagelinks
		if (this.pagecount>1){
			
			var firstpage=1;
			var lastpage=this.pagecount;
			if (this.pagecount>=5){
				if (this.currentpage<=3){
					firstpage=1;
					lastpage=5;
				} else if (this.currentpage>=this.pagecount-2){
					firstpage=this.pagecount-4;
					lastpage=this.pagecount;
				} else {
					firstpage=this.currentpage-2;
					lastpage=this.currentpage+2;
				}
			}
					 
			var newpage = document.createElement('a');
			newpage.setAttribute('href','#');
			newpage.setAttribute('id','pagelinkDown');
			newpage.onclick=function(){document.singleclick.setPage('down');return false;};
			newpage.innerHTML = this.pageDownText;
			div.append(newpage);

			if (this.currentpage>3) {
				var newpage = document.createElement('span');
				newpage.innerHTML = '.....';
				newpage.setAttribute('id','pagelinkMoreBefore');
				div.append(newpage);
			}
				
			for (var p=firstpage;p<=lastpage;p++){
				var newpage = document.createElement('a');
				newpage.setAttribute('href','#');
				newpage.setAttribute('id','pagelink'+p);
				newpage.onclick=function(){document.singleclick.setPage(parseInt(this.innerHTML));return false;};
				newpage.innerHTML = (p);
				if (p==this.currentpage) newpage.className='Selected';
				div.append(newpage);
			}
			
			if (lastpage<this.pagecount) {
				var newpage = document.createElement('span');
				newpage.setAttribute('id','pagelinkMoreAfter');
				newpage.innerHTML = '.....';
				div.append(newpage);
			}
			
			var newpage = document.createElement('a');
			newpage.setAttribute('href','#');
			newpage.setAttribute('id','pagelinkUp');
			newpage.onclick=function(){document.singleclick.setPage('up');return false;};
			newpage.innerHTML = this.pageUpText;
			div.append(newpage);
		}
	},
		
	/***********
	Resets the seleted items.... clears the selected items, and shows all selected lists.
	*************/
	setSeletedToNone: function(){
	
		this.LogDebug("setSeletedToNone: start");
	
		var div = $('#optionsSelectedItems');	//the div holding the selected items

		//remove all options
		div.empty();
		
		// add "none" node
		if(div.children().length==0){
			var newspan = document.createElement('span');
			newspan.setAttribute('id','selectedNone');
			newspan.innerHTML = this.selectedNoneText;
			div.append(newspan);
			$('#optionsSelected').css("display","none");
		}
		
		//Show all selectionlists, if there are options
		if ($("#options_monthChoice").children().length>0)	this.showSelectionlist("monthChoice");
		else 												this.hideSelectionlist("monthChoice");
		
		if ($("#options_monthChoice").children().length>0)	this.showSelectionlist("dateChoice");
		else												this.hideSelectionlist("dateChoice");
		
		this.hideSelectionlist("specificdateChoice");
		
		if ($("#options_monthChoice").children().length>0)	this.showSelectionlist("peoplesChoice");
		else 												this.hideSelectionlist("peoplesChoice");
		
		if ($("#options_monthChoice").children().length>0)	this.showSelectionlist("cottagetypeChoice");
		else												this.hideSelectionlist("cottagetypeChoice");
		
		if ($("#options_monthChoice").children().length>0)	this.showSelectionlist("countriesChoice");
		else 												this.hideSelectionlist("countriesChoice");
		
		this.hideSelectionlist("regionChoice");
		
		if ($("#options_monthChoice").children().length>0)	this.showSelectionlist("parkChoice");
		else												this.hideSelectionlist("parkChoice");
		
		if (!this.showpricesortalways == 'true') {
			this.showPriceSort=false;
			this.pricesort='';
		}			
		
		this.LogDebug("setSeletedToNone: done");
	},
	
	resetselections: function(){
		if (!this.isLoading || this.isInitializing){
			this.selectionsRendered = false; // IRQ-317
			this.LogDebug("resetselections: start");
		
			this.setSeletedToNone();
			this.currentpage=1;
			if (!this.isLoading) this.loadData();
			
			this.LogDebug("resetselections: done");
		}
	},
	
	/************
	Removes the selected option from the selected options box
	*************/
	removeSelectedOption: function(group, reload){
		if (!this.isLoading || this.isInitializing){

			this.LogDebug("removeSelectedOption: start");
		
			var gr = $("#"+group); 				//the div holding all the selectable items
			var div = $('#optionsSelectedItems');	//the div holding the selected items
		
			// Show the selction group
			if ($("#options_"+group).children.length>0)		this.showSelectionlist(group);
			else													this.hideSelectionlist(group);

			//remove option node
			//var selectedItems = $ES("span","optionsSelectedItems");
			var selectedItems = $("#optionsSelectedItems > span");
			if (selectedItems[0].getAttribute("id")!="selectedNone") {
				for (var i=0 ; i<selectedItems.length ; i++) {
					var selecteditem=selectedItems[i];
					if (selecteditem.getAttribute("type")==group) {
						$(selecteditem).remove();
					}
				}
			}

			// add "none" node, if there are no children left
			if(div.children().length==0){
				this.setSeletedToNone();
			}

			//If a village was de-selected, hide  the price sort section
			//If a village was de-selected, hide the region selection
			if (group=="parkChoice") {
				if (this.showpricesortalways=='true') {
					this.showPriceSort=true;
				} else {
					this.showPriceSort=false;
				}
				this.pricesort='';	
			}

			//If a country was de-selected, hide the region selection
			if (group=="countriesChoice") {
				this.showRegionsSelection=false;		
				this.removeSelectedOption("regionChoice", false);		
				this.hideSelectionlist("regionChoice");
			}

			//If a staycode was de-selected, hide the specific date selection
			if (group=="dateChoice") {
				this.showSpecificDateSelections=false;		
				this.removeSelectedOption("specificdateChoice", false);
				this.hideSelectionlist("specificdateChoice");
			}
				
			//Load new data
			this.currentpage=1;
			if (!this.isLoading) this.loadData();
			
			this.LogDebug("removeSelectedOption: done");
		}
	},
	
	/************
	Adds the selected option from the selected options box
	*************/
	addSelectedOption: function(group, id, text){
		if (!this.isLoading || this.isInitializing){

			this.LogDebug("addSelectedOption: start");

			if (text==null) text = $("#hidden"+group+id+"Name").val();
			
			var gr = $("#"+group); 				//the div holding all the selectable items
			var div = $('#optionsSelectedItems');	//the div holding the selected items
			var el = $('#option'+group+id);		//the element that is selected
		
			$('#optionsSelected').css("display","block");
			
			this.hideSelectionlist(group, id);

			// remove "none" node
			//if(div.firstChild.id=='selectedNone'){
			if(div.children()[0].id=='selectedNone'){
				var selectedNoneElement = $('#selectedNone');
				this.selectedNoneText=selectedNoneElement.html();
				selectedNoneElement.remove();
			}

			//add option node
			var newspan = document.createElement('span');
			newspan.setAttribute('id','selected'+group+id);
			newspan.setAttribute('type',group);
			newspan.setAttribute('choiceid',id);
					
			var newHTML = this.selectedOptionTemplate;
			newHTML = newHTML.replace(/\{0\}/g,group);
			newHTML = newHTML.replace(/\{1\}/g,id);
			newHTML = newHTML.replace(/\{2\}/g,text);
			newspan.innerHTML = newHTML;
				
			div.append(newspan);
			
			//Show other selection options  based on selcted option
			if (group=="parkChoice") {
				this.showPriceSort=true;				//If a village was selected, display the price sort section
			}
			
			if (group=="countriesChoice") {		
				this.showRegionsSelection=true;		//If a country was selected, display the region selection
				this.showSelectionlist("regionChoice");
			}

			if (group=="dateChoice") {
				this.showSpecificDateSelections=true;		//If a staycode was selected, display the specific date selection
				this.showSelectionlist("specificdateChoice");
			}
			
			//Load new data
			this.currentpage=1;
			
			if (!this.isLoading) this.loadData();
			
			this.LogDebug("addSelectedOption: done");
		}
	}, 

	/*******
	Reads the selcted items from the xml and rebuilds the selections part of the page
	*******/
	updateCurrentSelections: function() {
		this.LogDebug("updateCurrentSelections: start");
	
		var selecteditems;
		if (this.currentselectionXMLData!=null){
			selecteditems=this.currentselectionXMLData.getElementsByTagName("currentselection");
		}
		this.setSeletedToNone();

		if (selecteditems!=null){

			var bMonthChoiceSelected=false;
			var bDateChoiceSelected=false;
			var bSpecificdateChoiceSelected=false;
			var bPeoplesChoiceSelected=false;
			var bCottagetypeChoiceSelected=false;
			var bCountriesChoiceSelected=false;
			var bRegionChoiceSelected=false;
			var bParkChoiceSelected=false;
			
			for (var i=0;i<selecteditems.length;i++) {
				
				var selecteditem = selecteditems[i];
				var optionstring=""
				var bShowSelectionList=true;
				switch (selecteditem.getAttribute("type")){
					case "month":
						optionstring="monthChoice";
						parentelementname='months';
						elementname="month";
						bMonthChoiceSelected=true;
						bShowSelectionList=false;
						break;
					case "staycode":
						optionstring="dateChoice";
						parentelementname='staycodes';
						elementname="staycode";
						bDateChoiceSelected=true;
						bShowSelectionList=false;
						break;
					case "specificdate":
						optionstring="specificdateChoice";
						parentelementname='specificdates';
						elementname="specificdate";
						bSpecificdateChoiceSelected=true;
						bShowSelectionList=false;
						break;
					case "persons":
						optionstring="peoplesChoice";
						parentelementname='persons';
						elementname="person";
						bPeoplesChoiceSelected=true;
						bShowSelectionList=false;
						break;
					case "cottagetype":
						optionstring="cottagetypeChoice";
						parentelementname='cottagetype';
						elementname="cottagetype";
						bCottagetypeChoiceSelected=true
						bShowSelectionList=false;
						break;
					case "country":
						optionstring="countriesChoice";
						parentelementname="countries";
						elementname="country";
						bCountriesChoiceSelected=true;
						bShowSelectionList=false;
						break;
					case "region":
						optionstring="regionChoice";
						parentelementname="regions";
						elementname="region";
						bRegionChoiceSelected=true;
						bShowSelectionList=false;
						break;
					case "village":
						optionstring="parkChoice";
						parentelementname="villages";
						elementname="village";
						bParkChoiceSelected=true;
						bShowSelectionList=false;
						break; 
					default:
						alert ("Unknown selection type: "+ selecteditem.getAttribute("type"));
				}
				
				this.addSelectedOption(optionstring, selecteditem.getAttribute("id"), selecteditem.firstChild.nodeValue);
			}
			
			if (!bMonthChoiceSelected) 			this.showSelectionlist("monthChoice");
			if (!bDateChoiceSelected) 			this.showSelectionlist("dateChoice");
			//if (!bSpecificdateChoiceSelected) 	this.showSelectionlist("specificdateChoice");
			if (!bPeoplesChoiceSelected) 		this.showSelectionlist("peoplesChoice");
			if (!bCottagetypeChoiceSelected) 	this.showSelectionlist("cottagetypeChoice");
			if (!bCountriesChoiceSelected) 		this.showSelectionlist("countriesChoice");
			//if (!bRegionChoiceSelected) 		this.showSelectionlist("regionChoice");
			if (!bParkChoiceSelected) 			this.showSelectionlist("parkChoice");
      
      this.selectionsRendered = true; // IRQ-317
      
		} else {
			this.setSeletedToNone();
		}
		
		this.LogDebug("updateCurrentSelections: done");
	},
	
	//Updates the totals that are displayed next to the selectors. If a total is 0, the selector is greyed
	setOptionNumber: function(group, id, number){
		var link = document.getElementById('option'+group+id);
		if (link!=null){
			document.getElementById('option'+group+id+'Number').innerHTML=number;
			if (number == 0) {
				link.className = 'GreyedOut';
				link.removeAttribute('onclick');
				link.removeAttribute('href');
				link.removeEvent('click');
			} else {
				// reset link
				link.className = '';
				link.removeEvent('click');
				link.addEvent('click', function(ele){ document.singleclick.addSelectedOption(group,id);return false; });
				//link.onclick=function(){document.singleclick.addSelectedOption(group,id);return false;};
				link.setAttribute('href', "#");
			} 
		} else {
			alert('option'+group+id+" not found");
		}
	},
	
	/*
	Updates the list of possible selections ,.for the given group
		parentelementname: name of the element that contains the list
		elementname: name of the elements to create
		selectionname:internal group name
		createnewoptions: true if the while list need to be recreates. False only updates the counts
	*/
	updateSelectionSection: function(parentelementname, elementname, selectionname, createnewoptions) {
		var newHTML="";
		var selectionelements;

		if (this.selectionsXMLData!=null){
			selectionelements=this.selectionsXMLData.getElementsByTagName(parentelementname)[0].getElementsByTagName(elementname);
		}
		
		if (createnewoptions){
			var optionsdiv = $("#options_"+selectionname);
			
			if (optionsdiv==null){
				alert("#options_"+selectionname+" not found");
				return;
			}
			
			//Clear old options
			optionsdiv.html("");
			
			if (selectionelements!=null && selectionelements.length!=0){
				for (var i = 0; i < selectionelements.length; i++) {
					var selectionelement=selectionelements[i];

					// CPSU-4198 - BiSa - 30-1-09
					if(parentelementname=="villages")
					{
						if (selectionelement.getAttribute("count")!=0){
							var newHTMLselection = this.optionsSelectorVillageTemplate;
							
							newHTMLselection = newHTMLselection.replace(/\{0\}/g,selectionname);
							newHTMLselection = newHTMLselection.replace(/\{1\}/g,selectionelement.getAttribute("id"));
							newHTMLselection = newHTMLselection.replace(/\{2\}/g,selectionelement.firstChild.nodeValue);
							newHTMLselection = newHTMLselection.replace(/\{3\}/g,this.formatCountValue(selectionelement.getAttribute("count")));
							newHTMLselection = newHTMLselection.replace(/\{4\}/g,selectionelement.getAttribute("previousnametext"));
					
							newHTML = newHTML + newHTMLselection;
							
						} else {
							var newHTMLselection = this.optionsSelectorVillageTemplateCount0;
							
							newHTMLselection = newHTMLselection.replace(/\{0\}/g,selectionname);
							newHTMLselection = newHTMLselection.replace(/\{1\}/g,selectionelement.getAttribute("id"));
							newHTMLselection = newHTMLselection.replace(/\{2\}/g,selectionelement.firstChild.nodeValue);
							newHTMLselection = newHTMLselection.replace(/\{3\}/g,this.formatCountValue(selectionelement.getAttribute("count")));
							newHTMLselection = newHTMLselection.replace(/\{4\}/g,selectionelement.getAttribute("previousnametext"));
							
							newHTML = newHTML + newHTMLselection;
						}
					}					
					else
					{
						if (selectionelement.getAttribute("count")!=0){
							var newHTMLselection = this.optionsSelectorTemplate;
							
							newHTMLselection = newHTMLselection.replace(/\{0\}/g,selectionname);
							newHTMLselection = newHTMLselection.replace(/\{1\}/g,selectionelement.getAttribute("id"));
							newHTMLselection = newHTMLselection.replace(/\{2\}/g,selectionelement.firstChild.nodeValue);
							newHTMLselection = newHTMLselection.replace(/\{3\}/g,this.formatCountValue(selectionelement.getAttribute("count")));
					
							newHTML = newHTML + newHTMLselection;
							
						} else {
							var newHTMLselection = this.optionsSelectorTemplateCount0;
							
							newHTMLselection = newHTMLselection.replace(/\{0\}/g,selectionname);
							newHTMLselection = newHTMLselection.replace(/\{1\}/g,selectionelement.getAttribute("id"));
							newHTMLselection = newHTMLselection.replace(/\{2\}/g,selectionelement.firstChild.nodeValue);
							newHTMLselection = newHTMLselection.replace(/\{3\}/g,this.formatCountValue(selectionelement.getAttribute("count")));
							
							newHTML = newHTML + newHTMLselection;
						}
					}
				}
			
				optionsdiv.html(newHTML);

				return true;
			} else {
				this.hideSelectionlist(selectionname);
				return false;
			}
		} else {	
			for (var i = 0; i < selectionelements.length; i++) {
				var selectionelement=selectionelements[i];
				this.setOptionNumber(selectionname,selectionelement.getAttribute("id"),this.formatCountValue(selectionelement.getAttribute("count")));
			}
		}
	},
	
	/* IRQ-514 */
	formatCountValue: function(value) {
			return (value < 10) ? value : ">10";	
	},
	
	
	/* 
	Updates the counts of the possible selections.
	paramter createnewoptions indicates if th selectionoptions need to be recreated
	*/
	updateSelectionSections: function(createnewoptions){
		this.LogDebug("updateSelectionSections: start");
		
		var hasselections=false;
		/*********
		MONTHS
		*********/
		parentelementname='months';
		elementname='month';
		selectionname='monthChoice';
		this.updateSelectionSection(parentelementname,elementname,selectionname,createnewoptions);
		
		/***************
		SPECIFIC DATES
		***************/
		parentelementname='specificdates';
		elementname='specificdate';
		selectionname='specificdateChoice';
		this.updateSelectionSection(parentelementname,elementname,selectionname,createnewoptions);

		/*********
		STAYCODE
		*********/
		parentelementname='staycodes';
		elementname='staycode';
		selectionname='dateChoice';
		this.updateSelectionSection(parentelementname,elementname,selectionname,createnewoptions);
		
		/*********
		PERSONS
		*********/
		parentelementname='persons';
		elementname='person';
		selectionname='peoplesChoice';
		this.updateSelectionSection(parentelementname,elementname,selectionname,createnewoptions);

		/*********
		COTTAGE
		*********/
		parentelementname='cottagetypes';
		elementname='cottagetype';
		selectionname='cottagetypeChoice';
		this.updateSelectionSection(parentelementname,elementname,selectionname,createnewoptions);
		
		/*********
		COUNTRY
		*********/
		parentelementname='countries';
		elementname='country';
		selectionname='countriesChoice';
		this.updateSelectionSection(parentelementname,elementname,selectionname,createnewoptions);

		/*********
		VILLAGES
		*********/
		parentelementname='villages';
		elementname='village';
		selectionname='parkChoice';
		this.updateSelectionSection(parentelementname,elementname,selectionname,createnewoptions);
		
		/*********
		REGIONS
		*********/
		parentelementname='regions';
		elementname='region';
		selectionname='regionChoice';
		this.updateSelectionSection(parentelementname,elementname,selectionname,createnewoptions);
		
		this.LogDebug("updateSelectionSections: done");
	},	
	
	// function to toggle the price per person
	togglePricePP: function (type){
		this.currentPrice=type;
		if (type=='PPD'){
			for(i = 0; i < this.currentpagesize; i++){
				$('#priceBeforePPD'+i).css("display","block");
				$('#priceBeforePPN'+i).css("display","none");
				$('#priceBefore'+i).css("display","none");
				$('#priceAfterPPD'+i).css("display","block");
				$('#priceAfterPPN'+i).css("display","none");
				$('#priceAfter'+i).css("display","none");
			}
		}
		if (type=='PPN'){
			for(i = 0; i < this.currentpagesize; i++){
				$('#priceBeforePPD'+i).css("display","none");
				$('#priceBeforePPN'+i).css("display","block");
				$('#priceBefore'+i).css("display","none");
				$('#priceAfterPPD'+i).css("display","none");
				$('#priceAfterPPN'+i).css("display","block");
				$('#priceAfter'+i).css("display","none");
			}
		}
		if (type=='Total'){
			for(i = 0; i < this.currentpagesize; i++){
				$('#priceBeforePPD'+i).css("display","none");
				$('#priceBeforePPN'+i).css("display","none");
				$('#priceBefore'+i).css("display","block");
				$('#priceAfterPPD'+i).css("display","none");
				$('#priceAfterPPN'+i).css("display","none");
				$('#priceAfter'+i).css("display","block");
			}
		}
	},
	
	//Parses the passed in xmlDoc and:
	//  1. create offerrows
	//  2. update the counts of the search items 
	parseData: function(p_xmlDoc){
	
		this.LogDebug("parseData: start");
		//Set variables
		this.xmlDoc = p_xmlDoc;
		if (this.xmlDoc.getElementsByTagName("htmldata")[0]!=null){
			this.htmldata = this.xmlDoc.getElementsByTagName("htmldata")[0].firstChild.nodeValue;
		} else {
			this.htmldata = "";
		}
		this.LogDebug("parseData: read xmldata and selectiondata");
		this.selectionsXMLData = this.xmlDoc.getElementsByTagName("selections")[0];
		this.currentselectionXMLData = this.xmlDoc.getElementsByTagName("currentselections")[0];

		// Display the offerrows	
		this.LogDebug("parseData: show offers");
		this.offerrows.html(this.htmldata);

		//Set the counts of the selectoncriteria
		this.LogDebug("parseData: set counts and selections");
		if (this.isInitializing || (!this.selectionsRendered)) this.updateCurrentSelections(); // IRQ-317
		this.updateSelectionSections(true);


		//Set main counts
		var result=this.xmlDoc.getElementsByTagName("result")[0];
		if (result != null) {
			this.totalcount = (result.getAttribute("totalrows"));

			/* IRQ-514 */
			if (this.totalcount >= 10) { 
					document.getElementById('less-results').style.display = 'none';
					document.getElementById('more-results').style.display = 'block';
			} else {
					document.getElementById('numberResults').innerHTML = this.totalcount;
					document.getElementById('less-results').style.display = 'block';
					document.getElementById('more-results').style.display = 'none';
			}

			this.currentpagesize= result.getAttribute("currentpagesize");

			//Show the cplight information, if cplight offers are available.
			if (result.getAttribute("cplight")=="true"){
				$("#cplightinfo").css("display","block");
			} else {
				$("#cplightinfo").css("display","none");
			}	
		} else {
			$("#cplightinfo").css("display","none");
			document.getElementById('numberResults').innerHTML = "0";
			this.currentpagesize = "0";
		}
		
		//update pages
		this.LogDebug("parseData: update pages");
		this.pagecount=result.getAttribute("pages");
		this.createPagesLinks();

		//show the correct pricecolumn
		this.LogDebug("parseData: show correct pricecolumn");
		var priceperDiv = $('#priceper'+this.currentPrice);
		if (priceperDiv!=null) priceperDiv.attr("checked",true);
		this.togglePricePP(this.currentPrice);

		if (this.isInitializing){
			//Create link back to park, if entered with prefiltered park	
			if (gup("s_village")!="") {

				/* IRQ-428 */
				var linkinfo = this.xmlDoc.getElementsByTagName("linkinfo")[0];
				if (linkinfo != null) {
					var urlParkInfoDetailLink = linkinfo.getElementsByTagName("parklink")[0].firstChild.nodeValue;
				
					var selectedItems = $("#optionsSelectedItems > span");
					if (selectedItems[0].getAttribute("id")!="selectedNone"){
						for (var i=0 ; i<selectedItems.length ; i++) {
							var selecteditem=selectedItems[i];
							
							if (selecteditem.getAttribute("type")=="parkChoice") {
								this.LogDebug("5");
								// IRQ-317 "setAttribute" changed to jQuery method "attr" and "innerHtml" 
								// changed to jQuery method "html" (was mootools methods)
								$("#BackLinkLink").attr("href", urlParkInfoDetailLink);
								$("#findoutmoreparkname").html(selecteditem.firstChild.firstChild.nodeValue);
								$("#BackLink").css("display","block");
							}
						}
					}
				}	
			} else {
				$("#BackLink").css("display","none");
			}

			this.isInitializing=false;
		}
		
		//Bind thickbox popups to new links
		tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
				
		this.LogDebug("parseData: done");
	},
	
	
	//Loads the data from the server
	loadData: function() {
		if (!this.isLoading || this.isInitializing){
			this.LogDebug("loadData: start");
			
			this.isLoading=true;
			
			this.offerwrapper.addClass("wait");
			
			var request = new XMLHttpRequest;

			var urloptions="";
			//when initializing, read the inital search criteria from the url
			if (this.isInitializing){
			
				if (gup("s_month")!="") urloptions = urloptions+"&s_month="+gup("s_month");
				if (gup("s_village")!="") urloptions = urloptions+"&s_village="+gup("s_village");
				if (gup("s_staycode")!="") urloptions = urloptions+"&s_staycode="+gup("s_staycode");
				if (gup("s_cottagetype")!="") urloptions = urloptions+"&s_cottagetype="+gup("s_cottagetype");
				if (gup("s_persons")!="") urloptions = urloptions+"&s_persons="+gup("s_persons");		
				//these two are nog specified in the functional specifications as needed for pre-filters.
				if (gup("s_country")!="") urloptions = urloptions+"&s_country="+gup("s_country");		
				if (gup("s_region")!="") urloptions = urloptions+"&s_region="+gup("s_region");		

				if (gup("s_priceorder")!="") this.pricesort= gup("s_priceorder");	// possible =A# when using sortorder widgets
				if (gup("s_daterange")!="") urloptions = urloptions+"&s_daterange="+gup("s_daterange");
			
			} else {
			
				//Get the currentselections from the selected filters
				//var selectedItems = $ES("span","optionsSelectedItems");
				var selectedItems = $("#optionsSelectedItems > span");
				if (selectedItems[0].getAttribute("id")!="selectedNone"){
					for (var i=0 ; i<selectedItems.length ; i++) {
						var selecteditem = selectedItems[i];
						var optionstring="";
						switch (selecteditem.getAttribute("type")){
							case "monthChoice":
								optionstring="s_month";
								break;
							case "dateChoice":
								optionstring="s_staycode";
								break;
							case "specificdateChoice":
								optionstring="s_specificdate";
								break;
							case "peoplesChoice":
								optionstring="s_persons";
								break;
							case "cottagetypeChoice":
								optionstring="s_cottagetype";
								break;
							case "countriesChoice":
								optionstring="s_country";
								break;
							case "regionChoice":
								optionstring="s_region";
								bRegionChoiceSelected=true;
								break;
							case "parkChoice":
								optionstring="s_village";
								break;
							default:
								alert ("Unknown selection type: "+ selecteditem.getAttribute("type"));
								return;
						}
						
						if (optionstring!=""){
							urloptions = urloptions+"&"+optionstring+"="+selecteditem.getAttribute("choiceid")
						}
						
					}
				}
			}
			
			//Setup the request
			var url=
				"/cs/Satellite?pagename=Sunparks/Offer_C/SPGuidedSingleClickOfferLoadDataXML&c=Offer_C&p=0"
				+"&cid="+this.offerid
				+"&country="+this.country
				+"&lang="+this.language
				+"&agentcode="+this.agentcode
				+"&actioncode="+this.actioncode
				+"&villageorder="+this.villageorder
				+"&page="+this.currentpage
				+"&pagesize="+this.pagesize;
      if (this.pricesort!=''){
        url=url+"&pricesort="+this.pricesort;
      }
/* SCD-1818 */
      if (this.checkavailability!=''){
        url=url+"&checkavailability="+this.checkavailability;
      }
      if (this.portalcode!=''){
        url=url+"&portalcode="+this.portalcode;
      }
			if (gup("rendermode")!="" && gup("rendermode")!="live") url = url+"&rendermode="+gup("rendermode");
			url=url+urloptions;
			
			this.LogDebug("loadData: open request to " + url);	

			request.open("GET", url, true);

			//When the data is loaded, call the function that parses the data
			/* requeststates are:
        0 = Uninitialised 
        1 = Loading 
        2 = Loaded 
        3 = Interactive 
        4 = Completed 
			*/
			
			request.theparent = this;

			request.onreadystatechange = function() {
				if (request.readyState == 4) {
					var responsetext = request.responseText;
					// strip off invalid chars
					var xmlDoc = '<?xml version="1.0" encoding="ISO-8859-1"?>' + responsetext.substring(responsetext.indexOf('<singleclickdata>'));
					request.theparent.parseData(customloadXMLDoc(xmlDoc));
					request.theparent.isLoading=false;
					request.theparent.offerwrapper.removeClass("wait");
				} 
			}

			//Do the request
			request.send(null);
			
			this.LogDebug("loadData: done");

		}
	},
	
	
	testfunction: function(text){
		alert(text);
	},
	
	/***********************************************
	initializes the single click page
		p_language: Langiage to use
		p_country: Coutnry of the visitor
		p_offerid: Offer asset id
		p_pagesize: number of offers per page
		p_priceOption: None/PPN/PPD: show Proce per person per night or price per person or to No extra option
		p_currentPrice: PPN/PPD/Total: Initialy show Total price, Proce per perosn night  or price per person
		p_villageorder: the order of the villages
		p_showpricesortalways: show the prise sort always or only when a village is selected
	************************************************/
  initialize: function (p_language, p_country, p_offerid, p_agentcode, p_actioncode, p_pagesize, p_priceOption, p_currentPrice, p_villageorder, p_showpricesortalways, p_checkavailability, p_portalcode){
		//init variables
		if (gup("s_debug")!="") {
			this.isDebugging=true;
			this.SetupDebug();
		} else {
			this.isDebugging=false;
		}
			
		this.isInitializing = true;
    this.selectionsRendered = false; // IRQ-317
		this.isLoading=false;
		this.xmlDoc;
		this.htmlData;
		this.selectionsXMLData;
		this.currentselectionXMLData;
		
		//Save some strings that need to be inserted again later
		var selectedNoneElement = $('#selectedNone');
		if (selectedNoneElement!=null){
			this.selectedNoneText=selectedNoneElement.html();
		} else {
			this.selectedNoneText="None";
		}
		
		//save the previous and next texts
		this.pageDownText = $("#pagelinkDown").html();
		this.pageUpText = $("#pagelinkUp").html();
		
		//initialize settings
		this.priceOption=p_priceOption;
		this.currentPrice=p_currentPrice;

		if (this.currentPrice=="PPD" && this.priceOption=="PPN"){
			this.currentPrice=this.priceOption;
		}
		if (this.currentPrice=="PPN" && this.priceOption=="PPD"){
			this.currentPrice=this.priceOption;
		}

		if (this.priceOption=='None') {
			$("#priceperperson").css("display","none");
		} else if (this.priceOption=='PPD') {
			$("#priceperPPD").parent().css("display","");
			$("#priceperPPN").parent().css("display","none");
		} else if (this.priceOption=='PPN') {
			$("#priceperPPD").parent().css("display","none");
			$("#priceperPPN").parent().css("display","");
		} else {
			alert("Illegal priceoption: " + this.priceOption);
		}
		
		this.pagesize=p_pagesize;
		this.country=p_country;
		this.language=p_language;
		this.offerid=p_offerid;
		this.agentcode=p_agentcode;
		this.actioncode=p_actioncode;
		this.villageorder=p_villageorder;
    this.showpricesortalways=p_showpricesortalways;
    
    
    /* SCD-1818 */
    this.checkavailability=p_checkavailability;
    this.portalcode=p_portalcode;

		//create other variables
		this.pagecount=0;
		this.currentpage=1;
		this.totalcount=0;
		this.pricesort='';   //'' or 'A' or 'D'
		this.showPriceSort = this.showpricesortalways;
		this.LogDebug("this.showPriceSort:[" + this.showPriceSort + "]");
		
		this.showRegionsSelections=false;
		this.showSpecificDateSelections=false;
		this.currentpagesize=0;
		
		//setup variables for accessing parts of the page
		this.offerwrapper = $('#offerwrapper');
		this.offerrows = $('#offerrows');
		
		//Templates 
		//templarte for optionsSelector
		//Placeholders:
		//{0}: type of choide (parkchoice, monthchoice, etc.
		//{1}: the option-code
		//{2}: the text of the option
		//{3}: the count
		this.optionsSelectorTemplate=
			"<div class=\"optionsSelectorItem\">\n" +
			"	<a href=\"#\" id=\"option{0}{1}\" onclick=\"document.singleclick.addSelectedOption('{0}','{1}');return false;\" title=\"{2}\">{2} (<span id=\"option{0}{1}Number\">{3}</span>)</a>\n" +
			"	<input type=\"hidden\" name=\"hidden{0}{1}Value\" 	id=\"hidden{0}{1}Value\"	value=\"{1}\" />\n" +
			"	<input type=\"hidden\" name=\"hidden{0}{1}Number\" 	id=\"hidden{0}{1}Number\"	value=\"{3}\" />\n" +
			"	<input type=\"hidden\" name=\"hidden{0}{1}Name\" 	id=\"hidden{0}{1}Name\"		value=\"{2}\" />\n" +
			"</div>\n"
			
		this.optionsSelectorTemplateCount0=
			"<div class=\"optionsSelectorItem\">\n" +
			"	<a class=\"GreyedOut\" id=\"option{0}{1}\" title=\"{2}\">{2} (<span id=\"option{0}{1}Number\">{3}</span>)</a>\n" +
			"	<input type=\"hidden\" name=\"hidden{0}{1}Value\" 	id=\"hidden{0}{1}Value\"	value=\"{1}\" />\n" +
			"	<input type=\"hidden\" name=\"hidden{0}{1}Number\" 	id=\"hidden{0}{1}Number\"	value=\"{3}\" />\n" +
			"	<input type=\"hidden\" name=\"hidden{0}{1}Name\" 	id=\"hidden{0}{1}Name\"		value=\"{2}\" />\n" +
			"</div>\n"
		
		// CPSU-4198 - BiSa - 30-1-09
		// {4}: the previous name of the village
		this.optionsSelectorVillageTemplate=
			"<div class=\"optionsSelectorItem\">\n" +
			"	<a href=\"#\" id=\"option{0}{1}\" onclick=\"document.singleclick.addSelectedOption('{0}','{1}');return false;\" title=\"{2}\">{2} (<span id=\"option{0}{1}Number\">{3}</span>)<br/><em>{4}</em></a>\n" +
			"	<input type=\"hidden\" name=\"hidden{0}{1}Value\" 	id=\"hidden{0}{1}Value\"	value=\"{1}\" />\n" +
			"	<input type=\"hidden\" name=\"hidden{0}{1}Number\" 	id=\"hidden{0}{1}Number\"	value=\"{3}\" />\n" +
			"	<input type=\"hidden\" name=\"hidden{0}{1}Name\" 	id=\"hidden{0}{1}Name\"		value=\"{2}\" />\n" +
			"</div>\n"

		// CPSU-4198 - BiSa - 30-1-09
		// {4}: the previous name of the village			
		this.optionsSelectorVillageTemplateCount0=
			"<div class=\"optionsSelectorItem\">\n" +
			"	<a class=\"GreyedOut\" id=\"option{0}{1}\" title=\"{2}\">{2} (<span id=\"option{0}{1}Number\">{3}</span>)<br/><em>{4}</em></a>\n" +
			"	<input type=\"hidden\" name=\"hidden{0}{1}Value\" 	id=\"hidden{0}{1}Value\"	value=\"{1}\" />\n" +
			"	<input type=\"hidden\" name=\"hidden{0}{1}Number\" 	id=\"hidden{0}{1}Number\"	value=\"{3}\" />\n" +
			"	<input type=\"hidden\" name=\"hidden{0}{1}Name\" 	id=\"hidden{0}{1}Name\"		value=\"{2}\" />\n" +
			"</div>\n"
			

			//templarte for SelectedOptions
		//Placeholders:
		//{0}: type of choide (parkchoice, monthchoice, etc.
		//{1}: the option-code
		//{2}: the text of the option
		this.selectedOptionTemplate=
			"<a class=\"selected\" title=\"{2}\" onclick=\"document.singleclick.removeSelectedOption('{0}', true);return false;\" href=\"#\">{2}</a>"

		//Load the data
		this.loadData();
	},
	
	/*
	Posts the select form with the data from the selected offer
	*/
	selectOffer: function(p_staycode,p_arrivalday,p_arrivalmonth, p_arrivalyear, p_countryCode, p_villageCode, p_villaCategoryCode, p_nrOfBedRooms, p_villaType, p_offerPrice, p_bundlePrice, p_maxPersons, p_stayLength){
		var fp = new FlowPoster();
		fp.setForm("singleClickForm");

		document.form.__event.value = "book";
		document.form.stayCode.value = p_staycode;
		document.form.arrivalDay.value = p_arrivalday;
		document.form.arrivalMonth.value = p_arrivalmonth;
		document.form.arrivalYear.value = p_arrivalyear;	
		document.form.countryCode.value = p_countryCode;
		document.form.villageCode.value = p_villageCode;
		document.form.villaCategoryCode.value = p_villaCategoryCode;
		document.form.nrOfBedRooms.value = p_nrOfBedRooms;
		document.form.villaType.value = p_villaType;
		document.form.offerPrice.value = p_offerPrice;
		document.form.bundlePrice.value = p_bundlePrice;
		document.form.maxPersons.value = p_maxPersons;	
    document.form.stayLength.value = p_stayLength;  
		document.form.submit();
	},		

  /* For WebRes4 (IMPWB-313)
   * This function will replace function selectOffer() in the future
   * Posts the select form with the data from the selected offer
   */
  selectOffer_WR4: function(p_villaType,p_arrivalDate,p_stayLength,p_villageCode){
    var fp = new FlowPoster();
    fp.setForm("singleClickForm_WR4");
    document.form.stayLength.value       = p_stayLength;  
    document.form.arrivalDate.value      = p_arrivalDate;
    document.form.villageCode.value      = p_villageCode;
    document.form.accomodationCode.value = p_villaType;
    document.form.submit();
  }   

};

function offerhover(item){
//    $(item).css("backgroundImage","url(/cs/Sunparks/images/style/backgrounds/bg_offer_over.jpg)");
}

function offerout(item){
//	$(item).css("backgroundImage","url(/cs/Sunparks/images/style/backgrounds/bg_offer.jpg)");
}

function gup(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function customloadXMLDoc(str) {
	var _xmlDoc = null;
	if (document.implementation && document.implementation.createDocument)
	{
		_xmlDoc = document.implementation.createDocument("", "", null);
		var parser = new DOMParser();
		_xmlDoc = parser.parseFromString(str,"text/xml");
		
	}
	else if (window.ActiveXObject)
	{
		_xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		_xmlDoc.loadXML(str);
		
 	}
	else
	{
		alert('Your browser can\'t handle this script');
		return _xmlDoc;
	}

	return _xmlDoc;
}
