/**************************************************
	UI Tabs Initialization and some tabs customization
 **************************************************/

	$(document).ready(function(){
		
		// Initialize Jquery UI Tabs 					   
		$("#hero > ul").tabs({ 
			/*fx: [null, { height: 'show' }] */
			/*$('.selector').tabs({ cache: true });*/

		});
	
		// Run Check Tabs on body load to make sure another tab isn't selected  
		checkTabs();
		
		// Run Check tabs whenever a tab is clicked to get set proper styles
		$("#tabs > li > a").click(function() { checkTabs(); });
		
		// When a panel is clicked, run the omniture tracking code function */
		omnitureCode();

	}); /* Document.ready */

	// Had to add some overwriting styles in the .css and here so that Tab one would load smoothly with no flickering.
	// These conditionals then style the tab since it already has overwriting styles 
	function checkTabs() {
		// Identify the tabs							   
		var $tabs = $('#hero > ul').tabs();
		// Identify the selected tab
		var selected = $tabs.data('selected.tabs');
		// If Tab one isn't selected:
		if(selected != 0){
			$("#hero > #tabs > li#tablink1").hover(function() {
				$(this).css("background","#f6f6ef url(/images/homepage/tabs/buttons-bg-hover.jpg) top repeat-x");
			}, function() {
				$(this).css("background","#f6f6ef url(/images/homepage/tabs/buttons-bg.jpg) top repeat-x");
			});
			$("#hero > #tabs > li#tablink1").css("background","#f6f6ef url(/images/homepage/tabs/buttons-bg.jpg) top repeat-x"); 
			$("#hero > ul#tabs > li#tablink1 > a > span.icon").css("background","url(/images/homepage/tabs/icon-graph-off.png) top left no-repeat"); 
			$("#hero > ul#tabs > li#tablink1 > a > span.tab-title").css("color","#98907b");
			$("#hero > ul#tabs > li#tablink1 > a > span.tab-title-minor").css("color","#98907b");
			$("#hero .panel#panel-1").css("z-index","-1");
		}
		// If Tab one is selcted:
		if(selected == 0){
			$("#hero > #tabs > li#tablink1").hover(function() {
				$(this).css("background","transparent");
			}, function() {
				$(this).css("background","transparent");
			});
			$("#hero > ul#tabs > li#tablink1").css("background","transparent");
			$("#hero > ul#tabs > li#tablink1 > a > span.icon").css("background","url(/images/homepage/tabs/icon-graph-on.png) top left no-repeat"); 
			$("#hero > ul#tabs > li#tablink1 > a > span.tab-title").css("color","#d78a0d");
			$("#hero > ul#tabs > li#tablink1 > a > span.tab-title-minor").css("color","#d78a0d");
			$("#hero .panel#panel-1").css("z-index","10");
		}
	};

	function omnitureCode() {
		// Omniture Custom Link Tracking for panels
		$("#panel-1").click(function(){
			var s=s_gi("arenasolutionscom");
			s.linkTrackVars="prop7,eVar7";
			s.linkTrackEvents="None";
			s.prop7="Panel 1 - Outsourcing";
			s.evar7="Panel 1 - Outsourcing";
			s.tl(this,"o","Panel 1 - Outsourcing");
			});
		$("#panel-2").click(function(){
			var s=s_gi("arenasolutionscom");
			s.linkTrackVars="prop7,eVar7";
			s.linkTrackEvents="None";
			s.prop7="Panel 2 - Change Cycles";
			s.evar7="Panel 2 - Change Cycles";
			s.tl(this,"o","Panel 2 - Change Cycles");
			});
		$("#panel-3").click(function(){
			var s=s_gi("arenasolutionscom");
			s.linkTrackVars="prop7,eVar7";
			s.linkTrackEvents="None";
			s.prop7="Panel 3 - Compliance";
			s.evar7="Panel 3 - Compliance";
			s.tl(this,"o","Panel 3 - Compliance");
			});
		$("#panel-4").click(function(){
			var s=s_gi("arenasolutionscom");
			s.linkTrackVars="prop7,eVar7";
			s.linkTrackEvents="None";
			s.prop7="Panel 4 - Time to Market";
			s.evar7="Panel 4 - Time to Market";
			s.tl(this,"o","Panel 4 - Time to Market");
			});

	};

//	This is what makes the News & Events and Selected Customers sections on the homepage tick.
//	Requires the jQuery include for this to work.

//	We need to reference these across several functions, so global variables are necessary here
var selectedCustomersData;
var newsAndEventsFrozen = false;
var customerRotationStatus = 0;
var customersShown;	//	This is merely global because setInterval is scoped to the window object

//	jQuery plugins to be used later
jQuery.preloadImages = function() {
	for(var i = 0; i < arguments.length; i++) {
		jQuery("<img>").attr("src", arguments[i]);
	}
}

