// this script is made with AJAX: Asynchronous JavaScript and XML
//
//	Author: Nico Lubbers		
//   www.booleanpark.com
//

var useAJAX = true;
var globalURL;
var needToRepopulate = false;
var AvailabilityPanelLocation = "../../datapark/AvailabilityPanelXmlCabs.aspx"

if(typeof useCabsProxyJS == 'undefined')
{
    alert("useCabsProxyJS is undefined");
}
else if (useCabsProxyJS)
{
    AvailabilityPanelLocation = "../../datapark/AvailabilityPanelXmlCabsProxy.aspx"
}

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 cntCode,prkCode; // from parkselector

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 && !is_safari) 
	useAJAX = false;

var theTimer;

var xmlDoc;
var isLoadingXML = false;
var thema;
var taalcode;

// global flag
var isIE = false;
// global request and XML document objects
var req;
function loadXMLDoc(url) {
	globalURL = url;
    // branch for native XMLHttpRequest object
	if (isLoadingXML) {
		req.abort();
	}
	isLoadingXML = true;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url, true);
            req.send();
        }
    }
}

// handle onreadystatechange event of req object
function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
				parseAll();
         } else {
            alert("There was a problem retrieving the XML data:\n(" + req.status + ") " +
                req.statusText);
                //exception;
         }
    }
}

	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 {
				//alert('Deze zoek-functie werkt alleen op de volgende browsers:\nInternet Explorer 5.0 of hoger\nNetscape 6.0 of hoger\nMozilla \nFirefox');
				return;
			}
		}

		// disable all options to prevent changes while xml is loading
		// display loading movie
		theTimer = setTimeout('hidePanel()',200);
		
		var dropdownptr;
		dropdownptr = document.getElementById('avstay');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('avym');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('avdd');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('avnum');
			if (dropdownptr!=null) dropdownptr.disabled = true;

		if(useAJAX)
			loadXMLDoc(xmlFile);
		else
			xmlDoc.load(xmlFile);
	}
	
	function hidePanel() {
		var theMovie = document.getElementById('theloadingmovie');
		var thePanel = document.getElementById('availabilityform');
		theMovie.style.display = 'block';
		thePanel.style.display = 'none';
	}

	function populateXMLSelect(fieldptr,tagname) {
		var urlString = location.href;
		var selectedID='', 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
					fieldptr.options[dropdowncnt] = new Option( collection[0].getAttribute('id'),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
				  fieldptr.options[dropdowncnt] = new Option( collection[0].getAttribute('id'),'');
				else
				  fieldptr.options[dropdowncnt] = new Option( collection[0].getAttribute('val'),'');
				//disableOption = true;
			}
			fieldptr.selectedIndex = dropdowncnt;
		}
		else { 
			var wasSelected=false;
			var canPopulate=true;
			for(cnt=0; cnt < collection.length; cnt++) 
			{
				if ((thema=='wintersport') && (tagname == 'ym')) 
				{
					switch (collection[cnt].getAttribute('id'))
					{
						case "200612":
						case "200701":
						case "200702":
						case "200703":
						case "200704":
						case "200712":
							canPopulate=true;
							break;
						default:
							canPopulate=false;
							break;
					}
				}
				if (canPopulate)
				{
					// create an option with values from xmlDoc
					if (collection[cnt].getAttribute('val') == null) // use id if val is not supplied
						fieldptr.options[dropdowncnt] = new Option(collection[cnt].getAttribute('id'), 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) {
	   		if (tagname == 'ym')
	   			needToRepopulate = true;
	   		fieldptr.selectedIndex = 0;
	   	}
		}
		fieldptr.disabled = disableOption;
	}

	function parseAll()	{
		if (!isLoadingXML)
			return;
		clearTimeout(theTimer);
		var theMovie = document.getElementById('theloadingmovie');
		var thePanel = document.getElementById('availabilityform');
		thePanel.style.display = 'block';
		theMovie.style.display = 'none';
			
		populateXMLSelect(document.getElementById('avstay'),'stay');
		populateXMLSelect(document.getElementById('avnum'),'num');
		populateXMLSelect(document.getElementById('avym'),'ym');
		populateXMLSelect(document.getElementById('avdd'),'dd');
		isLoadingXML = false;
		if (needToRepopulate) {
			needToRepopulate = false;
			reloadXMLym();
		}
	}

	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

				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 defineQryString(ignoretag) {
	var qryStr = '';
	qryStr = appendQryString(qryStr, 'cnt', cntCode, false);
	qryStr = appendQryString(qryStr, 'prk', prkCode, false);
	qryStr = appendQryString(qryStr, 'taalcode', taalcode, false);
	qryStr = appendQryString(qryStr, 'stay', getSelectedValue(document.getElementById('avstay')), true);
	qryStr = appendQryString(qryStr, 'num', getSelectedValue(document.getElementById('avnum')), true);
	qryStr = appendQryString(qryStr, 'ym', getSelectedValue(document.getElementById('avym')), true);
	if (ignoretag!='dd')
		qryStr = appendQryString(qryStr, 'dd', getSelectedValue(document.getElementById('avdd')), true);
	else
		setCookie("dd","");
	if (thema=='wintersport')
		qryStr = appendQryString(qryStr, 'thema', 'wintersport', false);

	window.status = qryStr;
	return(qryStr);
  }

	function reloadXML() {
		var qryStr = defineQryString();
		loadXML(AvailabilityPanelLocation+qryStr);
	}

	function reloadXMLym() {
		var qryStr = defineQryString('dd');
		loadXML(AvailabilityPanelLocation+qryStr);
	}

	function reloadXMLnum() {
		var qryStr = defineQryString('num');
		loadXML(AvailabilityPanelLocation+qryStr);
	}
	
	function makeInitQRY(sCnt, sPrk, theThema, theTaalcode) {
		cntCode = sCnt;
		prkCode = sPrk;
		thema = theThema;
		taalcode = theTaalcode;

		var qryStr='';
		qryStr = appendQryString(qryStr, 'cnt', cntCode, false);
		qryStr = appendQryString(qryStr, 'prk', prkCode, false);
		qryStr = appendQryString(qryStr, 'taalcode', taalcode, false);

		// read from cookie
		if (getCookie("stay") != null)
			qryStr = appendQryString(qryStr, 'stay', getCookie("stay"), false);
		else
			qryStr = appendQryString(qryStr, 'stay', 'WE', false);
		if (getCookie("num") != null)
			qryStr = appendQryString(qryStr, 'num', getCookie("num"), false);
		if (getCookie("ym") != null)
		{
			var theym = getCookie("ym");
			if (thema=='wintersport')
			{
				// voor wintersport beginnen met dec-2006
				switch (theym)
				{
					case "200612":
					case "200701":
					case "200702":
					case "200703":
					case "200704":
					case "200712":
						break;
					default:
						theym = "200612";
						break;
				}
			}
			qryStr = appendQryString(qryStr, 'ym', theym, false);
		}
		else
		{
			if (thema=='wintersport')
				// voor wintersport beginnen met dec-2006
				qryStr = appendQryString(qryStr, 'ym', '200612', false);
		}
		if (thema=='wintersport')
			qryStr = appendQryString(qryStr, 'thema', 'wintersport', false);
		
		if (getCookie("dd") != null)
			qryStr = appendQryString(qryStr, 'dd', getCookie("dd"), false);
	  return(qryStr);
	}


	function searchAvailability(qryString) {	
		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;
			}
		}
		loadXML(AvailabilityPanelLocation+qryString);
	}

