//Edit this value to change the menus' opacity
var haloOpacity = 0.7;

var haloWhiteOpacity = 0.7;

$(document).ready(function(){
	//Change menu appearance for news page
	$("#menu-right li a").each(function(){
		var innerContent = $(this).html();
		switch(innerContent) {
			case 'New Model Articles':
				$(this).html('<strong>New Model</strong> <span>Articles</strong>');
				$(this).parent("li").css('background','none');
				break;
			case 'Future Model Articles':
				$(this).html('<strong>Future Model</strong> <span>Articles</span>');
				break;
			case 'All Subaru Articles':
				$(this).html('<strong>All Subaru</strong> <span>Articles</span>');
				break;
		}
	});
	
	//Display different test drive routes
	$(".testDriveRoute").click(function(){
		vis("#test-drive-form");
		var testDriveId = $(this).attr('id');
		h5 = $(this).attr('value');
		switch(testDriveId) {
			case 'test_drive_route_1':
				h6 = '10-15 minutes';
				testDriveContent = "<p><strong>Get in. Buckle your seatbelt. And turn the key.</strong></p><p>For the next quarter of an hour, you'll be giving your favourite Subaru the spin you've always wanted to. Zip around some of the surrounding suburban roads, feeling the gears, the handling and the grip.</p><p>There's time enough in this quick dash to get a good feel for the car, to get comfortable behind the wheel, and to feel how eagerly it responds to your every move. Time enough even to fall in love.</p>";
				break;
			case 'test_drive_route_2':
				h6 = '30-40 minutess';
				testDriveContent = "<p><strong>Here, you can really get a good feel for your chosen Subaru.</strong> And if you want to see what it can do in lots of different driving environments, this is the test drive for you. With over half an hour to play with on this predetermined route, you can get it out of the city and out there on the freeway.</p><p>Give yourself time to enjoy the power. Feel the sure-footedness. Then somehow find a way to give it back when you're done.</p>";
				break;
			case 'test_drive_route_3':
				h6 = '';
				testDriveContent = "<p><strong>With this option, you can choose your own way - literally.</strong> Spend time with your chosen Subaru in a variety of conditions, and feel free to take it on a route that mixes up different conditions - from city traffic to open freeways.</p><p>What did the car make of your favourite bit of road? How did it feel in traffic? This option really gives you the chance to answer these questions and more.</p>";
				break;
			case 'test_drive_route_4':
				h6 = '';
				testDriveContent = "<p><strong>This option starts with us bringing your chosen Subaru to your home or work.</strong> After all, you know those streets so well. Every corner, every shortcut, every scenic detour. This is your patch so there's no better place to put your favourite Subaru to the test. It's a great opportunity to show your Subaru sales consultant around your area of town!</p>";
				break;
		}
		
		$("#test-drive-form h5").html(h5);
		$("#test-drive-form h6").html(h6);
		$("#test-drive-form div").html(testDriveContent);
	});
	
	$("#new-vehicle-models h3").hover(function(){
		vis("#models-menu");
		$("#models-menu").stopTime();
	},function(){
		$("#models-menu").oneTime(500,function(){vis("#models-menu",true);});
	});
	
	//Hide relevant divs on press escape 
	 $('html').bind('keyup', function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
		 if(code == 27) {
			hideOverlay();
		 }
	});
	
	$("#menu-right li a:first").attr('class','active');
	
	Cufon.replace('#anav a, #footer h2,.home li a, #bnav a, #cnav span,.common h1,.cars-list-enquire a,#cars-actions a,#cars-search-actions a,#content-left-inside h2,#home-search h2,#content-left-inside h3,#content-left-inside h4,#new-vehicle-models h3,.model-car h4,#new-vehicle-nav li a,#models-menu li a,#new-vehicles li a,#cache-content h1,#service-specials h3');

	Cufon.replace('#menu-right li a, .bigbutton', {hover: true});
	
	$("#models-menu li a").click(function(){
		var hrefModel = $(this).attr('name');
		$(".model-car").each(function(){$(this).css('display','none');});
		vis(hrefModel);
		vis("#models-menu",true);
		$("#models-menu").stopTime();
	});
	
	$("#models-menu li a").hover(function(){
		$("#models-menu").stopTime();
	},function(){$("#models-menu").oneTime(500,function(){vis("#models-menu",true);});});
						   
	$("#new-vehicle-nav a").each(function(){
			var linkAttr = $(this).attr("href");
			if (linkAttr.indexOf("#") > -1 && linkAttr.indexOf("#") == 0) {
				$(this).attr("name",linkAttr);
				$(this).removeAttr("href");
			}
	});
	
	//Show/hide Features
	$("#new-vehicle-nav a").click(function(){
		var href = $(this).attr('name');
		if($(this).attr('id') != 'brochures') {
			if(href != '#' && !$(this).attr('href')) {
				$("#new-vehicle-nav a").each(function(){
					var hrefLi = $(this).attr('name');
					var thisId = $(this).attr('id');
					$(this).attr('class','');
					vis(hrefLi,true);
				});
				if(href != '#brochures' && href != '#pricelist') {
					vis(href);
				}
				else {
				}
			$(this).attr('class','active');
		   }
		}
	});
						   
	animateOpacity('.halo',haloOpacity);
	animateOpacity('.halo-white',haloWhiteOpacity);
	
	$(".home li a").hover(function(){
		animateOpacity($(this).parent().prev(),1);
	},function(){animateOpacity($(this).parent().prev(),haloWhiteOpacity);});
	
	$("#anav ul li div").css('opacity','0.9');
	$(".halo-cars").css('opacity','0.5');
	$("#cars-search-actions div").css('opacity','0.9');
	$(".inv-section, #cars-photos-more, #cars-tabs").css('opacity','0.8');
	
	//Hover colors on nav items
	changeFontColor('#anav ul li a:not(.active)','#0099FF','#FFF');
	changeFontColor('#anav ul li ul li a','#FF6600','#FFF');
	changeFontColor('#bnav ul li a','#FF6600','#7F7F7F');
	changeFontColor('.cars-list-enquire a','#FF6600','#FFF');
	changeFontColor('#cars-actions li a','#FF6600','#999');
	changeFontColor('#models-menu li a','#FFF','#999')
	
	$("#menu-right li a").livequery('click',function(){
		$("#menu-right li a").each(function(){
			$(this).attr('class','');
			Cufon.replace($(this),{hover: true});
		});
		$(this).attr('class','active');
		Cufon.replace($(this),{hover: true});
	});
	
	
	
	//Hide/displays submenu
	$("#anav li a:not(#anav li div ul li a)").hover(function(){
		$("#anav li a").each(function(){
			$(this).parent("li").children("div").children("ul").css('display','none');
		});
		$(this).stopTime();
		$(this).parent("li").children("div").children("ul").css('display','block');
	},function(){
		$(this).oneTime(500,function(){
			$(this).parent("li").children("div").children("ul").css('display','none');
		});
	});
	
	$("#anav li div ul li a").hover(function(){
		$(this).parent('li').parent('ul').parent('div').parent('li').children('a').stopTime();
	},function(){
		$(this).parent('li').parent('ul').parent('div').parent('li').children('a').oneTime(500,function(){
			$(this).parent("li").children("div").children("ul").css('display','none');
		});
	});
	

	//Hide/displays search overlays
	function showMyOverlay(){
		$(this).children("div").css('display','block');
		$(this).children("a").attr('class','searchover');
		Cufon.replace('#cars-search-actions ul li a');
	}
	function hideMyOverlay() {
		$(this).children("div").css('display','none');
		$(this).children("a").attr('class','');
		Cufon.replace('#cars-search-actions ul li a');
	}
	var overlayConfig = {interval:50, sensitivity:6, over:showMyOverlay, out:hideMyOverlay, timeout:300};
	
	$("#cars-search-actions li").hoverIntent(overlayConfig);
	
	
	//Hide/show search divs on home page
	$("#home-search div:first").css('display','block');
	$("#home-search h2").click(function(){
		$("#home-search div").css('display','none');
		$(this).next('div').css('display','block');
		
		$('#home-search h2').attr('class','inactive');
		$(this).attr('class','active');
		Cufon.replace('h2');
		
	});
	
	
	//Jquery calendar on service booking page
	$("#preferred_booking_date, #preferred_test_drive_date").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);
        $("#follower").css({
            top: (e.pageY + 15) + "px",
            left: (e.pageX + 15) + "px",
			display: 'block'
        });
      });
	 
	 $("td.cal_special,td.cal_normal").livequery('mouseout',function(e){
        $("#follower").css('display','none');
      });
	 
	 
	$("td.cal_special,td.cal_normal").livequery('click',function(){
		$("#service-special").remove();
		$("#preferred_booking_date").val($(this).attr('id'));
		if($(this).attr('class') == 'cal_special') {
			$("#comments").val('Service Special: '+$(this).children('span').html());
			$("#service-booking").children("div").prepend("<p id='service-special'>Please fill in this form to secure your special!</p>");
		}
		else {
			$("#comments").val('');
			$("#service-booking").children("div").prepend("<p id='service-special'>Please fill in this form to book a service</p>");
		}
		
		showSection('#service-booking','');
	});

	

	//Tooltip on hover over cnav items
	$("#cnav li a").hover(function(){
		var id = $(this).attr('id');
		if(id != 'share') {
			switch(id) {
				case 'home':
					left = '-6';
					break;
				case 'contact':
					left = 20;
					break;
				case 'directions':
					left = 69;
					break;
				case 'send':
					left = 104;
					break;
				default:
					left = 53;
					
			}
			$("#cnav ul").prepend('<div id="cnav-tip" style="left:'+left+'px"><span>'+$(this).html()+'</span></div>');
		}
	},function(){
		$("#cnav-tip").remove();
	});
	
	//Tooltip on hover over bus timetable
	$("#bus_time").hover(function(){
		$("#bus_time").before('<div id="cnav-tip" style="left:10px"><span>Timetable here</span></div>');
	},function(){
		$("#cnav-tip").remove();
	});
	
	//Add event listener to right menu items
	$("#menu-right a, .all4 #new-vehicles a, .add-link").click(function(){
		var linkAttr = $(this).attr("href");
		if(!linkAttr) {
			showSection($(this).attr('name'),$(this));
			vis("#all-menu",true);
		}
	});
	
	//reset links to preserve accessibility without making the screen "jump"
	$("#menu-right li a, .all4 #new-vehicles li a, .add-link").each(function(){
		var linkAttr = $(this).attr("href");
		if(linkAttr.indexOf('#') != -1 && linkAttr.indexOf('#') == 0) {
			$(this).attr("name",linkAttr);
			$(this).removeAttr("href");
		}
	});
	
	
	//Displays div according to url
	var URL = unescape(window.document.location);
	if (URL.indexOf("#") > -1 && URL.indexOf("specials-form") == -1) {
		var splitUrl = URL.split("#");
		var visDiv = splitUrl[1];
			$("#"+visDiv).css('display','block');
			$("#menu-right li a").each(function(){
				$(this).attr('class','');
				Cufon.replace($(this),{hover: true});
			});
			$("#menu-right li a[name='#"+visDiv+"']").attr('class','active');
			Cufon.replace($("#menu-right li a[name='#"+visDiv+"']"),{hover: true});
			if(visDiv == 'contact-directions') {
				$("#contact-directions").load('include-map.php');
			}
			vis("#all-menu",true);
	}
	else {
		$("#finance-products, #parts-overview, #service-overview,#contact-tellus,#specials-new,#showroom-car,#privacy-content,#careers-overview").css('display','block');
	}
	
	
	$("#models-menu li a").each(function(){
		var linkAttr = $(this).attr("href");
		$(this).attr("name",linkAttr);
		$(this).removeAttr("href");
	});
	
	//Directions on contact page when on contact page
	if (URL.indexOf("contact.html") > 1) {
		$('[href*=contact-directions]').click(function(){
			showSection('#contact-directions','');
			$("#contact-directions").load('include-map.php');
		});
	}
	
	
	//////// SPECIALS PAGE
	
	Cufon.replace('#current-offers h2, #current-offers h3', { fontFamily: 'Corbel' });
	$("#current-offers-content div img").css('bottom','0px');
	
	$("#current-offers img:first").hover(function(){							  
		$("#co-menu").stopTime();
		$("#co-menu").css('display','block');
	}, function(){
		$("#co-menu").oneTime(600,function(){$(this).css('display','none');});
		}
	);
							
	$(".co-disclaimer-img img").hover(function(){
		$("div.co-disclaimer").css('display','block');
	}, function(){$("div.co-disclaimer").css('display','none');});
							
	$(".co-details-img img").hover(function(){
		$("div.co-details").css('display','block');
		}, function(){$("div.co-details").css('display','none');});
							
	$("#co-menu li, #co-menu").hover(function(){
		$("#co-menu").stopTime();
		},function(){$("#co-menu").oneTime(600,function(){$(this).css('display','none');});});
							
	$("#co-menu li").click(function(){
		$("#co-menu, #co-hero").css("display","none");
		$("#current-offers").prepend('<div id="current-offers-content-cache"></div>');
		$("#current-offers-content-cache").css('opacity','0.9');
		var yPos = $(this).attr("id");
		var carName = $(this).html();
		$("#car_name").val(carName);
		$("#current-offers-content").animate({top:yPos+"px"},function(){$("#current-offers-content-cache").fadeOut("fast",function(){$(this).remove();});});
	});
	
	
	//Set the default colour picker description then deletes all title attributes for the colours list
	var firstTitle = $("#new-colours li:first").attr("title");
	$("#new-colours p").html(firstTitle);
	$("#new-colours li").each(function() {
        $this = $(this);
        $.data(this, 'title', $this.attr('title'));
        $this.removeAttr('title');
    });

	
	//Show different colours
	$("#new-colours li").click(function(){
		$("#new-colours p").css("visibility","hidden");
		$("#new-colours-switch").prepend("<div id='new-colours-switch-cache'></div>");
		$("#new-colours-switch-cache").css('opacity','0.9');
		var yPos = $(this).attr('id');
		var thisTitle = $.data(this, 'title');
		$("#new-colours p").html(thisTitle);
		$("#new-colours-switch img").animate({top :"-"+yPos+"px"},function(){
			$("#new-colours p").css("visibility","visible");
			$("#new-colours-switch-cache").fadeOut('fast',function(){$(this).remove();});
		});
	});
	
	
	//Reveal and adapt form
	/*$("#new-vehicle-nav #brochures, #new-vehicle-nav #pricelist").click(function(){
		showSection('#new-vehicle-form','');
		var attrVal = $(this).attr('id');
		switch(attrVal) {
			case '':
				break;
			case 'viewStock':
				vis('#currentStock')
				vis('#new-vehicle-form',true);
				break;
			default:	
				vis('.enquiry-trade');
				$("#formComment").html("Comments");
				var intro = '';
				var url = "http://www.phase.com.au/forms/afp_spam.asp?formid=";
				var formTitle = '';
				
				switch(attrVal) {
					case 'brochures':
						url += '1245';
						formTitle = "Accessing Brochures Area"+formTitle;
						$("#formComment").html("Comments");
						intro = 'Thank you for your interest. So that we can monitor the interest in this section of the site, please take a moment to complete the brief form below. You will gain instant access to the brochures area.';
						break;
					case 'pricelist':
						url += '1244';
						formTitle = "Get our Internet Price List"+formTitle;
						$("#formComment").html("Comments");
						intro = 'Thank you in advance for contacting us. Please complete this brief form to receive our internet price list. One of our friendly, professional consultants will be in touch with you shortly.';
						break;
					case 'mr-quote':
					default:
						url += '624';
						formTitle = "Quick Quote"+formTitle;
						$("#formComment").html("Comments");
						intro = 'Thank you in advance for contacting us. Please complete this brief form to make an obligation-free enquiry. One of our friendly, professional consultants will be in touch with you shortly.';
						break;
					case 'valueMyCar':
						url += '1246';
						formTitle = "Value my car"+formTitle;
						$("#formComment").html("Details about Your Car");
						$(".enquiry-trade").css("display","none");
						intro = 'Thank you in advance for contacting us about a valuation on your vehicle.<br>So that we can help you best, please complete this brief form. One of our representatives will be in touch with you shortly. ';
						break;
				}
				vis('#currentStock',true);
				$("#new-vehicle-form h2")
					.html(formTitle)
					.attr('id','h2-'+attrVal);
				$("#enquiry_form").attr("action",url);
				$("#new-vehicle-form p#info").html(intro);
				$("#new-vehicle-hero embed, object").css("visibility","hidden");
				vis('#new-vehicle-form');
		}
		Cufon.replace('#new-vehicle-form h2, #new-vehicle-directions h2');
		
	});*/
	
		$(".pricelist h3").click(function(){
			if(!$(this).attr('class')) {
				$(this).next("table").css('display','block');
				$(this).attr('class','active');
			}
			else {
				$(this).next("table").css('display','none');
				$(this).attr('class','');
			}
		});
	
	
});

