
 var crossFadeIVL= 0;
 var timeOutIVL = 0;
 
 var autocrossFadeSpeed=14000; //time between fades
 var restartTimerSpeed=14000; //time to restart after pausing in ms
 var blnAnimRunning=false;

 var tickerRunning=true;
 var newsTickerIntervalID;
 var weatherCurrentPage=1;
 var isFirstWeatherPass=true;
 var numWeatherItems=0;


 
$(document).ready(function(){

	var menuTimers=[];
	
	$('#topNavMain>ul>li').hover(function() {
			$(this).addClass('hover-dropdown');
			var id = jQuery.data( this );
			if (menuTimers[id] != "" ) {  
               clearTimeout( menuTimers[id] );  
			}
			
		}, function() {
			var id = jQuery.data( this );  
			if (menuTimers[id] != "" ) {  
               clearTimeout( menuTimers[id] );  
			}
			var elem=$(this)[0];
			menuTimers[id]=setTimeout(function(){remDDHover(elem); elem=null;menuTimers[id] = "";},500);
			//setTimeout(function(){remDDHover(elem); elem=null;},500);
	});
	

	
	/*Enable for keyboard users to access dropdowns*/
	/*Not currently working as tab key doesn't pick up initially hidden items*/
	/*
	$('#topNavMain>ul>li>a').focus(function() {
		$parent=$(this).parent();
		$parent.addClass('hover-dropdown');
	});
	
	$('#topNavMain>ul>li>a').blur(function() {
		$parent=$(this).parent();
		$parent.removeClass('hover-dropdown');
	});
	*/
	
			
			
	//cache background images for IE6
	if (document && document.execCommand) {
		try { document.execCommand("BackgroundImageCache",false,true); }
		catch (e) { }
	}

	//clear travel inputs
	initClearInputs();
	
	//start panel animation
	timeOutIVL=setTimeout("startCrossFade()",0); //start delay - restartTimerSpeed

	//start mouse over/keyboard actions on tabs
	initPanelLinkEvents();

	initTraffic();
	
	initFlash();
	
	initTicker();
	
	initWeather();
	
	changeZoneImg();
	
	setLargerMapLinks();
	
	showCookieLinks();	
	
	//setup travel ins links
	$("#top_nav\\.travel_insurance").click(function(){
		var href=$(this).attr("href");
		href=href+"?advertid=32375&utm_source=theAA.com&utm_medium=homesmall";
		$(this).attr("href",href);
	});
				
	preloadImages();
	
				
}); //end document.ready


