function renderRepaginator(id, n, s) {
	document.write('<label for="'+id+'">Results per page&nbsp;</label>');
	document.write('<select id="'+id+'" name="$ac_pp" onchange="repaginate(this.value, '+s+', '+n+')">');
	document.write('<option value="10"'+(n == 10 ? ' selected="selected"':'')+'>10</option>');
	document.write('<option value="20"'+(n == 20 ? ' selected="selected"':'')+'>20</option>');
	document.write('<option value="50"'+(n == 50 ? ' selected="selected"':'')+'>50</option>');
	document.write('</select>');
}

function repaginate(n, s, r) {
	var loc = unescape(document.location)

	loc = loc.replace(new RegExp("[&\?]repaginate=[0-9]+"),'');
	loc = loc.replace(new RegExp("[&\?]startrec=[0-9]+"),'');
	loc = loc.replace(new RegExp("[&\?]\\$ac_pp=[0-9]+"),'');

	loc += "&repaginate="+r;
	loc += "&startrec="+s;
	loc += "&$ac_pp="+n;

	document.location = loc;
}

function setSelect(p, id, lookup) {
	if (document.getElementById)
	{
		var s = document.getElementById(id);
		if (id == "ac_model" || id == "ac_variant") {
			if (s) {
				var ix = p.selectedIndex-1;
				while (s.getElementsByTagName("option").length > 1)
					s.removeChild(s.getElementsByTagName("option")[1]);
			}

			if (id == "ac_model") {
				var v = document.getElementById("ac_variant");
				if (v) {
					while (v.getElementsByTagName("option").length > 1)
						v.removeChild(v.getElementsByTagName("option")[1]);
				}

			}
		}

		if (!lookup && ix >= 0) {
			var m = models[ix];
			for (var i=0;i<m.length;i++) {
				var o = document.createElement("option");
				o.value = m[i];
				o.innerHTML = m[i];
				s.appendChild(o);
			}
		}

		var el = document.getElementById("carSearchMask").elements;
		var pa = "?req="+escape(p.name);
		var cp = p.id == "ac_make" || p.id == "ac_model" || p.id == "ac_variant";
		for (var i=0;i<el.length;i++) {
			if (el[i].name.indexOf("$") == 0 && el[i].value != "Enter Postcode") {
				var v = cp && (el[i].name == "$ac_min" || el[i].name == "$ac_max") ? "" : el[i].value;

				if (el[i].type == "checkbox") v = el[i].checked ? 1 : 0;

				pa += (pa==""?"?":"&")+escape(el[i].name)+"="+escape(v);
			}
		}

		//alert(unescape(pa).replace(/&/g, "\n"));

		smabtn = document.getElementById("btnSubmitSearch");
		smabtn.disabled = true;

		if (typeof sc == 'string')
			pa += '&sc='+sc;

		loadXMLDoc("/_/host/buydirect.com/applications/search.jsp"+pa, "updateSearchMask");
	}else{
		p.form.submit();
	}
}

function setSelectWidth(ob, auto) {
	if (ie) {
		if (auto)
			ob.style.width = "auto";
		else
			ob.style.removeAttribute("width");
	}
}

var increm = 0;
var incamt = 0;
var totcar = 0;
var incdir = 0;
var curtot = 0;
var smabtn = null;
var btnint = null;

function updateSearchMask(http) {
	var xml = http.responseXML;
	try {
		var roo = xml.getElementsByTagName("response")[0];
		var req = roo.getAttribute("request");

		if (roo.getElementsByTagName("variants").length == 1) {
			var v = document.getElementById("ac_variant");
			var os = roo.getElementsByTagName("variants")[0].getElementsByTagName("option");
			for (var i=0;i<os.length;i++) {
				var o = document.createElement("option");
				o.value = os[i].getAttribute("value");
				o.innerHTML = o.value;
				v.appendChild(o);
			}
		}

		//update # of cars available
		increm = 20;

		totcar = parseInt(roo.getAttribute("results"));

		curtot = parseInt(smabtn.value.replace(/view/i,"").replace(/cars/i,"").replace(/ /g,"").replace(/,/g,""));
		var diff = totcar > curtot ? totcar - curtot : curtot - totcar;
		incamt = Math.floor(diff/increm);
		if (incamt == 0) {
			incamt = 1;
			increm = diff;
		}
		incdir = curtot < totcar
		//btnint = window.setInterval("updateResultsBtn()",20);

		if (totcar > 0) {
			smabtn.disabled = false;
			smabtn.value = "View Results";
		}else{
			smabtn.disabled = true;
			smabtn.value = "No Results";
		}
		var min = roo.getAttribute("min") ? parseInt(roo.getAttribute("min")) : 3000;
		var max = roo.getAttribute("max") ? parseInt(roo.getAttribute("max")) : 150000;
		setPriceRangeOptions(req, min, max);
	}catch(E){
		alert(E);
	}
}

