/*	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;
}

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
function enableDisableGermanyAsAmbitCountry(){
	if (zipcode.length == 5) {
		try {
			// try to convert to number in order make sure zipcode is a number!
			Number(zipcode);
			// if successfull converted enable Germany as ambitCountry
			document.forms['searchForm'].elements["ambitCountry"].value = "DE";
		} catch (e) {
			document.forms['searchForm'].elements["ambitCountry"].value = "";
		}
	} else {
		document.forms['searchForm'].elements["ambitCountry"].value = "";
	}	
}

function enableDisableZipcodeRadius(zipcode) {	
	if (zipcode.length == 5) {
		try {
			// try to convert to number in order make sure zipcode is a number!
			Number(zipcode);
			// if successfull converted enable zipcodeRadiusField...
			document.getElementById("zipcodeRadius").disabled = false;
			if((document.forms['searchForm'].elements["zipcodeRadius"]) && (document.forms['searchForm'].elements["zipcodeRadius"].value == "")){
				document.forms['searchForm'].elements["zipcodeRadius"].value = "100";
			}
					
		} catch (e) {
			disableZipcodeRadius();
		}
	} else {
		disableZipcodeRadius();
	}
}

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 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 */

function printHits(hits, isExtensionHitscounter){
	var thousandSeparator = ".";
	switch(language){
		case "en":
			thousandSeparator = ",";
			break;
		case "fr":
			thousandSeparator = " ";
			break;
	}
	if (hits.length > 3){
		if ((hits.length > 3) && (hits.length <= 6)) {
			hits = hits.substring(0, (hits.length-3)) + thousandSeparator + hits.substring((hits.length-3), (hits.length));
		} else if ((hits.length > 6) && (hits.length <= 9)) {
			hits = hits.substring(0, (hits.length-6)) + thousandSeparator + hits.substring((hits.length-6), (hits.length-3)) + thousandSeparator + hits.substring((hits.length-3), (hits.length));
		} else if ((hits.length > 9) && (hits.length <= 12)) {
			hits = hits.substring(0, (hits.length-9)) + thousandSeparator + hits.substring((hits.length-9), (hits.length-6)) + thousandSeparator + hits.substring((hits.length-6), (hits.length-3)) + thousandSeparator + hits.substring((hits.length-3), (hits.length));
		}
	}
	if(isExtensionHitscounter){
		if ($('extensionHitsCounter0')) {
				$('extensionHitsCounter0').update(hits);
	    		highlightCounter("extensionHitsCounter0");
		    	window.setTimeout('delightCounter("extensionHitsCounter0")', 150);
		}
	}else{ 
		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 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);	
}

function submitSearchForExtendedHits(){
alert("TODO");
	for(var i = 0; i < document.forms['searchForm'].elements['siteIds'].length; i++){
		var field = document.forms['searchForm'].elements['siteIds'][i];
		if(field.type == 'checkbox'){
			field.click();
		} 
	}  
	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));
	    }
	}
    
    
    params += '&lang=' + language;
    
   	new Ajax.Request("models.html", {
			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){
	if(go2searchMask){
		document.forms["searchForm"].isSearchRequest.disabled = true;
		document.forms["searchForm"].editSearch.disabled = false;		
		document.forms["searchForm"].editSearch.value = 1;
	}else{
		document.forms["searchForm"].editSearch.disabled = true;
		document.forms["searchForm"].isSearchRequest.disabled = false;		
		document.forms["searchForm"].isSearchRequest.value = "true";
	}
	if(document.forms["searchForm"].zipcodeRadius != null && document.forms["searchForm"].zipcodeRadius.value != ""){
		document.forms["searchForm"].ambitCountry.value = "DE";
	}
	document.forms["searchForm"].submit();
}

function changeHiddenSortByField(searchFieldName) {
	document.getElementById('sortBy').value = searchFieldName;
}

function changePriceSortBySelectOption(priceSearchFieldName) {
	// price option is the first option in the selection list!!!!!
	document.getElementById('sortBy').options[0].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 switchUrl = location.href.replace(/\?.*$/, "?" + "editSearch=1&switchRandom=" + Math.random() + "&" + Form.serialize($('formForSearch')));
	//alert(switchUrl.replace(/&/g,"\n&"));
	location.href = switchUrl;
}

