$(document).ready(function(){

						   
	// Put your headers that need to be converted to Cufon here
	 Cufon.replace('.blueSide > ul, .details h4,.cta li,#header li,#header span,#footer h3, #left li a, h1, h2,.listItem > div h4, #model-features h4, #build_status h5,#bt_to_next_step, #model-features li, #testimonials h3', { fontFamily: 'Eurostile', hover: true });
	 
	 // Display first png image on model details page
	 if($("#model-features").length) {
		var hImg = $(".listItem:first > div img").attr('src')
		$("#model-features").prepend('<img src="'+hImg+'" />')
	 }
	 
	 // Blue side box behaviors
	 vis(".blueSide > div:first")
	 
	 $(".blueSide > ul li").click(function() {
	 	//$(".blueSide > ul li").removeClass('active')
		//$(this).addClass('active')
		vis(".blueSide > div",true)
		vis(".blueSide > div:eq("+$(this).index()+")")
		Cufon.refresh()
	 })
	 
	 $(".bsLocate").click(function(){
	 	$("#bsLocate > div:first").load('include-map.php')
	 })
	 
	 // Trigger chosen plugin
	 $(".chzn-select").chosen()
	 
	 $(".cars-gallery").each(function(){$(this).children("a:first").css('display','block')})
	 //vis(".cars-gallery a:first")
	 
	 $(".pcs_list p").hover(function(){$(this).addClass('over')},function(){$(this).removeClass('over')})
	 
	 // ???
	 $("#left ul li > a").each(function(){
		if($(this).next('div').length) {			
	 		showHideSub('#'+$(this).attr('id'),'#overlay-'+$(this).attr('id'))
		 }
	 })
	 
	 // Preferred contact method
	 $(".pcm").live('click',function(){
	 	vis("#pcm")
		val = $(this).val();
		$("#pcm label").html(val+"<span>*</span>")
	 })
	 
	 $("#newsForm").attr('action','http://www.phase.com.au/forms/afp_spam.asp?formid=1240')
	
	// Parts / accessories
	$("#hondaParts").change(function(){
		val = $(this).val()
		$("#hpVars")
			.html('<img src="images/loading.gif" />')
			.load("hp.php?model="+val)
	})
	
	// Show / hide accessories for a given variant
	$("#hpVars select").live('change',function(){
		vis("#hpVars table",true)
		vis("#hpVars table:eq("+$(this).val()+")")
	})
	 
	 showHideSub("#specials h5","#specials > div > div > div > span")
	 showHideSub("#whyBuySub","#whyBuy")
	 showHideSub("#bt-search-refine",".refine")
	 showHideSub("#bt-search-budget",".budget")
	 
	 //$(".vec-features").each(function(){alert($(this).index())})
	 
	 // Specials menu behaviors
	 $("#specials > div > ul li a").click(function() {
	 	$("#specials > div > ul li a").removeClass('active')
		$("#specials > div > ul li img").remove()
		$(this).addClass('active')
		$(this).parent().prepend('<img src="images/bg-special-active.jpg" alt="" />')
		vis("#specials .vec-features",true)
		vis("#specials .vec-features > span",true)
		vis("#specials > div > div > div:nth-child("+($(this).parent().index()+1)+")")
	 })
	 
	 // Display first div for vehicle features
	 vis('.vec-features:first')
	 
	 // ??
	 $("#model-features > div li a").click(function(){
	 	var tId = $(this).attr('id')
		vis(".vec-features",true)
		vis("#div-"+tId)
		$("#model-features > div li").removeClass('active')
		 Cufon.replace("#model-features > div li")
		$(this).parent('li').addClass('active')
		 $("#model-features > div li img").remove()
		 $(this).prepend('<img src="images/arrow-blue.png" alt="" />')
	 })
	 
	 
	 /******************************/
	// Forms
	/******************************/
	
	// Remove empty class from items that need to be corrected by user on focus
	$(".ajForm input.empty").live('focus',function(){$(this).removeClass('empty')})
	
	// Update form action list
	$(".pFormCheck").live('click',function(){
		var checked = $(this).attr('checked')
		if(!checked) vis("#"+$(this).val(),true)
		else vis("#"+$(this).val())
	})
	
	// Launch the form processing action via ajax
	$(".pFormSubmit").live('click',function(event){					   
		var me = $(this).prev('.ajForm')
		$.ajax({
		  type: 'POST',
		  url: 'form-processor.php',
		  data: me.serialize(),
		  success: function(data){me.after(data);},
		  dataType: 'text'
		})
	})
	
	$("#fClose").live('click',function(){
		$("#formContainer").html('')
	})
	
	// Jquery UI date picker
	$(".jCal").live('focus', function() {
		if($(this).hasClass('noSunday')) $(this).datepicker({ minDate: 0, dateFormat: 'dd/mm/yy',firstDay: 1,beforeShowDay:noSunday})
        else $(this).datepicker({ minDate: 0, dateFormat: 'dd/mm/yy',firstDay: 1,beforeShowDay: $.datepicker.noWeekends })
    })
	
	 function noSunday(date){ 
          var day = date.getDay(); 
          return [(day > 0), '']; 
      }; 
	 
	 
	 //Trim list behaviors (hover and onclick)
	$("#trim_container ul li")
		.live('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>');
			//$(this).parent().append('<div class="model_tab_colours_info"><p>'+$(this).children('span').html()+'</p></div>');
		})
		.live('click',function() {
			$("#build_container ul li, #trim_container ul li").removeClass('active');
			$(this).addClass('active');
			var newTrim = $(this).find('span').html()
			$(this).parent().children(".model_tab_colours_info").remove();
			$("#bt_to_next_step").attr("href",$("#bt_to_next_step").attr("href").replace(/trim=([_\s\+0-9a-z-]+)+/i,'trim='+newTrim))
			//info_window($(this),0,true);
		});
	 
	 
	 //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() {
			$("ul.model_colours_tab_ul li").removeClass('active');
			$(this).stopTime();
			$(this).addClass('active');
			
			// Load colour image via ajax
			loadImg($("#colour_image_container").children('img'),$(this).children('input').val());
			var actTrim = ''
			// 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)
			}
			var colName = $(this).children('span').html()
			//alert(actTrim)
			updateLink("&colour="+colName+'&trim='+actTrim)
			$("#colStatus div").html(colName)
			//updateLink("&colour="+$(this).children('span').html()) // TEMP, replace asap!!!!!!!!!!!!
			//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)
		});
		
		vis(".model_tab_range div.feats.active");
	 
	 
	 	/*$("#subscribe input.subscribe").focus(function(){
			if($(this).val() == 'Enter your name' || $(this).val() == 'Enter your email address') {
				$(this).val('');
			}
		});*/
		
		
		// Finance tab
		
		vis("#model-expand.finance > div:first")
		
		$("#model-expand.finance > ul li a").click(function(){
			$("#model-expand.finance > ul li a").removeClass('active')
			$("#model-expand.finance > ul li img").remove()
			vis("#model-expand.finance > div",true)
			$(this).parent().append('<img src="images/arrow-green.png" />')
			$(this).addClass('active')
			//alert($(this).parent().index())
			vis("#model-expand.finance > div",true)
			vis("#model-expand.finance > div:eq("+$(this).parent().index()+")")
		})
		
		$("#hp-search h3").click(function(){
			if(!$(this).hasClass('active')) {
				vis("#hp-search div",true)
				$("#hp-search h3").removeClass('active').addClass('inactive')
				$(this).addClass('active').removeClass('inactive')
				vis($(this).next('div'))
			}
		})
		
		
		$("#search_pcs_make").live('change',function(){
			//alert('yes')
			searchRefresh()
		})
		
		$(".search_check").live('click',function(){
			//alert('yes')
			searchRefresh()
		})
		
})



