
// Virtual-Showroom.com stocklist functions. Copyright virtual-showroom.com 2010
// Written by Andy Bryan

var errorTag = "";
var errorText = "";
var intListArray = new Array();
var comListArray = new Array();
var noOfCookies = 0;

// General Functions

function doNothing(){
	//
}

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return null;
}

function isEven(value){
	if (value%2 == 0)
		return true;
	else
		return false;
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	pence = num%100;
	num = Math.floor(num/100).toString();
	if(pence<10)
	pence = "0" + pence;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '&#163;' + num);
}

// Stock list listing page functions

function itemLength(x){
	if(x.length < 1){
		return false;
	} else {
		return true;
	}
}

function checkEmail(x) { // Email format validation
	email = x.value
	AtPos = email.indexOf("@")
	StopPos = email.lastIndexOf(".")
	errorText = ""
	if (email == "") {
		errorText = "email field does not appear to contain a valid email address"
	}
	if (AtPos == -1 || StopPos == -1) {
		errorText = "email field does not appear to contain a valid email address"
	}
	if (StopPos < AtPos) {
		errorText = "email field does not appear to contain a valid email address"
	}
	if (StopPos - AtPos == 1) {
		errorText = "email field does not appear to contain a valid email address"
	}
}

function checkFormItem(x,y){ // Form validation
	if(itemLength(x.value)){
		if(y == "email"){
			checkEmail(x);
			if(errorText.length > 0){
				x.className = "errorHighlight";
				errorTag = true;
			} else {
				x.className = "";
			}
		 } else {
			x.className = "";
		 }
	} else {
		x.className = "errorHighlight";
		errorTag = true;
	}
}

function listPageFormSubmit(x, y){ // Form validation driver function
	errorTag = false;
	errorText = "";
	var targetForm = y + x;
	
	var formName = document[targetForm].name;
	var formEmail = document[targetForm].from_address;
	
	checkFormItem(formName, 'text');
	checkFormItem(formEmail, 'email');
	
	
	if(y.indexOf("tellAFriendForm") != 0){
		var formPhone = document[targetForm].phone;
		checkFormItem(formPhone, 'text');
	} else {
		var toName = document[targetForm].to_name;
		var toEmail = document[targetForm].to_address;
		
		checkFormItem(toName, 'text');
		checkFormItem(toEmail, 'email'); 

	}
	
	if(errorTag){
		alertTxt = "There appears to be missing information from the submission form.\n\nThese fields are marked in red.\n\n";
		if(errorText.length > 0){
			alertTxt = alertTxt + "Also " + errorText;
		}
		alert(alertTxt);
	} else {
		document[targetForm].submit();
	}
}

function toggle(x){
	targetObj = document.getElementById(x);
	targetSpacer = document.getElementById(x + "Spacer");
	if(targetObj.style.display == "none"){
		targetObj.style.display = "";
		targetSpacer.style.display = "";
	} else {
		targetObj.style.display = "none";
		targetSpacer.style.display = "none";
	}
}

function stockSearchToggle(){ // Search container show / hide function
	var targetObj = document.getElementById("searchContainer");
	var targetObjMin = document.getElementById("searchContainerMin");
	if(targetObj.style.display == "none"){
		targetObj.style.display = "";
		targetObjMin.style.display = "none";
		setCookie('searchContainer','open',5);
	} else {
		targetObj.style.display = "none";
		targetObjMin.style.display = "";
		setCookie('searchContainer','closed',5);
	}
}

// Interest / Showroom functions

function intList(vehId, thumb, manu, model, price){ // Main vehicle addition function
	if (navigator.cookieEnabled == 0) {
  		alert("You need to enable cookies to use this option");
	} else {
		if (dupListCheck(vehId, 'int')){
			alert("This vehicle is already on your showroom list");
		} else {
			for(i=0; i<=7; i++){
				tempVal = getCookie('interestList' + i);
				if (tempVal != null){
					intListArray[i] = getCookie('interestList' + i);
				}
			}
			noOfCookies = intListArray.length;
			if (noOfCookies > 7){
				alert("You have reached the maximum number of vehicles allowed on your interest list.\n\nYou must remove an item before adding a new one.");
			} else {
				if (noOfCookies == 0){
					document.getElementById("interestListContainer").style.display = "";
				}
				tempVal = vehId + "~" + thumb + "~" + manu + "~" + model + "~" + formatCurrency(price);
				tempName = "interestList" + noOfCookies;
				setCookie(tempName, tempVal, 1);
				alert(manu + " " + model + " has been added you your showroom list");
				intListRefresh(noOfCookies);
			}
		}
	}
}

