noCuf = false
cntRangeSlide = 1

$(document).ready(function(){

	
	// Put your headers that need to be converted to Cufon here
	Cufon.replace('.cars-list-title2,.cars-list-price,#cars-actions li,#footer,div.model_tab_feats div h3,.orangeBt,.model_tab_range div.feats h4,#anav,.grey_calls,#breadcrumbs,h2,#new_vehicles li,#model_tabs,#build_status h5,.inv-col-head,#carTabs li a,#modDetails h3', { fontFamily: 'Myriad Pro', hover: true });	
	
	//if($.browser.msie) alert($.browser.version.substring(0))
	
	//if(!($.browser.msie && $.browser.version.substring(0) == "7.0") && noCuf) {
		Cufon.replace('.special_unit h3,.special_unit h4,ul.specials,.common h3')
	//}

	 
	 //.model_tab_range h3
	$("#cars-photos-more").hover(function(){
		 	
		$(this).text("Click here for more photos");
	 
	},
	function(){
		
	     $(this).text("Click on images for larger view");
	  
	 
		
	});
	$(".anav li a:not(.active)").hover(function(){
		$(this).addClass("active");
		$(this).parent().addClass("active");
	},function(){
		$(this).removeClass("active");
		$(this).parent().removeClass("active");
	});
	
	
	
	$("#carTabs li a").click(function(){
		
		var thisref = $(this).attr('id').replace("link","tab");
		vis(".carTabs",true)
		$("#carTabs li a").removeClass("active");
		$("#"+thisref).show();
		$(this).addClass("active")
		if(thisref=="tab-locate")
		$("#tab-locate").height(500);
	    else
		$("#tab-locate").height(0);
		
	});
	
	$(".customer_success h3").click(function(){
		var childP = $(this).parent().children("p");
		if(childP.css("display") == "none") childP.slideDown(500,'easeInQuad');
		else childP.slideUp();
	});
	
	$("#nav-sale").hover(function(){
		$(this).stopTime();
		vis("#subMenu");
	},function(){
		$(this).oneTime(500,function(){
			vis("#subMenu",true);
		})
	});
	
	$("#subMenu").hover(function(){
		$("#nav-sale")
			.addClass('active')
			.stopTime()
			.parent('li').addClass('active');
	},function(){
		$("#nav-sale").oneTime(500,function(){
			$(this)
				.removeClass('active')
				.parent('li').removeClass('active');
			vis($("#subMenu"),true);
		})
	});
	
	
	/***********************/
	// Calls to action
	/***********************/
	
	$(".calls_action li a, .call_to_action, .cal_normal, .cal_special").livequery('click',function(){
		var thisId = $(this).attr('id');
		var thisMod = $(this).attr('title');
		var thisBrand = $(this).attr('name');
		var thisMsg = $(this).attr('rel');
		var thisClass = $(this).attr('class');
		var service = false
		
		if(thisClass == 'cal_special' || thisClass == 'cal_normal') {
			service = true
			var serviceSpecial =  $(this).children('span').length ? $(this).children('span').html() : ''
		}
		
		// Email my build configuration
		if(thisId == 'call_build_email') {
			var emUrl = $(this).next('input').val()
		}
		
				if (!$("#blackened").length) $("body").prepend('<div id="blackened"></div>');
				$("#blackened")
					.css('opacity',0.7)
					.fadeIn('fast');
				var imgPosX = ($(document).width() - 748) / 2;
				var imgPosY = ($(window).height() - 150);
				
				$("#calls_action")
					.addClass('boxClass2')
					.css('max-height',imgPosY+'px')
				$("#calls_action_container")
					.addClass('boxClass')
					.css({"left":imgPosX+"px","top":"50px"})

			
			//Insert wait graphic while loading...
			$("#calls_action").html('<img src="'+THIS_SITE_URL+'images/loading.gif" title="Please wait" />');
			
			//Load ajax
			//alert(THIS_SITE_URL)
			$("#calls_action_container").fadeIn('normal',function(){
					if(service) { //If service specials calendar
						$("#calls_action").load('calls.php?call=call_service&serviceDate='+escape(thisId)+'&serviceSpecial='+escape(serviceSpecial),function(){
							$(this).prepend('<img src="'+THIS_SITE_URL+'images/calls-close.gif" title="Close this window" id="calls-close" />')
							//Cufon.replace('#calls_action h2, #calls_action h3,.orangeBt', { fontFamily: 'Myriad Pro', hover: true })
							$("#calls_action").css('display','block');
							}
						);
					}
					else {
						$("#calls_action").load('calls.php?call='+thisId+'&brand='+escape(thisBrand)+'&model='+escape(thisMod)+'&msg='+escape(thisMsg),function(){
							$(this).prepend('<img src="'+THIS_SITE_URL+'images/calls-close.gif" title="Close this window" id="calls-close" />')
							//Cufon.replace('#calls_action h2, #calls_action h3, .orangeBt', { fontFamily: 'Myriad Pro', hover: true })
							$("#calls_action").css('display','block');
							}
						);
					}
			});
	});
	
	//close button
	$("#calls-close").livequery('click',function(){
		$("#calls_action_container").fadeOut(function(){
			$("#calls_action").html('');
			$("#calls_action").css('display','none');
			$("#blackened").fadeOut('fast',function(){$(this).remove();});
		});
	});
	
	
	/***********************/
	// Specials
	/***********************/
	
	$("ul.specials li a")
		.click(function(){
			var leftX = ($(this).attr('id') * 455) * -1;
			$("#special_container")
				.css('opacity',0.4)
				.animate({left:leftX+'px'},function(){$(this).css('opacity',1); $(this).css('filter','');});
			$("ul.specials li a").removeClass('active');
			$(this).addClass('active');
		})
	
	//Assigns the first range Id value to rangeId
	$("#rangeId").val($(".model_tab_range h3:first input").val());
	
	var clear;

	//Trim list behaviors (hover and onclick)
	$("#trim_container ul li")
		.livequery('hover',function(){
			var offset = $(this).position();
			$(this).parent().children(".model_tab_colours_info").remove();
			$(this).parent().append('<div class="model_tab_colours_info" style="left:'+(offset.left + 2)+'px"><p>'+$(this).children('span').html()+'</p></div>');
		})
		.livequery('click',function() {
			$("#build_container ul li").removeClass('active');
			$(this).addClass('active');
			var newTrim = $(this).find('span').html()
			$("#bt_to_next_step").attr("href",$("#bt_to_next_step").attr("href").replace(/trim=([_\s\+0-9a-z-]+)+/i,'trim='+newTrim))
		});
	
	//Colours list behaviors (hover and onclick)
	
	$("ul.model_colours_tab_ul li")
		.hover(function(){
			var offset = $(this).position();
			$(this).parent().children(".model_tab_colours_info").remove();
			info_window($(this),offset);
		})
		.click(function() {
			$(this).stopTime();
			$("ul.model_colours_tab_ul li").children('img').attr('src',THIS_SITE_URL+'images/model_tab_colours_bg_colour.png');
			$(this).children('img').attr('src',THIS_SITE_URL+'images/model_tab_colours_bg_colour_selected.png');
			
			var actTrim = '';
			
			// Load colour image via ajax
			loadImg($("#colour_image_container").children('img'),$(this).children('input').val());
			
			// Load trim name & image for current colour
			if ($(this).children('div:first').children('div').size() > 0 ) {
				var tcv = '<ul>'
				var cntTrims = 0
				$(this).children('div:first').children('div').each(function(){
					var active = !cntTrims ? ' class="active"' : ''
					if(!cntTrims) actTrim = $(this).children('input:first').val()
					tcv += '<li'+active+'><img src="'+$(this).children('input:last').val()+'" /> <span>'+$(this).children('input:first').val()+'</span></li>'
					cntTrims++
					//$("#trim_container div").html($(this).children('input:first').val())
					//loadImg($("#trim_container img"),$(this).children('input:last').val())
				})
				tcv += '</ul>'
				$("#trim_container").html(tcv)
			}
			
			updateLink("&colour="+$(this).children('span').html()+'&trim='+actTrim)
			info_window($("#trim_container ul li.active"),$("#trim_container ul li.active").position());
			
		});
		
		
	//accessories
	$("div.model_tab_feats div").click(function(){
		var thisParent = $(this);
		var thisChecked = $(this).children('input').attr('checked');
		if(!thisChecked) $(this).children('input').attr('checked', true);
		else $(this).children('input').attr('checked', false);
		if(thisParent.hasClass("active")) thisParent.removeClass('active');
		else thisParent.addClass("active");
		updateLink('',true)
	});
	
	$("#subscribe input.subscribe").focus(function(){
		if($(this).val() == 'Enter your name' || $(this).val() == 'Enter your email address') {
			$(this).val('');
		}
	});
	
	vis(".model_tab_range div.feats.active");
	
	
	//Sliding menu
	$("#sliding_arrow").click(function(){
		slidingMenu();
	});
	
	$("#slide-budget").livequery('click',function(){toggleSearch('budget');});
	$("#slide-regular").livequery('click',function(){toggleSearch('regular');});
	
	$("#cars-search-actions ul li a").hover(function(){
		var nextDiv = $(this).next('div');
		var parentLi = $(this).parent('li');
		parentLi.stopTime();
		parentLi.oneTime(350,function(){
			vis(nextDiv);
		});
	},function(){
		parentLi.oneTime(350,function(){
			vis(nextDiv,true);
		});
	});
	
	$("#cars-search-actions ul li div:first").hover(function(){
		var myself = $(this);
		var parentLi = $(this).parent('li');
		parentLi.stopTime();
	},function(){
		parentLi.oneTime(350,function(){
			vis(myself,true);
		});
	});
	
	var mouseondiv=0;
	
	$("#cars-search-actions2 ul li a").hover(function(){
		
	    nextDiv = $(this).next('div');
		parentLi = $(this).parent('li');
		$("#cars-search-actions2 ul li div").css("display","none");
		nextDiv.css("display","block");
														 });
	
    $("#cars-search-actions2 ul li a").mouseout(function(){
		     nextDiv = $(this).next('div');					 
			nextDiv.oneTime(350,function(){
				               if(mouseondiv==0)
							       $(this).css("display","none");
																	  });
			
			                                      });
	$("#cars-search-actions2 ul li div").mouseover(function(){
		   $(this).css("display","block");
		   mouseondiv=1;
														   });
		$("#cars-search-actions2 ul li div").mouseout(function(){
		   $(this).css("display","none");
		   mouseondiv=0;
														   });
	
	
	
	
	//Jquery calendar on service booking page
	$("#preferred_booking_date, #preferred_test_drive_date").livequery('click',function(){
		$(this).datepicker({showOn:'focus',dateFormat: 'dd/mm/yy', minDate: 0}).focus();
	});
	
	//Service specials calendar
	 $("td.cal_special, td.cal_normal").livequery('mousemove',function(e){
		var action = '<p><strong>Click to book a service on that date!</strong></p>';
		if($(this).attr('class') == 'cal_normal')	$("#follower").html(action);
		else $("#follower").html('<p>'+$(this).children('span').html()+'</p>'+action);
		//alert(e.pageX);
        $("#follower").css({
            top: (e.pageY + 15) + "px",
            left: (e.pageX - $("#follower").width()) + "px",
			display: 'block'
        });
      });
	 
	 $("td.cal_special,td.cal_normal").livequery('mouseout',function(e){
        $("#follower").css('display','none');
      });
	 
	
	$("#rangeSlideUp.on").livequery('click',function(){
		rangeSlide(true);
	})
	$("#rangeSlideDown.on").livequery('click',function(){
		rangeSlide(false);
	})
	
	
	//Model range behaviors (hover and onclick)
		$(".model_tab_range h3:not(.active)").css('opacity',0.6);
		$(".model_tab_range h3")
		.click(function(){
			var id = $(this).attr('id');
			$(".model_tab_range h3.active, .model_tab_range div.feats").removeClass('active');
			vis('.feats',true);
			vis('#div-'+id);
			$(".model_tab_range h3").css('opacity',0.6);
			$('#div-'+id).addClass('active');
			//changeContainerHeight('#div-'+id);
			$(this)
				.css('opacity',1)
				.addClass('active');
			var clear = false;
			$("#rangeId").val($(this).children('input:first').val());
			
			updateLink('?variant='+encodeURIComponent($(this).find('span').html()))
		})
		.hover(function(){
			var clear = false;
			if($(this).css('opacity') != 1) {		
				$(this).css('opacity',1);
				clear = true;
			}
		},function(){if(clear) $(this).css('opacity',0.6);});	
	
	
});

