var DHTML_SUITE_THEME_FOLDER = "includes/dhtml-suite-batur/themes/";
var DHTML_SUITE_THEME = 'blue';

var txtIndex = document.location.pathname;
if (document.location.hostname.indexOf('crackle01') != -1)
	txtIndex = '/Go Leasing/www/index.php';
else if (document.location.hostname.indexOf('go-leasing.com') != -1)
	txtIndex = '/index.php';

function funInclude(txtFile)
{
	document.write('<'+'script');
	document.write(' language="javascript"');
	document.write(' type="text/javascript"');
	document.write(' src="'+txtFile+'">');
	document.write('</'+'script'+'>');
}

/*
funInclude('includes/dhtml-suite-batur/js/ajax.js');
funInclude('includes/dhtml-suite-batur/js/separateFiles/dhtmlSuite-common.js');
funInclude('includes/dhtml-suite-batur/js/separateFiles/dhtmlSuite-ajaxUtil.js');
funInclude('includes/dhtml-suite-batur/js/separateFiles/dhtmlSuite-imageEnlarger.js');
funInclude('includes/dhtml-suite-batur/js/separateFiles/dhtmlSuite-dynamicContent.js');
funInclude('includes/dhtml-suite-batur/js/separateFiles/dhtmlSuite-modalMessage.js');
*/

//var enlargerObj = '';

OldOnLoad = function() {};

if (typeof(window.onload) == 'function')
	OldOnLoad = window.onload;

window.onload=function() {
	OldOnLoad();
	
	funLoadMMD();
	funInitialiseCompareDialog();
	
	//enlargerObj = new DHTMLSuite.imageEnlarger();
	
	/*
	objAjax = new DHTMLSuite.ajaxUtil();
	
	messageObj = new DHTMLSuite.modalMessage();
	messageObj.setWaitMessage('Loading ....');
	messageObj.setShadowOffset(5);	// Large shadow

	DHTMLSuite.commonObj.setCssCacheStatus(false);
	*/
	try
	{
		funPerPageLoad();
	}
	catch(err)
	{
	}
	
	$('select').combobox();
	
	preloader();
}

var intProductImage = 0;

function funProductImageSwap(num)
{
	var divRef1 = document.getElementById('product-image-'+num);
	var divRefThumb1 = document.getElementById('product-thumb-'+num);
	var divRef2 = document.getElementById('product-image-'+intProductImage);
	var divRefThumb2 = document.getElementById('product-thumb-'+intProductImage);
	
	divRef1.style.display = '';
	divRefThumb1.style.display = 'none';
	divRef2.style.display = 'none';
	divRefThumb2.style.display = 'inline';
	
	intProductImage = num;
}

function funProductImageLarge(imagePath,title,description)
{
	enlargerObj.displayImage(imagePath,title,description);
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  var OptionWindow = window.open(theURL,winName,features);
  OptionWindow.focus();
}

function funShowGallery()
{
	var divRef = document.getElementById('gallery-area-backing');
	var divRef2 = document.getElementById('gallery-area');
	
	divRef.style.opacity = 0;
    divRef.style.MozOpacity = 0;
    divRef.style.filter = "alpha(opacity=0)";
    divRef.style.display = '';
    divRef.style.position = 'absolute';
    divRef.style.top = 0+'px';
    divRef.style.left = 0+'px';
    divRef.style.zIndex = 90000;
    divRef.style.width = funGetBrowserWidth() + 'px';
    if (document.body.clientHeight + 50 < funGetBrowserHeight)
    	divRef.style.height = document.body.clientHeight + 50 + 'px';
    else
    	divRef.style.height = '3000px';
    
    divRef2.style.zIndex = 90001;
    divRef2.style.display = '';
    funPositionCenter(divRef2.id);
   	divRef2.style.display = 'none';
    
   	funFadeIn('gallery-area-backing',0,5,10,'document.getElementById(\'gallery-area\').style.display=""; funPositionCenter(\'gallery-area\');');
}

function funHideGallery()
{
	var divRef = document.getElementById('gallery-area-backing');
	var divRef2 = document.getElementById('gallery-area');
	divRef.style.opacity = 1;
    divRef.style.MozOpacity = 1;
    divRef.style.filter = "alpha(opacity=100)";
    divRef.style.display = '';
    divRef.style.position = 'absolute';
    divRef.style.top = 0+'px';
    divRef.style.left = 0+'px';
    divRef.style.zIndex = 100000;
    divRef.style.width = funGetBrowserWidth() + 'px';
    divRef.style.height = document.body.clientHeight + 50 + 'px';
    
    divRef2.style.zIndex = 100001;
    divRef2.style.display = 'none';
    
   	funFadeOut('gallery-area-backing',80,5,10,'document.getElementById(\'gallery-area-backing\').style.display="none";');
}

function funFadeIn(id,opacity,fadeStep,fadeSpeed,callOnFinish)
{
	var i = 0;
	var a = 0;
	var multiplier = (document.all ? 2 : 1);
	
	var divRef = document.getElementById(id);
	callOnFinish = unescape(callOnFinish);
	
	divRef.style.opacity = (opacity / 100);
    divRef.style.MozOpacity = (opacity / 100);
    divRef.style.filter = "alpha(opacity=" + opacity + ")";
    
    opacity += (fadeStep * multiplier);
	
	if (opacity >= 100)
	{
		divRef.style.opacity = (opacity / 100);
	    divRef.style.MozOpacity = (opacity / 100);
	    divRef.style.filter = "alpha(opacity=" + opacity + ")";
		if (callOnFinish)
			eval(callOnFinish);
	}
	else
	{
		setTimeout('funFadeIn(\'' + id + '\','+ opacity +','+fadeStep+','+fadeSpeed+',\''+escape(callOnFinish)+'\')',(fadeSpeed / multiplier));
	}
}

