// this script is made with AJAX technique : Asynchronous JavaScript and XML
//
//	Author: Nico Lubbers		
//   www.booleanpark.com
//

var useAJAX = true;
function strltrim() {return this.replace(/^\s+/,'');}
function strrtrim() {return this.replace(/\s+$/,'');}
function strtrim() {return this.replace(/^\s+/,'').replace(/\s+$/,'');}
String.prototype.ltrim = strltrim;
String.prototype.rtrim = strrtrim;
String.prototype.trim = strtrim;

var agt=navigator.userAgent.toLowerCase();
var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_mac    = (agt.indexOf("mac")!=-1);
var is_safari = (agt.indexOf("safari")!=-1);
var is_gecko = (agt.indexOf('gecko') != -1);
// netscape6.x implementatie werkt niet met AJAX
if (is_gecko)
	useAJAX = false;
var theTimer;

var xmlDoc;
var isLoadingXML = false;
var isAdvancedSearch = false;
var mySortdir = getCookie("sortdir");
var isIE = false;
var req;
function loadXMLDoc(url) {
	if (isLoadingXML) {
		req.abort();
	}
	isLoadingXML = true;
    if (window.XMLHttpRequest) {
		// geen IE
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url, true);
        req.send(null);
    } else if (window.ActiveXObject) {
    // IE
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url, true);
            req.send(); 
        }
    }
}