//Generates an info bubble
function info_window(trigger,offset) {
	if(offset) {
		trigger.parent().append('<div class="model_tab_colours_info" style="left:'+(offset.left + 2)+'px"><p>'+trigger.children('span').html()+'</p></div>');
	}
}

//Update right hand side status window
function update_status() {
	$("#build_status div:first")
		.html('<img src="'+THIS_SITE_URL+'images/loading.gif" width="200" title="Please wait" />')
		.load(THIS_SITE_URL+'model_build_status.php');
}

//Hide/show an element
function vis(element,hide) {
	if(!hide) var hide = false;
	var change = hide ? 'none' : 'block';
	$(element).css('display',change);
}

function update_model_tabs(first,firstEffect,second,secondEffect) {
	$("#model_tabs li"+first+", #model_tabs li"+first+" strong").removeClass('active').addClass(firstEffect);
	$("#model_tabs li"+second+", #model_tabs li"+second+" strong").addClass(secondEffect);
}


function changeContainerHeight(newHeight) {
	var murf = parseInt($(newHeight).css('height'))+60;
	$("#build_container").css('height',murf+'px');
}

function slidingMenu() {
	//Expand menu
	if(!$("#sliding_arrow").hasClass('active')) {
			$("#sliding_container").animate({right:'+=304'},function(){
				$("#sliding_arrow")
					.addClass('active')
					.attr('src',THIS_SITE_URL+'images/sliding_arrow_active.png');
				$('#sliding_menu').animate({width:'304'},function(){
					$(this).html('<img src="'+THIS_SITE_URL+'images/loading.gif" title="Please wait" />');
					$(this).load(THIS_SITE_URL+'sliding_menu.php',function(){$('#sliding_menu div:first').fadeIn()});
				});
			});
	}
	//Minimize menu
	else {
		$("#sliding_arrow").removeClass('active');
		$('#sliding_menu div:first').animate({opacity:'0'},function(){
				$('#sliding_menu')
					.html('')
					.animate({width:'0'},function(){
						$("#sliding_container").animate({right:'-=304'});
						$("#sliding_arrow").attr('src',THIS_SITE_URL+'images/sliding_arrow.png');
					});
		})
	}
}

