/**************************************************
	UI Tabs Initialization and some tabs customization
 **************************************************/



//	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();", 6000);
});

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();", 1200);
	}
	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);
	});
	
	/* Video Colorbox */
	$.fn.colorbox.settings.opacity = "0.4"; 
	$.fn.colorbox.settings.transition = "none";
	var videoWidth = 640;
	var videoHeight = 427;
	var popupWidth = videoWidth+4;
	var popupHeight = videoHeight+124;
	
	
	if (jQuery.browser.msie){
		if(parseInt(jQuery.browser.version) < 8) {
			$("a[href='/resources/videos/dl/product-overview.html']").colorbox({width:popupWidth,height:popupHeight+30,iframe:true, href:"/resources/videos/dl/product-overview.html"});
		}
		else {
			$("a[href='/resources/videos/dl/product-overview.html']").colorbox({width:popupWidth,height:popupHeight,iframe:true, href:"/resources/videos/dl/product-overview.html"});
		}
	}
	else{
		$("a[href='/resources/videos/dl/product-overview.html']").colorbox({width:popupWidth,height:popupHeight,iframe:true, href:"/resources/videos/dl/product-overview.html"});
	}
}