//	Now we can get started. This runs the following functions on page load.
$(function() {
	initNewsAndEvents();
	initSelectedCustomers();
	fixBackgroundImageFlickering();
	
	//	There is a bug with Firefox 2 where setting more than one interval causes the timing to be off,
	//	so we have to group everything that we want on an interval into a single function.
	window.setInterval("intervalHandler();", 5000);
});

function intervalHandler() {
	if (newsAndEventsFrozen == false) {
		//	We have a slight delay before starting the news cycle, because the customers animation takes a little longer.
		//	The value of 900 for the offset is rather arbitrary and was reached by trial and error.
		window.setTimeout("cycleNewsItems();", 4000);
	}
	rotateSelectedCustomers();
}

function initNewsAndEvents() {
	//	We want to build this navigation if there is a news section on the page, and if it has more than one piece.
	if ($("#news") && $("#news li").length > 1) {
		//	Now we create an ordered list to hold the little selector menu on the right.
		var selector = $("<ol></ol>");
		$(selector)
			.attr("id", "news-selector")
			.appendTo("#news");
			
		var newSelectorItemLink;

		//	Now we have to create a new list item in the selector for each item in the news-items list.
		$("#news-events li").each(function(i) {

			//	Assign a unique id to each news item so that we can identify them from the selector.
			$(this).attr("id", "news-item-" + i);
			
			//	Construct the link to be added to the new selector item
			newSelectorItemLink = $('<a id="link-to-news-item-' + i + '" href="#" onclick="newsEventLinkHandler(this.id); return false;">&nbsp;</a>');
			
			//	Since we're initializing, the first news item will be selected automatically.
			//	So we just assign the "selected" class to the first selector list item.
			if (i == 0) {
				$(newSelectorItemLink).addClass("selected");
			}
			
			$("<li></li>")
				.append(newSelectorItemLink)
				.appendTo(selector);
		});
		
		//	This adds the divs for the transparent fade images at the top and bottom
		//	of the news section. The if statement screens out IE6, since these are transparent PNGs.
		if (window.XMLHttpRequest) {
			$('<div id="news-fade-top"></div>').appendTo("#news");
			$('<div id="news-fade-bottom"></div>').appendTo("#news");
		}
	}
}

function newsEventLinkHandler(linkToNewsItemId) {
	
	//	First, now that one of the buttons has been clicked, we want to turn off the automatic cycle.
	newsAndEventsFrozen = true;
	
	//	Then we manage which selector item is being highlighted.
	//	To do this we first remove the class from whatever list item currently has it.
	$("#news-selector li a.selected").removeClass("selected");
	//	Then we add the class to the link that was just clicked.
	$("#" + linkToNewsItemId).addClass("selected");
	
	//	Then we extract the news item we want to navigate to from the link's id.
	var newsItemId = linkToNewsItemId.substr(8);
	var newsItemIdNumber = linkToNewsItemId.substr(18);
	
	//	In order to calculate where to scroll to, we'll need the height of a news item.
	//	To get this we take the height of the news events list and divide by how many items are in it.
	var itemHeight = $("#news-events").height() / $("#news-events li").length;
	
	//	Then we get the pixel position to scroll to by multiplying that height by the number of the news item
	var scrollAmount = itemHeight * newsItemIdNumber;
	
	scrollIt(newsItemIdNumber);
	
//	return false;
}

//	This function, to be called on a set interval, scrolls the news section to the next item in order
function cycleNewsItems() {
	
	//	First we find which news item is currently selected.
	var fullLinkId = $("#news-selector a.selected").attr("id");
	//	Then we extract the number from its id.
	var numberWeNeed = fullLinkId.substr(18);
	
	//	Remove the "selected" class from whatever currently has it.
	$("#news-selector a.selected").removeClass("selected");
	
	//	Now we determine whether we are currently on the last list item.
	var newsItems = $("#news-selector li").length - 1;
	
	if (numberWeNeed == newsItems) {
		//	If so, cycle back to the first item.
		numberWeNeed = 0;
	} else {
		//	If not, increment to the next item.
		numberWeNeed++;
	}
	
	//	Then we construct the id of the next link so we can take that and add the "selected" class
	var newId = "link-to-news-item-" + numberWeNeed;
	
	var newElem = document.getElementById(newId);
	
	//	Then we add the class to that link
	$(newElem).addClass("selected");
	
	//	Now we scroll to the next one
	scrollIt(numberWeNeed);
}