function funFadeOut(id,opacity,fadeStep,fadeSpeed,callOnFinish)
{
	var i = 0;
	var a = 0;
	var multiplier = (document.all ? 2 : 1);
	
	var divRef = document.getElementById(id);
	callOnFinish = unescape(callOnFinish);
	
	divRef.style.opacity = (opacity / 100);
    divRef.style.MozOpacity = (opacity / 100);
    divRef.style.filter = "alpha(opacity=" + opacity + ")";
    
    opacity -= (fadeStep * multiplier);
	
	if (opacity <= 1)
	{
		if (callOnFinish)
			eval(callOnFinish);
	}
	else
	{
		setTimeout('funFadeOut(\'' + id + '\','+ opacity +','+fadeStep+','+fadeSpeed+',\''+escape(callOnFinish)+'\')',(fadeSpeed / multiplier));
	}
}

function funGetBrowserWidth()
{
	if(self.innerWidth)
		return self.innerWidth;
	
	return document.documentElement.offsetWidth;
}
	
function funGetBrowserHeight()
{
	if(self.innerHeight)
		return self.innerHeight;
	
	return document.documentElement.offsetHeight;
}

function funPositionCenter(id)
{
	var divRef = document.getElementById(id);
	
	divRef.style.position = 'absolute';
	
	var browserHeight = funGetBrowserHeight();
	var browserWidth = funGetBrowserWidth();
	var browserOffsetTop = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
	
	intTop = ((browserHeight - divRef.offsetHeight)/2)+browserOffsetTop;
	if (intTop < 0)
		intTop=0;
	if (browserOffsetTop > intTop)
		intTop = browserOffsetTop;
	
	intLeft = ((browserWidth - divRef.offsetWidth)/2);
	if (intLeft < 0)
		intLeft=0;
	
	divRef.style.top = intTop+'px';
	divRef.style.left =  intLeft+ 'px';
}

function preloader() 
{
     // counter
     var i = 0;

     // create object
     imageObj = new Array;

	 
	 // set image list
    images = new Array();
	images[0]="/images/bar-button-over.png"
	images[1]="/images/button-go-over.png"
	images[2]="/images/button-info-left-over.png"
	images[3]="/images/button-info-over.jpg"
	images[4]="/images/button-info-over.png"
	images[5]="/images/button-info-right-over.png"
	images[6]="/images/combobox-140-over.png"
	images[7]="/images/combobox-over.gif"
	images[8]="/images/combobox-over.png"
	images[9]="/images/compare-button-over.jpg"
	images[10]="/images/compare-select-middle-over.gif"
	images[11]="/images/compare-select-over.jpg"
	images[12]="/images/drop-down-over.png"
	images[13]="/images/feature-help-over.jpg"
	images[14]="/images/help-button-over.jpg"
	images[15]="/images/login-arrow-over.jpg"
	images[16]="/images/more-button-over.png"
	images[17]="/images/nav-manu-over.gif"
	images[18]="/images/page-next-over.gif"
	images[19]="/images/page-prev-over.gif"
	images[20]="/images/quote-button-over.jpg"
	images[21]="/images/rolling-arrow-left-over.jpg"
	images[22]="/images/rolling-arrow-right-over.jpg"
	images[23]="/images/tld-over.gif"
	images[24]="/images/type-4x4-over.jpg"
	images[25]="/images/type-convertible-over.jpg"
	images[26]="/images/type-coupe-over.jpg"
	images[27]="/images/type-estate-over.jpg"
	images[28]="/images/type-lrghatch-over.jpg"
	images[29]="/images/type-medhatch-over.jpg"
	images[30]="/images/type-mpv-over.jpg"
	images[31]="/images/type-nav-over.jpg"
	images[32]="/images/type-pickup-over.jpg"
	images[33]="/images/type-supermini-over.jpg"
	images[34]="/images/type-van-over.jpg"
	
	// start preloading
	for(i=0; i<images.length; i++) 
	{
		imageObj[i] = new Image();
		imageObj[i].src=images[i];
	}
}

window.onresize = function() {
	if (document.getElementById('gallery-area-backing'))
	{
		if (document.getElementById('gallery-area').style.display == '')
		{
			var divRef = document.getElementById('gallery-area-backing');
		
			divRef.style.position = 'absolute';
	    	divRef.style.top = 0+'px';
		    divRef.style.left = 0+'px';
	    	divRef.style.width = funGetBrowserWidth() + 'px';
		    divRef.style.height = document.body.clientHeight + 50 + 'px';
		    
	    	funPositionCenter('gallery-area');
		}
	}
}

function displayMessage(url)
{	
	messageObj.setSource(url);
	messageObj.setCssClassMessageBox(false);
	messageObj.setSize(500,300);
	messageObj.setShadowDivVisible(true);	// Enable shadow for these boxes
	messageObj.display();
}

function displayMessageIframe(url,width,height)
{	
	messageObj.setHtmlContent('<iframe src="' + url + '" width="' + width + '" height="' + height + '" frameborder="0"></iframe>');
	messageObj.setSize(width,height);
	messageObj.setShadowDivVisible(true);
	messageObj.display();
}

function closeMessage()
{
	messageObj.close();	
}

function aboutMessage(url)
{
	MM_openBrWindow(url,'aboutWin','width=950, height=150, scrollbars=yes');
}

function funAddToCart(name)
{
	var frmRef=document.getElementById(name);
	var params = "method=xml"
	var txtSep = "&"
	
	for (i=0;i<frmRef.elements.length;i++)
	{
		ename = frmRef.elements[i].name;
		
		if (frmRef.elements[i].type.toLowerCase() == 'checkbox' )
		{
			if (frmRef.elements[i].checked)
				params = params + txtSep + ename + '=' + funURLEncode(frmRef.elements[i].value);
			else
				continue;
		}
		else if (frmRef.elements[i].type.toLowerCase() == 'radio' )
		{
			if (frmRef.elements[i].checked)
				params = params + txtSep + ename + '=' + funURLEncode(frmRef.elements[i].value);
		}
		else
		{
			params = params + txtSep + ename + '=' + funURLEncode(frmRef.elements[i].value);
		}
		txtSep = "&";
	}
	objAjax.sendRequest('cart.php',params,'funAddToCartResponse');
}

