
function pagefix() {
	//admin column
	var admin = document.getElementById("pgs2");
	if(admin && admin.innerHTML.indexOf("class")!=-1){ //check if right column has content, then check if admin width applied
		var pgContainer = admin
		while(pgContainer != null && pgContainer.className!="pgContainer")pgContainer = pgContainer.parentNode;
		if(pgContainer.offsetWidth<1100){
			addCSSRule(".pgContainer","width:1200px;")
			admin.style.display = "block";
		}
	}
	var eml1= "contactus";	
	var eml2 = "buyacar";
	var eml = document.getElementById('email1');
	if(typeof(URLpgAnchor)!="undefined" && URLpgAnchor !=""){
		window.location = "#"+URLpgAnchor;
	}
	if(eml){
		eml.innerHTML=eml1 + '@' + eml2 +'.co.uk';
		eml.href='mailto:' + eml1 + '@' + eml2 +'.co.uk';
	}
}

var adinittile=1;
function adinit(pos,size,cb){
	if(pos==""){
		var pp = Math.floor(Math.random()*10000000000)
		setTimeout('adinit("topAd","468x60,1x1",' + pp +');', 500)
		setTimeout('adinit("mpu","300x250,1x1",' + pp +');', 500)
		return
	}
	//if (/MSIE (5\.5|6)/.test(navigator.userAgent) && !/MSIE (7)/.test(navigator.userAgent)) return;
	var loc = window.location.toString();
	if(window.location.protocol.indexOf("https")>-1)return;
	if(loc.indexOf('/buyacar/')>-1 || loc.indexOf('mybuyacar')>-1)return;
	var ad1 = document.getElementById(pos);
	if(!ad1)return; //element not on page
	var url = loc.split("/");
	var make="", model="",section="";
	for (var i=0;i<url.length;i++){ //review section
		if(url[i]=="cars"){
			section="452021";
			if(url.length>i+1 && url[i+1].indexOf('jhtml')==-1)make = url[i+1]
			if(url.length>i+2 && url[i+2].indexOf('jhtml')==-1)model = url[i+2].replace(make+"_","")
		}
	}
	if(section=="" && url[url.length-1].indexOf("new_car")==0){ //new car search
		section="452022";
		var t = url[url.length-1].substring(8)	
		var e = t.lastIndexOf("_")
		if(e>-1){
			if(t.indexOf("alfa_romeo")>-1){
				make="alfa_romeo";
				if(e>11)model=t.substring(11,e)
			}else if(t.indexOf("aston_martin")>-1){
				make="aston_martin";
				if(e>13)model=t.substring(13,e)
			}else if(t.indexOf("mercedes_benz")>-1){
				make="mercedes_benz";
				if(e>14)model=t.substring(14,e)
			}else if(t.indexOf("land_rover")>-1){
				make="land_rover";
				if(e>11)model=t.substring(11,e)
			}else{
				make=t.substring(0,t.indexOf("_"));
				if(e>t.indexOf("_")+1)model=t.substring(t.indexOf("_")+1,e);
			}
		}
	}
	if(section=="" && loc.indexOf('used')>-1)section="452023";//used section
	if(section=="")section="452014";//default
	var e = document.createElement("iframe");
	if(make=="")make="ros";
	e.src = "/layout/ba" + "nner_ad" + ".jsp?" + "size=" +size + "&make=" + make.replace(/_/g,"-") + "&model=" + model.replace(/_/g,"-") + "&section=" + section + "&adinittile=" + adinittile + "&cb=" + cb;
	adinittile++;
	e.setAttribute('frameBorder','0');
	ad1.appendChild(e); 	
}

function addCSSRule(ruleName,value) {
	if (document.styleSheets) {
		var n = document.styleSheets.length;
		if (document.styleSheets[0].addRule) {
			document.styleSheets[n-1].addRule(ruleName, value,0);
		}else{
			document.styleSheets[n-1].insertRule(ruleName+' {'+value+'}',document.styleSheets[n-1].cssRules.length);
		}
   }
	//document.styleSheets[1].cssRules[1].cssText firefox
	//document.styleSheets[s].rules[r].style.background ie
} 

var param = {urlRoot:null,cooky:false}