function ajaxTransition() {
	$("#build_container").html('<img src="'+THIS_SITE_URL+'images/loading.gif" />');
}

function sendMy(args) {
	alert(args);
}

function toggleSearch(toAppear) {
	var toDisappear = toAppear == "budget" ? "regular" : "budget";
	vis("#slide-search-"+toAppear);
	vis("#slide-search-"+toDisappear,true);
	$("#slide-"+toAppear).addClass('active');
	$("#slide-"+toDisappear).removeClass('active');
}

function displayCalendar(month,year) {
	$("#service-specials").prepend('<div id="wait"></div>');
	$("#wait").html('<img src="images/loading.gif" />');
    $("#wait").css('display','block');
	$("#service-specials").load('include-calendar.php?month='+month+'&year='+year, function(){
		Cufon.replace('#service-specials h3');
		$("#wait").css('display','none');
		$("#wait").remove();
		}
	);
}


function rangeSlide(up) {
	if(up) {
		$("#rangeH3s").animate({top:'+=400'});
		cntRangeSlide--;
	}
	else {
		$("#rangeH3s").animate({top:'-=400'});
		cntRangeSlide++;
	}
	//alert(cntRangeSlide+' and '+totalRangeSlide);
	rangeUpdateBt(cntRangeSlide);
}