function updateResultsBtn() {
	if (increm > 0) {
		curtot = incdir ? curtot += incamt : curtot -= incamt;
		setResultsBtn(curtot);
		increm--;
	}else{
		setResultsBtn(totcar);
		window.clearInterval(btnint);

		if (totcar > 0) smabtn.disabled = false;

		btnint = null;
	}
}

function setResultsBtn(value) {
	if (value == null){
		smabtn = document.getElementById("btnSubmitSearch");
		value = parseInt(smabtn.value.replace(/view/i,"").replace(/cars/i,"").replace(/ /g,"").replace(/,/g,""));
	}

	value = acNumFormat(value);
	smabtn.value = "View "+value+" Cars";
}

function setPriceRangeOptions(req, x, y) {
	var limits = new Array(x,y);
	var selMin = document.getElementById("ac_min");
	var min = selMin.options;
	var lmin = null;
	var x = 0;

	for (var i=1;i<min.length;i++) {
		min[i].className = min[i].value < limits[0] || min[i].value > limits[1] ? "OutOfRange" : "";
		if (min[i].className == "OutOfRange") x++; else lmin = min[i];
	}

	if (req == "ac_make" || req == "ac_model" || req == "ac_variant") {
		if (x == min.length - 1) {
			//min[0].selected = "selected";
		}else{
			for (var i=1;i<min.length;i++) {
				if (min[i].className != "OutOfRange") {
					//min[i].selected = "selected";
					break;
				}
			}
		}
	}

	if (req == "ac_make" || req == "ac_model" || req == "ac_variant")
		min[0].selected = "selected";

	var selMax = document.getElementById("ac_max");
	var max = selMax.options;
	var lmax = null;
	x = 0;
	for (var i=1;i<max.length;i++) {
		max[i].className = limits[0] >= max[i].value || limits[1] < max[i].value ? "OutOfRange" : "";
		if (max[i].className == "OutOfRange") x++; else lmax = max[i];
	}

	if (req == "ac_make" || req == "ac_model" || req == "ac_variant") {
		if (x == max.length - 1) {
			max[0].selected = "selected";
		}else{
			for (var i=max.length-1;i>0;i--) {
				if (max[i].className != "OutOfRange") {
					//max[i].selected = "selected";
					break;
				}
			}
		}
	}

	if (req == "ac_make" || req == "ac_model" || req == "ac_variant")
		max[0].selected = "selected";

	if ((lmin != null && lmax != null) && lmin.value == lmax.value)
		lmin.className = "OutOfRange";
}

function acNumFormat(value) {
	value = parseInt(value);

	if (value > 10000) {
		var tmp = ""+value;
		value = tmp.substring(0, tmp.length-3)+","+tmp.substring(tmp.length-3);

	}
	return value;
}

function checkParams(form) {
	form.$ac_js.value = 1;
	return true;
}

function checkActiveInput(ob, clk, str) {
	if (clk && ob.value == str)
		ob.value = "";
	else if (!clk && ob.value == "")
		ob.value = str;

	ob.className = "maskTxt" + (ob.value == str ? " maskTxtGrey" : "");
}

var arrowOpen = new Image();
arrowOpen.src = "/images/template/arrow_open.png";
var arrowClosed = new Image();
arrowClosed.src = "/images/template/arrow_closed.png";

function getParentElement(ob, tagName) {
	var oParent = ob.parentNode;
	while (oParent.tagName.toLowerCase() != tagName.toLowerCase() && oParent != document.body)
		oParent = oParent.parentNode;

	return oParent;
}

function toggleRowVisibility(ob, tagName, session) {
	var oParent = getParentElement(ob, tagName);

	var open = oParent.className == "hideHiddenRows";
	oParent.className = open ? "" : "hideHiddenRows";
	if (ob.getElementsByTagName("img").length > 0)
		ob.getElementsByTagName("img")[0].src = open ? arrowOpen.src : arrowClosed.src;

	if (session)
		loadXMLDoc("/$/ac/session.jsp?id="+session, null);

	fixColumns(true, false);
	fixColumns(false, true);
}

function toggleBranchDetails(ob) {
	var open = ob.className == "branch"

	ob.className =  open ? "branchOpen" : "branch";
	document.getElementById("map").style.display = open ? "block" : "none";
	return false;
}

