/*
jQuery XML Parser with Sorting and Filtering
Written by Ben Lister (darkcrimson.com) revised 25 Apr 2010
Tutorial: http://blog.darkcrimson.com/2010/01/jquery-xml-parser/

Licensed under the MIT License:
http://www.opensource.org/licenses/mit-license.php
*/

var CYCLE_TIME = 4000;  // time between images
var DELAYED_TIME = 10000;  // delayed time (when you click on thumbnail)

var ANIMATION_SPEED = 300; // how fast the search slider moves

var imageSwitcher_Href = new Array();
var imageSwitcher_HrefFR = new Array();
var imageSwitcher_Alt = new Array();
var imageSwitcher_AltFR = new Array();
var imageSwitcher_Img = new Array();
var imageSwitcher_ImgFR = new Array();

var imageSwitcher_Thumb = "img/home/button.png";
var imageSwitcher_ThumbON = "img/home/buttonON.png";

var imageSwitcher_State = 0; // the current img state
var imageSwitcher_Timer;  // used to cancel the automatic image switch

// On page load...
jQuery("document").ready(function(){	
    function xml_parser(wrapper) {
    
	//Construct and display preloader
     $('<div id="preload_xml"></div>').html('<img src="/img/ajax-loader.gif" alt="loading data" /><h3>Loading Data...</h3>').prependTo($('body'));
     	
     	//Hide Content (this is sloppy but easy to customize..)
        $(wrapper).hide();
		
		//Get XML Data --note special case for IE http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
        $.ajax({
            type: 'GET',
            url: '../xml/FieldsHomePageHeroes.xml',
            dataType: ($.browser.msie) ? 'text' : 'xml', 
            success: function (data) {
			         var xml_list;
                     
                    if ($.browser.msie) 
					{
						xml_list = new ActiveXObject('Microsoft.XMLDOM');
						xml_list.async = false;
						xml_list.loadXML(data);
					} 
					else 
					{
						xml_list = data;
					}
            
			  //Remove preloader HTML & show data
       		  $('#preload_xml').remove();
       		  $(wrapper).show();
				
				var xmlArrPositional = [];
				var xmlArrPromo = [];
				
				var imageOffset = 0;
				var imageOffsetFR = 0;
			
                $(xml_list).find('hero').each(function() {
				
					//Meta Data
					var xml_startdate  	= $(this).attr('start_date');
					var xml_enddate  	= $(this).attr('end_date');
					var xml_position  	= $(this).attr('position');
					
					//var xml_type      	= $(this).attr('type'); 
                    //var xml_object 	  	= $(this).attr('object');
					//var xml_category  	= $(this).attr('category');
					
					//check if date is within range
					if(checkDateRange(xml_startdate, xml_enddate ))
					{
						var positionIndex = parseInt(xml_position);
					
						if (GetLanguage() == "fr") {
							var navigateUrl = $(this).find('navigate_url_fr').text();
							if (navigateUrl == null || navigateUrl == '') {
								imageOffsetFR--;
							}
							else {
								imageSwitcher_HrefFR[positionIndex + imageOffsetFR] = navigateUrl;
								imageSwitcher_AltFR[positionIndex + imageOffsetFR] = $(this).find('alt_tag_fr').text();
								imageSwitcher_ImgFR[positionIndex + imageOffsetFR] = $(this).find('image_fr').text();
							}
						}
						else {
							var navigateUrl = $(this).find('navigate_url_en').text();
							if (navigateUrl == null || navigateUrl == '') {
								imageOffset--;
							}
							else {
								imageSwitcher_Href[positionIndex + imageOffset] = navigateUrl;
								imageSwitcher_Alt[positionIndex + imageOffset] = $(this).find('alt_tag_en').text();
								imageSwitcher_Img[positionIndex + imageOffset] = $(this).find('image_en').text();
							}
						}
					}
                }); // end each loop

				// make some changes if we are french
				if (GetLanguage() == "fr"){
					imageSwitcher_Href = imageSwitcher_HrefFR;
					imageSwitcher_Img = imageSwitcher_ImgFR;
					imageSwitcher_Alt = imageSwitcher_AltFR;
				}
				var imgIndex = 0;
				var current = "<img id=\"tn_"+imgIndex+"\" src=\""+imageSwitcher_ThumbON+"\" onclick=\"thumbClick(this)\">";
				
				// Create all the thumbnail buttons
				for (imgIndex = 1; imgIndex < imageSwitcher_Img.length; imgIndex ++){
					current += "<img id=\"tn_"+imgIndex+"\" src=\""+imageSwitcher_Thumb+"\" onclick=\"thumbClick(this)\">";
				}
				// dynamically add alt, title, and links
				updateImages();
				
				// Add the thumbnails to the page
				document.getElementById("imageSwitcher-thumbnails").innerHTML = current;
					
				//Start cycling the images
				imageSwitcher_Timer = setTimeout (imageSwitch,CYCLE_TIME); // cycle main image x/1000 seconds later
  			  
				// end init
			  
			} // end post AJAX call operaitons
        }); // end AJAX
	
    } // end function
    
 	//Function Call
	var wrapper = '#content'; // Id of wrapper
 	xml_parser(wrapper);
});