param.init = function(){
	var use=false,pc,sp;
	with(param){
		try{
			urlRoot= window.location.protocol + "//" + window.location.host;
			if(window.location.toString().indexOf(urlRoot+'/buyacar/')>-1)urlRoot=urlRoot+"/buyacar"
			pc=cookie("pageCheck");
			sp=cookie("sessionParams");
			var loc=getPage();
			if(pc!=null && sp!=null && loc==pc && encodeURIComponent(sp)!=sessionParams){
				cookie("pageCheck", "off");
				cookie("sessionParams", null);
				location=urlRoot+pc + "?" + sp.replace(/\.\./g, "&").replace(/:/g, "=");
			}else if(pc==null || (pc!="off" && loc!=pc)){
				cooky=setPageCheck();
				if(sp!=null)cookie("sessionParams", null);
				if(!cooky)cookie("pageCheck", "off");
				sp=cookie("sessionParams");
			}else if(pc!=null && pc!="off")cooky=true;
			use=(cooky && sp!=null && sp!="");
		}catch(er){}	
		var aTags=document.getElementsByTagName("a");
		for (var i=0;i<aTags.length;i++){
			if(aTags[i].name && aTags[i].name.indexOf(":")!=-1){
				if(!cooky || !aTags[i].href){
					if(aTags[i].href=="" && aTags[i].name.indexOf("loc:")!=-1){
						var q=aTags[i].name.substring(aTags[i].name.indexOf("..")+2).replace(/\.\./g, "&").replace(/:/g, "=");
						aTags[i].href=urlRoot + aTags[i].name.substring(4,aTags[i].name.indexOf("..")) + ".jhtml" + ((q=="")?"":"?"+q);
					}else{
						aTags[i].href=urlRoot + getPage(aTags[i].href) + "?" + aTags[i].name.replace(/\.\./g, "&").replace(/:/g, "=");
					}
					aTags[i].name=null;
				}else if(cooky && aTags[i].href){
					addEvent(aTags[i],"click",param.setSessionParam);
				}
			}
			if(use)addEvent(aTags[i],"click",param.setSessionParam);
		}
	}
}

param.setPageCheck = function(a){
	a=param.getPage(a);
	param.cookie("pageCheck",a);
	return (param.cookie("pageCheck")==a);
}

param.getPage = function(a){
	with(param){
		if(arguments.length==0 || !a || (a && a.toString().lastIndexOf(".jhtml")==-1))a=location;
		a=a.toString();
		var end = (cooky)? a.lastIndexOf(".jhtml")+6: (a.lastIndexOf("?")==-1)?a.length: a.lastIndexOf("?"); // jsession? & del ?blar
		var start = (a.indexOf(urlRoot)==-1)?0:urlRoot.length;
		a=a.substring(start, end);
		return a;
	}
}

param.cookie = function(name,value){
	if(arguments.length == 1){
		var c = document.cookie;
		var idx = c.lastIndexOf(name+'=');
		if(idx == -1){ return null;}
		var start = idx+name.length+1;
		var end = c.indexOf(';', start);
		if(end == -1){ end = c.length; }
		return decodeURIComponent(c.substring(start, end)); 
	}else{
		if(value!=null){
			document.cookie = name + "=" + encodeURIComponent(value) + ";path=/"
		}else{
			document.cookie = name + "=;path=/"
		}
	}
}

param.setSessionParam = function(e){
	if(!e){
		var e = window.event;
		obj = e.srcElement;
	}else{
		obj = (e.target)? e.target : e.srcElement;
	}
	while(obj != null && obj.tagName!="A")obj = obj.parentNode;
	with(param){
		setPageCheck(obj.href);
		cookie("sessionParams", obj.name);
		var sp = cookie("sessionParams")
		if(sp!=obj.name && sp!=null && obj.name!=null){
			cookie("pageCheck", "off");
			obj.href=obj.href + "?" + obj.name.replace(/\.\./g, "&").replace(/:/g, "=");
		}
	}
}

param.addSessionParam = function(val){
	if(!param.cooky) return false;
	var sp = param.cookie("sessionParams")
	val=((sp==null)?"":sp) +".."+val;
	param.cookie("sessionParams", val);
	return true;
}
param.delSessionParam = function(val){
	if(param.cooky){
		var sp = param.cookie("sessionParams")
		if(sp!=null){
			sp=sp.replace(eval("/\.\."+val+"/g"),"");
			param.cookie("sessionParams", sp);
		}
	}
}

