// this script is made with AJAX: Asynchronous JavaScript and XML
//
//	Author: Nico Lubbers		
//   www.booleanpark.com
//
var useAJAX = true;
var globalURL;
var DealerCode;

var isFirstRequest = false;
if (getCookie("firstRequest") == null) {
	isFirstRequest = true;
	setCookie("firstRequest","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 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)
//	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 {
         if(req.status != "0")
            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('merk');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('model');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('bouwjaar');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('kmrange');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('regio');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('carrosserievorm');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('prijsrange');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('brandstof');
			if (dropdownptr!=null) dropdownptr.disabled = true;
		dropdownptr = document.getElementById('transmissie');
			if (dropdownptr!=null) dropdownptr.disabled = true;
*/	

		if(useAJAX)
			loadXMLDoc(xmlFile);
		else
		{
		alert('peop');
			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) {
		    var theXMLString = req.responseText;
		    if (theXMLString.indexOf('<iframe') > -1)
		    {
		      var iframeidx = theXMLString.indexOf('<iframe');
		      theXMLString = theXMLString.substring(0, iframeidx);
		    }
		    if (window.ActiveXObject)
            {
                var theXML=new ActiveXObject("Microsoft.XMLDOM");
                theXML.async="false";
                theXML.loadXML(theXMLString);
            }
            // code for Mozilla, Firefox, Opera, etc.
            else
            {
                var parser=new DOMParser();
                var theXML=parser.parseFromString(theXMLString,"text/xml");
            }
            // documentElement always represents the root node
		    var xmlobject = theXML.documentElement;
			collection= xmlobject.getElementsByTagName(tagname);
			//collection= req.responseXML.getElementsByTagName(tagname);
		}
		else
			collection = xmlDoc.getElementsByTagName(tagname);
		dropdowncnt = 0;
		
		//alert(tagname+' '+collection.length);
		// 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 { 
			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
					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++;
	   	}
		}
		fieldptr.disabled = disableOption;
	}

	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('true');
		  }
		}
		return('');
	}

	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';
		
		if (document.getElementById('brand') != null) {
			populateXMLSelect(document.getElementById('brand'),'brand');
		}
				
		populateXMLSelect(document.getElementById('model'),'model');
		populateXMLSelect(document.getElementById('manufacturing_year'),'manufacturing_year');
		populateXMLSelect(document.getElementById('mileagerange'),'mileagerange');
		if (document.getElementById('region') != null) {
			populateXMLSelect(document.getElementById('region'),'region');
		}
		populateXMLSelect(document.getElementById('bodywork'),'bodywork');
		populateXMLSelect(document.getElementById('pricerange'),'pricerange');
		populateXMLSelect(document.getElementById('fuel'),'fuel');
		populateXMLSelect(document.getElementById('transmission'),'transmission');
		if (document.getElementById('top_selection') != null) {
		    populateXMLCheckbox(document.getElementById('top_selection'),'top_selection')
		}
		populateCounter();

		isLoadingXML = false;
	}

	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){
			    var theXMLString = req.responseText;
		        if (theXMLString.indexOf('<iframe') > -1)
		        {
		          var iframeidx = theXMLString.indexOf('<iframe');
		          theXMLString = theXMLString.substring(0, iframeidx);
		        }
		        if (window.ActiveXObject)
                {
                    var theXML=new ActiveXObject("Microsoft.XMLDOM");
                    theXML.async="false";
                    theXML.loadXML(theXMLString);
                }
                // code for Mozilla, Firefox, Opera, etc.
                else
                {
                    var parser=new DOMParser();
                    var theXML=parser.parseFromString(theXMLString,"text/xml");
                }
                // documentElement always represents the root node
		        var xmlobject = theXML.documentElement;
			    collection= xmlobject.getElementsByTagName(tagname);
			    //collection= req.responseXML.getElementsByTagName(tagname);
			}
			else
				collection = xmlDoc.getElementsByTagName(tagname);
  		
  		//alert(collection.length);
		  // 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 == 'True') {		  // J 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;
			  if(!isFirstRequest)
			  {
    		    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);
	}