// Handles clicks on pagination buttons
function thumbClick(obj){
	pageOff();
	imageSwitcher_State = parseInt(obj.id.substring(3),10);
	pageOn();
	updateImages();	
	clearTimeout(imageSwitcher_Timer); // remove old timer
	imageSwitcher_Timer = setTimeout (imageSwitch,DELAYED_TIME); // cycle x/1000 seconds later
}

// automatically cycles through main display images
function imageSwitch(){
	
	pageOff();
	imageSwitcher_State ++;
	if (imageSwitcher_State == imageSwitcher_Img.length)
		imageSwitcher_State = 0;
	updateImages();
	pageOn();
	imageSwitcher_Timer = setTimeout (imageSwitch,CYCLE_TIME); // cycle x/1000 seconds later
}

// Replaces active pagination with default image
function pageOff(){
	document.getElementById("imageSwitcher-thumbnails").getElementsByTagName("img")[imageSwitcher_State].src = imageSwitcher_Thumb;
}

// When you click on a pagination button, replace with active image
function pageOn(){
	document.getElementById("imageSwitcher-thumbnails").getElementsByTagName("img")[imageSwitcher_State].src = imageSwitcher_ThumbON;
}

//Dynamically set HREF of link, SRC of image, and Alt and Title tags.
function updateImages(){

	$("#imageSwitcher-image").fadeOut(ANIMATION_SPEED,function(){
		document.getElementById("imageSwitcher-link").href = imageSwitcher_Href[imageSwitcher_State];
		document.getElementById("imageSwitcher-image").src = imageSwitcher_Img[imageSwitcher_State];
		document.getElementById("imageSwitcher-image").title = imageSwitcher_Alt[imageSwitcher_State];
		document.getElementById("imageSwitcher-image").alt = imageSwitcher_Alt[imageSwitcher_State];
		$("#imageSwitcher-image").fadeIn(ANIMATION_SPEED);
	});
}

//Return en or fr paged on Query string or server folder path
function GetLanguage()
{		
	if ((window.location+" ").indexOf("/fr/") != -1){
		return "fr";
	}else{
		// So were not in a french folder, check if we used query string
		if (queryString("language") == "fr"){
			return "fr";
		}else{
			return "en";
		}			
	}
}	

// Isolates a query string variable from the window URL
function PageQuery(q) {
	if (q.length > 1) this.q = q.substring(1, q.length);
	else this.q = "null";
	this.keyValuePairs = new Array();
	if (q) {
		for (var i = 0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
		for (var j = 0; j < this.keyValuePairs.length; j++) {
			if (this.keyValuePairs[j].split("=")[0] == s)
				return this.keyValuePairs[j].split("=")[1];
		}
		return "null";
	}
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for (var j = 0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }
}
function queryString(key) {
	var page = new PageQuery((window.location.search).toLowerCase());
	return unescape(page.getValue(key.toLowerCase()));
}


// checkDateEntries - Checks to ensure that the values entered are dates and 
//       are of a valid range.
function checkDateRange(start, end) 
{
   // Parse the entries
   var startDate = Date.parse(start);
   var endDate = Date.parse(end);
   var now = new Date();

   // Make sure they are valid
    if (isNaN(startDate)) {
     //alert("The start date provided is not valid, please enter a valid date.");
      return false;
   }
   if (isNaN(endDate)) {
      // alert("The end date provided is not valid, please enter a valid date.");
       return false;
   }
   // Check the date range, 
    if (endDate < startDate)  {
     //  alert("The start date must come before the end date.");
       return false;
   }
   if (startDate > now || now > endDate)
   {
     // alert("The article is not within the valid dates");
       return false;
    }
   return true;
}
