//detect language and set alt text for image navigation
var thisPage = location.href.toString();
var lang = thisPage.substring(thisPage.lastIndexOf("_"), thisPage.lastIndexOf("."));
if(lang=="_en"){
	var altNext="Next >>";
	var altPrev="<< Previous";
}else{
	var altNext="Suivant >>";
	var altPrev="<< Précédent";
}

// set variables
var myImageFile = "home_events"+lang+".html";		// HTML file that contains the images
var myImageArea = "bannerArea";					// Div id that will host the images
var myImagePrefix = "itm";						// Prefix that will be used in building the image ids
var imagePath = "images/";					// Path to navigation images
var myImageNav = "featureNav";					// Div id that will host the navigation bar
var myNewsFile = "home_news"+lang+".html";		// HTML file that contains the articles
var myNewsArea = "upcomingEvents";				// Div id that will host the news items
var myNewsPrefix = "news";						// Prefix that will be used in building the news ids

// Limit of elements for each group to be displayed on the page
var imageLimit = 7; 			// holds the limit of banners to display, also is used to generate the navigation
var featureLimit = 7; 			// holds the limit of articles to display

// each block of animated content needs to have an array of it's own
var myBannerArray = new Array();
var myFeatureArray = new Array();

// temporary array used to create the different arrays declared abobe
// is only used when loading the HTML file
var elemArray = new Array();

// variable that will contain total number of elements in the image array
var count=0;

// variable that controls the length of time in milliseconds that a banner image will be displayed on the page
// when counting the two fades, this value will translate to about 7000 milliseconds of viewing time
var timer = 5000;
var fadeSpeed = 1;

// variable that holds the duration in milliseconds that the news items will be displayed
var newsTimer = 4000;

// set initial index for each block of elements
var currElemIndex = 0;
var currNewsItem = 0;

// function that loads the images and starts animation when dom is ready, 
// this is a better method than <body onLoad="firstLoad();"> since it doesn't 
// wait for the browser to finish loading all of the other elements on the page
document.observe("dom:loaded", function() {
  	getContent(myImageFile,myImageArea,myBannerArray,myImagePrefix,imageLimit);
  	getContent(myNewsFile,myNewsArea,myFeatureArray,myNewsPrefix,featureLimit);
	// count is updated here
	count = myBannerArray.length-1;
	// build the image navigation
	buildNav(myBannerArray,myImageNav,imageLimit);
	// display first image
	displayImage();
	// start rotating the banners
	startAnimation();
	setTimeout(getNewsItems,1000);
});

function loadXMLDoc(url)
{
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
		xmlhttp.open("GET",url,false);
		xmlhttp.send(null);
		
	}
	else
	{// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		xmlhttp.open("GET",url,false);
		xmlhttp.send();
	}
	
	var myText = xmlhttp.responseText;

	// Strip out all of the unwanted white space in the file
	myText = myText.replace(/(\n\r|\n|\r)/gm,"<1br />");
	myText = myText.replace(/\t/g," ");
	re1 = /\s+/g;
	myText = myText.replace(re1," ");
	re2 = /\<1br \/>/gi;
	myText = myText.replace(re2, "");
	
	// set markers for splitting text
	myText = myText.replace(/<p>/g,'###<p>');
	myText = myText.replace(/> </g,'><');
	var lastP = myText.lastIndexOf("<\/p>");
	var firstP = myText.indexOf("###")+3;
	myText = myText.substr(firstP,lastP);
	
	// remove trailing </div> dont know why it's there in the first place
	myText = myText.replace('<\/div>','');
	// create element arrays
	elemArray = myText.split("###");
}

// function getContent gets the HMTL files via the loadXMLDoc function, it has four parameters:
// file -> HTML file to parse
// htmltag -> ID of the HTML elemement that will display the items on the page
// array -> Name of the array that will contain the items
// identifier -> A unique prefix that will be used to generate IDs for the display elements
// limit -> th maximum number of elements to shw for any given item
function getContent(file,htmltag,array,identifier,limit)
{
	var elemLimit = limit;
	// function loads the file and inserts it into a temporary array
	loadXMLDoc(file);
	var myLen = elemArray.length;
	var counter = 0;
	var txt="";
	for (i=0;i<myLen;i++)
	{
		if (elemArray[i].indexOf('<p') !== -1)
		{
			// text transformations to apply to the HTML file
			elemArray[i] = elemArray[i].replace('border="1"','border="0"');
			// this will add a unique ID to the <p> tags
			elemArray[i] = elemArray[i].replace('<p>','<p id="'+identifier+"_"+counter+'" style="display:none;">');
			// will compensate for a weird MS word bug that does not always nest tags properly
			elemArray[i] = elemArray[i].replace('<\/p><\/a>','<\/a><\/p>');
			// this will add a unique ID to the <img> tags
			elemArray[i] = elemArray[i].replace('<img','<img id="'+identifier+"_"+counter+'_img"');
			if(counter<elemLimit){
				txt+=elemArray[i];
				array[counter] = identifier+"_"+counter;
				counter++;
			}
		}
	}
	document.getElementById(htmltag).innerHTML=txt;
	elemArray="";
	txt="";
}