function rangeUpdateBt(cntRangeSlide) {
	if(cntRangeSlide < totalRangeSlide) $("#rangeSlideDown").addClass("on");
	else $("#rangeSlideDown")
		.removeClass('on')
		.addClass("off");
		
	if(cntRangeSlide > 1) $("#rangeSlideUp").addClass("on");
	else $("#rangeSlideUp")
		.removeClass('on')
		.addClass("off");
}



/***** Finance Calculator ****/

function cmdCalc_Click(frm) {
    if (frm.price.value == 0 || frm.price.value.length == 0 || GetValue(frm.price.value)=="") {
        alert ("Please enter a purchase price");
        frm.price.focus(); }
    else if (frm.ir.value == 0 || frm.ir.value.length == 0) {
        alert ("Please enter a valid interest rate");
        frm.ir.focus(); }
    else
        calculatePayment(frm);
	return false;
}

function checkNumber(input, msg) {
    msg = msg ;
    var str = input.value;
    for (var i = 0; i < str.length; i++) {
        var ch = str.substring(i, i + 1)
        if ((ch < "0" || "9" < ch) && ch != '.') {
            alert(msg);
            return false;
        }
    }
    input.value = str;
    return true;
}

function GetValue(str) {
	str2 = "";
	for( i = 0; i < str.length; i++ )
	{
		if ((str.charAt(i) >= '0' && str.charAt(i) <= '9')||str.charAt(i)=='.') str2 = str2 + str.charAt(i)
	}
	return str2;
}