function intListClear(){ // Clear all items off the Interest / Showroom list
	var answer = confirm ("Are you sure you wish to remove all items from your showroom list?")
	if (answer){
		for(i=0; i<=7; i++){
			setCookie('interestList' + i, null, -1);
		}
		intListArray.length = 0;
		document.getElementById("interestList").innerHTML = "";
	}
}

function dupListCheck(x, y){ // Duplicate vehicle / cookie check
	var dup = false;
	if(y == "com"){
		var limit = 2;
		var cookieName = "comparisonList";
	} else {
		var limit = 7;
		var cookieName = "interestList";
	}
	for(i=0; i<=limit; i++){
		var tempCookie = getCookie(cookieName + i);
		if (tempCookie != null){
			var tempArray = tempCookie.split("~");
			if (parseFloat(x) == parseFloat(tempArray[0])){
				dup = true;
			}
		}
	}
	return dup;
}

function intListRemove(x){ // Vehicle removal function
	setCookie('interestList' + x, null, -1);
	for(i=0; i<=7; i++){
		tempVal = getCookie('interestList' + i);
		if (tempVal != null){
			intListArray[i] = tempVal;
		} else {
			intListArray[i] = null;
		}
	}
	count = 0;
	for(i=0; i<=7; i++){
		setCookie('interestList' + i, null, -1);
	}
	for(i=0; i<=7; i++){
		tempVal = intListArray[i];
		if (tempVal != null){
			setCookie("interestList" + count, tempVal, 1);
			count = count + 1;
		}
	}
	if(count == 0){
		intListArray.length = 0;
		document.getElementById("interestList").innerHTML = "";
	} else {
		intListArray.length = count;
		intListRefresh(count-1);
	}
}

function intListCodeMeUp(x){ // Cookie parse function
	var tempCookie = getCookie('interestList' + x);
	var tempArray = tempCookie.split("~");
	returnCode = "<a href=\"/VehicleDetail.aspx?VehicleId=" + tempArray[0] + "\"><img src=\"" + tempArray[1] + "\" border=\"0\" alt=\"" + tempArray[2] + " " + tempArray[3] + "\" title=\"" + tempArray[2] + " " + tempArray[3] + " - Click for full details\" /></a><br />";
	returnCode = returnCode + tempArray[2] + "<br />" + tempArray[3] + "<br />" + tempArray[4] + "<br />";
	returnCode = returnCode + "<a href=\"javascript:intListRemove('" + x + "')\">remove from list</a><br />"
	return returnCode;
}

function intListRefresh(x){ // Interest list build function
	var intListCode = "<div id=\"interestHeader\" title=\"Click to expand / contract\"  class=\"rightExpander\">Your showroom list</div>";
	intListCode = intListCode + "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" id=\"intListTbl\"><tr>";
	for(i=0; i<=x; i++){
		if (isEven(i) == true){
			intListCode = intListCode + "<tr>";
		}
		intListCode = intListCode + "<td>" + intListCodeMeUp(i) + "</td>";
		if (isEven(i) == false){
			intListCode = intListCode + "</tr>";
		}
	}
	if (isEven(x) == true){
		intListCode = intListCode + "<td>&nbsp;</td></tr>";
	}
	intListCode = intListCode + "<tr><td colspan=\"2\"><a href=\"javascript:intListClear();\">Clear all items off your showroom list</a></td></tr>";
	intListCode = intListCode + "</table>";
	document.getElementById("interestList").innerHTML = intListCode;
	jQuery('div#interestHeader').bind('click', function(event, ui){stateLoggin('intListTbl', 'table')});
	jQuery('div#interestHeader').bind('click', function(event, ui){var target = jQuery('table#intListTbl'); target.toggle('slide', { direction: 'up' }, 0)});
}

// Comparison list functions

