/* 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 = new Class({
	intialize: function (p_group, p_id, p_text){
		this.group = p_group;
		this.id = p_id;
		this.text = p_text;
	}
});

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

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

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

	showSelectionlist: function(group, id){
		var gr = $E("#"+group); 				//the div holding all the selectable items
		var el = $E('#option'+group+id);		//the element that is selected
		
		if (gr!=null){
			gr.className = '';		
			
			if (el!=null){	
				el.className = '';
			}
		}
	},	
	
	/*****************************
	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(){
		this.LogDebug("showPriceSort:[" + this.showPriceSort + "]");
    if (this.showPriceSort){
			document.getElementById('resultsPagination_1').style.display = "block";	
			document.getElementById('resultsPaginationBottom_1').style.display = "block";	
		} else{
			document.getElementById('resultsPagination_1').style.display = "none";	
			document.getElementById('resultsPaginationBottom_1').style.display = "none";	
		}
	},

	createPagesLinksForDiv: function(p_divname){
		var div = $E('#'+p_divname);
                div.innerHTML = "";
	
		//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.appendChild(newpage);

			if (this.currentpage>3) {
				var newpage = document.createElement('span');
				newpage.innerHTML = '.....';
				newpage.setAttribute('id','pagelinkMoreBefore');
				div.appendChild(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.appendChild(newpage);
			}
			
			if (lastpage<this.pagecount) {
				var newpage = document.createElement('span');
				newpage.setAttribute('id','pagelinkMoreAfter');
				newpage.innerHTML = '.....';
				div.appendChild(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.appendChild(newpage);
		}
	},
		
	/***********
	Resets the seleted items.... clears the selected items, and shows all selected lists.
	*************/
	setSeletedToNone: function(){
	
		this.LogDebug("setSeletedToNone: start");
	
		var div = $E('#optionsSelectedItems');	//the div holding the selected items

		//remove all options
		for (var i=div.childNodes.length-1;i>=0;i--){
			div.removeChild(div.childNodes[i]);
		}
		
		// add "none" node
		if(!div.hasChildNodes()){
			var newspan = document.createElement('span');
			newspan.setAttribute('id','selectedNone');
			newspan.innerHTML = this.selectedNoneText;
			div.appendChild(newspan);
			document.getElementById('optionsSelected').style.display = 'none';
		}
		
		//Show all selectionlists, if there are options
		if ($E("#options_monthChoice").getChildren().length>0)		this.showSelectionlist("monthChoice");
		else this.hideSelectionlist("monthChoice");
		
		if ($E("#options_monthChoice").getChildren().length>0)		this.showSelectionlist("dateChoice");
		else	this.hideSelectionlist("dateChoice");
		
		this.hideSelectionlist("specificdateChoice");
		
		if ($E("#options_monthChoice").getChildren().length>0)		this.showSelectionlist("peoplesChoice");
		else 	this.hideSelectionlist("peoplesChoice");
		
		if ($E("#options_monthChoice").getChildren().length>0)		this.showSelectionlist("cottagetypeChoice");
		else	this.hideSelectionlist("cottagetypeChoice");
		
		if ($E("#options_monthChoice").getChildren().length>0)		this.showSelectionlist("countriesChoice");
		else 	this.hideSelectionlist("countriesChoice");
		
		this.hideSelectionlist("regionChoice");
		
		if ($E("#options_monthChoice").getChildren().length>0)		this.showSelectionlist("parkChoice");
		else this.hideSelectionlist("parkChoice");
		
		if (!this.showPriceSortAlways) {
			this.showPriceSort=false;
			this.pricesort='';
		}			
		this.LogDebug("pricesort:[" + this.pricesort + "] showPriceSort:[" + this.showPriceSort + "] showPriceSortAlways:[" + this.showPriceSortAlways + "]");
		
		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 = $E("#"+group); 				//the div holding all the selectable items
			var div = $E('#optionsSelectedItems');	//the div holding the selected items
		
			// Show the selction group
			if ($E("#options_"+group).getChildren().length>0)		this.showSelectionlist(group);
			else													this.hideSelectionlist(group);

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

			// add "none" node
			if(!div.hasChildNodes()){
				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") {
				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 = $E("#hidden"+group+id+"Name").value;
		
			var gr = $E("#"+group); 				//the div holding all the selectable items
			var div = $E('#optionsSelectedItems');	//the div holding the selected items
			var el = $E('#option'+group+id);		//the element that is selected
		
			document.getElementById('optionsSelected').style.display = 'block';
			
			this.hideSelectionlist(group, id);

			// remove "none" node
			if(div.firstChild.id=='selectedNone'){
				var selectedNoneElement = $E('#selectedNone');
				this.selectedNoneText=selectedNoneElement.innerHTML;
				div.removeChild(selectedNoneElement);
			}

			//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.appendChild(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 = $E("#options_"+selectionname);
			
			if (optionsdiv==null){
				alert("#options_"+selectionname+" not found");
				return;
			}
			
			//Clear old options
				optionsdiv.innerHTML='';
			
			if (selectionelements!=null && selectionelements.length!=0){
				for (var i = 0; i < selectionelements.length; i++) {
					var selectionelement=selectionelements[i];

					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.innerHTML=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++){
				document.getElementById('priceBeforePPD'+i).style.display = 'block';
				document.getElementById('priceBeforePPN'+i).style.display = 'none';
				document.getElementById('priceBefore'+i).style.display = 'none';
				document.getElementById('priceAfterPPD'+i).style.display = 'block';
				document.getElementById('priceAfterPPN'+i).style.display = 'none';
				document.getElementById('priceAfter'+i).style.display = 'none';
			}
		}
		if (type=='PPN'){
			for(i = 0; i < this.currentpagesize; i++){
				document.getElementById('priceBeforePPD'+i).style.display = 'none';
				document.getElementById('priceBeforePPN'+i).style.display = 'block';
				document.getElementById('priceBefore'+i).style.display = 'none';
				document.getElementById('priceAfterPPD'+i).style.display = 'none';
				document.getElementById('priceAfterPPN'+i).style.display = 'block';
				document.getElementById('priceAfter'+i).style.display = 'none';		
			}
		}
		if (type=='Total'){
			for(i = 0; i < this.currentpagesize; i++){
				document.getElementById('priceBeforePPD'+i).style.display = 'none';
				document.getElementById('priceBeforePPN'+i).style.display = 'none';
				document.getElementById('priceBefore'+i).style.display = 'block';
				document.getElementById('priceAfterPPD'+i).style.display = 'none';
				document.getElementById('priceAfterPPN'+i).style.display = 'none';
				document.getElementById('priceAfter'+i).style.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.innerHTML = 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");
			
			if (this.totalcount >= 10) { /* IRQ-514 */
					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=this.xmlDoc.getElementsByTagName("result")[0].getAttribute("currentpagesize");

			//Show the cplight information, if cplight offers are available.
			if (result.getAttribute("cplight")=="true"){
				$E("#cplightinfo").style.display = 'block';
			} else {
				$E("#cplightinfo").style.display = 'none';
			}	
		} else {
			$E("#cplightinfo").style.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 = $E('#priceper'+this.currentPrice);
		if (priceperDiv!=null) priceperDiv.checked="checked";
		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.getAttribute("parklink");
					
					var selectedItems = $('optionsSelectedItems').getElements('span');
					if (selectedItems[0].getAttribute("id")!="selectedNone") {
						for (var i=0 ; i<selectedItems.length ; i++) {
							var selecteditem=selectedItems[i];
							
							if (selecteditem.getAttribute("type")=="parkChoice") {
								$E("#BackLinkLink").setAttribute("href", urlParkInfoDetailLink);
								$E("#findoutmoreparkname").innerHTML=selecteditem.firstChild.firstChild.nodeValue;
								$E("#BackLink").style.display="block";			
							}
						}
					}
				}	
			} else {
				$E("#BackLink").style.display="none";
			}
		
			this.isInitializing=false;
		}

		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 = null;
			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').getElements('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=B2C/Offer_C/B2CSingleClickLoadDataXML&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;
      }
      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: Order of villages
    p_checkavailability: check the availability in Fastbooking
    p_portalcode: Alternativ portalcode
    p_showpricesortalways: force display of sort order for pricing widgets
	************************************************/
  initialize: function (p_language, p_country, p_offerid, p_agentcode, p_actioncode, p_pagesize, p_priceOption, p_currentPrice, p_villageorder, p_checkavailability, p_portalcode, p_showpricesortalways){
		//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 = $E('#selectedNone');
		if (selectedNoneElement!=null){
			this.selectedNoneText=selectedNoneElement.innerHTML;
		} else {
			this.selectedNoneText="None";
		}
		
		//save the previous and next texts
		this.pageDownText = $E("#pagelinkDown").innerHTML;
		this.pageUpText = $E("#pagelinkUp").innerHTML;
		
		//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') {
			$E("#priceperperson").style.display='none';
		} else if (this.priceOption=='PPD') {
			$E("#priceperPPD").parentNode.style.display='';
			$E("#priceperPPN").parentNode.style.display='none';
		} else if (this.priceOption=='PPN') {
			$E("#priceperPPD").parentNode.style.display='none';
			$E("#priceperPPN").parentNode.style.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;
    /* SCD-1818 */
    this.checkavailability=p_checkavailability;
    this.portalcode=p_portalcode;
		
		/* IRQ-513 */
		this.showPriceSortAlways = p_showpricesortalways;

		//create other variables
		this.pagecount=0;
		this.currentpage=1;
		this.totalcount=0;
		this.pricesort='';   //'' or 'A' or 'D'
		this.showPriceSort=this.showPriceSortAlways;
		this.showRegionsSelections=false;
		this.showSpecificDateSelections=false;
		
		this.currentpagesize=0;
		
		//setup variables for accessing parts of the page
		this.offerwrapper = $E('#offerwrapper');
		this.offerrows = $E('#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"

			//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 initial 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_WR4 = new FlowPoster();
    fp_WR4.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.style.backgroundImage = 'url(/cs/B2C/images/style/backgrounds/bg_offer_over.jpg)';
}

function offerout(item){
	item.style.backgroundImage = 'url(/cs/B2C/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;
}