function funAddToCartResponse(obj)
{
	try
	{
		var xmlDoc = obj.responseXML.documentElement;
	}
	catch(err)
	{
		alert('There was an error adding the item to the cart');
	}
	
	var ErrorMessage = "";
	var Services="";
	var CartLineID = "";
	
	if (xmlDoc.getElementsByTagName('ErrorMessage').length > 0)
	{
		if (xmlDoc.getElementsByTagName('ErrorMessage')[0].childNodes.length > 0)
			ErrorMessage = xmlDoc.getElementsByTagName('ErrorMessage')[0].childNodes[0].nodeValue;
	}
	if (xmlDoc.getElementsByTagName('CartLineID').length > 0)
	{
		if (xmlDoc.getElementsByTagName('CartLineID')[0].childNodes.length > 0)
			var CartLineID = xmlDoc.getElementsByTagName('CartLineID')[0].childNodes[0].nodeValue;
	}
	if (xmlDoc.getElementsByTagName('Services').length > 0)
	{
		if (xmlDoc.getElementsByTagName('Services')[0].childNodes.length > 0)
			var Services = xmlDoc.getElementsByTagName('Services')[0].childNodes[0].nodeValue;
		
		if (Services == 1)
			Services = true;
		else
			Services = false;
	}
	
	if (ErrorMessage == "" && CartLineID == "")
	{
		alert('There was an error processing your request');
	}
	else if (ErrorMessage == "")
	{
		if (Services)
			displayMessageIframe('includes/site/product-options.php?PostCart=1&CartLineID=' + CartLineID,520,420);
		else
			window.location.reload();
	}
	else
	{
		alert(ErrorMessage);
	}
}

function funURLEncode(txtValue)
{
	txtValue = encodeURI(txtValue);
	//txtValue = txtValue.replace(/%C2%A3/g,'%A3');
	txtValue = txtValue.replace(/&/g,'%26');
	txtValue = txtValue.replace(/=/g,'%3D');
	txtValue = txtValue.replace(/\?/g,'%3F');
	
	return txtValue;
}

function funManuTab(txtType)
{
	if (txtType == 'car')
	{
		$('#manu-tabs').removeClass('manu-type-van').addClass('manu-type-car');
		$('#manu-type-car-tab').removeClass().addClass('manu-type-active');
		$('#manu-type-van-tab').removeClass();
		$('#manu-type-car-options').removeAttr('style');
		$('#manu-type-van-options').attr('style','display:none');
	}
	else if (txtType == 'van')
	{
		$('#manu-tabs').removeClass('manu-type-car').addClass('manu-type-van');
		$('#manu-type-car-tab').removeClass();
		$('#manu-type-van-tab').removeClass().addClass('manu-type-active');
		$('#manu-type-car-options').attr('style','display:none');
		$('#manu-type-van-options').removeAttr('style');
	}
}

var intRollingOffer = 0;
var refTimeout = null;

function funInitiateRollingOffer()
{
	intWidth = $('.rolling-offer').outerWidth();
	intRollingOffer = $('#rolling-offers .rolling-offer').size();
	intRollingOffer += 2;
	$('#rolling-offer-slide').attr('style','width:' + intWidth*intRollingOffer + 'px');
	
	$('#rolling-offers .rolling-offer:first').clone().appendTo('#rolling-offer-slide');
	$('#rolling-offers .rolling-offer:nth-child(' + (intRollingOffer-2) + ')').clone().prependTo('#rolling-offer-slide');
	
	$('#rolling-offer-slide').css('left',(0-intWidth));
	$('#rolling-arrow-left').click(function(){if ($('#rolling-offer-slide').queue('fx').length < 2) { $('#rolling-offer-slide').queue('fx',function(){funRollingOfferSlide('left');})}});
	$('#rolling-arrow-right').click(function(){if ($('#rolling-offer-slide').queue('fx').length < 2) { $('#rolling-offer-slide').queue('fx',function(){funRollingOfferSlide('right');})}});
	
	refTimeout = setTimeout(function(){funRollingOfferSlide('left');},5000);
}

function funRollingOfferSlide(txtDirection)
{
	clearTimeout(refTimeout);
	
	intWidth = $('.rolling-offer').outerWidth();
	objPos = $('#rolling-offer-slide').position();
	intLastPos = 0-((intWidth*(intRollingOffer-2)));
	
	if (txtDirection == 'left')
	{
		if (objPos.left-intWidth < intLastPos) $('#rolling-offer-slide').css('left',0);
		$('#rolling-offer-slide').animate({left: '-='+intWidth},800,'easeInOutQuart');
	}
	else
	{
		if (objPos.left+intWidth > 0) $('#rolling-offer-slide').css('left',intLastPos);
		$('#rolling-offer-slide').animate({left: '+='+intWidth},800,'easeInOutQuart');
	}
	$('#rolling-offer-slide').dequeue();
	
	if ($('#rolling-offer-slide').queue('fx').length < 2)
		refTimeout = setTimeout(function(){funRollingOfferSlide('left');},5000);
}

var arrVehicleOptions = Object();
var blnInitVehicleOptions = true;

function funInitialiseVehicleOptions(txtForm)
{
	arrVehicleOptions = $.parseJSON($('#' + txtForm + '_export').val());
	
	funFetchVehicleOption('ContractType',txtForm);
}