function openLookAndBook(tocode)
{
	// cookie zetten voor 7 dagen
	if (tocode=='') {
		setCookie("RTL", "set", 7);
	}
	
	var qryStr = '';
	var selNum = getSelectedValue(document.getElementById('avnum'));
	var selStay = getSelectedValue(document.getElementById('avstay'));
	var selDate = getSelectedValue(document.getElementById('avym')) + getSelectedValue(document.getElementById('avdd'));
	if (prkCode == '') {
		qryStr = appendQryString('ingang=availability', 'vk_land', cntCode, false);
		qryStr = appendQryString(qryStr, 'boekditpark', prkCode, false);
		qryStr = appendQryString(qryStr, 'vk_duur', selStay, false);
		qryStr = appendQryString(qryStr, 'vk_bungalow_user', selNum , false);
		
		var YYYYMMDD = selDate;
		var YMMDD='';
		if (YYYYMMDD.length == 8)
		{
			YMMDD = YYYYMMDD.substring(3,8);
			qryStr = appendQryString(qryStr, 'vk_aankomst_YMMDD', YMMDD, false);
		}
		openSps(qryStr);
	}
	else {
		this.open('../../template3.aspx?cp=parkcontentalgemeen1&menu=parken&mid=parkenalgemeen&contentcode=algemeen&parkcode=' + prkCode + '&sel_num=' + selNum + '&sel_stay=' + selStay + '&sel_date=' + selDate + '&tocode=' + tocode, "newWindow12");
	}
}

/**
 * Sets a Cookie with the given name and value.
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
 
function setCookie(name, value, expires, path, domain, secure)
{
	var today = new Date();
	var expire = new Date();
	expire.setTime(today.getTime() + 3600000*24*expires);
	
	if (expires) {
		document.cookie = name + "=" + escape(value) + ";expires="+expire.toGMTString() + ";path=/";
	}
	else {
		document.cookie = name + "=" + escape(value) + ";path=/";
	}	
}

/**
 * Gets the value of the specified cookie.
 * name  Name of the desired cookie.
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
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));
}