var blinkcount = 0;
var blinkstate = true;
var blinktmr;
	function populateCounter() {
		// displays number of database items that match criteria
		var collection;
		var collectionTot;
		var currentcount;
		var currentcountTot;
		if (useAJAX)
		{
			var theXMLString = req.responseText;
		    if (theXMLString.indexOf('<iframe') > -1)
		    {
		      var iframeidx = theXMLString.indexOf('<iframe');
		      theXMLString = theXMLString.substring(0, iframeidx);
		    }
		    if (window.ActiveXObject)
            {
                var theXML=new ActiveXObject("Microsoft.XMLDOM");
                theXML.async="false";
                theXML.loadXML(theXMLString);
            }
            // code for Mozilla, Firefox, Opera, etc.
            else
            {
                var parser=new DOMParser();
                var theXML=parser.parseFromString(theXMLString,"text/xml");
            }
            // documentElement always represents the root node
		    var xmlobject = theXML.documentElement;
			collection= xmlobject.getElementsByTagName('counter');
			//collection= req.responseXML.getElementsByTagName('counter');
		}	
		else
			collection    = xmlDoc.getElementsByTagName('counter');
			
		if (collection.length > 0)
		{
			currentcount    = collection[0].getAttribute('id');
			blinkcount = 0;
			blinkstate = true;
			blinkText();
		}
		//voor het tonen van het totaal aantal occasions van een dealer; dus zonder verdere selectiecriteria
		if (useAJAX)
		{
				    var theXMLString = req.responseText;
		    if (theXMLString.indexOf('<iframe') > -1)
		    {
		      var iframeidx = theXMLString.indexOf('<iframe');
		      theXMLString = theXMLString.substring(0, iframeidx);
		    }
		    if (window.ActiveXObject)
            {
                var theXML=new ActiveXObject("Microsoft.XMLDOM");
                theXML.async="false";
                theXML.loadXML(theXMLString);
            }
            // code for Mozilla, Firefox, Opera, etc.
            else
            {
                var parser=new DOMParser();
                var theXML=parser.parseFromString(theXMLString,"text/xml");
            }
            // documentElement always represents the root node
		    var xmlobject = theXML.documentElement;
			collectionTot= xmlobject.getElementsByTagName('countertotal');
			
			//collectionTot= req.responseXML.getElementsByTagName('countertotal');
		}
		else
			collectionTot = xmlDoc.getElementsByTagName('countertotal');
		if (collectionTot.length > 0)
		{
			currentcountTot = collectionTot[0].getAttribute('id');
			rewriteCount(currentcount,currentcountTot);
		}
	}
	

	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=='-') // ignore these values
					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 getValue(optionPtr) {
		if (optionPtr == null)
			return('');
		return optionPtr.value;
	}

  function defineQryString(ignoretag) {
	var qryStr = '';
	if (DealerCode!=null) {  // alleen in 'dealer'-mode moeten we een dealercode en merk meesturen
		qryStr = appendQryString(qryStr, 'dealercode', DealerCode, false);
		qryStr = appendQryString(qryStr, 'brand', getSelectedValue(document.getElementById('brand')), true);
	}
	else {
		qryStr = appendQryString(qryStr, 'region', getSelectedValue(document.getElementById('region')), true);
	}
	
	qryStr = appendQryString(qryStr, 'model', getSelectedValue(document.getElementById('model')), true);
	qryStr = appendQryString(qryStr, 'manufacturing_year', getSelectedValue(document.getElementById('manufacturing_year')), true);
	qryStr = appendQryString(qryStr, 'mileagerange', getSelectedValue(document.getElementById('mileagerange')), true);
	qryStr = appendQryString(qryStr, 'bodywork', getSelectedValue(document.getElementById('bodywork')), true);
	qryStr = appendQryString(qryStr, 'pricerange', getSelectedValue(document.getElementById('pricerange')), true);
	qryStr = appendQryString(qryStr, 'fuel', getSelectedValue(document.getElementById('fuel')), true);
	qryStr = appendQryString(qryStr, 'transmission', getSelectedValue(document.getElementById('transmission')), true);
	if (document.getElementById('top_selection') != null) {
	    qryStr = appendQryString(qryStr, 'top_selection', getCheckedValue(document.getElementById('top_selection')), true);
	}

	window.status = qryStr;
	return(qryStr);
  }

	function reloadXML() {
		var qryStr = defineQryString();
		//alert(qryStr);
		loadXML('xml/occasion.aspx'+qryStr);
	}

	function makeInitQRY(myDealerCode) {
		var qryStr='';
		if (myDealerCode!=null) 
			DealerCode = myDealerCode;
		
		// read from cookie
		if (getCookie("model") != null)
			qryStr = appendQryString(qryStr, 'model', getCookie("model"), false);
		if (getCookie("manufacturing_year") != null)
			qryStr = appendQryString(qryStr, 'manufacturing_year', getCookie("manufacturing_year"), false);
		if (getCookie("mileagerange") != null)
			qryStr = appendQryString(qryStr, 'mileagerange', getCookie("mileagerange"), false);
		
		if (document.getElementById('region') != null) {	
			if (getCookie("region") != null)
				qryStr = appendQryString(qryStr, 'region', getCookie("region"), false);
		}	

		if (DealerCode!=null) {  // alleen in 'dealer'-mode moeten we een dealercode en merk meesturen
			qryStr = appendQryString(qryStr, 'dealercode', DealerCode, false);
			if (getCookie("brand") != null) 
				qryStr = appendQryString(qryStr, 'brand', getCookie("brand"), false);
			else
				//geef leeg object mee, zodat in 'dealer'-mode de merk dropdown 'geen voorkeur' als initiele waarde laat zien
				qryStr = appendQryString(qryStr, 'brand', '', false);
		}
		
		if (getCookie("bodywork") != null)
			qryStr = appendQryString(qryStr, 'bodywork', getCookie("bodywork"), false);
		if (getCookie("pricerange") != null)
			qryStr = appendQryString(qryStr, 'pricerange', getCookie("pricerange"), false);
		if (getCookie("fuel") != null)
			qryStr = appendQryString(qryStr, 'fuel', getCookie("fuel"), false);
		if (getCookie("transmission") != null)
			qryStr = appendQryString(qryStr, 'transmission', getCookie("transmission"), false);
		if (getCookie("top_selection") != null) {
			qryStr = appendQryString(qryStr, 'top_selection', getCookie("top_selection"), false);
		}
		else {
			if (isFirstRequest)
				if (DealerCode==null)
				{
					qryStr = appendQryString(qryStr, 'top_selection', 'false', false);
				}
				else
				{
					//qryStr = appendQryString(qryStr, 'top_selection', 'false', false);
				}
		}
	  return(qryStr);
	}

	function initSearch(qryString) {	
		if(!document.getElementById) {
			// see documentation at http://www.mozilla.org/docs/web-developer/faq.html
  			status.write('no xml');
			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;
			}
		}
		//alert('xml/occasion.aspx'+qryString);
		loadXML('xml/occasion.aspx'+qryString);
	}

	function showResults() {
		var qryStr = defineQryString();
		qryStr = appendQryString(qryStr,"newsearch","y",false);
		var theURL = '/occasions/occasionresultlist.aspx' + qryStr;
		//alert(window.location.href);
		window.location.href = theURL;
	}

/**
 * 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)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * 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));
}
function blinkText()
{
	clearTimeout(blinktmr);
	blinkstate = !blinkstate;
	blinkcount++;
	if (blinkcount > 6) 
	{
		document.getElementById('ocN').style.visibility = 'visible';
		return;
	}
	if (blinkstate)
		document.getElementById('ocN').style.visibility = 'visible';
	else
		document.getElementById('ocN').style.visibility = 'hidden';
	blinktmr = setTimeout('blinkText()', 100 );
}