function comList(vehId, thumb, manu, model, price){ // Main vehicle addition function
	if (navigator.cookieEnabled == 0) {
  		alert("You need to enable cookies to use this option");
	} else {
		if (dupListCheck(vehId, 'com')){
			alert("This vehicle is already on your comparision list");
		} else {
			for(i=0; i<=3; i++){
				tempVal = getCookie('comparisonList' + i);
				if (tempVal != null){
					comListArray[i] = getCookie('comparisonList' + i);
				}
			}
			noOfCookies = comListArray.length;
			if (noOfCookies > 2){
				alert("You have reached the maximum number of vehicles allowed on your comparision list.\n\nYou must remove an item before adding a new one.");
			} else {
				if (noOfCookies == 0){
					document.getElementById("comparisonListContainer").style.display = "";
				}
				tempVal = vehId + "~" + thumb + "~" + manu + "~" + model + "~" + formatCurrency(price);
				tempName = "comparisonList" + noOfCookies;
				setCookie(tempName, tempVal, 1);
				alert(manu + " " + model + " has been added you your comparision list");
				comListRefresh(noOfCookies);
			}
		}
	}
}

function comListRefresh(x){ // Comparison list build function
	var idList = "";
	var tempCookie = "";
	var comListCode = "<div id=\"comparisonHeader\" title=\"Click to expand / contract\" class=\"rightExpander\">Your comparision list</div>";
	comListCode = comListCode + "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" id=\"comListTbl\"><tr>";
	comListCode = comListCode + "<tr><td>max 3 vehicles</td></tr>";
	for(i=0; i<=x; i++){
		comListCode = comListCode + "<tr><td>";
		
		tempCookie = getCookie('comparisonList' + i);
		var tempArray = tempCookie.split("~");
		comListCode = comListCode + "<img src=\"" + tempArray[1] + "\" border=\"0\" alt=\"" + tempArray[2] + " " + tempArray[3] + "\" title=\"" + tempArray[2] + " " + tempArray[3] + " - Click for full details\" /><br />";
		comListCode = comListCode + tempArray[2] + "<br />" + tempArray[3] + "<br />" + tempArray[4] + "<br />";
		comListCode = comListCode + "<a href=\"javascript:comListRemove('" + i + "')\">remove from list</a><br />"
		
		idList = idList + "VehicleId" + i + "=" + tempArray[0] + "&";
			
		comListCode = comListCode + "</td></tr>";
	}
	if(x > 0){
		comListCode = comListCode + "<tr><td><a href=\"/VehicleCompare.aspx?" + idList + "\">Compare these vehicles</a></td></tr>";
	} else {
		comListCode = comListCode + "<tr><td>You'll need more than one vehicle to do a comparison </td></tr>";
	}
	comListCode = comListCode + "<tr><td><a href=\"javascript:comListClear();\">Clear all items off your comparision list</a></td></tr>";
	comListCode = comListCode + "</table>";
	document.getElementById("comparisonList").innerHTML = comListCode;
	jQuery('div#comparisonHeader').bind('click', function(event, ui){stateLoggin('comListTbl')});
	jQuery('div#comparisonHeader').bind('click', function(event, ui){var target = jQuery('table#comListTbl'); target.toggle('slide', { direction: 'up' }, 0)});
}

function comListRemove(x){ // Vehicle removal function
	setCookie('comparisonList' + x, null, -1);
	for(i=0; i<=2; i++){
		tempVal = getCookie('comparisonList' + i);
		if (tempVal != null){
			comListArray[i] = tempVal;
		} else {
			comListArray[i] = null;
		}
	}
	count = 0;
	for(i=0; i<=3; i++){
		setCookie('comparisonList' + i, null, -1);
	}
	for(i=0; i<=3; i++){
		tempVal = comListArray[i];
		if (tempVal != null){
			setCookie("comparisonList" + count, tempVal, 1);
			count = count + 1;
		}
	}
	if(count == 0){
		comListArray.length = 0;
		document.getElementById("comparisonList").innerHTML = "";
	} else {
		comListArray.length = count;
		comListRefresh(count-1);
	}
}

function comListClear(){ // Clear all items off the Comparison list
	var answer = confirm ("Are you sure you wish to remove all items from your comparison list?")
	if (answer){
		for(i=0; i<=2; i++){
			setCookie('comparisonList' + i, null, -1);
		}
		comListArray.length = 0;
		document.getElementById("comparisonList").innerHTML = "";
	}
}

function tellAFriend(){
	targetDiv = document.getElementById("tellAFriend");
	if(targetDiv.style.display == "none"){
		targetDiv.style.display = "";
	} else {
		targetDiv.style.display = "none";
	}
}