function processReqChange() {
    if (req.readyState == 4) {
        if (req.status == 200) {
				parseAll();
         } else {
            alert("Fout bij ophalen XML data:\n(" + req.status + ") " + req.statusText);
         }
    }
}

	function loadXML(xmlFile) {
		if (!useAJAX)
		{
			if (isLoadingXML)
				// XML is currently loading -> cancel request
				xmlDoc.abort();
				
			if (document.implementation && document.implementation.createDocument) {
				// hier komt safari ook terecht
				xmlDoc = document.implementation.createDocument("","", null);
				isLoadingXML = true;
				xmlDoc.onload = parseAll;
			}
			else if (window.ActiveXObject) {
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				isLoadingXML = true;
				xmlDoc.onreadystatechange = function () { if (xmlDoc.readyState == 4) parseAll(); }
			}
			else {
				return;
			}
		}

		var dropdownptr;
		dropdownptr = document.getElementById('avcnt');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('avarea');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('avcap');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('avstar');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('avstay');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('avad');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		
		if (isAdvancedSearch)
		{
			dropdownptr = document.getElementById('avsleep');
				if (dropdownptr!=null) dropdownptr.disabled = true;
			dropdownptr = document.getElementById('avprice');
				if (dropdownptr!=null) dropdownptr.disabled = true;
			for (var mycount=1;mycount<10;mycount++)
			{
				dropdownptr = document.getElementById('kenmerk'+mycount);
					if (dropdownptr!=null) dropdownptr.disabled = true;
			}
		}
		theTimer = setTimeout('hidePanel()',200);

		if(useAJAX)
			loadXMLDoc(xmlFile);
		else
			xmlDoc.load(xmlFile);
	}

	function hidePanel() {
		var theMovie = document.getElementById('theloadingmovie');
		var thePanel = document.getElementById('avform');
		if (theMovie!=null)
			theMovie.style.display = 'block';
		if (thePanel!=null)
			thePanel.style.display = 'none';
	}
	
	function populateXMLSelect(fieldptr,tagname) {
		var urlString = location.href;
		var selectedID='';
		var disableOption = false;
			
		// check if <select> object exists. 
		// delete values in it to repopulate again
		if (fieldptr != null) {
			if (fieldptr.selectedIndex != null) {
				if (fieldptr.selectedIndex != -1) {
					if (fieldptr.options.length >= 0) {
			 			// delete all options
						fieldptr.options.length = 0;	
					}
				}
			}
		}

		// populate option-list with the XML-tag values
		var collection;
		if (useAJAX)
			collection= req.responseXML.getElementsByTagName(tagname);
		else
			collection = xmlDoc.getElementsByTagName(tagname);
		dropdowncnt = 0;
		
		// checks if collection contains NO items
		if (collection.length == 0)	{
			//  display message and disable option-box
			fieldptr.options[dropdowncnt++] = new Option( "  ","");
			disableOption = true;
		}
		// checks if collection contains only one item 
		else if (collection.length == 1) {
			// check if this TAG was selected by user
			if (collection[0].getAttribute('selected') == null)
			  selectedID = ''
			else
			  selectedID = collection[0].getAttribute('id');

			// then display only THE ONE item   
			if (selectedID == collection[0].getAttribute('id')) { // this option was selected by User (so user may change it again)
				if (collection[0].getAttribute('val') == null) // use id if val is not supplied
				{
					var strLabel = translateTag(tagname,collection[0].getAttribute('id'));
					fieldptr.options[dropdowncnt] = new Option( strLabel,collection[0].getAttribute('id'));
				}
				else
					fieldptr.options[dropdowncnt] = new Option( collection[0].getAttribute('val'),collection[0].getAttribute('id'));
			}
			else { // this option was selected by this routine because theres only one item found. (User may NOT change it)
				if (collection[0].getAttribute('val') == null) // use id if val is not supplied
				{
					var strLabel = translateTag(tagname,collection[0].getAttribute('id'));
					fieldptr.options[dropdowncnt] = new Option( strLabel,'');
				}
				else
				  fieldptr.options[dropdowncnt] = new Option( collection[0].getAttribute('val'),'');
				disableOption = true;
			}
			fieldptr.selectedIndex = dropdowncnt;
		}
		else { 
			var wasSelected=false;
			for(cnt=0; cnt < collection.length; cnt++) 
			{
				// create an option with values from xmlDoc
				if (collection[cnt].getAttribute('val') == null) // use id if val is not supplied
				{
					var strLabel = translateTag(tagname,collection[cnt].getAttribute('id'));
					fieldptr.options[dropdowncnt] = new Option( strLabel, collection[cnt].getAttribute('id'));
				}
				else
					fieldptr.options[dropdowncnt] = new Option(collection[cnt].getAttribute('val'),collection[cnt].getAttribute('id'));
				
				// checks if this option was selected by the user
 				if (collection[cnt].getAttribute('selected') != null) {
					fieldptr.selectedIndex = dropdowncnt;  // select that option again
					wasSelected = true;
 				}
				dropdowncnt++;
	   	}
	   	if (!wasSelected) {
	   		fieldptr.selectedIndex = 0;
	   	}
		}
		fieldptr.disabled = disableOption;
	}

	function populateXMLCheckbox(fieldptr,tagname) {
	  var xmlvalue = '';
	  var selectedOption = '';
	  var disableOption = false;

		// check if <INPUT> object exists. 
		var collection;
		if (fieldptr != null)
		{
			fieldptr.checked = false;
			if (useAJAX)
				collection = req.responseXML.getElementsByTagName(tagname);
			else
				collection = xmlDoc.getElementsByTagName(tagname);
  		
		  // check if tagname is found. 
		  if (collection.length == 0)	{
			  //  not found. disable option-box
			  //  this is actually an incompletion of powersearch.aspx XML
			  fieldptr.disabled = true;
			  disableOption	= true;
		  }
		  // a checkbox can only have two values:  Y or empty
		  // the following states are possible
		  // - Only one value is found in the collection
		  //  3 states are possible:
		  //	  1) value = empty. No other possibility for user to choose. -> DISABLE
		  //	  2) value = Y and selected=true (checked by user). User may unselect -> ENABLE
		  //	  3) value = Y and NO selected=true (no other possibility) -> DISABLE
		  // - both Y and empty are found in the collection
		  //	  4) 
		
		  else if (collection.length == 1) {
			// only 1 value found in XML
			xmlvalue = collection[0].getAttribute('id');
			if (xmlvalue == 'Y') {		  // Y found > select
			  // state 2) or 3)
			  fieldptr.checked = true;
			  selectedOption = collection[0].getAttribute('selected');
			  if (selectedOption == 'true') {
				// state 2)
    			fieldptr.disabled = false;
			  }
			  else { 
				//  state 3)
    			fieldptr.disabled = true;
				disableOption = true;
    		  }
			}
			else {						  // empty > deselect
			  fieldptr.checked = false;
    		  fieldptr.disabled = true;
			  disableOption = true;
			}
		  }
		  else if (collection.length == 2) {
			// state 4) . Enable checkbox
			fieldptr.disabled = false;
			disableOption = false;
  		  }
		  else {
			// something wrong in the database. only Y and N are valid
			alert('more than 2 values in XML found for tagname: '+tagname)
			disableOption = false;
		  }
		}
		else
			alert('no checkbox found for tagname: '+tagname);
	}


	function parseAll()	{
		if (!isLoadingXML)
			return;
		clearTimeout(theTimer);
		var theMovie = document.getElementById('theloadingmovie');
		var thePanel = document.getElementById('avform');
		if (theMovie!=null)
			theMovie.style.display = 'none';
		if (thePanel!=null)
			thePanel.style.display = 'block';

		var collection;
		if (useAJAX)
			collection = req.responseXML.getElementsByTagName('ex');
		else
			collection = xmlDoc.getElementsByTagName('ex');
		if (collection.length > 0)
		{
				alert('Error in XML\n'+collection.context.text);
				return;
		}
		populateXMLSelect(document.getElementById('avcnt'),'cnt');
		populateXMLSelect(document.getElementById('avarea'),'area');
		populateXMLSelect(document.getElementById('avcap'),'cap');
		populateXMLSelect(document.getElementById('avstar'),'star');
		populateXMLSelect(document.getElementById('avstay'),'stay');
		populateXMLSelect(document.getElementById('avad'),'ad');
		if (isAdvancedSearch)
		{
			populateXMLSelect(document.getElementById('avsleep'),'sleep');
			populateXMLSelect(document.getElementById('avprice'),'price');
			populateXMLCheckbox(document.getElementById('kenmerk1'),'golf')
			populateXMLCheckbox(document.getElementById('kenmerk2'),'water')
			populateXMLCheckbox(document.getElementById('kenmerk3'),'wintersport')
			populateXMLCheckbox(document.getElementById('kenmerk4'),'swim')
			populateXMLCheckbox(document.getElementById('kenmerk5'),'pets')
			populateXMLCheckbox(document.getElementById('kenmerk6'),'toys')
			populateXMLCheckbox(document.getElementById('kenmerk7'),'tv')
			populateXMLCheckbox(document.getElementById('kenmerk8'),'dishw')
			populateXMLCheckbox(document.getElementById('kenmerk9'),'microw')
		}	
		populateCounter();
		isLoadingXML = false;
	}

	function appendQryString(queryString, strParamlabel, strParamvalue, toCookie) {
		// test of deze ook opgeslagen moet worden in de cookie
//		if (toCookie==true)
//			setCookie(strParamlabel,strParamvalue);

		// return directly if parameters are null
		if ((strParamlabel == null) || (strParamvalue == null))
		  return(queryString);
		// this function builds a URL querystring 
		if (strParamlabel.length > 0) { // only append label when label is valid
			if (strParamvalue.length > 0) { // only append label + value when filled with a value
				if (strParamvalue=='-')
					return(queryString);
				queryString = queryString.trim(); // remove trailing and leading spaces
				if (queryString.length == 0)
					var strDivider = '?'; // first parameter
				else
					var strDivider = '&'; // next parameters

				// voordat er geURLencoded wordt eerst +coderen
  				var tmpstrParamvalue = escape(strParamvalue);
				while (tmpstrParamvalue.indexOf('+') > -1) {
				  tmpstrParamvalue = tmpstrParamvalue.replace('+', '%2B');
				}
				
				queryString = queryString + strDivider + escape(strParamlabel) + '=' + tmpstrParamvalue
			}
		}
		return(queryString);
	}

	function getSelectedValue(optionPtr) {
		if (optionPtr == null)
			return('');
		return optionPtr.options[optionPtr.selectedIndex].value;
	}

	function getCheckedValue(optionPtr) {
		// returns the value of the checkbox. Y or N 
		//    assumes a pointer to a <input type="checkbox"> object
		if (optionPtr == null) {
	  		alert('specified checkbox not found');
			return('');
		}
		if (optionPtr.checked) {
		  if (!optionPtr.disabled) {
			return('Y');
		  }
		}
		return('');
	}

  function defineQryString(ignoreKey) {
	var qryStr = '';
	qryStr = appendQryString(qryStr, 'cnt', getSelectedValue(document.getElementById('avcnt')), true);
	if (ignoreKey != 'area')
		qryStr = appendQryString(qryStr, 'area', getSelectedValue(document.getElementById('avarea')), true);
	else
	{
		// country changed -> refresh all options.
		if (isAdvancedSearch)
			qryStr = appendQryString(qryStr, 'advanced', 'true', false);
		return(qryStr);
	}

	qryStr = appendQryString(qryStr, 'cap', getSelectedValue(document.getElementById('avcap')), true);
	qryStr = appendQryString(qryStr, 'star', getSelectedValue(document.getElementById('avstar')), true);
	qryStr = appendQryString(qryStr, 'stay', getSelectedValue(document.getElementById('avstay')), true);
	qryStr = appendQryString(qryStr, 'ad', getSelectedValue(document.getElementById('avad')), true);
	if (isAdvancedSearch)
	{
		qryStr = appendQryString(qryStr, 'advanced', 'true', false);
		qryStr = appendQryString(qryStr, 'sleep', getSelectedValue(document.getElementById('avsleep')), true);
		qryStr = appendQryString(qryStr, 'price', getSelectedValue(document.getElementById('avprice')), true);
		qryStr = appendQryString(qryStr, 'golf', getCheckedValue(document.getElementById('kenmerk1')), true);
		qryStr = appendQryString(qryStr, 'water', getCheckedValue(document.getElementById('kenmerk2')), true);
		qryStr = appendQryString(qryStr, 'wintersport', getCheckedValue(document.getElementById('kenmerk3')), true);
		qryStr = appendQryString(qryStr, 'swim', getCheckedValue(document.getElementById('kenmerk4')), true);
		qryStr = appendQryString(qryStr, 'pets', getCheckedValue(document.getElementById('kenmerk5')), true);
		qryStr = appendQryString(qryStr, 'toys', getCheckedValue(document.getElementById('kenmerk6')), true);
		qryStr = appendQryString(qryStr, 'tv', getCheckedValue(document.getElementById('kenmerk7')), true);
		qryStr = appendQryString(qryStr, 'dishw', getCheckedValue(document.getElementById('kenmerk8')), true);
		qryStr = appendQryString(qryStr, 'microw', getCheckedValue(document.getElementById('kenmerk9')), true);
		qryStr = appendQryString(qryStr, 'sort', getRadioValue(), false);
		
		qryStr = appendQryString(qryStr, 'sortdir', mySortdir, false);
	}
	return(qryStr);
  }

	function showResults() {
		var qryStr = defineQryString();
		if (qryStr.length == 0)
			qryStr = "?"
		else
			qryStr += "&"
		var theURL = '/template1.aspx' + qryStr + 'cp=vs_resultaten&menu=villaselect&mid=villaselectzoekenboek&taal=nl-nl';
		window.location.href = theURL;
	}
	
	function reloadXML(ignoreKey) {
		var qryStr = defineQryString(ignoreKey);
		// loadXML('../InterfaceComponent/villaselect/availabilityxml.aspx'+qryStr);
		loadXML('/datapark/villaselect/availabilityxml.aspx'+qryStr);
	}

	function searchAvailability(isAdvanced) {	
		if (isAdvanced==true)
			isAdvancedSearch = true;
		if(!document.getElementById) {
			// see documentation at http://www.mozilla.org/docs/web-developer/faq.html
  			status.write('Availability E000');
			return;
		}
		if(is_mac) 
		{
			if (is_ie) 
			{	
				if (firstTimeAlert != true)
				{
					firstTimeAlert = true;
		  			alert('Please use one of the following browsers:\nSafari 1.2 or higher\nNetscape 7\nFirefox\nMozilla 1.0 or higher');
		  		}
				return;
			}
		}
		var qryStr='';
		qryStr = appendQryString(qryStr, 'cnt', getCookie("cnt"), false);
		qryStr = appendQryString(qryStr, 'area', getCookie("area"), false);
		qryStr = appendQryString(qryStr, 'cap', getCookie("cap"), false);
		qryStr = appendQryString(qryStr, 'stay', getCookie("stay"), false);
		qryStr = appendQryString(qryStr, 'star', getCookie("star"), false);
		qryStr = appendQryString(qryStr, 'ad', getCookie("ad"), false);

		if (isAdvancedSearch)
		{
			qryStr = appendQryString(qryStr, 'advanced', 'true', false);
			qryStr = appendQryString(qryStr, 'sleep', getCookie("sleep"), false);
			qryStr = appendQryString(qryStr, 'price', getCookie("price"), false);
			qryStr = appendQryString(qryStr, 'golf', getCookie("golf"), false);
			qryStr = appendQryString(qryStr, 'water', getCookie("water"), false);
			qryStr = appendQryString(qryStr, 'wintersport', getCookie("wintersport"), false);
			qryStr = appendQryString(qryStr, 'swim', getCookie("swim"), false);
			qryStr = appendQryString(qryStr, 'pets', getCookie("pets"), false);
			qryStr = appendQryString(qryStr, 'toys', getCookie("toys"), false);
			qryStr = appendQryString(qryStr, 'tv', getCookie("tv"), false);
			qryStr = appendQryString(qryStr, 'dishw', getCookie("dishw"), false);
			qryStr = appendQryString(qryStr, 'microw', getCookie("microw"), false);
			qryStr = appendQryString(qryStr, 'sort', getCookie("sort"), false); 
			// zet de sort default !
			setRadioValue(getCookie("sort"));
		}
		loadXML('/datapark/villaselect/availabilityxml.aspx'+qryStr);
		// loadXML('../InterfaceComponent/villaselect/availabilityxml.aspx'+qryStr);
	}

