/*	mobileSearch.js	*/
/* not yet final, not yet unobstrusive */


function checkBoxes (form, check) {
	for (var c = 0; c < form.elements.length; c++)
		if (form.elements[c].type == 'checkbox')
	    form.elements[c].checked = check;
}

function setField(field, value) {
   document.forms['searchForm'].elements[field].value=value;
}

//TODO remove, replaced by ambitSearchController
function deleteZipcodeAndZipcodeRadiusIfNotGermany(){
	if(document.forms['searchForm'].elements["ambitCountry"].value != "DE"){
		document.forms['searchForm'].elements["zipcode"].value = "";
		disableZipcodeRadius();
	}
}

//used in quicksearch, remove this after introduction of european ambit search
//TODO remove, replaced by ambitSearchController
function enableDisableAmbitCountry(zipcode, countryId, zipPattern){
	if (zipcode != null && zipcode != "" && zipPattern != null && zipPattern != ""){
		var zipValid = zipcode.match(new RegExp(zipPattern));
		if (zipValid) {
				document.forms['searchForm'].elements["ambitCountry"].value = countryId;
				return;
		}			
	}
	document.forms['searchForm'].elements["ambitCountry"].value = "";
}

//TODO remove, replaced by ambitSearchController
function enableDisableZipcodeRadius(zipcode, zipPattern) {
	if (zipcode != null && zipcode != "" && zipPattern != null && zipPattern != ""){
		var zipValid = zipcode.match(new RegExp(zipPattern));
		if (zipValid) {
			document.getElementById("zipcodeRadius").disabled = false;
			if((document.forms['searchForm'].elements["zipcodeRadius"]) && (document.forms['searchForm'].elements["zipcodeRadius"].value == "")){
				document.forms['searchForm'].elements["zipcodeRadius"].value = "100";
				return;
			}
		}
	}
	disableZipcodeRadius();
}

// TODO remove, replaced by ambitSearchController
function disableZipcodeRadius() {
	var radiusOptions = document.getElementById("zipcodeRadius");
	for (var i = 0; i < radiusOptions.length; i++) {
		if(radiusOptions[i].value == "") {
			radiusOptions[i].selected = true;
			break;
		}
	}
	document.getElementById("zipcodeRadius").disabled = true;
}

function checkCountriesConsistence(countryCheckbox){
	if (countryCheckbox.value == ''){
		if (countryCheckbox.checked == true){
			var allCheckboxes = document.getElementsByTagName('input');
			for (var i = 0; i < allCheckboxes.length; i++) {
				if (allCheckboxes[i].className == 'countriesSelector') {
					allCheckboxes[i].checked = false;				    	
				}
			}
		}
	} else if (countryCheckbox.checked == true) {
		// a country checkbox is activated
		document.getElementById("countriesWorldWide").checked = false; 
	} else if (countryCheckbox.checked == false) {
		var countriesSelected = false;
		var allCheckboxes = document.getElementsByTagName('input');
		for (var i = 0; i < allCheckboxes.length; i++) {
			if (allCheckboxes[i].className == 'countriesSelector' && allCheckboxes[i].checked == true) {
				countriesSelected = true;				    	
			}
		}
		if ( countriesSelected == false ) {
			document.getElementById("countriesWorldWide").checked = true;
		}	
	}
}


/* ---- *carSearch.ftl: search by bodystyle ---- */
function uncheckBodyStyle() {
   	for (var i=0 ; i<8 ; i++){
   		document.forms['searchForm'].categories[i].checked= false;
	}
}

function checkBodyStyleStatus() { //onload
	for (var i=0 ; i<8 ; i++){
		if (document.forms['searchForm'].categories[i].checked == true){
			if(document.forms['searchForm'].bodyStyleRadioSelect){
		   		document.forms['searchForm'].bodyStyleRadioSelect.checked = true;
		   		document.forms['searchForm'].bodyStyleRadioAll.checked = false;
		   		makeRadiobuttonActive('bodyStyleInput2', 'bodyStyleInput1');
		   		break;
	   		}
   		}
   		else {
   			setBodyStyleRadioAll();
   		}	   		
	}
	
	var allCheckboxes = document.getElementsByTagName('input');
	for (var i=0; i < allCheckboxes.length; i++) {
		
		if (allCheckboxes[i].className == 'bodyStyleSelector') {
			allCheckboxes[i].onclick = function() {
				checkBodyStyleStatus();
				retrieveModelsForAllMakeSelections(); 
				requestHitsWithDelay();
			}
		}
	}
	
}

function setBodyStyleRadioAll() {
   	if (document.forms['searchForm'].bodyStyleRadioAll) {
    	document.forms['searchForm'].bodyStyleRadioAll.checked = true;
   		makeRadiobuttonActive('bodyStyleInput1', 'bodyStyleInput2');  	
   	}

}