/*	Modifed from the original code entitled Animated Scrolling with jQuery 1.2 by Karl Swedberg
	http://www.learningjquery.com/2007/09/animated-scrolling-with-jquery-12
*/
function scrollIt(newsItemIdNumber) {
	var divOffset = $('#news-events').offset().top;
	var liOffset = $('#news-events li:eq(' + newsItemIdNumber + ')').offset().top;
	var liScroll = liOffset - divOffset;
	$('#news-events').animate({scrollTop: '+=' + liScroll + 'px'}, 1000);
}

function fixBackgroundImageFlickering() {
	/*	We only want to run this in IE6, because it affects performance otherwise. */
	if (!window.XMLHttpRequest) {
		try {
		  document.execCommand("BackgroundImageCache", false, true);
		} catch(err) {}
	}
}

function initSelectedCustomers() {
	$.ajax({
		type: "GET",
		url: "/data/selected_customers.xml",
		dataType: "xml",
		success: function(xml) {
			
			//	First we GET the XML data and map it to our global var, so it can be referenced from any other function.
			//	This is so we only have to run the GET request once.
			selectedCustomersData = xml;
			
			//	Since any of the images in the XML can be randomly called, we should preload them so there is no flickering.
			//	This loops through all images in the XML file and preloads them.
			$(xml).find("image-location").each(function() {
				$.preloadImages($(this).text());
			});
			
			//	Now that we have the data loaded, we can build the list that we'll populate with customer info.
			//	For now, this presumes that there will be always be four customer slots.
			//	And yes, these are SPACER GIFs. Believe me, I've exhausted plenty of other options before arriving at this.
			//	The root of the issue is that if there is an image on the page without a src attribute, IE6/7, display a red x
			//	(broken image location). So we have to give it something, and that something has to be invisible for this to look ok.
			$("<ul></ul>")
				.append("<li><a><img src='/images/spacer.gif' /></a></li>")
				.append("<li><a><img src='/images/spacer.gif' /></a></li>")
				.append("<li><a><img src='/images/spacer.gif' /></a></li>")
				.append("<li><a><img src='/images/spacer.gif' /></a></li>")
				.insertAfter("#selected-customers h3");
			
			//	And now that we have the list ready, we can begin to rotate customer info.
			initSelectedCustomersRotation();

		}
	});
}

function initSelectedCustomersRotation() {
	//	First we need to see how many customers we have data for in the XML.
	var customerNodes = $(selectedCustomersData).find("customer");
	
	//	We need an array that will store which customers have not been shown yet,
	//	so we can prevent any customers from showing multiple times in a row.
	//	Here we intialize the array, because it's possible it may still have values in it from a previous rotation cycle.
	customersShown = new Array();
	
	//	Then for each customer, we add an element to the array with its position.
	$.each(customerNodes, function(i, n) {
		customersShown.push(i);
	});

	//	Now we can begin rotating the images. The following will immediately rotate once to get started.
	rotateSelectedCustomers();
}

function rotateSelectedCustomers() {
	//	Before rotating logos we should check to see if there are enough logos left in the array.
	//	We'll need to compare the number of remaining elements in the array to the number of slots in the page.
	var customerSlots = $("#selected-customers li").length;
	
	//	If there are less remaining elements in the array than slots in the page...
	if (customersShown.length < customerSlots) {
		//	...then we call the init function to start over with a fresh array of all customers.
		initSelectedCustomersRotation();
	}

	//	Run the following for each customer slot in the Selected Customers section.
	$("#selected-customers li").each(function() {
		//	To get a random customer, we calculate a random integer between 0 and the number of customers that
		//	haven't been shown yet.
		var customerKey = Math.floor(Math.random() * customersShown.length);

		//	Grab the current link and image and assign them to variables, so we don't repeat the search.
		var currentLink = $(this).find("a");
		var currentImg = $(this).find("img");

		//	Parse the XML, grabbing the values we need from the customersShown element that matches customerKey.
		var customerName = $(selectedCustomersData).find("customer-name").eq(customersShown[customerKey]).text();
		var imageLocation = $(selectedCustomersData).find("image-location").eq(customersShown[customerKey]).text();
		var linkTitle = $(selectedCustomersData).find("link-title").eq(customersShown[customerKey]).text();
		var linkLocation = $(selectedCustomersData).find("link-location").eq(customersShown[customerKey]).text();

		//	First we fade out the existing logo, and do the rest as a callback function so that it 
		//	waits for the fade to finish before executing.
		$(currentImg).fadeOut(1400, function() {
			//	Then we replace the attributes of the link and image with their new values.
			$(currentLink).attr("title", linkTitle);
			$(currentLink).attr("href", linkLocation);
			$(currentImg).attr("src", imageLocation);
			$(currentImg).attr("alt", customerName);

			//	Then with the new values in place, we can fade it back in.
			$(currentImg).fadeIn(2400);
		});

		//	We remove the customer that we just displayed from the array, so that it is not repeated.
		customersShown.splice(customerKey, 1);
	});
}