// The three global variables below are named here for the sake of clarity.
// They are assigned a value in quickSearch.js, searchResults.jsp and advert.jsp
//var endecaSearchLogMessageActionUrl;
//var endecaSearchGarajActionUrl;
//var endecaSearchActionPath;
var fromNV="n";
var bestbuyvalue="";
var loadMPU = 0;
var pageLoaded = false;
var oldspn = "",oldsmlc = "";

var isIE6 = (navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) && (navigator.userAgent.toLowerCase().indexOf('msie 7') == -1);

function blockEnter(evt) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode :((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13) {
        return false;
    } else {
        return true;
    }
}

if (typeof(pageIdCookieParas) != 'undefined') {
//document.cookie = "pageIdCookieParas" + '=' + pageIdCookieParas + "; expires=-1; domain=.autotrader.co.uk; path=/";
var date = new Date();
date.setTime(date.getTime() + ("1" * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = "pageIdCookieParas" + '=' + pageIdCookieParas + expires + "; domain=.autotrader.co.uk; path=/";
}

//help for Netscape browsers starts here
function checkAndUpdateValue(elementName)
{
  formElement = $(elementName);
  if(formElement==null)
      {
      }
      else
      {
        if(elementName=='e_mmao_only')
		{
			if(!formElement.checked)
				formElement.checked=false;		
		}
		else
		{
	      	formElement.selectedIndex = 0;
	  	    formElement.value = "";
    	}
      }
}

function pushOverlayBGElementIntoBody(){
	
	if(isQuickRequest() && !document.getElementById("overlayBG")){
	
		var elel = document.createElement('div');
		elel.setAttribute('id','overlayBG');
	
		var elelappearBG = document.createElement('div');
		elelappearBG.setAttribute('id',"appearBG");
	
		var eleluserSearchesOverlay = document.createElement('div');
		eleluserSearchesOverlay.setAttribute('id','userSearchesOverlay');
		eleluserSearchesOverlay.setAttribute('style','display:none');
	
		var elelNIOverlay = document.createElement('div');
		elelNIOverlay.setAttribute('id','NIOverlay');
		elelNIOverlay.setAttribute('style','display:none');
	
		elel.appendChild(elelappearBG); 
		elel.appendChild(eleluserSearchesOverlay); 
		elel.appendChild(elelNIOverlay); 
	
		var overlayBGBodyElement = document.getElementsByTagName("body")[0];
		if(overlayBGBodyElement){
			overlayBGBodyElement.appendChild(elel);
		}
	}
	
}


function checkAndUpdateValues()
{
	//cars
      checkAndUpdateValue('e_source');
      checkAndUpdateValue('e_make');
      checkAndUpdateValue('e_model');
      checkAndUpdateValue('e_bodystyle');
      checkAndUpdateValue('e_fuel');
      checkAndUpdateValue('e_mileage');
//      checkAndUpdateValue('e_min_pr');
      checkAndUpdateValue('e_max_pr');
      checkAndUpdateValue('e_colour');
      checkAndUpdateValue('e_enginecc');
      checkAndUpdateValue('e_doors');
      checkAndUpdateValue('e_maximumage');
      checkAndUpdateValue('e_transmission');
      checkAndUpdateValue('e_mmao_only');

	//additions from new cars
      checkAndUpdateValue('e_cardealer');
      checkAndUpdateValue('e_prereg');
      checkAndUpdateValue('e_variant');
      checkAndUpdateValue('e_edition');

	//additions from plant
      checkAndUpdateValue('e_poa');
      
}
//ends here

// window onload function, used in conjuction of banner refresh on form change DB
function addEvent(obj, evType, fn) {
        if (obj.addEventListener) {
            obj.addEventListener(evType, fn, false);
            return true;
        } else if (obj.attachEvent) {
            var r = obj.attachEvent("on" + evType, fn);
            return r;
        } else {
            return false;
        }
    }



// this was copied and modified from prototype_v1_5_0.js
function $(element)
{
	if (arguments.length > 1)
	{
		for (var i = 0, elements = []; i < arguments.length; i++)
		{
			elements.push($(arguments[i]));
		}
		return elements;
	}
	return document.getElementById(element);
}

function GetActionResponseAsJavaScriptRequest(args)
{
	this.scriptTagId = (new Date()).getTime();
	this.url = args.url;
	this.destinationPath = args.destinationPath;
	this.responseHandler = args.responseHandler;
	this.onComplete = args.onComplete;
	this.onError = args.onError;
	this.parameters = args.parameters;
	this.action = args.action;
	
	this.execute = function()
	{
		var requestUrl = this.url;
		if (requestUrl.indexOf("?") > 0)
		{
			if (requestUrl.charAt(requestUrl.length - 1) != "&")
			{
				requestUrl = requestUrl + "&";
			}
		}
		else
		{
			requestUrl = requestUrl + "?";
		}
		requestUrl = requestUrl + "destinationPath=" + 
		    encodeURIComponent(this.destinationPath);
		if (this.responseHandler != null && this.responseHandler.length > 0)
		{
			requestUrl = requestUrl + "&responseHandler=" + 
			    encodeURIComponent(this.responseHandler);
		}
		requestUrl = requestUrl + "&onComplete=";
		if (this.onComplete != null && this.onComplete != "")
		{
			requestUrl = requestUrl + encodeURIComponent(this.onComplete);
			if (requestUrl.charAt(requestUrl.length - 1) != ";")
			{
				requestUrl = requestUrl + ";";
			}
			requestUrl = requestUrl + "\n";
		}
		requestUrl = requestUrl + encodeURIComponent("logRefreshTime(" + 
			(new Date()).getTime());
		if (this.action)
		{
			 requestUrl = requestUrl + ", '" + this.action + "'";
		}
		requestUrl = requestUrl + ");";
		if (this.onError != null && this.onError.length > 0)
		{
			requestUrl = requestUrl + "&onError=" + 
			    encodeURIComponent(this.onError);
		}
		if (this.parameters != null && this.parameters.length > 0)
		{
		    if (this.parameters.charAt(0) != "&")
		    {
		        requestUrl = requestUrl + "&";
		    }
		    requestUrl = requestUrl + this.parameters;
		}
		requestUrl = requestUrl + "&cacheBuster=" + this.scriptTagId;
		
		var scriptTag = document.createElement("script");
		scriptTag.setAttribute("id", this.scriptTagId);
		scriptTag.setAttribute("type", "text/javascript");
		scriptTag.setAttribute("src", requestUrl);
		
		var headElement = document.getElementsByTagName("head").item(0);
		headElement.appendChild(scriptTag);
	}
}

function logMessageToServer(message)
{
	var uniqueId = (new Date()).getTime();
	var scriptTag = document.createElement("script");
	scriptTag.setAttribute("id", "LogMessageToServer" + uniqueId);
	scriptTag.setAttribute("type", "text/javascript");
	scriptTag.setAttribute("src", endecaSearchLogMessageActionUrl + 
		encodeURIComponent(message) + "&cacheBuster=" + uniqueId);
	var headElement = document.getElementsByTagName("head").item(0);
	headElement.appendChild(scriptTag);
}

function logRefreshTime(startTime, action)
{
	var refreshTime = (new Date()).getTime() - startTime;
	var message = "Time taken to ";
	if (action)
	{
		message = message + action;
	}
	else
	{
		message = message + "refresh";
	}
	message = message + ": " + refreshTime + "ms";
	logMessageToServer(message);
}

function whichSearchForm()
{
	
	if ($("newqSearchForm") && $("newqSearchForm").innerHTML !=null)	{		
		return activeSearchForm = document.newadvancedSearch.elements;
	}
	else
	{
		return activeSearchForm = document.advancedSearch.elements
	}	
}

function showSearchFormFields()
{
	activeSearchForm = whichSearchForm();
	for (var i = 0; i < activeSearchForm.length; i++)
	{
		activeSearchForm[i].style.visibility = "visible";
	}
}

function hideSearchFormFields()
{
	whichSearchForm();
	for (var i = 0; i < activeSearchForm.length; i++)
	{
		activeSearchForm[i].style.visibility = "hidden";
	}
}

function whichBusyIndicator()
{

		return	activeBusyIndicator = $("busyIndicator");
	
}

function hideLoadingOverlay()
{
	whichBusyIndicator();
	
	if (!$("usedCarsQsearch")&&!$("newCarsQsearch") )
	{
		activeBusyIndicator.className = activeBusyIndicator.className.replace("busyShow busyHideOverlay", "busyHide");	
	}
	else
	{
		activeBusyIndicator.className = activeBusyIndicator.className.replace("busyShow qBusyHideOverlay", "busyHide");	
	}
}

function showLoadingOverlay()
{
	hideSearchFormFields();
	// Hide cursor if user presses enter on postcode overlib textbox, problem only occurs in firefox
	if (document.getElementById('pcode')) {document.getElementById('pcode').blur();}
	if (!$("usedCarsQsearch")&&!$("newCarsQsearch") )
	{
		whichBusyIndicator();
		$("formButtons").className = "hidden floatRight topMargin7";
		
		activeBusyIndicator.className = activeBusyIndicator.className.replace("busyHide","busyShow busyHideOverlay");
	}
	else
	{
		whichBusyIndicator();		
		activeBusyIndicator.className = "busyShow qBusyHideOverlay";	
		
		
	}
}

function helpPrompt(text)
{
	// help text for change values	
	var pc = false;
	
	if (text == "postcode")
	{
		pc = true; 
		text = "Type in your post code and select a maximum distance<br />*A postcode is required to calculate the vehicles distance";
	}
	else if (text == "qPostcode")
	{
		text = "Don't want to travel far for a test drive? <br/>*A postcode is required to calculate the vehicles distance ";
		 //hide dropdowns for IE6
	}
	
	else if (text == "newPostcode")
	{
		text = "Don't want to travel far for a test drive? <br/>*A postcode is required to calculate the vehicles distance ";
		 //hide dropdowns for IE6
	}
	
	else if (text == "mmao")
	{
		text = "Show adverts that allow you to make an offer <br/>on a car, direct to a dealer by e-mail";
	}
	else if (text == "keywords")
	{
		text = "Want leather upholstery or a CD player? <br/>Type in your requirements here";
	}
	else if ((text == "plantKeywords")||(text == "vansKeywords")||(text == "caravansKeywords")||(text == "trucksKeywords")||(text == "bikesKeywords"))
	{
		text = "Specify the type of vehicle or your requirements here";
	}
	// help text for contracted out values
	else if (text == "oneMake")
	{
		text = "Based on your current selection, <br/>only this make is available.";
	}
	else if (text == "oneModel")
	{
		text = "Based on your current selection, <br/>only this model is available.";
	}
	else if (text == "oneVariant")
	{
		text = "Based on your current selection, <br/>only this sub-model is available.";
	}
	else if (text == "oneTrim")
	{
		text = "Based on your current selection, <br/>only this edition is available.";
	}
	else if (text == "oneCarType")
	{
		text = "Based on your current selection, <br/>only this car type is available.";
	}	
	else if (text == "oneBody")
	{
		text = "Based on your current selection, <br/>only this vehicle type is available.";
	}
	else if (text == "oneColour")
	{
		text = "Based on your current selection, <br/>only this colour is available.";
	}
	else if (text == "oneEngine")
	{
		text = "Based on your current selection, <br/>only this engine size is available.";
	}
	else if (text == "oneMinPrice")
	{
		text = "Based on your current selection, <br/>only this minimum price is available.";
	}
	else if (text == "oneMaxPrice")
	{
		text = "Based on your current selection, <br/>only this maximum price is available.";
	}
	else if (text == "oneMaxMileage")
	{
		text = "Based on your current selection, <br/>only this maximum Mileage is available.";
	}
	else if (text == "oneMaxAge")
	{
		text = "Based on your current selection, <br/>only this age is available.";
	}
	else if (text == "oneTransmission")
	{
		text = "Based on your current selection, <br/>only this transmission type is available.";
	}
	else if (text == "oneDoors")
	{
		text = "Based on your current selection, <br/>only this number of doors is available.";
	}
	else if (text == "onePrivateTradeAds")
	{
		text = "Based on your current selection, <br/>only this type of advert is available.";
	}
	else if (text == "oneFuel")
	{
		text = "Based on your current selection, <br/>only this fuel type is available.";
	}
	else if (text == "POA Only")
	{
		text = "Based on your current selection, <br/>only POA adverts are available.";
	}
	
	else if (text == "Priced Only")
	{
		text = "Based on your current selection, <br/>only priced adverts are available.";
	}
	else if (text == "onePreReg")
	{
		text = "Based on your current selection, <br/>only this type of advert is available.";
	}
	
	else if (text == "preReg")
	{
		text = "New cars are unregistered with no miles on the clock.<br/>Pre-reg cars have been registered by a dealer and have delivery miles on the clock.";

	}
	
	else if (text == "oneLocal")
	{
		text = "Based on your current selection, <br/>only this type of advert is available.";
	}
	
		else if (text == "localAdvert")
	{
	
		text = " 'Nearest adverts' will show dealers with a forecourt. <br />'National adverts' will show all dealers, with the ability to deliver anywhere in the UK";
	}
	
	
	

	
	//help overlay call
	
	


	
		//Else don't Hide the skyscraper
		//Need to only hide select boxes in IE6 and on advanced search - hiding select boxes on quick search causes problem with postcode error message
		if (isQuickRequest()) {
		overlib('<strong>' + text + '</strong>', STICKY, ABOVE, RIGHT, TIMEOUT, 5000, FGCLASS, 'helpOverlib', VAUTO, BGCOLOR, '#000000', WRAP, CGCOLOR, '#000000', TEXTPADDING, 3);
		}
		else
		{
		overlib('<strong>' + text + '</strong>', STICKY, ABOVE, RIGHT, TIMEOUT, 5000, FGCLASS, 'helpOverlib', HIDESELECTBOXES, VAUTO, BGCOLOR, '#000000', WRAP, CGCOLOR, '#000000', TEXTPADDING, 3);
		}
	
	
	if ($("errorMessage")) {hideSearchFormFields();}
	
}

// Check to see if results are displaying.
// When form refreshes and results are display change the button to say update results. - required for usability
function changeSubmitButton()
{
	displayShowButton();	
	document.getElementById('showButton').focus();
}

function displayUpdateButton()
{
	document.getElementById('showButton').style.display = "none";
	document.getElementById('updateButton').style.display = "block";	
	
	//Javascript call to take away the blue selection, so that if user scrolls or uses 
	//the scroll ball on mouse the page doesn't jump, have taken this of the onload so it doesn't wait for the banners to load -
	document.getElementById('updateButton').focus();
}

function displayShowButton()
{
	document.getElementById('showButton').style.display = "block";
	document.getElementById('updateButton').style.display = "none";	
	
	//Javascript call to take away the blue selection, so that if user scrolls or uses 
	//the scroll ball on mouse the page doesn't jump, have taken this of the onload so it doesn't wait for the banners to load -
	document.getElementById('showButton').focus();
}

function isQuickRequest()
{
	var referrer = null;
	if ($("referrer") != null)
	{
		referrer = $("referrer").value;
	}
	return referrer == "quick";
}

function checkKeywords()
{
	var keywords = document.advancedSearch.keywords;
	if (keywords && (keywords.value == "e.g. 3 ton" || keywords.value == "e.g. Tipper" || keywords.value == "e.g. SWB or LWB" || keywords.value == "e.g. alarm" || keywords.value == "e.g. awning" || keywords.value == "e.g. TDi Sport" || keywords.value == "Keywords"))
	{
		keywords.value = "";
	}
	var model_keyword = document.advancedSearch.model_keyword;
	if (model_keyword && model_keyword.value == "Any model")
	{
		model_keyword.value = "";
	}
}

function redisplayForm(response)
{
	hideSearchFormFields();
	hideLoadingOverlay();
	if(fromNV=='y')
			$("searchAdvancedOptionNEWVEHICLEHTML").innerHTML = response;
		else	
			$("searchAdvancedOptionHTML").innerHTML = response;
	fromNV="";		
	
	if (typeof loadMakes == "function")
	{
		loadMakes();
		if (typeof loadModels == "function")
		{
			loadModels();
		}
		loadPlantCat();
	}
	
	if ($("NoResContainer"))
	{	
		hideSearchFormFields();
		$("formButtons").className = "hidden floatRight topMargin7";
		
		//Hide Update Message if Timeout error or No vehicles available
		if (($("NoResContainer")) && ($("messageText")))
		{
			$("messageText").className = "hidden";
		}
	}
	
	else if ($("qNoResContainer"))
	{
	$("moreOptionsLink").className = "busyHide tertiaryFontLinkBlack";
	$("searchButton").className = "busyHide";
	if ($("qMake")) {$("qMake").className = "busyHide";}
	if ($("qModel")) {$("qModel").className = "busyHide";	}
	if ($("qMin_pr")) {$("qMin_pr").className = "busyHide";}
	if ($("qMin_pr")) {$("qMax_pr").className = "busyHide";	}
	if ($("qEngineCC")) {$("qEngineCC").className = "busyHide";	}
	
	
		
	}
	
	if (!isQuickRequest() )
	{
		if (!$("noResContainer")) {changeSubmitButton();}
		// flash count call
		showCounter();
		chcolor('jsCounter','0');
		chcolor('jsCounter','0');
		chcolor('jsCounter','0');
		
	}
	else if ((isQuickRequest() )&&(!$("errorMessage")) )
	{
	
		showSearchFormFields();	
		showCounter();
		chcolor('jsCounter','0');
		chcolor('jsCounter','0');
		chcolor('jsCounter','0');
	}
		
	if ($("errorMessage"))
	{
			
		// flash count call		
		hideSearchFormFields();	
		//Hides Quick Search Button so they have to input postcode
		$("searchButton").className = "hidden floatRight topMargin3";			
		$("qMin_pr").className = "bgColorTransparent";
		$("qMax_pr").className = "bgColorTransparent";
		
		
	
	
	
	}
	
	checkAndUpdateValues();	
	updateSearchcookie();
}

function updateSearchcookie(){
	if(document.getElementById("searchpostcode")){
		document.cookie = document.getElementById("searchpostcode").innerHTML;		
	}
}

function changePostcode(response)
{
	hideSearchFormFields();
	hideLoadingOverlay();
	
	if (isQuickRequest())
	{
		
		$("pcContainer").innerHTML = response;
		$("opaqueOverlayID").className = "quickOpaqueOverlay";		
	}
	else
	{
		$("pcContainer").innerHTML = response;
		$("pcOverlayContainerID").className = "pcOverlayContainer";
	}
	
}

function isPostcodePopupOpen()
{
	return $("pcOverlayContainerID") || $("opaqueOverlayID");
}

//If post code starts with 'BT', check for cookie whether user has set not to show the NI popup. 
//If yes, do normal processing, else, show NI popup.
function doNIPopupCheck(showMoreOptions, params, action, newVehicle, fromPostcodePopup){

	if(newVehicle == 'y'){
		doProcessingAfterNIPopup(showMoreOptions, params, action, newVehicle, fromPostcodePopup);
	}else {
		if($('postcode') && $('postcode').value && $('postcode').value.match(/^BT/i)){
			
			if(getNICookie("s_NI")){
				doProcessingAfterNIPopup(showMoreOptions, params, action, newVehicle, fromPostcodePopup);
			} else {
				// show popup
				showNorthernIrelandPopup($('postcode').value, showMoreOptions, params, action, newVehicle);
			}
		} else {
			doProcessingAfterNIPopup(showMoreOptions, params, action, newVehicle, fromPostcodePopup);
		}
	}
}

function doProcessingAfterNIPopup(showMoreOptions, params, action, newVehicle, fromPostcodePopup){

	if(fromPostcodePopup){
		 advancedFormChange(showMoreOptions, params, action, newVehicle); 
	} else {
		// from quick search form?
		if(isQuickRequest()){
			advancedFormChange(showMoreOptions, params); 
		} else {
			// advanced search form
			advancedFormChange(showMoreOptions, params, action); 
		}
	}
}

function showNorthernIrelandPopup(pcode, showMoreOptions, pars, act, newVehicle)
{	  		  		
	// push overlay elements before NI overlay request is sent to server.
	pushOverlayBGElementIntoBody();
	
	var parame = "pcode_apply_params=" + encodeURIComponent(pars) + 
				"&postcode=" + encodeURIComponent(pcode) + "&action="; 
				if(act && typeof(act) != 'undefined'){
					parame+=encodeURIComponent(act);
				}
				parame+="&fmNV=";
				if(newVehicle && typeof(newVehicle) != 'undefined'){
					parame+=newVehicle;
				}
	
	var garajRequest = new GetActionResponseAsJavaScriptRequest(
			{
				url: endecaSearchGarajActionUrl,
				action: "redirect popup",
				destinationPath: endecaSearchActionPath + "NIPopup.action",
				responseHandler: "handleNIPopup",
				onError: "doNothing()",
				parameters:  parame
			});
			garajRequest.execute();
			
}

function handleNIPopup(response){
	showNIOverLay(response);
}

function showNIOverLay(popupHtml)
{
	flashToggle(false);
	frameToggle(false);
	
	document.getElementById("overlayBG").style.display = 'block';
	
	var niOverlay = document.getElementById("NIOverlay");
	niOverlay.style.display = 'none';
	niOverlay.style.left = ((document.documentElement.clientWidth/2) - 221.5) + 'px';
	
	var topOffset = (document.documentElement.clientHeight/2) - 175;
	topOffset = topOffset > 0 ? topOffset : 0;
	//userSearchesOverlay.style.top = (popupHtml.indexOf("id=\"mySavedSearches\"") > 0) ? topOffset + 'px' : (topOffset + 60) + 'px';
	niOverlay.style.top = topOffset + 'px';
	
	popupHtml = '<div class="mainPage" id="NIOverlay">' + popupHtml + '</div>';
	
	niOverlay.innerHTML = popupHtml;	
	niOverlay.style.display = 'block';
	
	//IE6 non fixed position issue
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
	{
		var ieVersion=new Number(RegExp.$1);
		if (ieVersion == 6)
			window.scroll(0,0);
	}	
	
	/* 
	 * page view hits commented as there is an issue with IE6
	 *  
	var locPn="";var locMlc="";
	if(window.spn!=null){
		oldspn=spn;
		locPn=spn;
	}
	if(window.smlc!=null){
		oldsmlc=smlc;
		locMlc=smlc;
	}
	_hbPageView("niOverlay", locMlc);
	*/
}


function doNothing(){
}

function doDynamicPostcodePopupRequest(pcode, showMoreOptions, pars,newVehicle)
{
	if (!isPostcodePopupOpen())
	{
		hideSearchFormFields();
		if ($("vehicleCountContainer"))
		{
			$("vehicleCountContainer").className = "busyHide";
		}
		
		// Shows something is loading
		showLoadingOverlay();
		$('postcode').value = '';
		
		var onError = null;
		if (isQuickRequest())
		{
			onError = "doQuickSearchFormRequestFailed();";
		}
		else
		{
			onError = "window.open('http://www.autotrader.co.uk/500.htm', '_self')";
		}
		
		var garajRequest = new GetActionResponseAsJavaScriptRequest(
		{
			url: endecaSearchGarajActionUrl,
			action: "update postcode",
			destinationPath: endecaSearchActionPath + "postcodePopup.action",
			responseHandler: "changePostcode",
			onError: onError,
			parameters: "pcode_apply_params=" + encodeURIComponent(pars) + 
				"&postcode=" + encodeURIComponent(pcode) + "&fmNV="+newVehicle
		});
		garajRequest.execute();
	}
}

function showVehicleCount()
{
	if ($("vehicleCountContainer"))
	{
		//Shows something loading
		showLoadingOverlay();
	}
}

function submitSearch()
{
	var pcode = $("postcode").value;
	checkKeywords();
	if (pcode == null || pcode == "" || pcode == "Full Postcode")
	{
		var params = $("formSearchParams").value;
		var showMoreOptions = $("showMoreOptions").value;
		doDynamicPostcodePopupRequest(pcode, showMoreOptions, params);
		return false;
	}
	return true;
}

function buildNonDimensionUrlParams()
{
	var params='';
	// If the search form page is requested, the page will not have the sort form defined on it so we check for it's existence
	// before blindly appending it to the url 
	if (document.sortForm)
	{
		params = params + "&sort=" + document.sortForm.sort.value;
	}
	if (document.advancedSearch.keywords)
	{
		//Note: using $("keywords").value in method below doesn't work in IE because on the cars homepage there is a meta tag with a name
		// of 'keywords' which IE picks up and assumes we want this. This is a bug in because it should only look for html elements with
		// an id of 'keywords' - this is why we use document.advancedSearch syntax
		params = params + "&keywords=" + encodeURIComponent(document.advancedSearch.keywords.value);
	}
	if ($("cab"))
	{
		params = params + "&cab=" + encodeURIComponent(document.advancedSearch.cab.value);
	}
	if ($("axle"))
	{
		params = params + "&axle=" + encodeURIComponent(document.advancedSearch.axle.value);
	}
	if ($("referrer"))
	{
		params = params + "&referrer=" + document.advancedSearch.referrer.value;
	}
	if ($("make_keyword"))
	{
		params = params + "&make_keyword=" + encodeURIComponent(document.advancedSearch.make_keyword.value);
	}
	if ($("model_keyword"))
	{
		params = params + "&model_keyword=" + encodeURIComponent(document.advancedSearch.model_keyword.value);
	}
	if ($("category_keyword"))
	{
		params = params + "&category_keyword=" + encodeURIComponent(document.advancedSearch.category_keyword.value);
	}
	if ($("postcode"))
	{
		params = params + "&postcode=" + encodeURIComponent($("postcode").value);
	}
	if ($("radius"))
	{
		params = params + "&radius=" + document.advancedSearch.radius.value;
	}
	
	if ($("e_dealer_status"))
	{
		params = params + "&e_dealer_status=" + $("e_dealer_status").value;
	}
	return params;
}

function doQuickSearchFormRequestFailed()
{
	html = "<div id='searchUnavail' class='searchUnavailContainer'>" +
		"<h2 class='errorHeading'>Search temporarily unavailable</h2>" + 
		"<p class='topMargin5 textAlignCenter'>Please " +
		"<a href='javascript:loadQuickSearchForm();'><strong>try again" +
		"</strong></a> in a few minutes</p><br/><br/></div>";
	
	if ($("moreOptionsLink"))
	{
		$("moreOptionsLink").className = "invisible";
	}
	if ($("qSearchForm"))
	{
		$("qSearchForm").innerHTML = html;
	}
	else
	{
		$("searchAdvancedOptionHTML").innerHTML = html;
	}
	
	checkAndUpdateValues();
}
		var checkfortheforce;
		function multimpuforce(){
		if(typeof calltheadvertmpu=='function'){
		calltheadvertmpu('1');
		clearInterval(checkfortheforce);
		}else{return false;
		}}

		
function setPageLoaded() { pageLoaded=true;}


function hideBanners() {
	
		if ($("carsOuterContainer")) {	
			if ($("tempBannerContainer")) { $("tempBannerContainer").className = "busyHide";	} 	
			if ($("tempBanner2Container")) { $("tempBanner2Container").className = "busyHide";} 
			if ($("tempResultsTopRightMPU")) { $("tempResultsTopRightMPU").className = "busyHide";	}
			if ($("topResultsRightMPU")) { $("topResultsRightMPU").className = "busyHide ";	}
		}
		else if ($("newCarOuterContainer") ) {
			if ($("tempBanner2Container")) {$("tempBanner2Container").className = "busyHide ";}
		}
		else {
			if ($("tempResultsTopRightMPU")) { $("tempResultsTopRightMPU").className = "busyHide";	}
			if ($("topResultsRightMPU")) { $("topResultsRightMPU").className = "busyHide ";	}
			if ($("tempBanner2Container")) {$("tempBanner2Container").className = "busyHide ";} 
		}

}

function displayMPULandingBanners() {
			loadMPU = 1;
			hideBanners(); // hide Banners whilst loading
			if (pageLoaded==true)  {		
			hideBanners(); // hide after loaded in case missed whilst page was loading
			setTimeout("calltheadvertmpu('1')", 500);
			}else { setTimeout("displayMPULandingBanners()", 1500); } 
}

function hideResultsOverlay() {
	
	if ($("hideResultsOverlay") && $("hideBottomOverlay") && $("hideResultsMessage") )
	{
	$("hideResultsOverlay").className = "busyHide";
		if($("hideBottomOverlay")) {
			$("hideBottomOverlay").className = "busyHide";
		}
		
		if($("hideResultsMessage")) {
			$("hideResultsMessage").className = "busyShow";	
		}
		
		if ($("topSponsoredPosition") && $("tempSponsoredAdResult") )
		{
		$("topSponsoredPosition").className = "busyHide";	
		$("tempSponsoredAdResult").className = "busyHide";
		if ($("hideResultsMessage"))	{	$("hideResultsMessage").className = "moveShowText"; $("noSearchFooter").className = "moveNoSearchFooter";}
		}
		
	}
	else
	{
		setTimeout("hideResultsOverlay()", 0);
	}
}

function doDynamicSearchFormRequest(showMoreOptions, pars, action,newVehicle)
{
	
	// show an indicator in the search form to let user know we are doing something 
	if ($("vehicleCountContainer"))
	{
		$("vehicleCountContainer").className = "busyHide";
	}
	
	if ($("hideResultsOverlay"))
	{
		
		hideResultsOverlay()
		setTimeout("displayMPULandingBanners()", 0);		
		
		
	}
	
	showLoadingOverlay();	
	var destinationPath = endecaSearchActionPath;
	var onError = null;
	
	if (isQuickRequest())
	{
		destinationPath = destinationPath + "quick_search_form.action";
		onError = "doQuickSearchFormRequestFailed();";
	}
	else
	{
		if(newVehicle=="y" ){
				fromNV='y';
				destinationPath = destinationPath + "searchAdvancedOptionsNewVehicle.action";
				}
			else
				destinationPath = destinationPath + "searchAdvancedOptions.action";
		onError = "window.open('http://www.autotrader.co.uk/500.htm', '_self')";
	}
	
	var garajRequest = new GetActionResponseAsJavaScriptRequest(
	{
		url: endecaSearchGarajActionUrl,
		action: action,
		destinationPath: destinationPath,
		responseHandler: "redisplayForm",
		onError: onError,
		parameters: "formparams=" + encodeURIComponent(pars) + 
			buildNonDimensionUrlParams()
	});
	
	garajRequest.execute();
	
	if (isIE6){
		doIe6pause(2000);
	}
}


function advancedFormChange(showMoreOptions, params, action,newVehicle)
{
	var pcode = $("postcode").value;
	if (pcode != null && pcode != "" && pcode != "Full Postcode" && pcode != "Full postcode")
	{
		checkKeywords();		
		doDynamicSearchFormRequest(showMoreOptions, params, action,newVehicle);
	} 
	else
	{
		// force user to enter postcode before they can use form		
		doDynamicPostcodePopupRequest(pcode, showMoreOptions, params,newVehicle);
	}
}

function advancedFormChangeAvoidPostCode(showMoreOptions, params, action,newVehicle)
{		
/*	
	var pcodeAvoid=$("postcode").value;
		if(pcodeAvoid==null || pcodeAvoid=="")
		{
			$("postcode").value = "Post Code";
		}	
	*/	
	checkKeywords();
		doDynamicSearchFormRequest(showMoreOptions, params, action,newVehicle);
}

function advancedFormChangeLocalDealer(showMoreOptions, params, action,newVehicle,localDealerCode)
{
	//292 Endeca constant for Local Dealers
	if(params.indexOf(localDealerCode)==-1)
	{
		advancedFormChangeAvoidPostCode(showMoreOptions, params, action,newVehicle);
	}
	else
	{ 
		advancedFormChange(showMoreOptions, params, action,newVehicle);
	}
}

function setNationalAdvertChanged()
{
	$('e_dealer_status').value = 'changed';
}

/*
 * The following functions relate to the clipboard 
 */
var isUpdatingClipboard = false;


function showMaxItemsReachedOverlay(searchbase)
{
	var text = "<div class=\"semiTransBack noMoreClip\"><strong><img src=\"http://search-cache.autotrader.co.uk/es-uk/img/Icons/exclamation.gif\" align=\"left\" border=\"0\" width=\"11\" height=\"11\" vspace=\"1\" />Your compare list is full. Remove a vehicle from your <a href=\"javascript:void(0);\" onClick=\"javascript:compareAdverts('comparator.action?searchtargetbase=" + searchbase + "', 'results','" + searchbase + "'";
	text=text + "); return false;\" target=\"_self\">compare list</a> to add this vehicle.</strong></div>";
	overlib(text, NOCLOSE, AUTOSTATUS, WRAP, NOFOLLOW, TIMEOUT, 4000, BORDER, 0, BGCOLOR, "", FGCOLOR, "", ABOVE, RIGHT, WIDTH, 250, HIDESELECTBOXES);

//	overlib("<div class=\"semiTransBack noMoreClip\"><strong><img src=\"http://search-cache.autotrader.co.uk/es-uk/img/Icons/exclamation.gif\" align=\"left\" border=\"0\" width=\"11\" height=\"11\" vspace=\"1\" />Your compare list is full. Remove a vehicle from your <a href=\"javascript:void(0);\" onClick=\"javascript:compareAdverts('comparator.action', 'results',searchbase); return false;\" target=\"_self\">compare list</a> to add this vehicle.</strong></div>", NOCLOSE, AUTOSTATUS, WRAP, NOFOLLOW, TIMEOUT, 4000, BORDER, 0, BGCOLOR, "", FGCOLOR, "", ABOVE, RIGHT, WIDTH, 250, HIDESELECTBOXES);
}

function updateClipboardAdLinks(advertId, clipboardAction)
{
	if (clipboardAction == "add")
	{
		$(advertId + "_Rem").className = "clipLinkShow";
		$(advertId + "_Add").className = "clipLinkHide";
	}
	else
	{
		$(advertId + "_Rem").className = "clipLinkHide";
		$(advertId + "_Add").className = "clipLinkShow";
	}
}

function updateClipboardPageData(response, advertId, clipboardAction,searchbase)
{
	document.getElementById("rightBoxContainer").innerHTML = response;
	clipboardCountResponse = document.getElementById("clipboardCount").innerHTML;
	
	if (clipboardCountResponse != "MaxLimitReached")
	{
		if ($("clipboardCounterTop"))
		{
			$("clipboardCounterTop").innerHTML = clipboardCountResponse;
			$("clipboardCounterBottom").innerHTML = clipboardCountResponse;
			updateClipboardAdLinks(advertId, clipboardAction);
		}
	}
	else
	{
		showMaxItemsReachedOverlay(searchbase);
	}
}

function showClipboardActionIndicator(action, referrer)
{
	var html;
	if (action == "add")
	{
		html = "<div class=\"semiTransBack\"><div class=\"addClip\"><img src=\"http://search-cache.autotrader.co.uk/es-uk/img/Icons/loader.gif\" align=\"left\" border=\"0\" width=\"16\" height=\"16\" border=\"0\"><strong>Adding to compare list</strong><div></div>";
	}
	else
	{
		html = "<div class=\"semiTransBack\"><div class=\"removeClip\"><img src=\"http://search-cache.autotrader.co.uk/es-uk/img/Icons/loader.gif\" align=\"left\" border=\"0\" width=\"16\" height=\"16\" border=\"0\" ><strong >Removing from compare list</strong><div></div>";
	}
	overlib(html, WRAP, TIMEOUT, 2500, BORDER, 0, BGCOLOR, "", FGCOLOR, "", ABOVE, RIGHT, STICKY);
}

function clipboardAction(advertId, referrer, clipboardAction,searchbase,capId)
{
	if (isUpdatingClipboard)
	{
		overlib("<div class=\"semiTransBack noMoreClip\"><strong>Please wait until the vehicle has been added to the compare list before adding another vehicle.</strong></div>", NOCLOSE, AUTOSTATUS, WRAP, NOFOLLOW, TIMEOUT, 4000, BORDER, 0, BGCOLOR, "", FGCOLOR, "", ABOVE, RIGHT, WIDTH, 250, HIDESELECTBOXES);
	}
	else
	{
		isUpdatingClipboard = true;
		showClipboardActionIndicator(clipboardAction, referrer);
		var garajRequest = new GetActionResponseAsJavaScriptRequest(
		{
			url: endecaSearchGarajActionUrl,
			destinationPath: endecaSearchActionPath + "clipboard.action",
			parameters: "clipboard=" + clipboardAction + "&id=" + advertId +"&searchtargetbase="+searchbase+"&capId="+capId,
			onComplete: "updateClipboardPageData(endecaSearchActionResponse, '"
				+ advertId + "', '" + clipboardAction +  "','"+ searchbase+
				"');\nisUpdatingClipboard = false;"
		});
		garajRequest.execute();
	}
}

function clipboardAdd(advertId, referrer,searchbase,capId)
{
	clipboardAction(advertId, referrer, "add",searchbase,capId);
}

function clipboardRemove(advertId, referrer,searchbase)
{
	clipboardAction(advertId, referrer, "remove",searchbase);
}

function showNotEnoughItemsToCompareOverlay(referrer)
{
	var overlib2Str = 'overlib';
	var html;
	if (referrer=='clipboard')
	{
		// the clipboard is rendered by an overlay, so the only way to display an overlay on top of this one
		// is to use the overlib2 method call
		overlib2Str = 'overlib2';
	}
	html ="<div id=\"noClipCompare\" class=\"semiTransBack\"><strong><img src=\"http://search-cache.autotrader.co.uk/es-uk/img/Icons/exclamation.gif\" align=\"left\" border=\"0\" width=\"11\" height=\"11\" />Your compare list is empty, add a vehicle to continue.</strong></div>"	;
	eval(overlib2Str + "(html, NOCLOSE, BORDER,0, BGCOLOR,'', FGCOLOR,'', REFC, 'LL', WRAP, NOFOLLOW, TIMEOUT, 3000, HIDESELECTBOXES)");
}

function doCompare(response, url, referrer)
{
	if (response < 1)
	{
		showNotEnoughItemsToCompareOverlay(referrer);
	}
	else
	{
		window.open(url, '_self');
	}
}

function compareAdverts(comparatorUrl, referrer,searchbase)
{
	var garajRequest = new GetActionResponseAsJavaScriptRequest(
	{
		url: endecaSearchGarajActionUrl,
		destinationPath: endecaSearchActionPath + "clipboard.action",
		parameters: "clipboard=get_count&searchtargetbase="+searchbase,
		onComplete: "doCompare(endecaSearchActionResponse, '" + comparatorUrl + 
			"', '" + referrer + "');"
	});
	garajRequest.execute();
}

function getNICookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function setNICookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function handleNIPopupClick(lid, lpos, params, action, frmv, setcookie){
	
	_hbLink(lid, lpos);
	closeNIOverLay();
	if(setcookie){
		setNICookie('s_NI','true', '10000', '/');
	}
	
	doProcessingAfterNIPopup('',params, action, frmv);
	
}

function doIe6pause(numberMillis) { 
    var dialogScript =  
       'window.setTimeout(' + 
       ' function () { window.close(); }, ' + numberMillis + ');'; 
    var result =  
// For IE5. 
     window.showModalDialog( 
       'javascript:document.writeln(' + 
        '"<script>' + dialogScript + '<' + '/script>")'); 
 } 


function closeNIOverLay()
{

	var niOverlay = document.getElementById("NIOverlay");
	niOverlay.style.display = 'none';
	document.getElementById("overlayBG").style.display = 'none';

	flashToggle(true);
	frameToggle(true);

	/* 
	 * page view hits commented as there is an issue with IE6
	 *  
	_hbPageView(oldspn, oldsmlc);
	*/

}