function makeRadiobuttonActive (id1, id2){
	if (document.getElementById) {
		if (document.getElementById(id1)){
			document.getElementById(id1).style.fontWeight = "bold";
			document.getElementById(id2).style.fontWeight = "normal";
		}
	}
}
/* ---- /carSearch.ftl: search by bodystyle ---- */

function showHideSimple(id) {

	if (document.getElementById) {
		if (document.getElementById(id).style.display=="none"){
			document.getElementById(id).style.display="block";
		}
		else{
			document.getElementById(id).style.display="none";
		}
	} 
	else if (document.all) {
		if (document.all[id].style.display=="none"){
			document.all[id].style.display="block";
		}
		else {
			document.all[id].style.display="none";
		}  
	} 
	else if (document.layers) {
		if (document.layers[id].display=="none"){
			document.layers[id].display="block";
		}
		else{
			document.layers[id].display="none";
		}
	}
}

function prepareShowId() {
	if(document.getElementsByTagName){
		var allLinks = document.getElementsByTagName('a');
		for (var i=0; i < allLinks.length; i++) {
			if (allLinks[i].className == 'popupSelectLink') {
				allLinks[i].parentNode.getElementsByTagName('div')[0].onmouseover = function() {
					this.parentNode.getElementsByTagName('div')[0].style.display = 'block';
				}
				allLinks[i].parentNode.getElementsByTagName('div')[0].onmouseout = function() {
					this.parentNode.getElementsByTagName('div')[0].style.display = 'none';
				}
				allLinks[i].onmouseover = function() {
					this.parentNode.getElementsByTagName('div')[0].style.display = 'block';
				}
				allLinks[i].onmouseout = function() {
					this.parentNode.getElementsByTagName('div')[0].style.display = 'none';
				}
			}
		}
	}
}

addEvent(window, 'load', prepareShowId);


// TODO
// popUps for search parameters 
// basically the same script as the checkLinks function in mobile.js
// when applications are being merged this should be put into mobile.js

function checkParameterLinks() 
{
	// check to see that the browser supports the getElementsByTagName method
	// if not, exit the loop 
	if (!document.getElementsByTagName) 
	{
		return false; 
	}

	var links = document.getElementsByTagName("a");
	// loop through each of these links (anchor tags) 	
	for (var i=0; i < links.length; i++) 
	{
		if (links[i].className.indexOf("parameterPopupLandscape") > -1) 
		{	
			// add an onclick event on the fly to pass the href attribute	
			// of the link to our second function, openPopUp 	
			links[i].onclick = function() 
			{	
			openPopUp(this.getAttribute("href"), 520, 250, 200, 400, 'no', 'no', 'no', 'no', 'yes', 'yes');	
			return false; 	
			} 	
		}
		
		if (links[i].className.indexOf("parameterPopupSmall") > -1) 
		{	
			// add an onclick event on the fly to pass the href attribute	
			// of the link to our second function, openPopUp 	
			links[i].onclick = function() 
			{	
			openPopUp(this.getAttribute("href"), 200, 200, 200, 400, 'no', 'no', 'no', 'no', 'yes', 'yes');	
			return false; 	
			} 	
		}
		
		if (links[i].className.indexOf("parameterPopupLong") > -1) 
		{	
			// add an onclick event on the fly to pass the href attribute	
			// of the link to our second function, openPopUp 	
			links[i].onclick = function() 
			{	
			openPopUp(this.getAttribute("href"), 250, 430, 200, 400, 'no', 'no', 'no', 'no', 'yes', 'yes');	
			return false; 	
			} 	
		}
	}
}

addEvent(window, 'load', checkParameterLinks);


function showId(id) {
  if (document.getElementById) {
  document.getElementById(id).style.display="block";
} else if (document.all) {
  document.all[id].style.display="block";
} else if (document.layers) {
  document.layers[id].display="block";
} } 

 function hideId(id) {
 	if (document.getElementById) {
		document.getElementById(id).style.display="none";
		}else if (document.all) {
			document.all[id].style.display="none";
		}else if (document.layers) {
			document.layers[id].display="none";
		} 
	}

function enableElement(id){
}
/*	/Scripts search 20 */

function showHideExtended(id,txtId,val1,val2) {

	if (document.getElementById) {
		if (document.getElementById(id).style.display=="none"){
			document.getElementById(txtId).firstChild.nodeValue = val2;
			document.getElementById(id).style.display="block";
		}
		else{
			document.getElementById(txtId).firstChild.nodeValue = val1;
			document.getElementById(id).style.display="none";
		}
	} 
	else if (document.all) {
		if (document.all[id].style.display=="none"){
			document.all[id].style.display="block";
		}
		else {
			document.all[id].style.display="none";
		}  
	} 
	else if (document.layers) {
		if (document.layers[id].display=="none"){
			document.layers[id].display="block";
		}
		else{
			document.layers[id].display="none";
		}
	}
}