param.addEvent = function(obj,action,fn){
	if(obj.onclick && obj.onclick.toString().indexOf("Frame")!=-1)return;
	if(window.addEventListener){
		obj.addEventListener(action,fn,false);
	}else{ // ^ msie
		obj.attachEvent("on"+action,fn);
	};
}
 
function selectrow(id,displayName){this.id=id; this.displayName=displayName;}

var dropsearch = {
	globalBoxOnChange:"", ncsForm:null, boxes:null, isIE:false,verIE:0,doAJAX:null,isDom2:false,showCnt:false,urlRoot:null,showImgLoading:true,
	boxesData:{BRAND:null,RANGE:null,MODEL:null,FINANCE:null,PRICE:null}
}

dropsearch.initBoxes = function (){
	with(dropsearch){
		var box, txt,vo, reloaddata = false
		dropsearch.ncsForm = document.getElementById("NewCarSearch");
		urlRoot= window.location.protocol + "//" + window.location.host;
		if(window.location.toString().indexOf('buyacar/')>-1)urlRoot=urlRoot+"/buyacar"
		if(document.getElementById("usedVehicleSearchForm")){
			//used car search so load model array
			var e = document.createElement("script");
			e.src = urlRoot+"/all_models.jsp";
			e.type="text/javascript";
			document.getElementsByTagName("head")[0].appendChild(e); 
			var pc=document.getElementById("searchPostCode"), uk=document.getElementById("usedKeywords")
			if(pc && pc.value=="")pc.value="Enter your postcode here";
			if(uk && uk.value=="")uk.value="Enter any keywords here";
		}	
		if(!dropsearch.ncsForm)return;
		if(ncsForm.action.toString().indexOf("http")>-1){
			if(ncsForm.action.toString().indexOf("https")>-1)ncsForm.action=ncsForm.action.toString().replace("https","http")
		}else if(window.location.protocol.indexOf("https")>-1){
			ncsForm.action="http://" + window.location.host+ncsForm.action;
		}
		//new car search so load dojo
		var htmlvalues = dropsearch.ncsForm.className.split(",");
		dropsearch.boxes = ncsForm.getElementsByTagName("SELECT");
		dropsearch.isIE =(vo=navigator.userAgent.indexOf("MSIE"))!=-1&&navigator.userAgent.indexOf("Opera")==-1 
		if(isIE)dropsearch.verIE= parseFloat(navigator.userAgent.substring(vo+5));
		var khtml=(navigator.appVersion.indexOf("Konqueror")>=0)||(navigator.appVersion.indexOf("Safari")>=0);
		var moz = ((navigator.userAgent.indexOf("Gecko")>=0)&&(!khtml));
		dropsearch.isDom2 = (moz || isIE);
		//if(boxes[0].offsetWidth>160)showImgLoading=false; //new layout disable instead
		for(var b=0;b<boxes.length;b++){
			if(boxes[b].selectedIndex<0)boxes[b].selectedIndex=0;
			if(!htmlvalues[b] || htmlvalues[b]=="")htmlvalues[b]=0;
			if(htmlvalues[b]!=boxes[b].options[boxes[b].selectedIndex].value) reloaddata=true;
			boxes[b].disabled=false;
			boxes[b].onchange=dropsearch.doEvent
			boxes[b].onmouseout=dropsearch.doEvent
			boxes[b].onmouseover=dropsearch.doEvent
			boxes[b].onfocus=dropsearch.doEvent
			boxes[b].onblur=dropsearch.doEvent
			boxes[b].onclick=dropsearch.doEvent
			//rebuild drop boxes
			box = boxes[b].id.substr(3)
			boxesData[box] = new Array();
			for(var o=1;o<boxes[b].options.length;o++){
				for(var o=1;o<boxes[b].options.length;o++){
					boxesData[box][o-1] = new selectrow(boxes[b].options[o].value , boxes[b].options[o].text )
				}
			}
			if(!boxes[b].focused && !reloaddata)updateBoxes(boxesData,box);

		}
		if(reloaddata)getBoxesData({id:"ncsINIT"})
	}
}