function startCrossFade() {
	 blnAnimRunning=true;
	 crossFadeIVL=setInterval('crossFade()', autocrossFadeSpeed); //miliseconds
	 $("#animController").fadeIn("slow");
}
 
 function initPanelLinkEvents()
 {
	$("#hpLink1").bind('click focus',function(event){ 
		event.preventDefault();
		clearInterval(crossFadeIVL);
		clearTimeout(timeOutIVL);
		togglePanel(1);
		blnAnimRunning=false;
		if($("#toggleAnim img").attr("src")!="/images/homepage-n/play-off.gif")
		{
			$("#toggleAnim").html('<img src="/images/homepage-n/play-off.gif" width="14" height="14" alt="Play"/>');
		}
		timeOutIVL=setTimeout("startCrossFade()",restartTimerSpeed);
		
	});
 
   $("#hpLink2").bind('click focus',function(event){
		event.preventDefault();
		clearInterval(crossFadeIVL);							
		clearTimeout(timeOutIVL);
		togglePanel(2);
		blnAnimRunning=false;
		if($("#toggleAnim img").attr("src")!="/images/homepage-n/play-off.gif")
		{
			$("#toggleAnim").html('<img src="/images/homepage-n/play-off.gif" width="14" height="14" alt="Play"/>');
		}
		timeOutIVL=setTimeout("startCrossFade()",restartTimerSpeed);
		
	});
   
    $("#hpLink3").bind('click focus',function(event){
		event.preventDefault();
		clearInterval(crossFadeIVL);
		clearTimeout(timeOutIVL);
		togglePanel(3);
		blnAnimRunning=false;
		if($("#toggleAnim img").attr("src")!="/images/homepage-n/play-off.gif")
		{
			$("#toggleAnim").html('<img src="/images/homepage-n/play-off.gif" width="14" height="14" alt="Play"/>');
		}
		timeOutIVL=setTimeout("startCrossFade()",restartTimerSpeed);
		
	});
	
	 $("#hpLink4").bind('click focus',function(event){
		event.preventDefault();
		clearInterval(crossFadeIVL);
		clearTimeout(timeOutIVL);
		blnAnimRunning=false;
		togglePanel(4);
		if($("#toggleAnim img").attr("src")!="/images/homepage-n/play-off.gif")
		{
			$("#toggleAnim").html('<img src="/images/homepage-n/play-off.gif" width="14" height="14" alt="Play"/>');
		}
		timeOutIVL=setTimeout("startCrossFade()",restartTimerSpeed);
		
	});
 
 
	$("#toggleAnim").click(function(event){
		event.preventDefault();
		if(blnAnimRunning)
		{
			clearInterval(crossFadeIVL);
			clearTimeout(timeOutIVL);
			blnAnimRunning=false;
			if($("#toggleAnim img").attr("src")!="/images/homepage-n/play-off.gif")
			{
				$("#toggleAnim").html('<img src="/images/homepage-n/play-off.gif" width="14" height="14" alt="Play"/>');
			}
		}
		else {
			crossFade();
			startCrossFade();
			if($("#toggleAnim img").attr("src")!="/images/homepage-n/pause-off.gif")
			{
			$("#toggleAnim").html('<img src="/images/homepage-n/pause-off.gif" width="14" height="14" alt="Pause"/>');
			}
		}
		
	});

	//animation controller
	$("#toggleAnim").hover(
	  function () {
		$img=$(this).find("img");
		$img[0].src = $img[0].src.replace("-off","-hover");
	  }, 
	  function () {
		$img=$(this).find("img");
		$img[0].src = $img[0].src.replace("-hover","-off");
	  }
	);
 }
 
function togglePanel(panelID)
{
  //removed anim
	for(i=1;i<5;i++)
	{
		if(panelID==i)
		{
			//fade in and remove link background image
			$panel=$("#homepromopanel" + i);
			if($panel.hasClass("panelCurrent"))
			{
				break;
			}
			$panel.fadeIn("fast",function(){
				if(!$.support.opacity) this.style.removeAttribute('filter'); 
			});
			$panel.addClass("panelCurrent");
			$("#promoTabsContainer #hpLink" + i).addClass("hpCurrentLink");
		}
		else {
			//fade out and add in background image
			$panel=$("#homepromopanel" + i);
			$panel.fadeOut("fast",function(){
				if (!$.support.opacity) this.style.removeAttribute('filter'); 
			});
			$panel.removeClass("panelCurrent");
			$("#promoTabsContainer #hpLink" + i).removeClass("hpCurrentLink");
		}
	}
}


function crossFade() {
	//work out current panel 
	//loop through each
	var arrPanels=new Array($("#homepromopanel1"),$("#homepromopanel2"),$("#homepromopanel3"),$("#homepromopanel4"));
	
	//get current
	var panelSelected=0;
	var nextPanel=0;
	for(i=0;i<4;i++)
	{
		if(arrPanels[i].hasClass("panelCurrent")) {
		panelSelected=i;	
		}
	}
	//select next panel;
	if(panelSelected!=3) {nextPanel=panelSelected+1;} else {nextPanel=0;}
	
	togglePanel(nextPanel+1);
}