// helper function, lets you add remove classes on the fly
// should be put into mobile.js once files get merged

function switchClass(a,o,c1,c2) {
  switch (a){
    case 'swap':
      o.className=!switchClass('check',o,c1)?o.className.replace(c2,c1):o.className.replace(c1,c2);
    break;
    case 'add':
      if(!switchClass('check',o,c1)){o.className+=o.className?' '+c1:c1;}
    break;
    case 'remove':
      var rep=o.className.match(' '+c1)?' '+c1:c1;
      o.className=o.className.replace(rep,'');
    break;
    case 'check':
      return new RegExp('\\b'+c1+'\\b').test(o.className)
    break;
  }
}

// tabbed browsing
function detailTabs() {
	
	if(document.getElementById('detailTabs')) {
		
		// hide all tabs and then show the first one
		hideAllDetails();
		// modified for developing
		document.getElementById('tabOverview').style.display = 'block';
		//document.getElementById('tabServices').style.display = 'block';
		
		var tabLinks = document.getElementById('detailTabs').getElementsByTagName('a');
		for (var i=0; i < tabLinks.length; i++) {
			if (tabLinks[i].href.split("#")[1] == 'tabOverview') {
				tabLinks[i].parentNode.className = 'active';
			}
		}
		
		// get the target of the links that is clicked and show the corresponding tab
		var tabLinks = document.getElementById('tabNav').getElementsByTagName('a');
		for (var i=0; i < tabLinks.length; i++) {
			tabLinks[i].onclick = function() {
				var whichTab = this.href;
				hideAllDetails();
				document.getElementById(whichTab.split("#")[1]).style.display = 'block';
				switchClass('add', this.parentNode, 'active');
				
				return false;
			}
		}


		// links referencing tabs		
		var allLinks = document.getElementsByTagName('a');
		for (var i=0; i < allLinks.length; i++) {
			if (allLinks[i].className.indexOf('tabOverview') > -1) {
				allLinks[i].onclick = function() {
					
					var whichTab = this.href;
					hideAllDetails();
					document.getElementById('tabOverview').style.display = 'block';
					
					var tabLinks = document.getElementById('detailTabs').getElementsByTagName('a');
					for (var i=0; i < tabLinks.length; i++) {
						if (tabLinks[i].href.split("#")[1] == 'tabOverview' ) {
							tabLinks[i].parentNode.className = 'active';
						}
					}
				}
			}
		}
		
		for (var i=0; i < allLinks.length; i++) {
			if (allLinks[i].className.indexOf('tabVehiclePictures') > -1) {
				allLinks[i].onclick = function() {
					
					var whichTab = this.href;
					hideAllDetails();
					document.getElementById('tabVehiclePictures').style.display = 'block';
					
					var tabLinks = document.getElementById('detailTabs').getElementsByTagName('a');
					for (var i=0; i < tabLinks.length; i++) {
						if (tabLinks[i].href.split("#")[1] == 'tabVehiclePictures' ) {
							tabLinks[i].parentNode.className = 'active';
						}
					}
				}
			}
		}
		
		for (var i=0; i < allLinks.length; i++) {
			if (allLinks[i].className.indexOf('tabDescription') > -1) {
				allLinks[i].onclick = function() {
					
					var whichTab = this.href;
					hideAllDetails();
					document.getElementById('tabDescription').style.display = 'block';
					
					var tabLinks = document.getElementById('detailTabs').getElementsByTagName('a');
					for (var i=0; i < tabLinks.length; i++) {
						if (tabLinks[i].href.split("#")[1] == 'tabDescription' ) {
							tabLinks[i].parentNode.className = 'active';
						}
					}
				}
			}
		}
		
		for (var i=0; i < allLinks.length; i++) {
			if (allLinks[i].className.indexOf('tabDealerInfo') > -1) {
				allLinks[i].onclick = function() {
					
					var whichTab = this.href;
					hideAllDetails();
					document.getElementById('tabDealerInfo').style.display = 'block';
					
					var tabLinks = document.getElementById('detailTabs').getElementsByTagName('a');
					for (var i=0; i < tabLinks.length; i++) {
						if (tabLinks[i].href.split("#")[1] == 'tabDealerInfo' ) {
							tabLinks[i].parentNode.className = 'active';
						}
					}
				}
			}
		}
		
		for (var i=0; i < allLinks.length; i++) {
			if (allLinks[i].className.indexOf('tabServices') > -1) {
				allLinks[i].onclick = function() {
					
					var whichTab = this.href;
					hideAllDetails();
					document.getElementById('tabServices').style.display = 'block';
					
					var tabLinks = document.getElementById('detailTabs').getElementsByTagName('a');
					for (var i=0; i < tabLinks.length; i++) {
						if (tabLinks[i].href.split("#")[1] == 'tabServices' ) {
							tabLinks[i].parentNode.className = 'active';
						}
					}
				}
			}
		}
		
		for (var i=0; i < allLinks.length; i++) {
			if (allLinks[i].className.indexOf('tabInsurance') > -1) {
				allLinks[i].onclick = function() {
					
					var whichTab = this.href;
					hideAllDetails();
					document.getElementById('tabInsurance').style.display = 'block';
					
					var tabLinks = document.getElementById('detailTabs').getElementsByTagName('a');
					for (var i=0; i < tabLinks.length; i++) {
						if (tabLinks[i].href.split("#")[1] == 'tabInsurance' ) {
							tabLinks[i].parentNode.className = 'active';
						}
					}
				}
			}
		}
		
		for (var i=0; i < allLinks.length; i++) {
			if (allLinks[i].className.indexOf('tabFinancing') > -1) {
				allLinks[i].onclick = function() {
					
					var whichTab = this.href;
					hideAllDetails();
					document.getElementById('tabFinancing').style.display = 'block';
					
					var tabLinks = document.getElementById('detailTabs').getElementsByTagName('a');
					for (var i=0; i < tabLinks.length; i++) {
						if (tabLinks[i].href.split("#")[1] == 'tabFinancing' ) {
							tabLinks[i].parentNode.className = 'active';
						}
					}
				}
			}
		}
		// end of links referencing tabs
		
	}
}