dropsearch.doEvent = function(e){
	if(!e){
		var e = window.event;
		var obj = e.srcElement
	}else{
		var obj = (e.target)? e.target : e.srcElement
	}
	if(!obj.options)return;
	var opt = obj.options[obj.selectedIndex]
	with(dropsearch){
		switch(e.type){
			case "change":
				dropsearch.getBoxesData(obj)
				break;
			case "mouseover":
				if(showCnt && opt.count && !obj.focused)opt.text = opt.name +" ("+ opt.count +")";
				if(isIE)dropsearch.ieResize(obj)
				break;
			case "mouseout":
				if(showCnt && opt.name && !obj.focused)opt.text = opt.name;
				if(isIE)dropsearch.ieResizeoff(obj)
				break;
			case "focus":
				obj.focused=true;
				if(isIE)dropsearch.ieResize(obj)
				break;
			case "click":
				obj.focused=true;
				if(isIE)dropsearch.ieResize(obj)
				break;
			case "blur":
				obj.focused=false;
				if(showCnt && opt.name)opt.text = opt.name;
				if(isIE)dropsearch.ieResizeoff(obj)
				break;
		}
	}
}

dropsearch.getBoxesData = function (obj){
   with(dropsearch){
	   dropsearch.showLoading(dropsearch.ncsForm)
	   var myUrl = urlRoot+"/AJAXVehicleData.jhtml?";
	   dropsearch.globalBoxOnChange = obj.id.substr(3);
	   var opt = obj.options
	   if(opt)opt = opt[obj.selectedIndex]
	   if(opt && opt.name) opt.text = opt.name 
	   switch (globalBoxOnChange){
			case "BRAND":
				myUrl += "manufacturer="+obj.form.manufacturer.value+"&range=&modelType=&pcp="+obj.form.pcp.value+"&price="+obj.form.price.value;
				if(obj.form.manufacturer.value !='0') myUrl+='&dropDownFilter='+obj.form.manufacturer.value;
				break;
			case "RANGE":
				myUrl += "manufacturer="+obj.form.manufacturer.value+"&range="+obj.form.range.value+"&modelType=&pcp="+obj.form.pcp.value+"&price="+obj.form.price.value;
				myUrl += '&dropDownFilter='+ obj.form.manufacturer.value;
				if(obj.form.range.value !='0') myUrl+='&dropDownFilter='+obj.form.range.value;
				break;
			case "MODEL":
				myUrl += "manufacturer="+obj.form.manufacturer.value+"&range="+obj.form.range.value+"&modelType="+obj.form.modelType.value+"&pcp="+obj.form.pcp.value+"&price="+obj.form.price.value;
				myUrl += '&dropDownFilter='+ obj.form.manufacturer.value+ '&dropDownFilter='+ obj.form.range.value
				if(obj.form.modelType.value !='0') myUrl+='&dropDownFilter='+obj.form.modelType.value;
				break;
			case "FINANCE":
			case "PRICE":
				myUrl += "manufacturer="+obj.form.manufacturer.value+"&range="+obj.form.range.value+"&modelType="+obj.form.modelType.value+"&pcp="+obj.form.pcp.value+"&price="+obj.form.price.value;  
				if(obj.form.pcp.value !='0') myUrl+='&dropDownFilter='+obj.form.pcp.value;
				if(obj.form.price.value !='0') myUrl+='&dropDownFilter='+obj.form.price.value;
				break;
			case "INIT":
				myUrl = urlRoot+"/AJAXSessionVehicleData.jhtml?"
				break;
		}
		myUrl += "&t=" +(new Date().getTime()) //inhibit browser cache
		$.getJSON(myUrl,dropsearch.gotBoxesData);	
   }
}

dropsearch.gotBoxesData = function (data){
	with(dropsearch){
		if(data['SELECTED']){
			updateBoxes(data,"BRAND",data['SELECTED'][0]['id']);
			updateBoxes(data,"RANGE",data['SELECTED'][1]['id']);
			updateBoxes(data,"MODEL",data['SELECTED'][2]['id']);
			updateBoxes(data,"FINANCE",data['SELECTED'][3]['id']);
			updateBoxes(data,"PRICE",data['SELECTED'][4]['id']);
		}else{
			updateBoxes(data,"BRAND");
			updateBoxes(data,"RANGE");
			updateBoxes(data,"MODEL");
			updateBoxes(data,"FINANCE");
			updateBoxes(data,"PRICE");
		}
		hideLoading(dropsearch.ncsForm)
	}
}	