function initTicker()
{

			//load additional news
			var newsfeedurl="/motoring_advice/news/data/news_ticker.xml";
			$.ajax({
				type: "GET",
				dataType: ($.browser.msie) ? "text" : "xml",

				url: newsfeedurl,
				success: parseNewsXml
			  });
			
			function parseNewsXml(data)
			{
			
			 /*remove before go live*/
			 if (typeof data == "string") {
			   xml = new ActiveXObject("Microsoft.XMLDOM");
			   xml.async = false;
			   xml.loadXML(data);
			 } else {
			   xml = data;
			 }

			 
			 
			var itemNo=0;
			$(xml).find("link").each(function()
			  {
				if(itemNo==0)
				{
					$("li","#tickerItems").removeClass("firstTI");
				}
				$link=$(this);

				strItem='<li ';
				
				if(itemNo==0) {strItem+='class="firstTI"';}
				strItem+='><a href="'+ $link.attr("url") + '">' + $link.text() +'</a></li>';
				$("#tickerItems").prepend(strItem);

				itemNo++;
			 });

			}

			//end load

			newsTickerIntervalID = setInterval("tickNews()", 7000);
			$("#hpTicker a.tickerItemController").css("visibility","visible");
			
			$("#tickerPause").click(function(event){
				event.preventDefault();
				if(tickerRunning) 
				{
					clearInterval(newsTickerIntervalID);
					tickerRunning=false;
					$(this).text("Play");
				}
				else {
					tickerRunning=true;
					newsTickerIntervalID=setInterval("tickNews()", 7000);
					$(this).text("Pause");
				}
			});
			
			$("#tickerNext").click(function(event){
				event.preventDefault();
				$("#tickerPause").text("Play");
				clearInterval(newsTickerIntervalID);
				tickerRunning=false;
				tickNews();
			});
			
			$("#tickerLast").click(function(event){
				event.preventDefault();
				clearInterval(newsTickerIntervalID);
				$("#tickerPause").text("Play");
				tickerRunning=false;
				tickNewsBack();
			});
}	
	
	
function showCookieLinks()
{
	//test if cookies supported
	$.cookie("testcookiesupport","true",{expires:1});
	if($.cookie("testcookiesupport"))
	{
			$("#remTrafficLinkContainer").show();
			$("#remWeatherLink").show();
	}
}
	
function initTraffic()
{
	$("#remTrafficLink").click(function(event){
	
		var origHTML=$(this).html();
		$(this).html("Saving location...");
		//get current map location
		var mapCenter=aaObjTraffic.map.getCenter();
		var mapZoom=aaObjTraffic.map.getZoom();
		var maplat=Math.floor( mapCenter.lat() *1000000)/1000000;
		var maplng=Math.floor( mapCenter.lng() *1000000)/1000000;
		
		//cookie data
		var loc="z=" + mapZoom + "&lat=" + maplat + "&lng=" + maplng;
		
		//set cookie
		$.cookie("trafficmap-loc",loc, { expires: 180 });

		setTimeout("resetRemText('remTrafficLink')",2000);
	
		event.preventDefault();
	});
}		

function tickNews()
{
		var newsTickItem1=$("#tickerItems li:first").html();
		$("#tickerItems li:first").fadeOut('slow', function() {
			$(this).remove();
			$("#tickerItems li:first").addClass('firstTI');
		});
		
		$('#tickerItems').append("<li>" + newsTickItem1 + "</li>");
}

function tickNewsBack()
{
		var newsTickItem1=$("#tickerItems li:last").html();
		$("#tickerItems li:last").remove();
		$("#tickerItems li").removeClass('firstTI');
		$('#tickerItems').prepend("<li class='firstTI'>" + newsTickItem1 + "</li>");
}
			
function remDDHover(elem)
{
	$(elem).removeClass('hover-dropdown');
}		
			
function resetRemText(id)
{
	$('#' + id).html('<a href="">Remember this location</' + 'a>');
}


function initFlash()
{

	
	//AA Channel
	swfobject.embedSWF("http://www.youtube.com/v/NVGAXvGpTV0&amp;hl=en_GB&amp;fs=1?rel=0", "aachannel1", "218", "176", "9.0.0","", "", {"allowFullScreen":true,"allowscriptaccess":"never"}, "");	

	//service and repair
	swfobject.registerObject("srFlashBanner", "9");
	
	
}

			