function hideAllDetails() {
	
	document.getElementById('tabOverview').style.display = 'none';
	document.getElementById('tabVehiclePictures').style.display = 'none';
	document.getElementById('tabDescription').style.display = 'none';
	document.getElementById('tabDealerInfo').style.display = 'none';
	document.getElementById('tabServices').style.display = 'none';	
	document.getElementById('tabFinancing').style.display = 'none';
	document.getElementById('tabInsurance').style.display = 'none';
	
	// make the navigation point active
	var tabs = document.getElementById('detailTabs').getElementsByTagName('li');
	for (var i=0; i < tabs.length; i++) {
		switchClass('remove', tabs[i], 'active');
	}
}

//addEvent(window, 'load', detailTabs);

/* ---- * DES: swap image ---- */
function preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.p) d.p=new Array();
    var i,j=d.p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.p[j]=new Image; d.p[j++].src=a[i];}}
}

function findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}
function swapImage() { //v3.0
  var i,j=0,x,a=swapImage.arguments; document.sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=findObj(a[i]))!=null){document.sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
	
function swapImgRestore() { //v3.0
  var i,x,a=document.sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
/* ---- / DES: swap image ---- */



/* ---- / DES: send contact mail to seller ---- */			
function sendMail(contactFormId) {
    new Ajax.Request('sendContactForm.html', {
    	asynchronous: false,
		method: 'post',
		parameters: Form.serialize('contactForm' + contactFormId),
		onSuccess: function(request) {
			$('contactFormDiv' + contactFormId).update(request.responseText);
		}
	});
}

function reloadCaptcha(div, url) {
	$(div).src=url+'?r='+Math.random();
}

function highlightCounter(id) {
	/*document.getElementById(id).style.backgroundColor = "#ff6600";*/
	document.getElementById(id).style.color = "#fafafa";
}
function delightCounter(id) {
	/*document.getElementById(id).style.backgroundColor = "transparent";*/
	document.getElementById(id).style.color = "black";
}



var lastHits = '';

var t;
function requestHitsWithDelayForUrl(hitCounterUrl) { 
	if(t) { window.clearTimeout(t) }
		t = window.setTimeout("requestHitsForUrl('" + hitCounterUrl + "')", 500);	
}

/* FIXME: the following number formatting does not respect locales */

/**
 * Print the hit counter to the hits counter box
 * and all relevant submit "buttons".s
 * 
 * param hits : (string) either a simple number or two numbers
 * separated by a comma, in which case 
 */
function printHits( hitsWithExtended ){
	var thousandSeparator = ".";
	switch(language){
		case "en":
			thousandSeparator = ",";
			break;
		case "fr":
			thousandSeparator = " ";
			break;
	}
	var tokens = hitsWithExtended.split(",");
	var hits = formatHitcounter( tokens[0] , thousandSeparator );
	
	// if we recieved two hit counters then
	// the second one is the count for the international search.
	var isExtensionHitscounter = tokens.length > 1;
	
	if(isExtensionHitscounter){
		var hitsExtended = formatHitcounter( tokens[1] , thousandSeparator );
		if ( $('extensionHitsCounterBox') ) {
			$('extensionHitsCounterBox').show();
			if ($('extensionHitsCounter0')) {
				$('extensionHitsCounter0').update(hitsExtended);
	    		highlightCounter("extensionHitsCounter0");
		    	window.setTimeout('delightCounter("extensionHitsCounter0")', 150);
			}
		}
		
	}
	else {
		if ( $('extensionHitsCounterBox') ) {
			$('extensionHitsCounterBox').hide();
		}
	}
	for(var i = 0; i < 3; i++){	
		if ($('hitsCounter' + i)) {
			$('hitsCounter' + i).update(hits);
	    	highlightCounter("hitsCounter0");
	    	window.setTimeout('delightCounter("hitsCounter0")', 150);
		}
	}
	for(var i = 0; i < 3; i++){	
		if ($('hitsCounterColon' + i)) {
			$('hitsCounterColon' + i).update(":");
		}
	}
}

function formatHitcounter( hits , thousandSep ) {
	var pattern = /(\d{3})*$/;
	var tokens = [];
	while ( hits.length > 0 ) {
		tokens.unshift( hits.substring( hits.length - 3 ) );
		hits = hits.substring( 0 , hits.length - 3 );
	}
	return tokens.join( thousandSep );
}


function requestHitsForUrl(url) { 
	var params = Form.serialize('searchForm', true);
	params['lang'] = ''; // unset lang to enable language independent caching
    
    new Ajax.Request(url, {
		method: 'get',
		parameters: params, 
		onSuccess: function(request) {
		
			// added points between thousands as separator
			var hits = String(request.responseText);
			hits = hits.substring(0, (hits.length-2)); //Leerzeichen abschneiden
			lastHits = hits;
			printHits(hits, false);
		} 
	});
    
}

function requestExtendedHitsForUrl(url) {

	var params = Form.serialize('searchForm', true);

	params['lang'] = ''; // unset lang to enable language independent caching
	
	if ( typeof params['siteIds'] != "string") {
		$('extensionHitsCounterBox').hide();
		return;		
	}

	$('extensionHitsCounterBox').show();

	params['countries'] = "ALL_EUROPE";
    
    new Ajax.Request(url, {
		method: 'get',
		parameters: params, 
		onSuccess: function(request) {
		
			// added points between thousands as separator
			var hits = String(request.responseText);
			hits = hits.substring(0, (hits.length-2)); //Leerzeichen abschneiden
			printHits(hits, true);
		} 
	});
}

var extendedT;
function requestExtendedHitsWithDelayForUrl(hitCounterUrl) {
	if(extendedT) { window.clearTimeout(extendedT) }
		extendedT = window.setTimeout("requestExtendedHitsForUrl('" + hitCounterUrl + "')", 500);	
}

/**
 * Submit the extended search :
 * 
 * -> manipulate the country selection to "", so that the search request
 *    will not include countries; and the zip code to "".
 *     
 * -> and submit.
 * 
 * @return
 */
function submitSearchForExtendedHits(){
	var countrySelect = $("ambitCountry");
	// store the current value and change it.
	
	if ( countrySelect.options ) { // <select>
		country = countrySelect.selectedIndex;
		countrySelect.selectedIndex = 0;
	}
	else { // <input type="hidden">
		country = countrySelect.value;
		countrySelect.value = "";
	}
	
	var zipInput = $("zipcode");
	zipInput.value = "";
	
	var zipcodeRadius = $("zipcodeRadius");
	zipcodeRadius.value = "";

	
	// submit the form.
	
	document.forms['searchForm'].submit();
	
}

/* makeModelVarian */
/* used in buyer-webapp and buyer-search-webapp */
/* this retrieves the models asynchronously */

function retrieveModelsForAllMakeSelections() {
	$R(1, 3).each(function(i) {
  		// invoked 3 times for i = 1 to 3
  		try {
			var selectedMake = $("selectMake" + i).getValue();
			if (selectedMake != "") {
				retrieveModels(selectedMake, i, "true");
			}
		}
		catch(e) {}
	});
} 
			
function retrieveModels(selectedMake, makeModelVariantIndex, keepModelSelection, modelValue) {

	var makeId = selectedMake;	
	
	if (makeId == '') {
		/* disable model list, if make is unselected */
		var modelSelection = '<select class="select" id="selectModel' + makeModelVariantIndex + '" name="makeModelVariant' + makeModelVariantIndex + '.modelId">';
		modelSelection += '<option selected value=""><\/option>';
		modelSelection += '<\/select>';
	  	$('modelSelection' + makeModelVariantIndex).update(modelSelection);
		disableModelSelection(makeModelVariantIndex);
		return;
	}
	
	
	// enable other fields in row + make selection of next row!		
    enableModelSelection(makeModelVariantIndex);
    
    
    // add parameters....
    
    // makeId
    var params = 'makeId=' + makeId;
   
   	if(document.searchForm.categories != null){
	   
	    if (document.searchForm.categories.type == "select-one") {
	    	if (document.searchForm.categories.value != "") {
		    	params += "&categories=" + document.searchForm.categories.value;
		    }
	    } else {
	    	params += '&' + Form.serializeElements($A(document.searchForm.categories).map(Element.extend));
	    }
	}

    var contextPath = extractContextPath(document.searchForm.action);
    var prospectiveURI = (contextPath && contextPath != "")? contextPath + "/models.html" : "models.html";
    var prospectiveURIParts = parseUri(prospectiveURI);
    var currentURI = document.location.href;
    var currentURIParts = parseUri(currentURI);

    //see MBL-9743
    var requestURI = (isAbsoluteURI(prospectiveURI) && prospectiveURIParts["domain"] != currentURIParts["domain"])?
    	requestURI = currentURIParts["protocol"] + "://" + currentURIParts["domain"] + currentURIParts["directoryPath"] + prospectiveURIParts["fileName"] :
    	requestURI = prospectiveURI;
    
    params += '&lang=' + language;

   	new Ajax.Request(requestURI, {
			method: 'get',
			parameters: params, 
			onSuccess: function (request) {
		
		      	var modelSelection =  '<select class="select" id="selectModel' + makeModelVariantIndex + '" name="makeModelVariant' + makeModelVariantIndex + '.modelId" onChange="requestHits();">' 
				modelSelection += request.responseText;
				modelSelection += '<\/select>';
				
				if (keepModelSelection == "true") {
				
					var modelOptions = $('selectModel' + makeModelVariantIndex).options;
					
					var selectedValue = "";
					if (modelValue) {
						selectedValue = modelValue;		
					} else {
						for (var i = 0; i < modelOptions.length; i++) {
							if (modelOptions[i].selected == true) {
								selectedValue = modelOptions[i].value;
								break;
							}
						}
					}
					
					var regex = "value=\"" + selectedValue +"\"";
					var replacement = "value=\"" + selectedValue +"\" selected";
					modelSelection = modelSelection.replace(regex, replacement);
				}
		
		        $('modelSelection' + makeModelVariantIndex).update(modelSelection);
		      }  
		});
  }
  
function enableModelSelection(index) {
	if ($('selectModel' + index) == null)
		return;
	$('selectModel' + index).disable();
}

function disableModelSelection(index) {
	if ($('selectModel' + index) == null)
		return;
	$('selectModel' + index).value = "";
	$('selectModel' + index).disable();
}
  
var numberOfMakeModels = 3;

function loadModelSelection() {
	var loaded = false;
	
	var state = loadState();
	
 	var values = new Array('', '', '', '');
	
	if (state != null) {
		values = state.split('_');
       	for (var i = 1; i <= numberOfMakeModels; i++) {
       		if ($('selectMake' + i) != null && $('selectMake' + i).getValue() != '') {
       			retrieveModels($('selectMake' + i).getValue(), i, "true", values[i - 1]);
	    		loaded = true;
           	}
      	}
	} 
	
	if (loaded) {
		lastHits = values[3];
   		printHits(lastHits);
   	} else {
   		requestHits(); 	
   	}	
}

function saveModelSelection(){
	var cValue = '';
   	for (var i = 1; i <= numberOfMakeModels; i++) {
   		if($('selectModel' + i) != null){
			cValue = cValue.concat($('selectModel' + i).getValue());
			cValue = cValue.concat('_');
		}
   	}
   	cValue = cValue.concat(lastHits);

	saveState(cValue);  	
}

function parkCompare(parkOrCompare){

	var paramName = '';
	if (parkOrCompare == 'park') {
		paramName = "adIdToPark"
	} else {
		paramName = 'adIds';
	}

	var idParams = '';
	
	var checkedItems = 0;
	if(document.parkAndCompareVehicle.parkAndCompare.length){
		for(var i = 0; i < document.parkAndCompareVehicle.parkAndCompare.length; i++) {
			var item = document.parkAndCompareVehicle.parkAndCompare[i];
			
			if (item.checked == true) {
				idParams += paramName + '=' + item.value + '&';
				checkedItems++;
			}
			
		}
	}else if(document.parkAndCompareVehicle.parkAndCompare){
		var item = document.parkAndCompareVehicle.parkAndCompare;
		if (item.checked == true) {
				idParams += paramName + '=' + item.value + '&';
				checkedItems++;
		}
	}
	
	//alert(idParams);
	
	if ( parkOrCompare == 'park' && idParams != ''){
		location = parkingUrl + '?lang=' + language + '&'+ idParams;
	} else if ( parkOrCompare == 'compare' && idParams != ''){
		window.open(vehicleComparisonUrl + '?' + idParams,'FzgVergleich', 'width=950,height=720,left=0,top=0,resizable=yes,scrollbars=yes');
	}

	return false;

}

// use id quicksearch for prefilling the detail search mask
function submitQuickSearch(go2searchMask){
	var searchForm = document.forms["searchForm"];
	if(go2searchMask){
		searchForm.isSearchRequest.disabled = true;
		searchForm.editSearch.disabled = false;		
		searchForm.editSearch.value = 1;
	}else{
		searchForm.editSearch.disabled = true;
		searchForm.isSearchRequest.disabled = false;		
		searchForm.isSearchRequest.value = "true";
	}
	if(searchForm.zipcodeRadius != null && searchForm.zipcodeRadius.value != ""){
		searchForm.ambitCountry.value = "DE";
	}
	searchForm.submit();
}

function changeHiddenSortByField(searchFieldName) {
	document.getElementById('sortBy').value = searchFieldName;
}

function changePriceSortBySelectOption(priceSearchFieldName) {
	// price option is the first option in the selection list!!!!!
	if ($('sortBy').tagName == 'SELECT'){
		$('sortBy').options[0].value = priceSearchFieldName;
	} else {
		$('sortBy').value = priceSearchFieldName;
	}
}

function loadRecommendations(url) {
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(request) {
		var r = String(request.responseText);
		if (r.length>2) {
			$('contentBoxRecommendations').update(r);
		}

	}	 
	});
}