function funFetchVehicleOption(txtName,txtForm)
{
	arrInitial = $('#'+txtForm+'_initial').val().split(';');
	if (arrVehicleOptions.length == 0)
		return false;
	
	if (txtName == 'ContractType')
	{
		divRef = $('#'+txtForm+''+txtName).get(0);
		for (i=divRef.options.length-1;i>=0;i--)
			divRef.remove(i);
		
		for (var key in arrVehicleOptions)
		{
			objOption = document.createElement('option');
			objOption.value = key;
			objOption.text = (key == 'pch' ? 'Personal' : 'Business');
			if (blnInitVehicleOptions && key == arrInitial[0])
				objOption.selected = true;
			try
			{
				divRef.add(objOption,null);
			}
			catch(err)
			{
				divRef.add(objOption);
			}
		}
		
		refCombo = $('#'+txtForm+txtName+'combobox').get(0);
		if (refCombo && divRef.selectedIndex != -1)
			refCombo.value = divRef.options[divRef.selectedIndex].text;
		if (divRef.selectedIndex != -1)
			funFetchVehicleOption('ContractLength',txtForm);
	}
	else if (txtName == 'ContractLength')
	{
		divRef = $('#'+txtForm+''+txtName).get(0);
		currentValue = divRef.value;
		for (i=divRef.options.length-1;i>=0;i--)
			divRef.remove(i);
		for (var key in arrVehicleOptions[$('#'+txtForm+'ContractType').val()])
		{
			objOption = document.createElement('option');
			objOption.value = key;
			objOption.text = (key/12) + ' Years';
			if ((blnInitVehicleOptions && key == arrInitial[1]) || (!blnInitVehicleOptions && key == currentValue))
				objOption.selected = true;
			try
			{
				divRef.add(objOption,null);
			}
			catch(err)
			{
				divRef.add(objOption);
			}
		}
		
		divRef2 = $('#'+txtForm+'ContractType').get(0);
		if (divRef2.value == 'ch')
		{
			$('#vehicle-options-bar').removeClass('bar-tall-ch');
			$('#frmQuote').removeClass('frmQuote-ch');
		}
		else
		{
			$('#vehicle-options-bar').addClass('bar-tall-ch');
			$('#frmQuote').addClass('frmQuote-ch');
		}
		
		refCombo = $('#'+txtForm+txtName+'combobox').get(0);
		if (refCombo && divRef.selectedIndex != -1)
			refCombo.value = divRef.options[divRef.selectedIndex].text;
		if (divRef.selectedIndex != -1)
			funFetchVehicleOption('Mileage',txtForm);
	}
	else if (txtName == 'Mileage')
	{
		divRef = $('#'+txtForm+''+txtName).get(0);
		currentValue = divRef.value;
		for (i=divRef.options.length-1;i>=0;i--)
			divRef.remove(i);
		for (var key in arrVehicleOptions[$('#'+txtForm+'ContractType').val()][$('#'+txtForm+'ContractLength').val()])
		{
			objOption = document.createElement('option');
			objOption.value = key;
			objOption.text = key + ' miles';
			if ((blnInitVehicleOptions && key == arrInitial[2]) || (!blnInitVehicleOptions && key == currentValue))
				objOption.selected = true;
			try
			{
				divRef.add(objOption,null);
			}
			catch(err)
			{
				divRef.add(objOption);
			}
		}
		
		refCombo = $('#'+txtForm+txtName+'combobox').get(0);
		if (refCombo && divRef.selectedIndex != -1)
			refCombo.value = divRef.options[divRef.selectedIndex].text;
		if (divRef.selectedIndex != -1)
			funFetchVehicleOption('Maintained',txtForm);
	}
	else if (txtName == 'Maintained')
	{
		divRef = $('#'+txtForm+''+txtName).get(0);
		currentValue = divRef.value;
		for (i=divRef.options.length-1;i>=0;i--)
			divRef.remove(i);
		for (var key in arrVehicleOptions[$('#'+txtForm+'ContractType').val()][$('#'+txtForm+'ContractLength').val()][$('#'+txtForm+'Mileage').val()])
		{
			objOption = document.createElement('option');
			objOption.value = key;
			objOption.text = (key == 0 ? 'No' : 'Yes');
			if ((blnInitVehicleOptions && key == arrInitial[3]) || (!blnInitVehicleOptions && key == currentValue))
				objOption.selected = true;
			try
			{
				divRef.add(objOption,null);
			}
			catch(err)
			{
				divRef.add(objOption);
			}
		}
		
		refCombo = $('#'+txtForm+txtName+'combobox').get(0);
		if (refCombo && divRef.selectedIndex != -1)
			refCombo.value = divRef.options[divRef.selectedIndex].text;
		if (divRef.selectedIndex != -1)
			funFetchVehicleOption('MonthDeposit',txtForm);
	}
	else if (txtName == 'MonthDeposit')
	{
		divRef = $('#'+txtForm+''+txtName).get(0);
		currentValue = divRef.value;
		for (i=divRef.options.length-1;i>=0;i--)
			divRef.remove(i);
		for (var key in arrVehicleOptions[$('#'+txtForm+'ContractType').val()][$('#'+txtForm+'ContractLength').val()][$('#'+txtForm+'Mileage').val()][$('#'+txtForm+'Maintained').val()])
		{
			if (key < 3)
				continue;
			
			objOption = document.createElement('option');
			objOption.value = key;
			objOption.text = key + ' Months';
			if ((blnInitVehicleOptions && key == arrInitial[4]) || (!blnInitVehicleOptions && key == currentValue))
				objOption.selected = true;
			try
			{
				divRef.add(objOption,null);
			}
			catch(err)
			{
				divRef.add(objOption);
			}
		}
		
		refCombo = $('#'+txtForm+txtName+'combobox').get(0);
		if (refCombo && divRef.selectedIndex != -1)
			refCombo.value = divRef.options[divRef.selectedIndex].text;
		if (divRef.selectedIndex != -1)
			funFetchVehicleOption('values',txtForm);
	}
	else if (txtName == 'values')
	{
		objRef = arrVehicleOptions[$('#'+txtForm+'ContractType').val()][$('#'+txtForm+'ContractLength').val()][$('#'+txtForm+'Mileage').val()][$('#'+txtForm+'Maintained').val()][$('#'+txtForm+'MonthDeposit').val()];
		var dblCost = new Number(objRef['Cost']);
		var dblDeposit = new Number(objRef['Deposit']);
		var dblArrangementFee = new Number(objRef['ArrangementFee']);
		$('#todays-price').html('&pound;' + dblCost.toFixed(2) + ($('#'+txtForm+'ContractType').val() == 'pch' ? ' inc' : ' excl') + ' VAT per month');
		$('#initial-payment').html('&pound;' + dblDeposit.toFixed(2) + ($('#'+txtForm+'ContractType').val() == 'pch' ? ' inc' : ' excl') + ' VAT');
		$('#arrangement-fee').html('&pound;' + dblArrangementFee.toFixed(2) + ($('#'+txtForm+'ContractType').val() == 'pch' ? ' inc' : ' excl') + ' VAT');
		$('#monthly-payment').html($('#'+txtForm+'ContractLength').val()-1);
		$('#frmQuoteTodaysPrice').val(dblCost.toFixed(2));
		$('#frmQuoteInitialPayment').val(dblDeposit.toFixed(2));
		$('#frmQuoteArrangementFee').val(dblArrangementFee.toFixed(2));
		blnInitVehicleOptions = false;
	}
}