function changeZoneImg()
{
	var pid=(Math.floor(Math.random()*9))+11;
	var pidsrc="/images/homepage-n/zoneperson" + pid + ".jpg";
	$("#zoneperson").attr("src",pidsrc);
}

function setLargerMapLinks()
{
	 $("#trafficMapExpLink").click(function(event){
		var href=$(this).attr("href");
		var mapCenter=aaObjTraffic.map.getCenter();
		var mapZoom=aaObjTraffic.map.getZoom();
		var lat=mapCenter.lat();
		var lng=mapCenter.lng();
		
		href=href+"?lat=" + lat + "&lon=" + lng + "&z=" + mapZoom;
		window.location.href=href;
		event.preventDefault();
	 });
	 
	 $("#parkingMapExpLink").click(function(event){
		event.preventDefault();
		var href=$(this).attr("href");
		var mapCenter=aaObjParking.map.getCenter();
		var mapZoom=aaObjParking.map.getZoom();
		var lat=mapCenter.lat();
		var lng=mapCenter.lng();
		
		href=href+"?lat=" + lat + "&lon=" + lng + "&z=" + mapZoom;
		window.location.href=href;
	 });
}

function initClearInputs()
{
	$("input.travelText").focus(function() {
		$this=$(this);
		if($this.val()=="From") $this.val("");
		if($this.val()=="To") $this.val("");
		if($this.val()=="Find place") $this.val("");
		if($this.val()=="Postcode, town, or place of interest") $this.val("");
		$this.addClass("inpfocussed");
	});
	$("input.travelText").blur(function() {
		$this=$(this);
		$this.removeClass("inpfocussed");
	});
}


function initWeather()
{
	//get lat/lng/placename
	 var cookieLoc=	$.cookie("weathermap-loc");

	 if(cookieLoc!=""&&cookieLoc!=undefined&&cookieLoc!=null)
	 {
		var arrGaz=cookieLoc.split("|");
		var placeName=arrGaz[1];
		var e=arrGaz[3];
		var n=arrGaz[4];
		
		getWeatherByLocation(n,e,placeName);
	 }
	else {
		getWeatherByLocation(selectedStartN,selectedStartE,selectedStartPlace);
	}
	
	$("#remWeatherLink").click(function(event){
		event.preventDefault();
		var origHTML=$(this).html();
		$(this).html("Saving location...");
		//get selected confirm place
		var selectedGazLoc=$("#confirmWeatherPlace  option:selected").val();
		//set cookie
		$.cookie("weathermap-loc",selectedGazLoc, { expires: 180 }); //days
		setTimeout("resetRemText('remWeatherLink')",2000);
	});
	
	initWeatherCarousel();
}

function getWeatherByLocation(n,e,placeName)
{
	$('#weatherMsg').html("<p>Loading weather...</p>").css("display","block");
	$('#weatherCarousel').css("display","none");

	//ajax
	var weatherurl='/aaservlet/weather';
	var params='east=' + e + '&north=' + n + '&days=5';
	$.ajax({
	  url:weatherurl,
	  type: "get",
	  data: params,
	  dataType: "json",
	  error: function(xhr, desc, exceptionobj) {
		if(!isFirstWeatherPass)
		{
			$("#weatherMsg").html('<p><a href="" onclick="hideElem(event,' + "'weatherMsg'" + ');return false;" id="closeWeatherMsg"><img width="10" height="10" src="/images/traffic/btn-10-close.gif" alt="Close message"></a>' + "There was a problem loading the weather data. Please try again later, or try another location.</p>").css("display","block");
		}
		else {
			$("#weatherMsg").html("").css("display","none");
			isFirstWeatherPass=false;
		}
	  },
	  success:function(data){	
		if(isFirstWeatherPass) {isFirstWeatherPass=false};
		displayWeather(data,placeName);
		}
	  });
}