function loadTopInCategory(url) {
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(request) {
		var r = String(request.responseText);
		if (r.length>2) {
			$('contentBoxTopInCategory').update(r);
		}

	}	 
	});
}


function changeSortOrder(searchField){
	if(searchField == "creationTime" || searchField == "specifics.firstRegistration"){
		document.getElementById("sortOrder").value="DESCENDING";						
	}else{
		document.getElementById("sortOrder").value="ASCENDING";
	}
}

function setPowerUnit(){
	document.getElementById('minPowerUnit').value = document.getElementById('powerUnit').value;
	document.getElementById('maxPowerUnit').value = document.getElementById('powerUnit').value;
}

function switchToExportSearch(){
    if (document.getElementById("formForSearch").negativeFeatures.value == 'EXPORT') {
       document.getElementById("formForSearch").negativeFeatures.value = "";
    }
	document.getElementById("formForSearch").isSearchRequest.disabled=true;

	var formActionURL = document.getElementById("formForSearch").action;
	var switchUrl = formActionURL + "?editSearch=1&switchRandom=" + Math.random() + "&" + Form.serialize($('formForSearch'));

	location.href = switchUrl;
}

function extractContextPath(path) {
	if (!path || path == "")
		return "";

	var re = /(.+)\/[^\.\/]*.html/;
  	re.ignoreCase;
  	if(!re.exec(path))
  		return "";

  	return RegExp.$1;
}

