/********************** Initialize page ************************************/

// 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() {
	
	// Load banner files and start animation
	firstLoad();
	// set twitter box height
	setTwitterBoxHeight();
	// set twitter header
	setTwitterHeader();
	// getTwitter RSS and start intervals
	getRSS();
	setInterval("getRSS()",120000);
});

/***************************** Banner Functions ****************************/
// arrays that hold the image and text elements
var myBannerArray = new Array();
var myTextArray = new Array();
var elemArray = new Array();

// variable that will contain total number of elements in the array
var count;
// set initial index 
var currElemIndex = 0;
// loads external File
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(/<div>/g,'###<div>');
	myText = myText.replace(/> </g,'><');
	var lastDiv = myText.lastIndexOf("</div>")+6;
	var firstDiv = myText.indexOf("###");
	myText = myText.substr(firstDiv,lastDiv);
	
	// 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
function getContent(file,htmltag,array,identifier)
{
	
	// 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('<div') !== -1)
		{
			// text transformations to apply to the HTML file
			elemArray[i] = elemArray[i].replace('border="1"','border="0"');
			elemArray[i] = elemArray[i].replace('<div><p>','<div id="'+identifier+"_"+counter+'" style="display:none;">');
			elemArray[i] = elemArray[i].replace('<div>','<div id="'+identifier+"_"+counter+'" style="display:none;">');
			elemArray[i] = elemArray[i].replace('<\/p><\/div>','<\/div>');
			elemArray[i] = elemArray[i].replace('> <','><');
			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});
	setTimeout(function(){Effect.Fade(myTextArray[arrayIndex],{duration: fadeSpeed})},600);
}

// Appear Effect
function showItem(arrayIndex){
	Effect.Appear(document.getElementById(myBannerArray[arrayIndex]),{duration: fadeSpeed });
	setTimeout(function(){Effect.Appear(myTextArray[arrayIndex],{duration: fadeSpeed})},200);
}

// 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";
			document.getElementById(myTextArray[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.gif";
	}
}

// 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.gif";
}

// 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(){
	//document.getElementById(myImageArea).style.background = imageBackgroundCol;
	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();
	//document.getElementById("pause").style.display="inline";
	//document.getElementById("resume").style.display="none";
}

// function that rotates the banners automaticaly according to the timer variable
function startAnimation()
{
	nextImgTO = setTimeout(resumeAnimation,timer-1000);
	bannerTO = setTimeout(startAnimation,timer);
}

