
var headlineCount;						// Total number of visible headlines
var headlineWidth;						// Headline DIV width
var containerWidth;						// Total container width, to hold all headlines, (including cloned First and Last)
var panelCount;							// Total number of headlines, (including cloned First and Last)
var headlineInterval;					// ID for the "setInterval" function
var currentHeadline = 1;				// Initial page load will show Headline #1
var nextHeadline = 0;					// Initialized to 0, but will set via code below
var currentRow = 0;						// Used in determining the Number bar
var lastRow = 0;						// Used in determining the Number bar
var headlineDisplayLimit = 5;			// Display only this many #'s in the Number bar
var headlineRotateInterval = 7000;  	// Time in milliseconds
var userClickedRotateInterval = 1000;	// Time in milliseconds
var scrollDirection = "R";  			// R and L for "right arrow" and "left arrow"
var userClickedOnHeadline = false;		// Stop the handleOut causing the auto-scroll if user has clicked

/*
	Notes:
			The upper righthand Number bar is Zero-based, ( ie. clicking on Number 1 will highlight the 0 LI element. )
			The headline DIVs not Zero-based, ( ie. clicking on Number 1 will display Headline.eq(1) )
			Uses the jQuery "scrollTo" plugin.
*/

$(document).ready(function() {

	// How many headlines do we have, and what is their width (used throughout this code)
	headlineCount = $("div.headline").size();	
	headlineWidth = $(".headline").width();
		
	// We only need the Headline Auto-Scrolling, and all its functionality, for 2 or more headlines.
	if ( headlineCount == 1 ) {
	
		containerWidth = headlineWidth;   
		$("#scrollup").css("width", containerWidth);	
	
	} else {
		
		// Append the first headline to the end and insert the last headline to the beginning.
		// We use this to give the appearance of continuous scrolling when the "scrollTo" plugin
		// reaches the headline limit.  (ie. in a 7 headline display, when reaching headline #7, we
		// will continue to #1.)  Without this functionality, the "scrollTo" plugin will 
		// quickly jump back to the beginning, (or end), which goes against the natural Left-to-Right,
		// or Right-to-Left, flow.
		var firstHeadline = $(".headline:first").clone();
		var lastHeadline = $(".headline:last").clone();
		$(firstHeadline).insertAfter(".headline:last");
		$(lastHeadline).insertBefore(".headline:first");	
		panelCount = $("div.headline").size();

		// Calculate a new width for the container so that it holds all headline panels.
		containerWidth = headlineWidth * panelCount;   
		$("#scrollup").css("width", containerWidth);	
	
		// Initialize the first set of alert numbers, displaying only the limit (headlineDisplayLimit).
		// Highlight the first alert number.  (Zero-based)
		$(".arrowLeft, .arrowRight").css({"display":"inline"});
		addNumericLabelLI();
		highlightScrollNumber(0);
		scrollToSpecificHeadline(1, true);

		// Initialize the "setInterval" for the headline rotation.
		headlineInterval = setInterval(headline_rotate, headlineRotateInterval);

		// Set the hover functions, (handleIn and handleOut)
		// The "handleOut" already sets the Auto-scroll process, and is triggered upon initial page load.		
		$('#scrollHover').hover(
			function() {			
				clearInterval(headlineInterval);			
			},
			function() {

				if ( !userClickedOnHeadline ) {		
					headlineInterval = setInterval(headline_rotate, headlineRotateInterval);			
					headline_rotate();
				}
			}
		);			

		// Left and Right arrows should scroll the headlines accordingly
		$(".arrowLeft").click( function() {
			userClickedOnHeadline = true;
			scrollDirection = "L";
			headline_rotate();
		});

		$(".arrowRight").click( function() {	
			userClickedOnHeadline = true;
			scrollDirection = "R";
			headline_rotate();				
		});

		// If the user wants to view a particular Headline.
		$("#scroll_controls_bar li a").click( function() {

			userClickedOnHeadline = true;
			var userClickedHeadlineNumber = parseInt($(this).html());
			var zeroBasedUserClicked = parseInt(userClickedHeadlineNumber) - 1;		
			
			clearAllScrollNumbers();
			highlightScrollNumber(zeroBasedUserClicked);
			scrollToSpecificHeadline(userClickedHeadlineNumber, false);
			currentHeadline = userClickedHeadlineNumber;				
		});		
	}  // if ( headlineCount > 1 ) {
	
	
	// Prevent any highlight or selection of text in the Arrow area, (fix for Safari mainly)
	$.extend($.fn.disableTextSelect = function() {

		return this.each(function() {
			if($.browser.mozilla){							//Firefox
				$(this).css('MozUserSelect','none');
			} else if($.browser.msie) {						//IE
				$(this).bind('selectstart',function(){return false;});
			} else {										//Opera, etc.
				$(this).mousedown(function(){return false;});
			}
		});
	});

	$('#scroll_controls_colRight').disableTextSelect();	
	
});