// Fade Effect
function fadeItem(arrayIndex){
	Effect.Fade(document.getElementById(myBannerArray[arrayIndex]),{duration: fadeSpeed});
}

// Appear Effect
function showItem(arrayIndex){
	Effect.Appear(document.getElementById(myBannerArray[arrayIndex]),{duration: fadeSpeed });
}

// main function that controls the images and navigation
function showMyItem(myIndex,userClick)
{		
	// set main div background to current element before fading to next
	setBgImage();
	// wait until background has changed then apply a 
	// fade transition to the current element
	var hasClicked = userClick;
	if(setBgImage)
	{
		fadeItem(currElemIndex);
		var previtem = currElemIndex;
		stopAnim();		
		// 01234 is a bogus number that represents the show next action	
		if(myIndex==01234)
		{
			if(currElemIndex<count){currElemIndex++;}else{currElemIndex = 0;}			
		}
		
		// 04321 is a bogus number that represents the show previous action	
		else if(myIndex==04321)
		{
			if(currElemIndex==0){currElemIndex=count;}else{currElemIndex--;}
		}
		
		// the specific indexes are handled here
		else
		{
			currElemIndex = myIndex;
		}
		if (hasClicked == 1){
			// immediately hide the current items to display the one that the user selected
			document.getElementById(myBannerArray[previtem]).style.display="none";
			
			// need to name timouts in order for them to be cleared
			// when clicking on another item
			bannerTO = setTimeout(displayImage,0);
			nextImgTO = setTimeout(startAnimation,timer-2000);
			hasClicked = 0;
			
		}else{
			setTimeout(displayImage,1000);
		}
	}
}

// removes the highlighting on the menu items
function resetLink(){
	for(i=0;i<=count;i++){
		document.getElementById("lnk_" + i).src = imagePath + "btn_back_off.png";
	}
}

// displays image using an appear effect
function displayImage(){
	showItem(currElemIndex);
	// removes the highlighting on the menu items
	resetLink();
	// highlights only the active menu item
	document.getElementById("lnk_" + currElemIndex).src = imagePath + "btn_back_on.png";
}

// stops the banner animation, clears the timers and resets the buttons;
function stopAnim(){
	clearTimeout(nextImgTO);
	clearTimeout(bannerTO);
}

// sets the background image to the current element before fading to the next one
// ensures a smooth transition between images
function setBgImage(){
	var bgImage = document.getElementById("itm_" + currElemIndex + "_img").src;
	document.getElementById(myImageArea).style.background = "url("+bgImage+")";
	return true;
}

// fuction that resumes the rotating banner routine
function resumeAnimation()
{
	showMyItem(01234,0);
	startAnimation();
}

// function that rotates the banners automaticaly according to the timer variable
function startAnimation()
{
	nextImgTO = setTimeout(resumeAnimation,timer-1000);
	bannerTO = setTimeout(startAnimation,timer);
}

// function to build the navigation bar for the images
function buildNav(array,htmlElement,limit){
	var elemLimit=limit;
	var itemArray = array;
	var container = htmlElement;
	var myNavItems="<div>";
	/* var myNavItems="<div><a href='javascript:void(0);' onClick='showMyItem(04321,1);' class='articleNav'><img src='" + imagePath + "btn_prev.png' border='0' alt='" + altPrev + "' title='" + altPrev + "'></a>"; */
	var x = 1;
	for (i=0;i<elemLimit;i++){
		var currentP = document.getElementById(itemArray[i]).id;
		var currentIMG = currentP+"_img";
		var currentALT = document.getElementById(currentIMG).alt;
		myNavItems+="<a href='javascript:void(0);' onClick='showMyItem("+i+",1);' class='articleNav'><img id='lnk_"+i+"' src='" + imagePath + "btn_back_off.png' border='0' alt='"+currentALT+"' title='"+currentALT+"'><\/a>";
		x++;
	}
	/* myNavItems+="<a href='javascript:void(0);' onClick='showMyItem(01234,1);' class='articleNav'><img src='" + imagePath + "btn_next.png' border='0' alt='" + altNext + "' title='" + altNext + "'></a></div>"; */
	document.getElementById(container).innerHTML = myNavItems;
}


// Function to animate news items
function getNewsItems(){
	var prevItem = currNewsItem-1;
	if (prevItem<0){prevItem = featureLimit-1}
	if(currNewsItem == featureLimit){
		currNewsItem = 0;
	}
	document.getElementById("news_"+prevItem).style.display="none";
	document.getElementById("news_"+currNewsItem).style.display="block";
	newsTO = setTimeout(getNewsItems,newsTimer);
	currNewsItem++;
}