function initWeatherCarousel()
{
	$("#weatherList").click(function(event)
	{
		event.preventDefault();

		var item_width = $('#weatherCarousel li').outerWidth();
		
		var $target = $(event.target);
		 //prev day
		if( $target.hasClass("nextDayLink") ) {

			var left_indent = weatherCurrentPage*item_width*-1;
			if(left_indent<-1*(numWeatherItems-1)*item_width) left_indent=-1*(numWeatherItems-1)*item_width;
			if(left_indent>0) left_indent=0;
			
			if(weatherCurrentPage>=numWeatherItems)
			{
				weatherCurrentPage=numWeatherItems;
				return;
			}
			$('#weatherCarousel ul').animate({'left' : left_indent},500, function()
				{
					weatherCurrentPage++;
				});
		}
		else if ($target.hasClass("prevDayLink"))
		{
			var left_indent =  (weatherCurrentPage-2)*item_width*-1;
			if(left_indent<-1*(numWeatherItems-1)*item_width) left_indent=-1*(numWeatherItems-1)*item_width;
			if(left_indent>0) left_indent=0;
			if(weatherCurrentPage<=0)
			{
				//stop
				weatherCurrentPage=0;
				return;
			}
            $('#weatherCarousel ul').animate({'left' : left_indent},500, function()
			{
				weatherCurrentPage--;
			});
		}
	});
					
}


function displayWeather(json,placeName)
{

if(json.message!=""&&json.message!=null)
{
	$("#weatherMsg").html('<p><a href="" onclick="hideElem(event,' + "'weatherMsg'" + '); return false;" id="closeWeatherMsg"><img width="10" height="10" src="/images/traffic/btn-10-close.gif" alt="Close message"></a>' + "Sorry, no forecast is available for the current location. Please try again later, or try another location.</p>");
	return;
}

	$('#weatherCarousel ul').css("left","0"); //reset to left 0
	weatherCurrentPage=1;
	numWeatherItems=0;	

	var strOut='';
	var dayOfTheWeek='';
	var dayDescription='';
	var nightDescription='';
	var minTemp='';
	var maxTemp='';
	
  $.each(json, function(i,item)
      {
		numWeatherItems++;
        dayOfTheWeek=item.dayOfTheWeek;
		dayDescription=item.dayDescription||'';
		nightDescription=item.nightDescription||'';
		minTemp=item.minTemp||'';
		maxTemp=item.maxTemp||'';	

		strOut+='<li>'
				+'<div class="weatherDateControl clearfix">'
					+'<div class="weatherPrevDay"><a href="" class="prevDayLink">';
					
					if(i!=0)
					{
						strOut+='&#0171; ' + json[i-1].dayOfTheWeek.substring(0,3);
					}
		strOut+='</a></div>'
					+'<div class="weatherNextDay"><a href="" class="nextDayLink">';
					
					if(i<=5)
					{	try {
						strOut+=json[i+1].dayOfTheWeek.substring(0,3) + ' &#0187';
						}
						catch(e){};
					}
		strOut+='</a></div>'
					+'<p class="weatherToday">' + dayOfTheWeek + '</p>'
				+'</div>'
					+'<img src="/images/travel/weather/' + getWeatherIconPath(dayDescription) + '.gif" alt="Weather icon - ' + dayDescription +'" width="54" height="44" />'
					+'<p id="weatherInfo">'
					+'<strong>' + placeName + '</strong><br/>'
					+dayDescription + '<br/>'
					+'Max ' + maxTemp+'&deg;C, min ' + minTemp + '&deg;C'
					+'</p>'
				+'</li>';
     }); 
	$("#weatherList").html(strOut);
	$("#weatherCarousel").css("display","block");
	$("#weatherMsg").css("display","none").html("");
}

function getWeatherIconPath(desc)
{
	return desc.replace(/ /g,"_").toLowerCase();
}

function hideElem(e,id)
{

	$("#" + id).hide();
	return false;
}