function headline_rotate() {

	if (headlineCount > 1) {

		if ( scrollDirection == "R" ) {
			nextHeadline = currentHeadline + 1;
		} else {
			nextHeadline = currentHeadline - 1;
		}
		
		// If we've reached a limit, show the cloned first or last, then quickly jump to the first or last actual headline
		// to give the impression of continuous scrolling flow.  (Without this functionality the "scrollTo"
		// plugin will visibly scroll in the opposite direction, counter to the flow that the user has been seeing.
		// We also need to reset the current headline number.
		// The line '$("#scrollContainer").stop(true);'	is very important as it prevents a noticeable delay when the "scrollTo" 
		// plugin has been reset to the beginning or ending of the Number bar.
		if ( nextHeadline == (headlineCount+1) ) {
		
			$("#scrollContainer").stop(true).attr({scrollLeft:0, scrollTop:0});
			nextHeadline = 1;
			scrollToSpecificHeadline(nextHeadline, false);
			$("#scrollContainer").stop(true);
			
		} else if ( nextHeadline == 0 ) {	
		
			var scrollLeftValue = headlineWidth * (headlineCount+1);
			$("#scrollContainer").stop(true).attr({scrollLeft:scrollLeftValue, scrollTop:0});
			nextHeadline = headlineCount;
			scrollToSpecificHeadline(nextHeadline, false);
			$("#scrollContainer").stop(true);
			
		}

		// What range of numbers should we see on the UI.
		//
		// ie.  If the "nextHeadline" is 7,
		//      then we should see < 6 7 8 9 10 >,
		//      or the 2nd row of numbers
		//
		// Note: Using zero-based rows, (where the first row of numbers is 0).
		
		var zeroBasedNextHeadline = nextHeadline-1;
		var currentRow = Math.floor( zeroBasedNextHeadline/headlineDisplayLimit );

		if ( currentRow != lastRow ) {

			var rowStart = currentRow * headlineDisplayLimit;
			var rowEnd   = rowStart + headlineDisplayLimit;
			$("#scroll_controls_bar li").css({"display":"none"});

			for ( var x = rowStart; x < rowEnd; x++ ) {
				$("#scroll_controls_bar li:eq(" + x + ")").css({"display":"inline"});
			}

			lastRow = currentRow;
		}
		
		// Scroll to the next headline
		scrollToSpecificHeadline(nextHeadline, false);
		
		// Box highlight the Next Alert
		clearAllScrollNumbers();
		highlightScrollNumber(zeroBasedNextHeadline);
		currentHeadline = nextHeadline;
	}	
}

function scrollToSpecificHeadline(headlineNumber, instantly) {

	var scrollToValue = headlineWidth*headlineNumber;
		
	if ( instantly ) {
		$("#scrollContainer").scrollTo( scrollToValue+"px" );
	} else {
		$("#scrollContainer").scrollTo( scrollToValue+"px", {duration:userClickedRotateInterval, easing:"linear", axis:"x"} );
	}
}

function clearAllScrollNumbers() {
	$("#scroll_controls_bar li a").removeClass("currentAlert");
}

function highlightScrollNumber(selectThis) {
	$("#scroll_controls_bar li a:eq(" + selectThis + ")").addClass("currentAlert");
}

// ** Add a numeric label LI element per headline, initially making only the first set visible.
// ** The first numeric label LI will have the highlighted background box,
//    and then the autoscrolling will highlight the next numeric label LI.
function addNumericLabelLI() {

	for ( var currHeadline = 1; currHeadline <= headlineCount; currHeadline++ ) {

		var newHeadlineLI = $('<li><\/li>');
		var newHeadlineLink = $('<a>' + currHeadline + '<\/a>').attr("href","#");

		if ( currHeadline > headlineDisplayLimit ) {
			newHeadlineLI.css({"display":"none"});
		}

		newHeadlineLI.append(newHeadlineLink);
		$("#scroll_controls_bar").append(newHeadlineLI);
	}
}