//Animates an element opacity
function animateOpacity(element,opacity) {
	$(element).animate({
    	opacity: opacity
  	});
}

//Change font color for cufons
function changeFontColor(element,colorIn,colorOut) {
		$(element).hover(function(){
			$(this).css('color',colorIn);
			Cufon.replace($(this));
		},function(){
			$(this).css('color',colorOut);
			if($(this).attr('class') != 'active') {
				Cufon.replace($(this));
			}
		});
}

function showSection(div,alink) {
	vis('#new-vehicle-form',true);
	$(".section-div").each(function(){
		$(this).css('display','none');
	});
	if(alink) {
		alink.attr('class','active');
		Cufon.replace(alink,{hover:true});
	}
	$(div).css('display','block');
	if($(this).attr('name') == '#contact-directions') google.maps.event.trigger(map[0], 'resize');
}

function vis(element,hide) {
	if(!hide) var hide = false;
	var change = hide ? 'none' : 'block';
	$(element).css('display',change);
}


function overlay(page) {
	var height = $(window).height();
    var width = $(document).width();
	$('body').prepend('<div id="page-cache"></div>');
	$("#page-cache").css('opacity','0.9');
	$("#page-cache").fadeIn('normal',function(){
		$(this).after('<div id="cache-content"><img src="images/wait30.gif" /></div>');
		$("#cache-content").css('bottom',''+(height/2-(450/2))+'px');
		$("#cache-content").css('left',''+((width/2)-(600/2))+'px');
		$("#cache-content").load(page);
	});
}

/***** 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(10000);
	priceBot = priceAdd - 10000;
	document.getElementById('searchlink').style.display = 'block';
	document.getElementById('searchlink').href = 'cars-list.asp?search=1&new=on&demo=on&used=on&make=ALL+MAKES&model=ALL+MODELS&yearmin=Year+Min&yearmax=Year+Max&pricemin=' + priceBot + '&pricemax=' + priceTop;
}

function displayCalendar(month,year) {
	$("#service-specials").prepend('<div id="wait"></div>');
	$("#wait").html('<img src="images/wait22trans.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 hideOverlay() {
	vis('#page-cache',true);
 	vis('#cache-content',true);
	$("#cache-content,#page-cache").remove();
	}