function buildNewsNav(){
	var myNavItems="<a href='javascript:void(0);' onClick='showMyItem(04321);'><img src='/images/rework2010/homePage/btn_prev.gif' border='0' title='"+prevLabel+"' alt='"+prevLabel+"' class='articleNav'></a>";
	var x = 1;
	for (i=0;i<elemLimit;i++){
		//myNavItems+="<span id='lnk_"+i+"' class='itemOff'><a href='javascript:void(0);' onClick='showMyItem("+i+",1);'>"+x+"<\/a><\/span>";
		var currText = document.getElementById(myTextArray[i]).innerHTML;
		var testStr = currText.toLowerCase();
		var currTitleStart = testStr.indexOf("<h2>")+4;
		var currTitleEnd = testStr.indexOf("</h2>")-4;
		var currTitle = currText.substr(currTitleStart,currTitleEnd);
		currTitle = currTitle.replace(/'/g,"&#39;");
		currTitle = currTitle.replace(/<(.*?)>/g," ");
		myNavItems+="<a href='javascript:void(0);' onClick='showMyItem("+i+",1);' class='articleNav'><img id='lnk_"+i+"' src='" + imagePath + "btn_back_off.gif' border='0' alt='"+ currTitle +"' title='"+ currTitle +"'><\/a>";
		x++;
	}
	document.getElementById("newsNav").innerHTML = myNavItems + "<a href='javascript:void(0);' onClick='showMyItem(01234);'><img src='/images/rework2010/homePage/btn_next.gif' border='0' title='"+nextLabel+"' alt='"+nextLabel+"' class='articleNav'></a>";
}
// displays the initial image and starts the banner rotation
function firstLoad()
{
	getContent(myImageFile,myImageArea,myBannerArray,myImagePrefix);
	getContent(mytextFile,myTextArea,myTextArray,myTextPrefix);
	// count is updated here
	count = myBannerArray.length-1;
	if(myBannerArray.length < elemLimit){ elemLimit = myBannerArray.length;}
	buildNewsNav();
	// display first image
	displayImage();
	// start rotating the banners
	startAnimation();
}




/***************************** Social media functions *********************************************/
					
// gets rss feed for twitter
function getRSS(){
	var htmlText="";
	new Ajax.Request(feed,
	{
		method:'get',
		onSuccess: function(transport)
		{
			
			var response = transport.responseText;
			
			response = response.replace(/(\r\n|[\r\n])/g, "");
			response = response.replace(/(\r\n|\r|\n)/g, "");
			response = response.replace(/>[\s]*</g, "><");
			var firstItem = response.indexOf("<item>");
			var myStringLen = response.indexOf("<\/channel>");
			var myString = response.substring(firstItem,myStringLen)
			var myOrigItems = myString.split('<item>');
			var myNewItems = myOrigItems.slice(1,itemsToShow+1);
			for(i=0;i<itemsToShow;i++)
			{
				
				var myTitleStart = myNewItems[i].indexOf("<title>")+7;
				var myTitleEnd = myNewItems[i].indexOf("</title>");
				var myTitle = myNewItems[i].substring(myTitleStart,myTitleEnd);
				var myTitleLength = myTitle.length;
				var myLinkStart = myTitle.indexOf("http");
				var myLink = "";
				if(myLinkStart>0){
					myTempLinkStr = myTitle.substring(myLinkStart,myTitleLength);
					myTempLinkEnd = myTempLinkStr.indexOf(" ");
					if (myTempLinkEnd < 0){
						myTempLinkEnd = myTitleLength;
					}
					myLink = myTempLinkStr.substring(0,myTempLinkEnd);
					myLinkLength = myLink.length;
					
					var dotPos = myLink.lastIndexOf(".");
					var commaPos = myLink.lastIndexOf(",");
					if (commaPos > 0){
						myLink = myLink.substring(0,myLinkLength-1);
					}
					if(dotPos > 0 && dotPos == myLinkLength)
					{
						myLink = myLink.substring(0,myLinkLength-1);
					}			
				}
				if(myLink){
					var myFinalLink = "<a href='"+myLink+"' target='_top'>"+myLink+"<\/a>";
					myTitle = myTitle.replace(myLink,myFinalLink);
				}
				
				myTitle = removeSrings(myTitle);
				
				if (i==(itemsToShow-1))
				{
					var myStyle = " class='lastFeed'";
				}else{
					var myStyle = "";
				}
				htmlText += "<div"+myStyle+">" + myTitle + "<br />";
				var myDateStart = myNewItems[i].indexOf("<pubDate>")+9;
				var myDateEnd = myNewItems[i].indexOf("</pubDate>");
				
				var myDate = myNewItems[i].substring(myDateStart,myDateEnd);
				var myDateStr = formatDateString(myDate);
				
				htmlText += "<span class='dateStr'>" + myDateStr +"<\/span><\/div>" ;
			}
			document.getElementById(elemForFeed).innerHTML = htmlText;
		}
	});
}

// function to format date into international string
function formatDateString(dateStr){
	var myDate = new Date(dateStr);
	var myDay = myDate.getDate();
	if(myDay < 10){
		myDay = "0"+myDay;
	}
	var myMonth = myDate.getMonth()+1;
	if(myMonth < 10){
		myMonth="0"+myMonth;
	}
	var myYear = myDate.getFullYear();
	
	var timeStr = "";
	var hours = myDate.getHours();
	var minutes = myDate.getMinutes();
	var timeEnd="";
	if (minutes < 10){
		minutes = "0" + minutes
	}
	if(pgLang == "en"){
		if(hours > 12){
			hours = (hours-12);
			timeEnd = "PM";
		}else{
			timeEnd = "AM";
		}

		timeStr += hours + ":" + minutes + " " + timeEnd;
	} else {
		timeStr += hours + " h " + minutes;
	}
	
	var myDateStr = myYear+"/"+myMonth+"/"+myDay + " - " + timeStr;
	return myDateStr;
}

// function that removes the unwanted elements from the tweet elements
function removeSrings(s){
	for(r=0;r<removeArrLen;r++){
		s = s.replace(removeArray[r],"");
		//alert(removeArray[r]);
	}
	return s;
}

// function to show and hide social media boxes
function showSocialBox(box){
	var boxToShow = box;
	document.getElementById(boxToShow+"Tab").className = "socTabSelected";
	var boxes = new Array("twitterBox","youtubeBox","flickrBox");
	var arrLen = boxes.length;
	for (i=0;i<arrLen;i++){
		if(boxToShow == boxes[i]){
			document.getElementById(boxes[i]).className = "socShowBox";
		}else{
			document.getElementById(boxes[i]).className = "socHideBox";
			document.getElementById(boxes[i]+"Tab").className = "";
		}
	}
}

var ip = '10.100.45.2';

// function to set twitter box height
function setTwitterBoxHeight()
{
	if (ip == '192.168.100.10') {
		document.getElementById(elemForFeed).style.height = "200px";
	}
}
// function to write twitter heading
function setTwitterHeader(){
	if (ip != '192.168.100.10'){
		document.getElementById(twitterHeading).innerHTML = "<a href=\""+twitterWebLink+"\"><img src=\"/templates/widgets/health/images/icon_twitter.gif\" height=\"16\" width=\"16\" alt=\"\" border=\"0\">"+twitterTag+"</a>&nbsp;";
		document.getElementById(twitterHeading).innerHTML += "<a href=\""+feed+"\"><img src=\"/templates/widgets/health/images/icon_rss.gif\" height=\"16\" width=\"16\" alt=\"\" border=\"0\">RSS</a>";
	}
}
// google translate function
function googleTranslateElementInit() {
  new google.translate.TranslateElement({
    pageLanguage: pgLang,
    includedLanguages: 'af,sq,ar,hy,az,eu,be,bg,ca,zh-CN,zh-TW,hr,cs,da,nl,en,et,tl,fi,gl,ka,de,el,ht,iw,hi,hu,is,id,ga,it,ja,ko,lv,lt,mk,ms,mt,no,fa,pl,pt,ro,ru,sr,sk,sl,es,sw,sv,th,tr,uk,ur,vi,cy,yi'
  }, 'google_translate_element');
}


/**************************** Old RSS function to reuse when going to production ***********************/
//	function getRSS() { 
//		var milis2keep = 24 * 3600000;
//		var oXMLHttpRequest = new XMLHttpRequest;
//		oXMLHttpRequest.open("GET", feed, true);
//		oXMLHttpRequest.onreadystatechange = function() {
//			if (this.readyState == XMLHttpRequest.DONE) {
//				obj = document.getElementById(elemForFeed);
//				obj.innerHTML = "";
//				var xmlDoc = oXMLHttpRequest.responseXML;
//				var items = xmlDoc.documentElement.getElementsByTagName("item");
//				//var itemsToShow = items.length;
//				var itemsToShow = 3;
//				for (var i = 0; i < itemsToShow; i++) {
//					var text = items[i].getElementsByTagName("title").item(0).firstChild.nodeValue;
//					var datestr = items[i].getElementsByTagName("pubDate").item(0).firstChild.nodeValue;
//					var d = new Date(datestr);
//					//var today = new Date();
//					//if ( (today.getDate() == d.getDate()) && (today.getMonth() == d.getMonth()) && (d.getFullYear() == today.getFullYear()))
//					//{
//						datestr = d.toLocaleString();
//						datestr = datestr.replace(/GMT.*/,"");
//						text = text.replace("ottawahealth: ", "");
//						text = text.replace("More info: http://tinyurl.com/otth1n1", "");
//						text = text.replace("http://tinyurl.com/otth1n1", "");
//                      if(i==itemsToShow-1){
//							obj.innerHTML += "<div class='lastFeed'>" + text  + "<br/><span class='dateStr'>" + datestr + "</span></div>";
//						}else{
//							obj.innerHTML += "<div>" + text  + "<br/><span class='dateStr'>" + datestr + "</span></div>";
//							}
//						
//					//}
//					}
//				}
//			}
//			oXMLHttpRequest.send(null);
//		}
