$(window).load(function() {	
	window.location.hash = "#landingPoint";
	
	if ($("#timeSlider").attr("id") != undefined)
	{
		var viewObjLeft = $("#timesHolder").offset().left;	
		var viewObjRight = ($("#timesHolder").offset().left + $("#timesHolder").width());
		var cellCount = $("table.times tbody tr:eq(0) td").size();
		var rowCount = $("table.times tbody tr").size();
		var leftCell = 0;
		var rightCell = cellCount;
		
		/*START:Scroller*/
		if ($("ul#ticker01").attr("id") != undefined)
		{
			$("div#trackworkScrollerHolder").removeClass("brownBg");
			$("div#trackworkScrollerHolder").slideDown("fast");			
			$("ul#ticker01").liScroll();			
		}
		
		/*remove javascript disabled classes*/
		$("#timetableHolder").removeClass("rightGreyBorder");
		$("#stations").removeClass("leftRightGreyBorder");
		
		/*show elements that are hidden when javascript is disabled*/
		$("div.ttDepartListMid").removeClass("hidden");
		$("#topPrintBtn").removeClass("hidden");
		$("#bottomPrintBtn").removeClass("hidden");
		$("#timeSlider.scriptOff").removeClass("scriptOff");		
		
		//handle short timetables with smaller next and previous arrows here.
		if (($("table.times").height() < $("#btnNext").height()) || ($("table.times").height() < $("#btnPrev").height()))
		{
			$("#btnNext").removeClass("btnTTNextLg");
			$("#btnNext").addClass("btnTTNextSm");
			$("#btnPrev").removeClass("btnTTPrevLg");
			$("#btnPrev").addClass("btnTTPrevSm");
		}
		
		
		/*START: Drag Drop*/
		
		//the following vars are used to offset the drag and drop calcs;
		/*
		 Date:14 May 2009
		 Author:Jason Taikato
		 they are done referentially (using parent selector method) so that if the 
		 Station 2 Station javascript can use the same function (if it gets ressurected)		 
		 */	
		$("#trackworkPop")
	    .bind("dragstart",function( event ){ 
	            if ( !$(event.target).is("#topArea") ) return false;
	            $( this ).addClass("active");
	            })
	    .bind("drag",function( event ){
	            $( this ).css({
	                    top: (event.offsetY),
	                    left: (event.offsetX)
	                    });

	            })
	    .bind("dragend",function( event ){
	            $( this ).removeClass("active");
	            }); 
		/*END: Drag Drop*/	
		
		/*START: Drag Drop*/		
		$("#timeSlider").bind("drag",function( event ){
			if ((event.offsetX <= viewObjLeft) && ((iTimeTableWidth + event.offsetX) > viewObjRight))
			{
				$( this ).css({left: (event.offsetX - viewObjLeft)});				
				xPos = event.offsetX - viewObjLeft;				
				//Calculate the amount left and right of viewer
				calculateRemainingLeftRight();
			}
			if (event.offsetX > viewObjLeft)
			{
				disableBtnPrev();
			}
			else
			{
				enableBtnPrev();
			}
			if ((iTimeTableWidth + event.offsetX) < viewObjRight)
			{
				disableBtnNext();
			}
			else
			{
				enableBtnNext();
			}
         });
        
		/*END: Drag Drop*/
		
		//if no trackwork details then don't assign click event to show popup for alert icons
		if ($("input#trackworkDetails").val() != "")
		{
			$("th.alert").click(function(e){				
				$("#trackworkPop").show();
				$("#trackworkPop").css({top: ($("#timesHolder").offset().top + 20) + "px",left:($("#timesHolder").offset().left + 187)  + "px"});	
				$("#trackworkPop #trackworkMessageArea #trackworkMessageContainer").html(renderAllTrackworkMsgs(trackWorkDetailsArray));
			});
		}
		else
		{
			$("th.alert").css({cursor:"default"})
		}
		
		
		
		//these vars are used to find and position the first trackwork overlay popup
		var trackWorkRenderCount = 0;
		var firstRenderedTrackworkID = null;
		var firstRenderedTrackworkArrPos = null;
		
		/*Place elements on resize*/
		$(window).resize(function(){
			$("#ttLeftShadow").css({height: $("#stations").height() + "px"});
			$("#ttRightShadow").css({height: $("#stations").height() + "px"});
			viewObjLeft = $("#timesHolder").offset().left;
			viewObjRight = ($("#timesHolder").offset().left + $("#timesHolder").width());
		});
		
		/*START: Timetable mover variables and functions*/
		/*===============================================================*/	
		var iScrollPos = 0;
		var iLastScrollPos = 0;
		
		var viewerObj = $("#timesHolder");
		var tableObj = $("table.times");
		
		var btnPrevX = $("#btnPrev").offset().left;
		var btnPrevY = $("#btnPrev").offset().top;
		
		var btnNextX = $("#btnNext").offset().left;
		var btnNextY = $("#btnNext").offset().top;
		
		var btnHeight = $("#btnNext").height();
		
		var iTopBounds = $("#timesHolder").offset().top;
		var iBottomBounds =  $("#timesHolder").height() - btnHeight;		
		
		var iViewWidth = viewerObj.width();
		var iTimeTableWidth = tableObj.width();
		var iRemainingLeft = 0;
		var iRemainingRight = (iTimeTableWidth - iViewWidth);
		
		var iInitialIncrement = 250;
		var iMoveIncrement = iInitialIncrement;		
		
		var containsZero = false;
		
		var jumpArrays = $("input.timeJumps").val().split(",");		
		
		/*START: Trackwork*/
		var trackWorkArray = new Array;
		var trackWorkDetailsArray = new Array;
		
		if ($("input.trackworks").attr("id") != undefined)
		{	
			trackWorkArray = $("input.trackworks").val().split("|");
		}
		
		if ($("input.trackworkDetails").attr("id") != undefined)
		{	
			trackWorkDetailsArray = $("input.trackworkDetails").val().split("|");
		}		
		/*END: Trackwork*/
		
		/*
		===============================================
		Move Prev/next buttons when window is scrolled
		===============================================
		*/
		
		$(window).scroll(function () 
		{		
			iScrollPos = ($(window).scrollTop());
						
			btnNextY = $("#btnNext").offset().top;
			btnPrevY = $("#btnPrev").offset().top;
			
			if ((iScrollPos > iTopBounds) && (iScrollPos < iBottomBounds))
			{
				$("#btnPrev").css({ top: (iScrollPos-250) + "px" });
				$("#btnNext").css({ top: (iScrollPos-250) + "px" });
			}
			
			if (iScrollPos > iBottomBounds)
			{	
				$("#btnPrev").css({ top: iBottomBounds + "px" });
				$("#btnNext").css({ top: iBottomBounds + "px" });
			}
			else if (iScrollPos < iTopBounds)
			{
				$("#btnPrev").css({ top: "auto" });
				$("#btnNext").css({ top: "auto" });
			}
			iLastScrollPos = iScrollPos;
		});		
		
		function autoSlider(n){
			var targetIndex = n;
			var targetCell = $("table.times tbody tr:first td:eq("+targetIndex+")");
			var targetCellPos = targetCell.offset().left;
			var targetCellWidth = targetCell.outerWidth();
			var viewerLeft = viewerObj.offset().left;
			var viewerRight = (viewerLeft + viewerObj.width());		
			var targetDestination = (viewerLeft + Math.round((viewerObj.width()/2)) - Math.round((targetCellWidth/2)));
			
			//Calculate the amount left and right of viewer
			calculateRemainingLeftRight();
			
			if (targetDestination < targetCellPos)
			{
				iMoveIncrement = targetCellPos - targetDestination;
				if (iMoveIncrement > iRemainingRight)
				{
					iMoveIncrement = iRemainingRight;
				}
				xPos = xPos - iMoveIncrement;
				setRightMoveVars();
			}
			else if (targetDestination > targetCellPos)
			{
				iMoveIncrement = targetDestination - targetCellPos;
				if (iMoveIncrement > iRemainingLeft)
				{
					iMoveIncrement = iRemainingLeft;
				}
				xPos = xPos + iMoveIncrement;
				setLeftMoveVars();
			}			
			moveTT();
		}
		
		var xPos = 0;
		var isLeftMove = false;
		var isRightMove = false;
		
		function moveTT()
		{
			$("#timeSlider").animate({left: xPos + "px"},"normal");
			
			//Calculate the amount left and right of viewer
			calculateRemainingLeftRight();

			if (iMoveIncrement > iInitialIncrement)
			{
				iMoveIncrement = iInitialIncrement;
			}			
				
			if (xPos < 0)
			{
				enableBtnPrev();
			}
			else if (xPos == 0)
			{
				disableBtnPrev();
				//reset move increment so that it won't be 0 on next move
				iMoveIncrement = iInitialIncrement;
			}
			
			if ((iTimeTableWidth + xPos) > iViewWidth)
			{
				enableBtnNext();			
			}
			else
			{
				disableBtnNext();
				iMoveIncrement = iInitialIncrement;
			}
		}		
		
		function disableBtnPrev()
		{
			$("#btnPrev").hide();
			/*Remove left arrow function*/
			$.hotkeys.remove("left",{type: "keyup"});
		}
		
		function enableBtnPrev()
		{
			$("#btnPrev").show();	
			/*===========================
			Add left arrow function
			left arrow key = scroll previous
			===========================*/
			$.hotkeys.add("left",{type: "keyup"}, function(){
				setLeftMoveVars();
				setLeftIncrement();
				xPos = xPos + iMoveIncrement;
				moveTT();
			});
		}
		
		function disableBtnNext()
		{
			$("#btnNext").hide();
			/*Remove right arrow function*/
			$.hotkeys.remove("right",{type: "keyup"});
		}
		
		function enableBtnNext()
		{
			$("#btnNext").show();	
			/*===========================
			Add right arrow function
			right arrow key = scroll next
			===========================*/
			$.hotkeys.add("right",{type: "keyup"}, function(){
				setRightMoveVars();
				setRightIncrement();
				xPos = xPos - iMoveIncrement;
				moveTT();
			});
		}
			
		function setRightMoveVars()
		{		
			isLeftMove = false;
			isRightMove = true;
		}
		
		function setLeftMoveVars()
		{		
			isLeftMove = true;
			isRightMove = false;
		}	
		
		$.hotkeys.add("home",{type: "keyup"}, function(){
			$("#btnPrev").css({ top: "0px" });
			$("#btnNext").css({ top: "0px" });
		});
		
		$.hotkeys.add("end",{type: "keyup"}, function(){
			$("#btnPrev").css({ top: iBottomBounds + "px" });
			$("#btnNext").css({ top: iBottomBounds + "px" });
		});
		
		$("#btnNext").click(function(){
			setRightMoveVars();
			setRightIncrement();
			xPos = xPos - iMoveIncrement;
			moveTT();
		});
			
		$("#btnNext").focus(function(){
			$.hotkeys.add("return",{type: "keyup"}, function(){
				setRightMoveVars();
				setRightIncrement();
				xPos = xPos - iMoveIncrement;
				moveTT();
			});
		});
		
		$("#btnNext").blur(function(){
			$.hotkeys.remove("return",{type: "keyup"});
		});
		
		$("#btnPrev").click(function(){
			setLeftMoveVars();
			setLeftIncrement();
			xPos = xPos + iMoveIncrement;
			moveTT();
		});
		
		$("#btnPrev").focus(function(){
			$.hotkeys.add("return",{type: "keyup"}, function(){
				setLeftMoveVars();
				setLeftIncrement();
				xPos = xPos + iMoveIncrement;
				moveTT();
			});
		});
		
		$("#btnPrev").blur(function(){
			$.hotkeys.remove("return",{type: "keyup"});
		});
		/*===============================================================*/
		/*END: Timetable mover functions*/	
		
		/*Function places passed element (movingEl) to X(extraX) & Y(extraY) coords relative to a positioned element (relEl)*/
		function placeElement(relEl,movingEl,extraX,extraY)
		{
			if (relEl.attr("id") != undefined)
			{
				var xPos = (relEl.offset().left + extraX);
				var yPos = (relEl.offset().top + extraY);
				movingEl.css({ left: xPos+"px", top: yPos+"px" });	
			}
		}
		enableBtnNext();
		disableBtnPrev();			
	}
		
	function setRightIncrement()
	{	
		if (iRemainingRight < iInitialIncrement && isRightMove)
		{
			iMoveIncrement = iRemainingRight;
		}
	}
	
	function setLeftIncrement()
	{
		if (iRemainingLeft < iInitialIncrement && isLeftMove)
		{
			iMoveIncrement = iRemainingLeft;
		}
	}
	
	function calculateRemainingLeftRight(){
		iRemainingLeft = iTimeTableWidth - (iTimeTableWidth + xPos);
		iRemainingRight = (iTimeTableWidth - iViewWidth) + xPos;
	}
		
		
	$("#trackworkPop #topArea .close").bind("click",function(e){
		$("#trackworkPop").hide();
	});
	
	
	
	/*Let's scroll timetable to the nearest time the user has requested*/
		
	if (jumpArrays != undefined)
	{
		defaultJump();
	}
	
	function defaultJump()
	{
		autoSlider(jumpArrays[0]);
	}
	
	$("span.threeAm").click(function(){
		autoSlider(jumpArrays[1]);
	});
	
	$("span.sixAm").click(function(){
		autoSlider(jumpArrays[2]);
	});
	
	$("span.nineAm").click(function(){
		autoSlider(jumpArrays[3]);
	});
	
	$("span.twelvePm").click(function(){
		autoSlider(jumpArrays[4]);
	});
	
	$("span.threePm").click(function(){
		autoSlider(jumpArrays[5]);
	});
	
	$("span.sixPm").click(function(){
		autoSlider(jumpArrays[6]);
	});
	
	$("span.ninePm").click(function(){
		autoSlider(jumpArrays[7]);
	});			

		$("#ttLeftShadow").css({height: $("#stations").height() + "px"});
		$("#ttRightShadow").css({height: $("#stations").height() + "px"});		
		
		if ((trackWorkArray != undefined) && trackWorkArray != "")
		{
			renderTrackWork(trackWorkArray);
		}
		if ($("input.trackworkDetails").attr("id") != undefined)
		{
			if ($("input.trackworkDetails").val().length > 0)
			{
				$("#trackworkPop").show();
				$("#trackworkPop").css({top: ($("#timesHolder").offset().top + 20) + "px",left:($("#timesHolder").offset().left + 187)  + "px"});			
				$("#trackworkPop #trackworkMessageArea #trackworkMessageContainer").html(renderAllTrackworkMsgs(trackWorkDetailsArray));
			}
		}
		function renderAllTrackworkMsgs(arr)
		{
			var returnedHTML = "";
			for (var i=0;i<arr.length;i++)
			{
				//this statement handles empty string (if 'Show popup on timetables' checkbox in admin has been unchecked)
				if (arr[i].length > 0)
				{
					returnedHTML = returnedHTML + "<p>" + arr[i] + "</p>";	
				}
			}
			return returnedHTML;
		}

	$("input.loaderImage").bind("click",function(){
		loaderInTimetable();
	});
	
	$("#ttActionForm").submit(function(){
		loaderInTimetable();
	});
	
	function loaderInTimetable()
	{
		var imageHoriPadding = ($("#timetableHolder").width()/2)-32;
		var imageVertPadding = ($("#timetableHolder").height()/2)-32;	

		var divHeight = $("#timetableHolder").height();
		var divWidth = $("#timetableHolder").width();	

		$("#stations").hide();
		$("#timesHolder").hide();		
		$("#timetableHolder").attr({style:"height:"+divHeight+"px;width:"+divWidth+"px;background:#ebebef url(/img/loadingAnimation.gif) no-repeat center center"});
		$("#timetableHolder span").remove();
		$("#timetableHolder").append("<span id=\"loadingText\" style=\"font-size:0.75em;font-weight:bold\"></span>");
		$("#loadingText").text("Loading...")
	}
	
	/*START:Printing */			
	
	$("a.printSection")
		.bind("click",clickPrintTimetable)
		.bind("keypress",printTimetable);
	
	function printTimetable(e)
	{
		var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		if (key == 13 || key == 32)
		{
			window.print();
		}
		return false;	
	}
	
	function clickPrintTimetable()
	{
		window.print();
		return false;	
	}
	
});