//parseUri JS v0.1.1, by Steven Levithan <http://stevenlevithan.com>
function parseUri(sourceUri){
	var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"],
		uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri),
		uri = {};
	
	for(var i = 0; i < 10; i++){
		uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
	}
	
	/* Always end directoryPath with a trailing backslash if a path was present in the source URI
	Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key */
	if(uri.directoryPath.length > 0){
		uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
	}
	
	return uri;
}

function isAbsoluteURI(uri) {
	var uriParts = parseUri(uri);
	return (uriParts["protocol"] && uriParts["protocol"] != "" 
		&& uriParts["domain"] && uriParts["domain"] != "");
}

// =====================================================================================================================
// Ambit search disable/enable radius for localized geo search by country, zip and radius
// =====================================================================================================================

/**
 * controller for the country / zip / radius
 * 
 * when entering a zip :
 * - if the current selected country supports geo search, disable / enable 
 *   the radius select.
 *   
 * - otherwise, change the selected country to the current site default country
 *   (e.g. romania...)
 *   
 * - disable and enable the radius depending on validation of the entered zip.
 * 
 * using YUI module pattern for private / public members
 * 
 * requires prototype.js
 * 
 * Usage:
 * ------
 * 
 * <select id='countries' onchange='ambitSearchController.onCountryChange'>
 * ...
 * <input id="zip" onkeyup='ambitSearchController.onZipChange'>
 * ...
 * <select id="radius">
 * ...
 * 
 * <script ...>
 * defCountry='RO'; // or 'DE' or whatever
 * zips = { 'DE' : '^\\d{5}$' , 'RO' : '...' };
 * ambitSearchController.init( defCountry , 'countries' , 'zip' , 'radius' , zips );
 * </script>
 * 
 */