var arrMMD = Object();

function funLoadMMD()
{
	/*$.ajax({
			url: txtIndex,
			cache: true,
			data: '_ajax=json',
			success: function(txtJson) {
				arrMMD = $.parseJSON(txtJson);
				try
				{
					funPerMMDLoad();
				}
				catch(err)
				{
				}
			},
			error: function() {
				
			}
		});*/
	try
	{
		funPerMMDLoad();
	}
	catch(err)
	{
	}
}

function funLoadVehicleOptions(txtForm)
{
	txtType = $('#'+txtForm+'type').val();
	txtManufacturer = $('#'+txtForm+'manufacturer').val();
	txtModel = $('#'+txtForm+'model').val();
	txtDerivative = $('#'+txtForm+'derivative').val();
	
	$('#todays-price').html('calculating...');
	$('#initial-payment').html('calculating...');
	$('#arrangement-fee').html('calculating...');
	$('#monthly-payment').html($('#'+txtForm+'ContractLength').val()-1);
	
	$.ajax({
			url: txtIndex,
			cache: true,
			data: '_ajax=json&_ajaxtype=leasing&type='+funURLEncode(txtType)+'&manufacturer='+funURLEncode(txtManufacturer)+'&model='+funURLEncode(txtModel)+'&derivative='+funURLEncode(txtDerivative),
			success: function(txtJson) {
				var arrTemp = $.parseJSON(txtJson);
				arrVehicleOptions = arrTemp[0];
				if ($('#'+txtForm+'_initial').val() == '')
					$('#'+txtForm+'_initial').val(arrTemp[1]);
				blnInitVehicleOptions = true;
				funFetchVehicleOption('ContractType',txtForm);
			},
			error: function() {
				
			}
		});
}

function funLoadVehicleImage(txtForm)
{
	txtType = $('#'+txtForm+'type').val();
	txtManufacturer = $('#'+txtForm+'manufacturer').val();
	txtModel = $('#'+txtForm+'model').val();
	txtDerivative = $('#'+txtForm+'derivative').val();
	
	$.ajax({
			url: txtIndex,
			cache: true,
			data: '_ajax=json&_ajaxtype=image&type='+funURLEncode(txtType)+'&manufacturer='+funURLEncode(txtManufacturer)+'&model='+funURLEncode(txtModel)+'&derivative='+funURLEncode(txtDerivative),
			success: function(txtJson) {
				var objImage = $.parseJSON(txtJson);
				if (objImage['smallImage'] != '')
					$('#'+txtForm+'VehicleImage').attr('href',objImage['largeImage']).css('backgroundImage','url(\'' + objImage['smallImage'] + '\')');
				else
					$('#'+txtForm+'VehicleImage').attr('href','#').css('backgroundImage','none');
			},
			error: function() {
				$('#'+txtForm+'VehicleImage').attr('href','#').css('backgroundImage','none');
			}
		});
}

function funSelectTypes(txtForm)
{
	refVType = $('#'+txtForm+'vtype').get(0);
	refType = $('#'+txtForm+'type').get(0);
	refManufacturer = $('#'+txtForm+'manufacturer').get(0);
	refModel = $('#'+txtForm+'model').get(0);
	refDerivative = $('#'+txtForm+'derivative').get(0);
	
	currentValue = refType.value;
	
	for (i=refType.options.length;i>=0;i--)
		refType.remove(i);
	
	try
	{
		if (refType)
		{
			$.ajax({
				url: txtIndex,
				cache: true,
				data: '_ajax=json&_ajaxtype=types',
				success: function(txtJson) {
					objTypes = $.parseJSON(txtJson);
					for (var key in objTypes)
					{
						objOption = document.createElement('option');
						objOption.value = key;
						objOption.text = objTypes[key];
						if (key == currentValue)
							objOption.selected = true;
						try
						{
							refType.add(objOption,null);
						}
						catch(err)
						{
							refType.add(objOption);
						}
					}
					
					refCombo = $('#'+txtForm+'typecombobox').get(0);
					if (refCombo)
						refCombo.value = refType.options[refType.selectedIndex].text;
					
					funSelectManufacturers(txtForm);
				},
				error: function() {
					
				}
			});
		}
	}
	catch(e)
	{
	}
}