dropsearch.updateBoxes = function (data,box,selectValue){
	var obj = document.getElementById("ncs"+box);
	var newnode, objnodes = obj.childNodes;
	var objText,objOption,otxt,oname,ocount;
	var selectValIndex = 0;
	if(!selectValue){selectValue = obj.options[obj.selectedIndex].value;}
	var listcount = 0
	var row = 0;
	for(var n=0;n<objnodes.length;n++)if(objnodes[n].nodeType == 1){
		ocount = -1;
		if(objnodes[n].nodeName=="OPTION" && objnodes[n].index == 0){ //first row skip
		}else if(!data[box][row] || !dropsearch.isDom2){ //more options than data rows
			obj.removeChild(objnodes[n]);
			n--
		}else{
			otxt = data[box][row]['displayName']
			if(otxt.lastIndexOf("(")>0 && otxt.lastIndexOf(")")>0){
				oname = otxt.substring(0,otxt.lastIndexOf("(")-1)
				ocount = parseInt(otxt.substring(otxt.lastIndexOf("(")+1,otxt.lastIndexOf(")")));
			}//else{alert("data zero count error 1")}
		}
		if(ocount==0 && (box=="FINANCE" || box=="PRICE")){ //skip this data row
			n--
			row++
		}else if(ocount==0 && objnodes[n].nodeName == "OPTGROUP"){ //optgroup
			objnodes[n].label = otxt;
			row++
		}else if(ocount==0){ //change to optgroup
			newnode = document.createElement('OPTGROUP');
			obj.replaceChild(newnode,objnodes[n]);
			newnode.label = otxt;
			if(dropsearch.isIE)newnode.style.color = "#e5e5e5";
			row++
		}else if(ocount >0){ //option
			if(objnodes[n].nodeName == "OPTGROUP"){	//convert optgroup to option
				newnode = document.createElement('OPTION');
				obj.replaceChild(newnode,objnodes[n]);
			}else{
				newnode = objnodes[n]
			}
			newnode.value=data[box][row]['id']
			newnode.name = oname;
			newnode.count = ocount;
			listcount ++
			if(newnode.value==selectValue){
				selectValIndex=listcount;
				newnode.text=oname;
			}else if(dropsearch.showCnt){
				newnode.text=otxt;
			}else{
				newnode.text=oname;
			}
			row++
		}		
	}
	for(boxrow=row;boxrow<data[box].length;boxrow++){
		otxt = data[box][boxrow]['displayName']
		if(otxt.lastIndexOf("(")>0 && otxt.lastIndexOf(")")>0){
			oname = otxt.substring(0,otxt.lastIndexOf("(")-1)
			ocount = otxt.substring(otxt.lastIndexOf("(")+1,otxt.lastIndexOf(")"));
		}// else{alert("data zero count error 2")}
		if(box=="BRAND" || box=="RANGE" || box=="MODEL" || ocount>0){
			if(ocount==0){
				objOption = document.createElement('OPTGROUP');
				obj.appendChild(objOption);
				objOption.label = otxt;
				if(dropsearch.isIE)objOption.style.color = "#e5e5e5";
			}else{
				objOption = document.createElement('OPTION');
				obj.appendChild(objOption);
				objOption.value=data[box][boxrow]['id']
				objOption.name = oname;
				objOption.count = ocount;
				listcount ++
				if(objOption.value==selectValue){
					selectValIndex=listcount;
					objOption.text=oname;
				}else if(dropsearch.showCnt){
					objOption.text=otxt;
				}else{
					objOption.text=oname;
				}
			}
		}
	}
	setTimeout('document.getElementById("ncs'+box+'").selectedIndex='+selectValIndex, 1) //bug in ie
	if(obj.resizeon)dropsearch.ieResize(obj);
}