var ambitSearchController = function() {
	
	// ----- private ----- 
	// -------------------
	
	// the default country ( siteId ) (string)
	var defaultCountry = null;
	
	// the countries select input (element).
	// or a hidden field with a country.
	var countriesSelect = null;
	
	// the zip text input (element)
	var zipInput = null;
	
	// the radius select box (element)
	var radiusSelect = null;
	
	// maps country code to zip regular expression (hash)
	var countries = null;
	
	// store for zip searches ( maps country to last entered zip ) (hash)
	var zipStore = {};
	
	// if countries is an hidden field (bool)
	var countriesHidden = false;
	
	/**
	 * Restore the zip code for the current selected country.
	 * Called on country-selection change.
	 */
	var restoreZip = function() {
		var country = Field.getValue( countriesSelect );
		var zip = null;
		if ( isCurrentCountrySupportsGeoSearch() ) {
			zip = zipStore[ country ];
		}
		if ( zip == null )
			zip = "";
		zipInput.value = zip;
		checkZipValid();
	};
	
	/**
	 * Store the zip code for the current selected country.
	 * Called on zip text change.
	 */
	var storeZip = function() {
		var country = Field.getValue( countriesSelect );
		var zip = zipInput.value;
		zipStore[ country ] = zip;
	};
	
	/** returns if the current zip is valid ( check against
	 * the zip pattern of the current selected country )
	 */
	var isZipValid = function() {
		var zip = Field.getValue( zipInput );
		if ( zip == null || zip == "" )
			return false;
		
		var currentCountry = Field.getValue( countriesSelect );
		var re = countries[ currentCountry ];
		if ( re == null )
			return false;
		
		// create a regular expression and replace the stored string 
		if ( typeof re == "string" ) {
			re = new RegExp( re );
			countries[ currentCountry ] = re;
		}
		
		return zip.match( re );
		
	};

	
	/** 
	 * Check if the current zip is valid,
	 * and enable/disable the radius select.
	 */
	var checkZipValid = function() {
		var valid = isZipValid();
		
		if ( valid ) {
			// enable
			Field.enable( radiusSelect );
			// select 100
			for ( var i = 0; i < radiusSelect.options.length; i++ ) {
				if ( radiusSelect.options[i].value == "100"  ) {
					radiusSelect.options[i].selected = true;
					break;
				}
			}
		}
		else {
			// select first options and disable
			radiusSelect.options[0].selected = true;
			radiusSelect.disabled = true;
		}
		
	};
	
	/**
	 * checks if the current selected country
	 * supports geo search.
	 * 
	 * The check is agains the ref data: if a zip regular expression
	 * for the country exists, then it supports geo search.
	 * 
	 * if the countriesSelect is a hidden field, and not
	 * a select element, assume support for geo search.
	 */
	var isCurrentCountrySupportsGeoSearch = function() {
		var currentCountry = Field.getValue( countriesSelect );
		return currentCountry != null && countries[ currentCountry ] != null;
	};
	
	
	// ----- public -----
	// ------------------

	return {
		
		/** 
		 * init the controller.
		 * 
		 * param defCountry : symbol of the default country ( site id ) (string)
		 * param countriesSelect : countries select input id or element.
		 * 			this can be either a select element, or a hidden input containing
		 * 			the country code of the current country.
		 * param zipInput : zip input id or element.
		 * param radiusSelect : radius select id or element
		 * param countries : hash in the format :
		 * 		{ 'DE' : 'zipRegularExpression' } 
		 */
		init : function( _defCountry , _countriesSelect , _zipInput , _radiusSelect , _countries) {
			defaultCountry = _defCountry;
			countriesSelect = $(_countriesSelect);
			zipInput= $(_zipInput);
			radiusSelect= $(_radiusSelect);
			countries = _countries;
			countriesHidden = countriesSelect.nodeName.toLowerCase() == "input";
			storeZip();
			
			// if the default country does not have a zip validation
			// hence, it does not support geo search,
			// we disable the zip search input. this is a temporal measure
			// to avoid problems until geo search is enabled for
			// a new site.
			if ( countries[ _defCountry ] == null ) {
				Field.disable( zipInput );
			}
		},
		
		/** 
		 * called when the country select input changes value.
		 */
		onCountryChange : function() {
			restoreZip();
		},
		
		/**
		 * event listener for the zip input change event.
		 * 
		 * if the current country does not support zip,
		 * change the country to the default.
		 * 
		 * if ths zip is valid, enable the radius select,
		 * otherwize, disable it.
		 */
		onZipChange : function() {
			var zip = Field.getValue( zipInput); 
			if ( countriesHidden ) {
				if ( zip == null || zip == "" )  
					countriesSelect.value = "";
				else
					countriesSelect.value = defaultCountry
			}
			else if ( ! isCurrentCountrySupportsGeoSearch() ) {
				// set countries to default
				for ( var i = 0; i < countriesSelect.options.length ; i++ ) {
					if ( countriesSelect.options[i].value == defaultCountry ) {
						countriesSelect.options[i].selected = true;
						break;
					}
				}
				return;
			}
			
			checkZipValid();
			
			storeZip();
			
		}
		
	};
	
	
}();
	