function funSelectManufacturers(txtForm)
{
	refVType = $('#'+txtForm+'vtype').get(0);
	refType = $('#'+txtForm+'type').get(0);
	refManufacturer = $('#'+txtForm+'manufacturer').get(0);
	refModel = $('#'+txtForm+'model').get(0);
	refDerivative = $('#'+txtForm+'derivative').get(0);
	
	currentValue = refManufacturer.value;
	
	for (i=refManufacturer.options.length;i>0;i--)
		refManufacturer.remove(i);
	
	try
	{
		if (refType)
		{
			$.ajax({
				url: txtIndex,
				cache: true,
				data: '_ajax=json&_ajaxtype=manufacturers&type='+encodeURIComponent(refType.value),
				success: function(txtJson) {
					objManufacturers = $.parseJSON(txtJson);
					for (var key in objManufacturers)
					{
						objOption = document.createElement('option');
						objOption.value = key;
						objOption.text = objManufacturers[key];
						if (key == currentValue)
							objOption.selected = true;
						try
						{
							refManufacturer.add(objOption,null);
						}
						catch(err)
						{
							refManufacturer.add(objOption);
						}
					}
					
					if (refManufacturer.options.length == 1)
					{
						objOption = document.createElement('option');
						objOption.value = '';
						objOption.text = 'No Manufacturers Found';
						objOption.className = 'red';
						try
						{
							refManufacturer.add(objOption,null);
						}
						catch(err)
						{
							refManufacturer.add(objOption);
						}
					}
					refCombo = $('#'+txtForm+'manufacturercombobox').get(0);
					if (refCombo)
						refCombo.value = refManufacturer.options[refManufacturer.selectedIndex].text;
					
					funSelectModels(txtForm);
				},
				error: function() {
					
				}
			});
		}
		else if (refVType)
		{
			$.ajax({
				url: txtIndex,
				cache: true,
				data: '_ajax=json&_ajaxtype=manufacturers&vtype='+encodeURIComponent(refVType.value),
				success: function(txtJson) {
					objManufacturers = $.parseJSON(txtJson);
					for (var key in objManufacturers)
					{
						objOption = document.createElement('option');
						objOption.value = key;
						objOption.text = objManufacturers[key];
						if (key == currentValue)
							objOption.selected = true;
						try
						{
							refManufacturer.add(objOption,null);
						}
						catch(err)
						{
							refManufacturer.add(objOption);
						}
					}
					
					if (refManufacturer.options.length == 1)
					{
						objOption = document.createElement('option');
						objOption.value = '';
						objOption.text = 'No Manufacturers Found';
						objOption.className = 'red';
						try
						{
							refManufacturer.add(objOption,null);
						}
						catch(err)
						{
							refManufacturer.add(objOption);
						}
					}
					refCombo = $('#'+txtForm+'manufacturercombobox').get(0);
					if (refCombo)
						refCombo.value = refManufacturer.options[refManufacturer.selectedIndex].text;
					
					funSelectModels(txtForm);
				},
				error: function() {
					
				}
			});
		}
	}
	catch(e)
	{
	}
}

function funSelectModels(txtForm)
{
	refVType = $('#'+txtForm+'vtype').get(0);
	refType = $('#'+txtForm+'type').get(0);
	refManufacturer = $('#'+txtForm+'manufacturer').get(0);
	refModel = $('#'+txtForm+'model').get(0);
	refDerivative = $('#'+txtForm+'derivative').get(0);
	
	currentValue = refModel.value;
	
	for (i=refModel.options.length;i>0;i--)
		refModel.remove(i);
	
	/*if (refDerivative)
	{
		for (i=refDerivative.options.length;i>0;i--)
			refDerivative.remove(i);
	}*/
	
	try
	{
		if (refType)
		{
			$.ajax({
				url: txtIndex,
				cache: true,
				data: '_ajax=json&_ajaxtype=models&type='+encodeURIComponent(refType.value)+'&manufacturer='+encodeURIComponent(refManufacturer.value),
				success: function(txtJson) {
					objModels = $.parseJSON(txtJson);
					for (var key in objModels)
					{
						objOption = document.createElement('option');
						objOption.value = key;
						objOption.text = objModels[key];
						if (key == currentValue)
							objOption.selected = true;
						try
						{
							refModel.add(objOption,null);
						}
						catch(err)
						{
							refModel.add(objOption);
						}
					}
					
					if (refModel.options.length == 1)
					{
						objOption = document.createElement('option');
						objOption.value = '';
						objOption.text = 'No Models Found';
						objOption.className = 'red';
						try
						{
							refModel.add(objOption,null);
						}
						catch(err)
						{
							refModel.add(objOption);
						}
					}
					
					refCombo = $('#'+txtForm+'modelcombobox').get(0);
					if (refCombo)
						refCombo.value = refModel.options[refModel.selectedIndex].text;
					
					if (refDerivative)
						funSelectDerivatives(txtForm);
				},
				error: function() {
					
				}
			});
		}
		else if (refVType)
		{
			$.ajax({
				url: txtIndex,
				cache: true,
				data: '_ajax=json&_ajaxtype=models&vtype='+encodeURIComponent(refVType.value)+'&manufacturer='+encodeURIComponent(refManufacturer.value),
				success: function(txtJson) {
					objModels = $.parseJSON(txtJson);
					for (var key in objModels)
					{
						objOption = document.createElement('option');
						objOption.value = key;
						objOption.text = objModels[key];
						if (key == currentValue)
							objOption.selected = true;
						try
						{
							refModel.add(objOption,null);
						}
						catch(err)
						{
							refModel.add(objOption);
						}
					}
					
					if (refModel.options.length == 1)
					{
						objOption = document.createElement('option');
						objOption.value = '';
						objOption.text = 'No Models Found';
						objOption.className = 'red';
						try
						{
							refModel.add(objOption,null);
						}
						catch(err)
						{
							refModel.add(objOption);
						}
					}
					
					refCombo = $('#'+txtForm+'modelcombobox').get(0);
					if (refCombo)
						refCombo.value = refModel.options[refModel.selectedIndex].text;
					
					if (refDerivative)
						funSelectDerivatives(txtForm);
				},
				error: function() {
					
				}
			});
		}
	}
	catch(e)
	{
	}
}