function compareEquipmentToggle(x){
	targetDiv = document.getElementById("compareEquipment" + x);
	targetLinkDiv = document.getElementById("compareEquipmentLink" + x);
	if(targetDiv.style.display == "none"){
		targetDiv.style.display = "block";
		targetLinkDiv.innerHTML = "[ click to close ]";
	} else {
		targetDiv.style.display = "none";
		targetLinkDiv.innerHTML = "[ click to view ]";
	}
}

function getStyle(oElm, strCssRule){
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}

function stateLoggin(x){
	var target = document.getElementById(x);
	var answer = target.style.display;
	if(answer == 'table' || answer == ""){
		setCookie(x, "is set", 1);
	} else {
		setCookie(x, null, -1);
	}
}

navHover = function() {
	var cssRule;
	var newSelector;
	for (var i = 0; i < document.styleSheets.length; i++)
		for (var x = 0; x < document.styleSheets[i].rules.length ; x++)
			{
			cssRule = document.styleSheets[i].rules[x];
			if (cssRule.selectorText.indexOf("LI:hover") != -1)
			{
				 newSelector = cssRule.selectorText.replace(/LI:hover/gi, "LI.iehover");
				document.styleSheets[i].addRule(newSelector , cssRule.style.cssText);
			}
		}
	var getElm = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<getElm.length; i++) {
		getElm[i].onmouseover=function() {
			this.className+=" iehover";
		}
		getElm[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" iehover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", navHover);

function liveClock()  {
         var today  = new Date();
         var second = today.getSeconds();
         var minute = today.getMinutes();
         var hour   = today.getHours();
         var hour24 = today.getHours();
         var ampm   = "";
         
         var day    = today.getDay();
         var date   = today.getDate();
         var month  = today.getMonth();
         var year   = today.getFullYear();
         
         var days   = new Array();
          days[0]   = "Sunday";
          days[1]   = "Monday";
          days[2]   = "Tuesday";
          days[3]   = "Wednesday";
          days[4]   = "Thursday";
          days[5]   = "Friday";
          days[6]   = "Saturday";
          
         var mns   = new Array();
          mns[0]   = "January";
          mns[1]   = "February";
          mns[2]   = "March";
          mns[3]   = "April";
          mns[4]   = "May";
          mns[5]   = "June";
          mns[6]   = "July";
          mns[7]   = "August";
          mns[8]   = "September";
          mns[9]   = "October";
          mns[10]  = "November";
          mns[11]  = "December";
           
        if(second<10)
            {
                second = "0"+second;
            }
            
        if(minute<10)
            {
                minute = "0"+minute;
            }
            
        if(hour24<=11)
            {
                ampm = "AM";
            }
            
        else
            {
                ampm = "PM"
            }
            
        if(hour24>=13)
            {
                hour= hour-12;
            }
            
        if(hour24==0)
            {
                hour=12;
            }
        
        document.getElementById('liveClock').innerHTML=(hour+":"+minute+":"+second+" "+ampm+' '+days[day]+', '+date+' '+mns[month]+' '+year);
}

function hideAdjuster(){
	target = document.getElementById("financeAdjuster");
	target.style.display = "none";
}

function scripts(){
	setInterval('liveClock()', 1000);
	showCustomer(true,-1,138);
}

function initPage(x){
	if(x == "new"){
		document.getElementById("interiorContainer").style.display = "none";
		document.getElementById("exteriorContainer").style.display = "none";
		document.getElementById("specificationContainer").style.display = "none";
	}
}

function carValueWindow() {
		stockWindow = window.open("http://www.virtual-showroom.co.uk/scripts/nuvv/nuvv1.asp?clientId=nq&laf=nq&nuvvpath=b&url=","stockListWindow","scrollbars=yes,resizable=yes,width=750,height=500,top=10,left=10");
}

function valueCar() {
			carValueWindow()
			stockWindow.focus();
}

$(document).ready(function(){
	
	jQuery('#accordion h3').click(function() {jQuery(this).next().toggle('fast'); return false;}).next().hide();
	jQuery('a#showHide').bind('click', function(event, ui){var target = jQuery('div#extraSearchOptions'); target.slideToggle(250)});
	
	$('img#requestGfx').click(function(){
		$('div#requestACallBack').slideToggle('fast')
	});
	$('div#miniSearchSummaryHeader').click(function(){
		$('div#miniSearchSummary').slideToggle('fast')
	});
	

});