var hiRow = null;
function hilightRow(r) {
	if (document.getElementById) {

		if (hiRow) {
			hiRow.className = "searchResult";
			var ns = hiRow.nextSibling;
			while (ns.tagName != "TR")
				ns = ns.nextSibling;

			ns.className = "searchResultBtns";
		}

		hiRow = r;

		if (hiRow) {
			hiRow.className = "searchResult searchResultHi";

			var ns = hiRow.nextSibling;
			while (ns.tagName != "TR")
				ns = ns.nextSibling;

			ns.className = "searchResultBtns searchResultHi";
		}
	}
}

function hilightPrevRow(r) {
	if (document.getElementById) {
		if (r) {
			var ps = r.previousSibling;
			while (ps.tagName != "TR")
				ps = ps.previousSibling;
		}else
			ps = r;

		hilightRow(ps);
	}
}

var franchiseLogos;
var franchiseLogoDefault = "";
function initializeFranchiseLogos() {
	var franchiseLinks = document.getElementById("franchiseMenu").getElementsByTagName("a");
	franchiseLogoDefault = document.franchiseLogo.src;
	franchiseLogos = new Array();
	for (var i=0;i<franchiseLinks.length;i++) {
		var img = new Image();
		img.src = "/images/franchise/logos/"+franchiseLinks[i].id+".png";
		franchiseLogos.push(img);
		franchiseLinks[i].setAttribute('ix', i);
		franchiseLinks[i].onmouseover = function(){try{setFranchiseLogo(this)}catch(E){}};
		franchiseLinks[i].onmouseout = function(){try{setFranchiseLogo(null)}catch(E){}};
	}
}

function setFranchiseLogo(ob) {
	if (document.franchiseLogo)
		document.franchiseLogo.src = ob ? franchiseLogos[parseInt(ob.getAttribute('ix'))].src : franchiseLogoDefault
}

function sc(o, c) {
	o.className = c;
}

var oIFrame = null;
var srUri = "/showroom/compare_vanilla.html";
function initShowroom() {
	if (document.getElementById) {
		//setResultsBtn(null);

		var b = BrowserDetect.browser;
		if (b == "Opera" || b == "Safari")
			document.getElementById("mainmenu").style.marginTop = "1px";

		var footer = document.getElementById("wf_footer_innerZones");

		var div = document.createElement("div");
		div.style.height = "270px";
		div.style.background = "#fff";
		div.style.border = "1px solid #333";

		oIFrame = document.createElement("iframe");
		oIFrame.name = "compare";
		oIFrame.scrolling = "no";
		oIFrame.style.width  = "585px";
		oIFrame.style.height = "250px";
		oIFrame.frameBorder = "0";

		div.appendChild(oIFrame);
		footer.appendChild(div);

		if (ie)
			oIFrame.src = "/static/blank.html";
		else{
			oIFrame = window.frames["compare"];
			oIFrame.location.href = "/static/blank.html";
		}
	}
}

var srSlide, currentH, targetH;
function toggleShowRoom() {
	if (document.getElementById) {
		var bh = document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
		if (bh < 390) return true;

		var footer = document.getElementById("wf_footer");
		var d;
		if (footer.getAttribute("open")) {
			d = 0;

			targetH = 40;
			currentH = 310;
			footer.removeAttribute("open");
		}else{
			d = 1;

			if (ie)
				oIFrame.src = srUri;
			else{
				try {
					oIFrame = window.frames["compare"];
					oIFrame.location.href = srUri;
				}catch(E){
					alert(E);
				}
			}


			targetH = 310;
			currentH = 40;
			footer.setAttribute("open",true);
		}

		srSlide = window.setInterval("slideShowRoom("+d+")", 20);
		return false;
	}else
		return true;
}

function slideShowRoom(d) {
	var footer = document.getElementById("wf_footer");

	var ch = currentH;
	var th = targetH;
	var h;

	var i = 20;
	if (d == 0)
		h = ch - parseInt(th - ch > i*-1 ? th - ch : i);
	else
		h = ch + parseInt(th - ch < i ? th - ch : i);

	footer.style.height = h+"px";

	if (h == th) {

		var lnk = gebi("lnkShowroom");

		if (footer.getAttribute("open"))
			lnk.innerHTML = "Close My Showroom";
		else
			lnk.innerHTML = "Open My Showroom";

		window.clearInterval(srSlide);
		srSlide = null;
		if (window.formToSubmit) {
			window.formToSubmit.submit();
			window.formToSubmit = null;
		}
	}else{
		currentH = h;
	}
}