function funSelectDerivatives(txtForm)
{
	refVType = $('#'+txtForm+'vtype').get(0);
	refType = $('#'+txtForm+'type').get(0);
	refManufacturer = $('#'+txtForm+'manufacturer').get(0);
	refModel = $('#'+txtForm+'model').get(0);
	refDerivative = $('#'+txtForm+'derivative').get(0);
	
	currentValue = refDerivative.value;
	
	for (i=refDerivative.options.length;i>0;i--)
		refDerivative.remove(i);
	
	try
	{
		if (refType)
		{
			$.ajax({
				url: txtIndex,
				cache: true,
				data: '_ajax=json&_ajaxtype=derivatives&type='+encodeURIComponent(refType.value)+'&manufacturer='+encodeURIComponent(refManufacturer.value)+'&model='+encodeURIComponent(refModel.value),
				success: function(txtJson) {
					objDerivatives = $.parseJSON(txtJson);
					for (var key in objDerivatives)
					{
						objOption = document.createElement('option');
						objOption.value = key;
						objOption.text = objDerivatives[key];
						if (key == currentValue)
							objOption.selected = true;
						try
						{
							refDerivative.add(objOption,null);
						}
						catch(err)
						{
							refDerivative.add(objOption);
						}
					}
					
					refCombo = $('#'+txtForm+'derivativecombobox').get(0);
					if (refCombo)
						refCombo.value = refDerivative.options[refDerivative.selectedIndex].text;
				},
				error: function() {
					
				}
			});
		}
		else if (refVType)
		{
			$.ajax({
				url: txtIndex,
				cache: true,
				data: '_ajax=json&_ajaxtype=derivatives&vtype='+encodeURIComponent(refVType.value)+'&manufacturer='+encodeURIComponent(refManufacturer.value)+'&model='+encodeURIComponent(refModel.value),
				success: function(txtJson) {
					objDerivatives = $.parseJSON(txtJson);
					for (var key in objDerivatives)
					{
						objOption = document.createElement('option');
						objOption.value = key;
						objOption.text = objDerivatives[key];
						if (key == currentValue)
							objOption.selected = true;
						try
						{
							refDerivative.add(objOption,null);
						}
						catch(err)
						{
							refDerivative.add(objOption);
						}
					}
					
					refCombo = $('#'+txtForm+'derivativecombobox').get(0);
					if (refCombo)
						refCombo.value = refDerivative.options[refDerivative.selectedIndex].text;
				},
				error: function() {
					
				}
			});
		}
	}
	catch(e)
	{
	}
}

function funInitialiseCompareDialog()
{
	$('#compare-dialog').dialog({
			autoOpen: false,
			height: 250,
			width: 220,
			modal: true,
			buttons: {
				'Add Vehicle': function() {
					var txtError = '';
					var txtForm = 'frmCompareDialog';
					if ($('#'+txtForm+'manufacturer').val() == '')
						txtError = 'Please select a manufacturer';
					else if ($('#'+txtForm+'model').val() == '')
						txtError = 'Please select a model';
					else if ($('#'+txtForm+'derivative').val() == '')
						txtError = 'Please select a derivative';
					
					if (txtError != '')
					{
						$(this).dialog('option','height',275);
						$('#compare-dialog .validateTips').text(txtError).attr('style','').addClass('ui-state-error');
						//setTimeout(function() {$('#compare-dialog .validateTips').removeClass('ui-state-error', 1500);}, 500);
					}
					else
					{
						$.ajax({
							url: txtIndex,
							cache: false,
							data: $('#frmCompareDialog').serialize(),
							success: function(html) {
								txtLocation = new String(document.location);
								if (txtLocation.indexOf('/compare.php') != -1)
									document.location.reload();
								else
									$('#p7ABc1_2').html(html);
								$('#compare-dialog').dialog('close');
							},
							error: function() {
								$('#compare-dialog').dialog('close');
							}
						});
					}
				},'Cancel': function() {
					$(this).dialog('close');
				}
			},
			open: function() {
				var selRef = $('#frmCompareDialogmanufacturer').get(0);
				selRef.selectedIndex = 0;
				funSelectTypes('frmCompareDialog');
				$('#compare-dialog .validateTips').attr('style','display:none');
				$('#frmCompareDialogslot').val($(this).data('slot'));
				$(this).dialog('option','height',250);
			}
		});
	//$("#compare-dialog").data('dvt',$('#compare-dialog .validateTips').text());
	
	$('#compare-dialog-confirm').dialog({
			autoOpen: false,
			resizable: false,
			height:160,
			modal: true,
			buttons: {
				'Remove': function() {
					$.ajax({
						url: txtIndex,
						cache: false,
						data: '_ajax=compare&_action=remove&VehicleID=' + $(this).data('VehicleID'),
						success: function(html) {
							txtLocation = new String(document.location);
							if (txtLocation.indexOf('/compare.php') != -1)
								document.location.reload();
							else
								$('#p7ABc1_2').html(html);
							$('#compare-dialog-confirm').dialog('close');
						},
						error: function() {
							$('#compare-dialog-confirm').dialog('close');
						}
					});
				},
				'New Comparison': function() {
					$(this).dialog('close');
					$('#compare-dialog').dialog('open');
				},
				'View': function() {
					document.location = $(this).data('href');
					$(this).dialog('close');
				}
			}
		});
	$("#compare-dialog-replace").dialog({
			autoOpen: false,
			resizable: false,
			height:280,
			width:400,
			modal: true,
			buttons: {
				'Cancel': function() {
					$(this).dialog('close');
				}
			}
		});
	$("#callback-dialog").dialog({
			autoOpen: false,
			resizable: false,
			height:375,
			width:300,
			modal: true,
			buttons: {
				'Request Call Back': function() {
					var txtForm = 'frmCallbackDialog';
					var txtName = $('#'+txtForm+'Name').val();
					var txtTel = $('#'+txtForm+'Phone').val();
					var txtDetail = $('#'+txtForm+'Details').val();
					
					if (txtDetail == 'Any details / comments')
						$('#'+txtForm+'Details').val('');
					
					var txtError = '';
					if (txtName == '' || txtName == 'Your Name')
						txtError = 'Please enter your name';
					else if (txtTel == '' || txtTel == 'Telephone Number')
						txtError = 'Please enter your telephone number';
					
					if (txtError != '')
					{
						$('#callback-dialog .validateTips').text(txtError).addClass('ui-state-error');
						//setTimeout(function() {$('#callback-dialog .validateTips').removeClass('ui-state-error', 1500);}, 500);
					}
					else
					{
						$.ajax({
							url: txtIndex,
							cache: false,
							data: $('#frmCallbackDialog').serialize(),
							success: function(txtResponse) {
								if (txtResponse == 'OK')
								{
									$('#callback-dialog-thank').dialog('open');
									$('#callback-dialog-thank').html($('#callback-dialog-thank').html()+'<!-- Google Code for Call Back Request Conversion Page --><script type="text/javascript">/* <![CDATA[ */var google_conversion_id = 1015909924;var google_conversion_language = "en";var google_conversion_format = "3";var google_conversion_color = "ffffff";var google_conversion_label = "5stHCOT3ngIQpJy25AM";var google_conversion_value = 0;/* ]]> */</script><script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion.js"></script><noscript><div style="display:inline;"><img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1015909924/?label=5stHCOT3ngIQpJy25AM&amp;guid=ON&amp;script=0"/></div></noscript>');
									$('#callback-dialog').dialog('close');
								}
								else
								{
									$('#callback-dialog .validateTips').text('There was a problem requesting your call back. Please try again.').addClass('ui-state-error');
									//setTimeout(function() {$('#callback-dialog .validateTips').removeClass('ui-state-error', 1500);}, 500);
									$('#callback-dialog .validateTips').text($(this).data('dvt'));
								}
							},
							error: function() {
								$('#callback-dialog .validateTips').text('There was a problem requesting your call back. Please try again.').addClass('ui-state-error');
								//setTimeout(function() {$('#callback-dialog .validateTips').removeClass('ui-state-error', 1500);}, 500);
								$('#callback-dialog .validateTips').text($(this).data('dvt'));
							}
						});
					}
				},
				'Cancel': function() {
					$(this).dialog('close');
				}
			},
			open: function() {
				$('#callback-dialog .validateTips').text($(this).data('dvt'));
				$('#frmCallbackDialogVehicleID').val($(this).data('VehicleID'));
				$(this).data('VehicleID',null);
				$('#frmCallbackDialogName').focus().blur();
			}
		});
	$("#callback-dialog").data('dvt',$('#callback-dialog .validateTips').text());
	$("#callback-dialog-thank").dialog({
			autoOpen: false,
			resizable: false,
			height:250,
			width:300,
			modal: true,
			buttons: {
				'Close': function() {
					$(this).dialog('close');
				}
			}
		});
}