function getRadioValue()
{
	if (document.getElementById('orderbystars').checked)
		return('Stars');
	else
		if (document.getElementById('orderbydate').checked)
			return('ArrivalDate');
		else
			return('Price');
}
function setRadioValue(thevalue)
{
	if(thevalue=='Stars') 
		document.getElementById('orderbystars').checked = true;
	else
		if(thevalue=='ArrivalDate') 
			document.getElementById('orderbydate').checked = true;
		else 
			document.getElementById('orderbyprice').checked = true;
}

function getCookie(name)
{	
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)  {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } 
    else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

var blinkcount = 0;
var blinkstate = true;
var blinktmr;

function populateCounter() {
	// displays number of database items that match criteria
	var collection;
	if (useAJAX)
		collection= req.responseXML.getElementsByTagName('counter');
	else
		collection = xmlDoc.getElementsByTagName('counter');
	if (collection.length > 0)
	{
		// window.status = 'Number of searchresults: '+collection[0].getAttribute('id');
		if (document.getElementById('totalresult') != null)
		{
			currentcount = collection[0].getAttribute('id');
			document.getElementById('totalresult').innerHTML = currentcount;
			blinkcount = 0;
			blinkstate = true;
			blinkText();
		}
	}
}

function blinkText()
{
	clearTimeout(blinktmr);
	blinkstate = !blinkstate;
	blinkcount++;
	if (blinkcount > 6) 
	{
		document.getElementById('totalresult').innerHTML = currentcount;
		return;
	}
	if (blinkstate)
		document.getElementById('totalresult').innerHTML = currentcount;
	else
		document.getElementById('totalresult').innerHTML = ' ';
	blinktmr = setTimeout('blinkText()', 100 );
}