function showOverlayHiddingANode(show,node,text){
	var imageloading = $('#ncsloadingimg');
	if(!show){
		imageloading.hide();
		return;
	}
	if(imageloading.length == 0){
		$("body").append('<div id="ncsloadingimg">'+text+'</div>')
		imageloading = $('#ncsloadingimg');
	}
	var jnode = $(node);
	var offset = jnode.offset();
	var nheight = jnode.innerHeight()-80
	if(nheight<0)nheight = 0;
	var nwidth = jnode.innerWidth()
	imageloading.css({top:offset.top,left:offset.left,width:nwidth,height:nheight,display:'block'});
}


dropsearch.showLoading = function (frm){
    var b = frm.getElementsByTagName("SELECT");
	 if(dropsearch.showImgLoading){
		showOverlayHiddingANode(true,frm.parentNode,"LOADING..")
		if(dropsearch.isIE && dropsearch.verIE<7){ //if ie hide dropdowns
			for(var o=0;o<b.length;o++){
				b[o].style.visibility="hidden"
			}
		}
	}else{
		for(var o=0;o<b.length;o++){
				b[o].disabled=true;
			}
	}
}

dropsearch.hideLoading = function (frm){
	 var b = frm.getElementsByTagName("SELECT");
	 if(dropsearch.showImgLoading){
		showOverlayHiddingANode(false);
		if(dropsearch.isIE){ //if ie hide dropdowns
			for(var o=0;o<b.length;o++){
				b[o].style.visibility="visible"
			}
		}
	}else{
		for(var o=0;o<b.length;o++){
				b[o].disabled=false;
			}
	}
}

dropsearch.getXY = function(obj){
	var xy = {t:0,l:0,w:0,h:0} 
	xy.w=obj.offsetWidth;
	xy.h=obj.offsetHeight;
	while(obj!=null){
		xy.t+=obj.offsetTop;
		xy.l+=obj.offsetLeft;
		obj = obj.offsetParent
	}
	return xy
}

dropsearch.ieResize = function (obj){
	if(!obj)obj=this //ie
    if(!obj.id)obj=this //moz
return;	
	var optWidth=0,xy
	obj.resizeon = true;
	if(obj.expanded)return;
	for(var o=0;o<obj.options.length;o++){if(obj.options[o].text.length>optWidth)optWidth=obj.options[o].text.length}
	var optGroups = obj.getElementsByTagName("OPTGROUP");
	for(var o=0;o<optGroups.length;o++){if(optGroups[o].label.length>optWidth)optWidth=optGroups[o].label.length}
	if(optWidth<((obj.offsetWidth-20)/6))return;
	obj.expanded = true
	xy = dropsearch.getXY(obj)
	if(!document.getElementById('temp'+obj.id)){
		var newsel = document.createElement('select');
		newsel.setAttribute('id','temp'+obj.id);
		obj.form.insertBefore(newsel,obj);
	}
	obj.style.left=xy.l+"px"
	obj.style.top=xy.t-8+"px"
	obj.style.width="auto";
	obj.style.position="absolute" 
}

dropsearch.ieResizeoff = function (obj){
	if(!obj)obj=this //ie
    if(!obj.id)obj=this //moz
	if(obj.resizeon!=true)return;
	obj.resizeon = false;
	if(!obj.focused && obj.expanded){
		obj.expanded = false;
		obj.style.position="";
		obj.style.width="";
		if(document.getElementById('temp'+obj.id)){obj.form.removeChild(document.getElementById('temp'+obj.id));}
	}
}
dropsearch.unloadBoxes = function(){
	with(dropsearch){
		if(dropsearch.boxes)for(var b=0;b<boxes.length;b++){
			boxes[b].onchange=null;
			boxes[b].onmouseout=null;
			boxes[b].onmouseover=null;
			boxes[b].onfocus=null;
			boxes[b].onblur=null;
			boxes[b].onclick=null;
		}
	}
}

$(document).ready(function() {
	param.init();
	pagefix();
	dropsearch.initBoxes();	
});

if(window.addEventListener){
	window.addEventListener('load',function(){adinit("",0,0);},false);
	window.addEventListener('unload',dropsearch.unloadBoxes,false);
}else{ // ^ msie
	window.attachEvent('onunload',dropsearch.unloadBoxes);
	window.attachEvent('onload',function(){adinit("",0,0);});
};