function funCompare(intVehicleID)
{
	intCount = 0;
	$('#frmCompareVehiclesRight li a').each(function(index){if ($(this).attr('href') == '#') return false; intCount++;});
	if (intCount == 3)
	{
		if ($('#compare-dialog-replace').data('slot') || $('#compare-dialog-replace').data('slot') == 0)
		{
			$.ajax({
				url: txtIndex,
				cache: false,
				data: '_ajax=compare&VehicleID='+funURLEncode(intVehicleID)+'&slot='+funURLEncode($('#compare-dialog-replace').data('slot')),
				success: function(html) {
					txtLocation = new String(document.location);
					if (txtLocation.indexOf('/compare.php') != -1)
						document.location.reload();
					else
						$('#p7ABc1_2').html(html);
				}
			});
			$('#compare-dialog-replace').data('slot',null);
		}
		else
		{
			$('#compare-dialog-replace-buttons').html('');
			$('#frmCompareVehiclesRight li a').each(
				function(index) {
					var html = '<button onclick="$(\'#compare-dialog-replace\').data(\'slot\','+index+').dialog(\'close\');funCompare('+intVehicleID+')">' + $(this).text() + '</button>';
					$('#compare-dialog-replace-buttons').html($('#compare-dialog-replace-buttons').html() + html);
				}
			);
			$("#compare-dialog-replace").dialog('open');
		}
	}
	else
	{
		$.ajax({
				url: txtIndex,
				cache: false,
				data: '_ajax=compare&VehicleID='+funURLEncode(intVehicleID),
				success: function(html) {
					txtLocation = new String(document.location);
					if (txtLocation.indexOf('/compare.php') != -1)
						document.location.reload();
					else
						$('#p7ABc1_2').html(html);
				}
			});
		$('#compare-dialog-replace').data('slot',null);
	}
}

function funValidateQuoteRequest(txtForm)
{
	var txtError = '';
	
	var txtForename = $('#'+txtForm+'Forename').val();
	var txtSurname = $('#'+txtForm+'Surname').val();
	var txtEmailAddress = $('#'+txtForm+'EmailAddress').val();
	var txtPhone = $('#'+txtForm+'Phone').val();
	
	if (txtForename == '')
		txtError = 'Please enter your first name';
	else if (txtSurname == '')
		txtError = 'Please enter your last name';
	else if (txtEmailAddress == '')
		txtError = 'Please enter your email address';
	else if (txtPhone == '')
		txtError = 'Please enter your phone number';
	
	if (txtError == '')
		return true;
	
	$('#'+txtForm+'ErrorText').removeAttr('style').text(txtError).addClass('ui-state-error');
	return false;
}

function funHelpMe()
{
	var txtError = '';
	var txtForm = 'frmNeedHelp';
	
	var txtName = $('#'+txtForm+'Name').val();
	var txtEmailAddress = $('#'+txtForm+'EmailAddress').val();
	var txtPhone = $('#'+txtForm+'Phone').val();
	var refContactMethodEmail = $('#'+txtForm+'ContactMethod').get(0);
	var refContactMethodTel = $('#'+txtForm+'ContactMethodTel').get(0);
	var txtContactMethod = (refContactMethodEmail.checked ? refContactMethodEmail.value : refContactMethodTel.value);
	
	if (txtName == 'Enter Name') txtName = '';
	if (txtEmailAddress == 'Enter Email') txtEmailAddress = '';
	if (txtPhone == 'Enter Telephone Number') txtPhone = '';
	
	if (txtName == '')
		txtError = 'Please enter your name';
	else if (txtEmailAddress == '' && txtContactMethod == 'Email')
		txtError = 'Please enter your email address';
	else if (txtPhone == '' && txtContactMethod == 'Telephone')
		txtError = 'Please enter your telephone number';
	
	if (txtError == '')
	{
		$.ajax({
			url: txtIndex,
			cache: false,
			data: $('#frmNeedHelp').serialize(),
			success: function(html) {
				$('#p7ABc1_1').html(html);
			},
			error: function() {
				txtError = 'There was a problem sending your request. Please try again';
				$('#'+txtForm+' .validateTips').removeAttr('style').text(txtError).addClass('ui-state-error');
			}
		});
	}
	else
	{
		$('#'+txtForm+' .validateTips').removeAttr('style').text(txtError).addClass('ui-state-error');
	}
}