function vis(element,hide) {
	if(!hide) var hide = false
	var change = hide ? 'none' : 'block'
	$(element).css('display',change)
}

function showHideSub(trigger,element) {
		var both = trigger+','+element
		$(both).live('hover',function(event){
									//  alert(event.type)
			if (event.type == 'mouseenter') {
				//alert('on')
				$(trigger).stopTime()
				$(trigger).addClass("hover")
				$(element).css('display','block')
			}
			else {
				//alert('off')
				$(trigger)
					.oneTime(250,function(){$(element).fadeOut(250,function(){$(trigger).removeClass("hover")})})
			}
		})
}

function subnavLoad(trigger) {
	$("#subnav-models a").removeClass('active')
	trigger.addClass('active')
	var modName = trigger.html()
	$("#subModelContent").html('<img src="images/wait22trans.gif" />')
	$("#subModelContent").load("subnav-ajax.php?model="+escape(modName))
 }
 
 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+"&tab=build#"+$("#variantName").val())
}


$.expr[':'].icontains = function(obj, index, meta, stack){ return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0; };

function cmdCalc_Click(frm) {
										
	//if (!checkNumber(frm.ir,'Please enter only digits'))
	//return false;
    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 if (frm.term.value == 0 || frm.term.value.length == 0) {
        alert ("Please enter a valid loan term");
        frm.term.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);
		}
	}
	
	if(str2=="")
	str2=0;
	
	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) + '*';
}

function genForm(args,container,scroll) {
	if(!scroll) scroll = false
	if(!container) {
		if(!$("#formContainer").length) $(".content").append('<div id="formContainer"></div>')
		container = '#formContainer'
	}
	$(container).prepend("<img src='images/loading.gif' />")
	$(container).load("form-generator.php?"+args,function(){
			$(".chzn-select").chosen()
			if(scroll) $.scrollTo(container,500)
	})
}

function searchRefresh() {
	//alert($("#search_pcs_make").val())
	var pcs_make = $("#search_pcs_make").val()
	var pcs_exclude = $("#pcs_exclude").val()
	//alert('ok')
	pcs_type = ''
	$(".search_check:checked").each(function(){
		pcs_type += pcs_type ? ',' : ''
		pcs_type += $(this).val()
	})
	pcs_model = $("#search_pcs_model").length ? $("#search_pcs_model").val() : ''
	//$("#pcs_search").html('images/loading.gif')
	$("#pcs_search").load('carsystem-ajax.html?pcs_make='+pcs_make+'&pcs_model='+pcs_model+'&pcs_type='+pcs_type+'&pcs_exclude='+pcs_exclude)
}



