$(document).ready(function(){
	
	
	// Comply with Mazda lower 'a' guideline
	$("em.lowera:contains('Mazda')").replaceWith("M{zd{")
						   
						   
	// Put your headers that need to be converted to Cufon here
	 Cufon.replace('.submit,h1,h2,h3,ul#fLeg,.speListItem h3,.speListItem h4,.speContItem h2,.btn,#breadcrumbs,.modelSpecial,#anav-models,#anav-cars,#anav-parts,#anav-owners,#anav-service,#anav-finance,#anav-contact, .pacc_specials_item h4, .pacc_specials_item h5, #new-models li, #explore h3,.hp-carousel-item h4,ul#hp-actions li', { fontFamily: 'Mazda', hover: true });
	 Cufon.replace('.inv-col-head, .speCalls li a,#footer h4,#explore h4,#explore-calls,h3.pacc_expandable,.cars-link-enquire-now, .cars-link-view-details,#callme-number,#hp-carousel h2, .pricelist li', { fontFamily: 'Florencesans SC', hover: true });
	
	 
	
	 
	 // Adjust right side explorer so that it fits its content's height
	 $("#explore-content.other").css('height',$(".explore-model.other").css('height'))
	
	// Check if # present in url
	var URL = unescape(window.document.location)
	var splitUrl = ""
	var visDiv = ""
	if (URL.indexOf("#") > -1) {
		var splitUrl = URL.split("#")
		var visDiv = splitUrl[1]
	}
	
	
	// Prefill directions on HP
	/*var dirsStart = "Enter start address"
	$("#hp-bottom #displayDirs #saddr")
		.val(dirsStart)
		.live('focus',function(){if($(this).val() == dirsStart) $(this).val('')})*/
	
	/******************************/
	// Specials
	/******************************/
	
	// Show a special's details when click on a menu item
	$(".speListItem").click(function(){
		var tId = $(this).attr('id').split('-')
		var tImg = $(this).children('input').val()
		var tDiv = "#spe-"+tId[1]
		vis(".speContItem",true)
		vis(".speTerms",true)
		$(tDiv).children('img').attr('src',tImg)
		vis(tDiv)
	})
	
	// Show first special
	vis(".speContItem:first")
	
	// Terms & conditions hover reveal
	showHideSub(".speTermsLink",".speTerms")
	
	// Show specific special if url var defined
	if(visDiv && visDiv.indexOf("speItem") > -1) {
		//alert(visDiv)
		spVis = visDiv.split('-')
		var sImg = $("#speList-"+spVis[1]).children('input').val()
		$("#spe-"+spVis[1]).children('img').attr('src',sImg)
		vis(".speContItem",true)
		vis("#spe-"+spVis[1])
	}

	
	/******************************/
	// 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() {
        $(this).datepicker()
    })
	
	
	
	
	 
	 // Load first model in the list in the subnav
	 subnavLoad($("#subnav-models a:first"))
	 
	 // Load ajax content for items in the subnav
	 $("#subnav-models a").hover(function(){
		$(this).oneTime(200,function(){
			subnavLoad($(this))
		})
	 },function(){$(this).stopTime()})
	 
	 //reset links to preserve accessibility without making the screen "jump"
	$("#new-vehicle-hero-right li a").each(function(){
		if($(this).attr('id')) {
			var linkAttr = $(this).attr("href")
			$(this).attr("name",linkAttr)
			$(this).removeAttr("href")
		}
	})
	
	// Ditto
	$("#new-vehicle-nav a").each(function(){
			var linkAttr = $(this).attr("href")
			$(this).attr("name",linkAttr)
			$(this).removeAttr("href")
	})
	
	// Display first tabbed div
	vis(".vec-features:first")
	
	
	//Show/hide Features
	$("#new-vehicle-nav a").click(function(){
		var href = $(this).attr('name')
		$("#new-vehicle-nav a").each(function(){
			var hrefLi = $(this).attr('name')
			vis(hrefLi,true)
			$(this).parent().removeClass('active')
		})
		vis(href)
		$(this).parent().addClass('active')
	})
	
	//Show different colours
	$("ul.colours li").click(function(){
		$("ul.colours li").removeClass('active')
		$(this).addClass('active')
	});
	
	$("#colourDesc").html($("#new-colours ul li:first span").html())
	
	// Model details page slideshow
	
	$("#nms-browser div li:first").addClass('active')
	
	$("#nms-hero").attr('src',$("#nms-browser div li:first img").attr('src'))
	
	$("#nms-browser div li").click(function(){
		var thisImgSrc = $(this).children('img').attr('src')
		$("#nms-hero").attr('src',thisImgSrc)
		$("#nms-browser div li").removeClass('active')
		$(this).addClass('active')
	})
	
	// anav submenus
	showHideSub("#anav-models","#subnav-models")
	showHideSub("#cp-mName","#cp-mName ul")
	showHideSub("#anav-offers","#subnav-offers")
	showHideSub("#anav-cars","#subnav-cars")
	showHideSub("#anav-owners","#subnav-owners")
	showHideSub("#anav-contact","#subnav-contact")

	/*$("#anav li a").each(function(){
								  //alert('yes')
		//alert($(this).next('ul').attr('id'))
		showHideSub($(this),$(this).next('ul'))
	})*/
	
	$("#specials_left li").click(function(){
		$("#specials_left li").each(function(){
			var thisH5 = $(this).children('h5')
			thisH5.removeClass("active")
		})
		var thisH5 = $(this).children('h5')
		thisH5.addClass("active")
	})
	
	var modSlide = 292
	$(".model-prev").click(function(){
		$("#explore-range").animate({left: '+='+modSlide})
		var prevDiv = $(".explore-model:nth-child("+($(this).parent().index())+")")
		if($(this).parent().hasClass('other')) {
			var tH = parseInt(prevDiv.css('height'))+10
			$("#explore-content").css('height',tH+'px')
		}
	})
	$(".model-next").click(function(){
		$("#explore-range").animate({left: '-='+modSlide})
		var nextDiv = $(".explore-model:nth-child("+($(this).parent().index()+2)+")")
		if($(this).parent().hasClass('other')) {
			//$("#explore-content.other").css('height',$(".explore-model.other").css('height'))
			var tH = parseInt(nextDiv.css('height'))+10
			$("#explore-content").css('height',tH+'px')
		}
		else {	
			var nextDivImgSrc = nextDiv.children("input").val()
			var nextDivCont = nextDiv.children("img")
			if(!nextDivCont.attr('src')) loadImg(nextDivCont,nextDivImgSrc)
		}
	})
	
	//$("#cFin")
	//alert($(window).height())
})



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 genForm(args) {
	if(!$("#formContainer").length) $("#content").prepend('<div id="formContainer"></div>')
	$("#formContainer").load("form-generator.php?"+args,function(){
			Cufon.replace('#multiform h2, #multiform h3', { fontFamily: 'Florencesans SC', hover: true });
			Cufon.replace('.fSend', { fontFamily: 'Mazda', hover: true });
			// Resize the form's max height to fit viewport (Tom 1/6/11)
			$("#multiform").css('max-height',($(window).height()-50)+'px')
		})
}


$.expr[':'].icontains = function(obj, index, meta, stack){ return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0; };