function calculatePaymentOld(frm) {
	princ = GetValue(frm.price.value) - GetValue(frm.deposit.value) + parseInt(GetValue(frm.onroad.value)) - GetValue(frm.tradein.value);
	intRate = ((frm.ir.value)/1200);
	months = frm.term.value*12;
	frm.pmt.value = '$' + (Math.floor((princ*intRate)/(1-Math.pow(1+intRate,(-1*months)))*100)/100) + '*';
}

function calculatePayment(frm) {
	princ = GetValue(frm.price.value) - GetValue(frm.deposit.value) + (GetValue(frm.onroad.value)*1) - GetValue(frm.tradein.value);
	intRate = ((frm.ir.value)/1200);
	months = frm.term.value*12;
	balper = GetValue(frm.residual.value);
	
	fv = -(princ*balper/100);
	fv = parseFloat(fv);
	princ = parseFloat(princ);

	x = Math.pow(1 + intRate,(1*months));
	pmttemp 	  = (Math.floor(((intRate * (fv + x * princ))/(-1 + x))*100)/100);
	frm.pmt.value = '$' + pmttemp.toFixed(2) + '*';
	
	priceAdd = GetValue(frm.price.value);
	priceTop = parseFloat(priceAdd) + parseFloat(5000);
	priceBot = priceAdd - 5000;
	document.getElementById('searchlink').style.display = 'block';
	document.getElementById('searchlink').href = 'cars-list.html?search=1&demo=on&used=on&make=All+Makes&model=All+Models&pricemin=' + priceBot + '&pricemax=' + priceTop + '&yearmin=Min&yearmax=Max&transmission=any';
	
}


function loadImg(container,imgSrc) {
	container.before('<div class="mCache"></div>')
	container
		.attr('src', imgSrc)
		.one("load",function(){
			var me = $(this)
				$(".mCache").fadeOut(function(){
					//$("#new-colours-switch div").html(me)
				})
		})
		// In case IE ignores load event, force image to display after 2 secs
		.oneTime(2000,function(){
			if(this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6)) 
			$(this).trigger("load");
		})
}

function updateLink(val,access) {
	if(!access) access = false
	else {
		val = ''
		$("div.model_tab_feats div.active").each(function(){
			val += val ? '||' : ''
			val += $(this).find('input').val()
		})
		val = '&accessories='+val
	}
	//alert($("#currLinkVal").val()+val+"#model_tabs")
	$("#bt_to_next_step,#nextLink").attr("href",$("#currLinkVal").val()+val+"#model_tabs")
}