var newAddition = null;
function addToShowroom(id) {
	//eraseCookie('showroom');

	var img = null;

	for (var i=1;i<4;i++) {
		img = eval("document.weePic"+i);

		if (img) break;
	}

	var src = img ? img.src.substring(img.src.indexOf("/images")) : "";

	if (startsWith(src,'/'))
		src = "http://www.arnoldclark.com"+src;

	var cookie = readCookie("showroom");

	var x = 1;
	if (cookie){
		//test length
		var tmp = cookie.replace(/{/g,'').split("}");
		x = tmp.length;
		for (var i=0;i<tmp.length;i++) {
			var value = tmp[i].split("|");
			if (value[0] == id) {
				alert("This car is already in your showroom.");
				return false;
			}
		}
	}else
		cookie = "";

	if (x > 6) {
		alert("You can only have a maximum of 6 cars in your showroom.");
		return;
	}

	if (src != "") {
		newAddition = document.images["showroom"+x];
		newAddition.src = src;
		newAddition.parentNode.id = "sr"+id;

		if (document.getElementById) {
			newAddition.parentNode.className = "zoom";
			window.setTimeout("shrinkNewAddition()",750);
		}
	}

	var host = location.protocol+"//"+location.host;
	var url  = location.toString().substring(host.length).replace(/,/g," ");



	cookie += "{"+id+"|"+src+"|"+url+"}";
	createCookie("showroom", cookie, 7);

	if (ie){
		oIFrame.src = srUri;
	}else
		oIFrame.location.href = srUri;

	alert("Car added to showroom.");
	return false;
}

function shrinkNewAddition() {
	newAddition.parentNode.className = "thumb";
}

function clearShowroom() {
	if (!confirm("Are you sure you want to clear your showroom?"))
		return;

	eraseCookie('showroom');
	var showroom = gebi("ac_showroom");
	var links = showroom.getElementsByTagName("a");
	for (var i=0;i<links.length;i++) {
		if (links[i].className == "thumb" || links[i].className == "zoom") {
			links[i].href = "";
			links[i].firstChild.src = "/images/template/showroom_empty.png";
			links[i].className = "thumb";
		}
	}

	if (ie)
		oIFrame.src = srUri;
	else
		oIFrame.location.href = srUri;

	toggleShowRoom();
}

function removeFromShowroom(id, spawn) {
	var cookie = readCookie("showroom");
	var update = "";
	var src = "";

	var x = 1;
	if (cookie){
		var tmp = cookie.replace(/{/g,'').split("}");
		for (var i=0;i<tmp.length;i++) {
			var v = tmp[i].split("|");
			if (v[0] != "" && v[0] != id)
				update += "{"+tmp[i]+"}";
		}
	}

	//move to end

	var link = document.getElementById("sr"+id);
	link.firstChild.src = "/images/template/showroom_empty.png";
	var td = link.parentNode;
	var tr = td.parentNode;
	tr.insertBefore(td, document.getElementById("heightFix"));

	//re-id images
	var slots = getElementsByClassName(tr, "img", "srImg");
	for (var i=0;i<slots.length;i++) {
		slots[i].id = "showroom"+(i+1);
		slots[i].name = "showroom"+(i+1);
	}

	createCookie("showroom", update, 7);
	alert("Car deleted from showroom.");

	if (spawn)
		spawn.location = spawn.location;
	else
		document.location = document.location;

	return false;
}

function checkComparisson(form) {

	var checked = 0;
	for (var i=1;i<7;i++) {
		var cbox = form.elements['-StockReference'+i];

		if (cbox && cbox.checked) checked++;
	}

	if (checked < 1) {
		if (confirm("You must have at least 1 car selected to perform this action, would you like to select all and proceed?"))
			toggleCheckAll(null, true);
		else
			return false;
	}

	return true;
}

function resetForm(form) {
	form.reset();

	for (var i=0;i<form.elements.length;i++) {

		if (form.elements[i].tagName == "SELECT")
			form.elements[i].selectedIndex = 0;
		else if (form.elements[i].type == "text")
			form.elements[i].value = "";

	}
	//form.submit();
	setSelect(gebi("ac_type"), null, true);
}

function toggleShowDateTime()
{
	var nn6=document.getElementById&&!document.all;
	var act = document.getElementById("contactTimeType").value;
	var oD = document.getElementById("contactDate_labeltd");
	var oT = document.getElementById("contactTime_labeltd");
	var oDTR = nn6 ? oD.parentNode : oD.parentElement;
	var oTTR = nn6 ? oT.parentNode : oT.parentElement;
	var disp = (act == 1) ? "none" : nn6 ? "table-row" : "block";
	oDTR.style.display = disp;
	oTTR.style.display = disp;
}

// added for Buy Direct

function switchSite(u) {
	if(u.length > 0) window.location = u;
}

function showOther() {
	if(document.getElementById("contactTitle").value == "Other") {
		document.getElementById("contactTitle_otherdiv").style.display="block";
	}else{
		document.getElementById("contactTitle_otherdiv").style.display="none";
	}
}


