/*
	News Ticker
	Reads RSS from local cfm page, parses it into arrays then displays the info at timed intervals in the 
	<span class="NewsTicker"><a class="NewsLink" href="http://localhost/imt_website/News.cfm" title="Click here to see all news on one page">Latest News</a>: <a id="NewsTicker_Link" style="text-decoration: none;" target="" href="News_View_Item.cfm?id=1"><span id="NewsTicker_Text">Royal Mail's International Mail Technical off</span></a></span>
	Brian Clear 31 Jan 2007
 */
	//=============================================
	var xmlHttp;	//Ajax HttpRequest object
	var xmlstring; 	//stores the XML returned from Ajax call
	var xmlDoc;    	//XMLDocument
	
	
	var iRetrieveNewsInterval = 10 *1000; //10 seconds
	var iAnimateTickerInterval = 9 *1000; //10 seconds
	
	//arrays to store the news items on for <title>/<description>/<link> for each <item>  from rss feed
	var arrayNews_title 	        = new Array();	//Array of Headlines for the news items - displayed in the ticker
	var arrayNews_description 	    = new Array();	//Full text of each news item
	var arrayNews_link 	            = new Array();	//Url for each news item
	var arrayNews_guid_id 	        = new Array();  //RSS-<guid> used to stored the id field for the news item from the db
	
	var arrayNews_descriptionCount = 0; // the current news item used to access the above arrays together

	var tempString		= "";	//typewriter text as printed out letter by letter
	var i 				= 1; 	//for typewriter text print out letter by letter
	var j				= 0;	//Current news item to display on ticker

	var bNewsRetrieved = false;

	var	timerAnimate;
	var bAnimationInProgress = false;
	var timerID1;
	//URL of rss feed to display. May be overwritten from StartNewsTicker
	//must be in same domain (www.internationalmailtechnical.com) as AJax cant call across domains
	var sRSSFeedURL = 'http://localhost/imt_website/RSS/feed.cfm';

	//----------------------------------------------------------------
	function StartNewsTicker(sRSSURL)
	{
		//override the default URL for the RSS feed with the one called in index.cfm/_Main_Menu.cfm
		//<body onload="StartNewsTicker('<cfoutput>#request.WEBSITE_ROOT_PATH#</cfoutput>RSS/feed.cfm')">
		sRSSFeedURL = sRSSURL;
		resetform(); //Debugging see //log() below for instructions
		//Start timer to retrieve news
		ScheduleAjaxTimer();	
		ScheduleNewsUpdateTimer();
	}	
	function ScheduleAjaxTimer() {
		
		//log("==========================================================");
		//log("ScheduleTimerRestart called");
		//Retrieve news for the first time
		bNewsRetrieved = false;
		ajax_RetrieveNews();
		bNewsRetrieved = true;
		//log("ScheduleTimerRestart - ajax_RetrieveNews finished");
		//updateNewsArea();
		log("window.setTimeout('ajax_RetrieveNews()', 5 * 1000);");

		//window.setTimeout('ajax_RetrieveNews()', iRetrieveNewsInterval);
	}
	function ScheduleNewsUpdateTimer() {
		//log("RestartTimer called");
		updateNewsArea();
		//Update the news item every second 
		//log("SETINTERVAL");
		timerID1 = window.setInterval('updateNewsArea()', iAnimateTickerInterval);
	}
	//============================================
	function updateNewsArea() {
		//only update news if ajax finished
		if(bNewsRetrieved)
		{
			if(arrayNews_title.length > 0)
			{
				//log("                           updateNewsArea called");
				//log("                           updateNewsArea j:" + j);
				//log("                           updateNewsArea arrayNews_title[j]:" + arrayNews_title[j]);
				//log("                           updateNewsArea arrayNews_title.length:" + arrayNews_title.length);
				
				tempString = arrayNews_title[j];//.substring(0, i);
	
				//i = i + 1;
				
				//if ( i > arrayNews_title[j].length ) {
					//i = 1;
		//			//log("CLEARINTERVAL");
		//			window.clearInterval(timerID1);
		//			ScheduleTimerRestart();

				//}
				if(arrayNews_link[j] === '')
				{
					a_href = "News_View_Item.cfm?id=" + arrayNews_guid_id[j];
					a_target = "";
				}
				else
				{
					a_href = arrayNews_link[j];
					//a_target = "target=&quot;_blank&quot;";
					a_target = "";
				}
				if(!bAnimationInProgress)
				{
					//log("UPDATE TICKER:" + tempString);
					updateNewsTicker( tempString, a_href, a_target );
					j = j + 1;
					if( arrayNews_title.length == j  ) {
						j = 0;
					}
				}
				else
				{
					//log('bAnimationInProgress is TRUE - updateNewsTicker cancelled')
				}

			}
		}
	}
	
	function updateNewsTicker( a_text, a_href, a_target ) {
		//log("                           updateNewsTicker called");
		//document.getElementById("NewsTicker_Text").innerHTML = "<a href='"+ a_href +"' target='"+ a_target +"' style='text-decoration: none;'>" + a_text + "<\/a>";
		//We had a problem where the ticker text updates too fast so clicking on the <a> didnt work everytime
		//I tried putting the displayed text between the <a><a/> into its own span but had same problem
		var NewsTicker_Hyperlink = document.getElementById("NewsTicker_Link");
		if(NewsTicker_Hyperlink)
		{
			NewsTicker_Hyperlink.href = a_href;
			NewsTicker_Hyperlink.target=a_target;
		}
		//log("WRITING TO DIV:" + a_text);
		document.getElementById("NewsTicker_Text").innerHTML = a_text;
		//stop the news item changing while your animating it
		//window.clearInterval(timerID1);
		animateWidth('NewsTicker_Text', 900);
		var clip_width = 1;
		
	}
	
	function updateTickerWithMessage( sMessage) {
		//log("updateTickerWithMessage() called with msg:'" + sMessage + "'");
		document.getElementById("NewsTicker_Text").innerHTML = sMessage;
	}
	//========================================================================================
	//animate layer width ====================================================================
	//========================================================================================
	/*
	Div being animated must have position:absolute
	#Layer1 {
			position:absolute;
			width:235px;
			height:25px;
			z-index:1;
			left: 256px;
			top: 80px;
			<!---background-color: #996600;//uncomment to see div appear--->
			}
	*/
	var clip_width = 1;
	function animateWidth(id, size)
	{
		bAnimationInProgress = true;
		el = document.getElementById(id);
		//var h_size1 = el.offsetWidth;
		if (clip_width < size)
		{
			////log("clip_width:" + clip_width + " size:" + size);
			clip_width = clip_width + 2;
			//el.style.width = h_size1 + 2+"px";
			el.style.clip="rect(0px," + clip_width  + "px" + ",50px,0px)"; 
			timerAnimate = setTimeout("animateWidth('" + id + "','" + size + "')", 1);
		}
		else
		{
			
			clip_width = 1;
			clearTimeout(timerAnimate);
			bAnimationInProgress = false;
			//log('SETTING bAnimationInProgress = false;')
		}
		
	}
	
	//========== AJAX RSS FUNCTIONS ==================================	

	//---------------------------------------------------------------------------
	// Cross browser script to create the AJAX Object XMLHttpRequest
	function ajax_Initialize()
	{
		log("ajax_Initialize called ==============================================");

		log("ERROR - on xmlHttp=new XMLHttpRequest(); ");

		// Internet Explorer    
		try
		{      
			log("try - xmlHttp=new ActiveXObject(Msxml2.XMLHTTP); ");
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");      
			log("USING - xmlHttp=new ActiveXObject(Msxml2.XMLHTTP); ");
		}
		catch (e)
		{      
			try
			{        
				log("ERROR trying - ActiveXObject(Microsoft.XMLHTTP); ");
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");        
				log("Using - ActiveXObject(Microsoft.XMLHTTP); ");
			}
			catch (e)
			{   
				try
				{    
					log("xmlHttp=new XMLHttpRequest();  called");
					// Firefox, Opera 8.0+, Safari    
					 xmlHttp=new XMLHttpRequest();  			 
					log("Using - XMLHttpRequest javascript object; ");
				}
				catch (e)
				{   
					log("Your browser does not support AJAX!");        
					return false;  
				}
			}      
		}  



		if(xmlHttp)
		{
			log("if(xmlHttp) OK");
			//Event handler - triggered by xmlHttp.open("GET",sRSSFeedURL,true); below
			xmlHttp.onreadystatechange=ajaxCallBack;
		}//if
		log("ajax_Initialize finished ==============================================");

	}
	//------------------------------------------------------------------------------------
	function ajaxCallBack()
	{
		//alert('ajaxCallBack called');
		try
		{    
			
			//Check the state of the event for more detailed info
			//The readyState property holds the status of the server's response.
			//Each time the readyState changes, the onreadystatechange function will be executed.
			//http://www.w3schools.com/ajax/ajax_xmlhttprequest.asp
			//Here are the possible values for the readyState propery:
			//State	Description
			//0	The request is not initialized
			//1	The request has been set up
			//2	The request has been sent
			//3	The request is in process
			//4	The request is complete

			log("ajaxCallBack called - xmlHttp.readyState:" + xmlHttp.readyState);
			if(xmlHttp.readyState==4)
			{
				log("ajaxCallBack called - xmlHttp.status:" + xmlHttp.status);
				//if request was successful 
				if (xmlHttp.status==200)
				{ 
					log("ajaxCallBack called - xmlHttp.status==200:");
				
					//Ajax call was ok and some response returned
					//parse the XML into our 4 arrays for description/link/headline and id
					//alert(xmlHttp.responseText);
					//document.myForm.time.value=xmlHttp.responseText;
		
					xmlstring = xmlHttp.responseText;
					// convert string to XML object
					//var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml");
					loadXML();
					//alert(xmlDoc);
					// get a reference to the root-element "rss"
					log("onreadystatechange - parsing XML into DOM");
					var root = xmlDoc.getElementsByTagName('rss')[0];
					if(root)
					{
						// get reference to "channel" element
						var channels = root.getElementsByTagName("channel");
						if(channels)
						{
							//========================= items 
							// now get all "item" tags in the channel
							var items = channels[0].getElementsByTagName("item");
							
							//Add newsitems from the start of the array
							arrayNews_descriptionCount=0;
							for (i=0;i<items.length;i++)
							{
								//document.write(mycars[x] + "<br />")
								//alert(i);
								//Find the <link>,<description> and <title> elements
								//These are retrieved using collection the finding the first element
								//title is mandatory to display news item but link and description aren't
								var titles = items[i].getElementsByTagName("title");
								if (titles)
								{
									var link_element = "";
									var description_element = "";
									var title_element =  "";
									//<title> may exist but may be blank <title></title> so firstChild might not exist
									if(titles[0].firstChild)
									{
										title_element = titles[0].firstChild.nodeValue;	
									}
									//------------- <guid - id in table> ----------------------------------
									var guids = items[i].getElementsByTagName("guid");
									if (guids)
									{		
										//link may exist but may be blank <guid></guid> so firstChild might not exist
										if(guids[0].firstChild)
										{
											guid_element = guids[0].firstChild.nodeValue;	
										}
									}
									
									//------------- <link> ----------------------------------
									var links = items[i].getElementsByTagName("link");
									if (links)
									{		
										//link may exist but may be blank <link></link> so firstChild might not exist
										if(links[0].firstChild)
										{
											link_element = links[0].firstChild.nodeValue;	
										}
									}
									
									//------------- <description> ----------------------------------
									var descriptions = items[i].getElementsByTagName("description");																	
									// in the "item" we have a description, so get that
									if (descriptions)
									{
										//description may exist but may be blank <description></description> so firstChild might not exist
										if(descriptions[0].firstChild)
										{
											description_element = descriptions[0].firstChild.nodeValue;	
										}
									}
	
									//Store the description as an array
									if(title_element !== "")
									{
										log("title from rss:" + title_element);
										arrayNews_description[arrayNews_descriptionCount] = description_element;
										arrayNews_link[arrayNews_descriptionCount] = link_element;
										arrayNews_title[arrayNews_descriptionCount] = title_element;
										arrayNews_guid_id[arrayNews_descriptionCount] = guid_element;										
										arrayNews_descriptionCount++;
									}
									else
									{
										//log("Skipping news item, <title> element blank")
									}
									
									//-------------------unused yet---------------------------------------------------			
									// we also get the "pubDate" element in the "item"
									var date = items[i].getElementsByTagName("pubDate");				
									// same for the pubDate
									var update = date[0].firstChild.nodeValue;								
									
									//alert(tooltipstring);	
								}
								else
								{
									// root element <rss> not found so rss feed not valid
									updateTickerWithMessage("Error Retrieving News.");	
									//log("Error Retrieving News, <title> element missing")
								}//channels
							}//for
						}
						else
						{
							// root element <rss> not found so rss feed not valid
							updateTickerWithMessage("Error Retrieving News.");	
							//log("Error Retrieve News, channels element missing")
						}//channels
						
					}
					else
					{
						// root element <rss> not found so rss feed not valid
						updateTickerWithMessage("Error Retrieving News.");
						//log("Error Retrieving  News, root <rss> element missing")						
					}
					log("onreadystatechange - parsing XML into DOM completed");

				}
				else
				{
					//xmlHttp.status != 200
					log("ajax_RetrieveNews - readyState == 4 but xmlHttp.status:" + xmlHttp.status);
					updateTickerWithMessage("Cannot Retrieve News, retrying...");
				}//if (xmlHttp.status==200)
				
				//only trirgger retireve news after the Ajax call reached stage 4 - even if it fails
				log("ajax_RetrieveNews - reset timer - window.setTimeout");
				// we shouldnt retrieve the news again till at least all the current news items have been displayed
				//this will prevent unnecessary AJAX calls
				// so we calculate the number of seconds before retrieveing the news again as follows
				// number of news items * length of time it takes to animate one line
				//so if it takes 4 secs to display one item and there are 10 items 
				//then dont call ajax until 40 seconds from now 
				//I subtract 5 seconds (5 * 1000 millisecs) so the RSS is called just before the next iteration 
				//NOTE this is not exact as the timer for the animation can be cancelled  if animation is still in progress
				iRetrieveNewsInterval = arrayNews_description.length * iAnimateTickerInterval - 5000;
				log("window.setTimeout('ajax_RetrieveNews() calling in " + iRetrieveNewsInterval/1000 + "secs. arrayNews_description.length(" + arrayNews_description.length + "). iAnimateTickerInterval(" + iAnimateTickerInterval + ")");
				window.setTimeout('ajax_RetrieveNews()', iRetrieveNewsInterval);
			}//if - // state == 4
		}
		catch (err)
		{   
			log("ERROR - " + err.description);
		}
	}//ajaxCallBack()
	//---------------------------------------------------------------------------------------------------------
	//Calls the actual RSS feed
	function ajax_RetrieveNews()
	{  
		try
		{
			log("ajax_RetrieveNews called");
			//first time this page is run creat the AJAX request object
//			if(!xmlHttp){
			xmlHttp = null;
				ajax_Initialize();
//			}
			log("xmlHttp exists");
			if(xmlHttp)
			{
				
				log("xmlHttp.open/send:xmlHttp.readyState:" + xmlHttp.readyState);
				//alert(xmlHttp.onreadystatechange);
				//xmlHttp.onreadystatechange=ajaxCallBack;
				xmlHttp.open("GET",sRSSFeedURL,true);
				
				xmlHttp.send();  
				log("xmlHttp.send(null) RETURNED");
			}
		}
		catch(errorAjax)
		{
			log("AJAX ERROR ==================================" );
			log("AJAX ERROR: " + errorAjax.message);
			log("AJAX ERROR ==================================" );
		}
	}//function
	//------------------------------------------------------------------------------------
	//Takes the XML retrieved from the RSS feed and creates a XML DOM object from it
	//cross-browser javascript xml parser - w3schools.com
	function loadXML()
	{
		log("loadXML called");
		//load xml file
		// code for IE
		//simple reference http://www.adp-gmbh.ch/web/js/msxmldom/methods_properties.html
		if (window.ActiveXObject)
		{
			var doc1=new ActiveXObject("Microsoft.XMLDOM");
			doc1.async="false";
			doc1.loadXML(xmlstring);
			xmlDoc=doc1;//.documentElement;
		}
		// code for Mozilla, Firefox, Opera, etc.
		else if (document.implementation && document.implementation.createDocument)
		{
  			var parser=new DOMParser();
  			var doc2=parser.parseFromString(xmlstring,"text/xml");
			xmlDoc=doc2;//.documentElement;
		}
		else
		{
			alert('Your browser cannot handle this script');
		}
		log("loadXML finished");
	}
	//----------- DEBUGGING --------------------------------------------------------
	function log(sText)
	{
		//to use the logger you need to add a text box for the output anywhere on you html
		/*
		  <form id="formDebug" name="formDebug" method="post" action="">
			  <label>
				<textarea name="txtDebug" rows="10" cols="120"></textarea>
			  </label>
		  </form>	
		*/
		var today=new Date();
		var h=today.getHours();
		var m=today.getMinutes();
		var s=today.getSeconds();
		if(document.formDebug){
			if(document.formDebug.txtDebug){
				if(document.formDebug.txtNumChars){
					var sLength = document.formDebug.txtDebug.value
					var iLength = sLength.length;
					//alert(iLength);
					if(iLength >10000)
					{
						resetform();
						iLength = 0;
					}
					document.formDebug.txtNumChars.value = iLength;
				}
				document.formDebug.txtDebug.value = h + ':' + m + ':' + s + ':' + sText  + "\n" + document.formDebug.txtDebug.value ;
			}
		}
	}
	//put in onload to clear debug textarea
	function resetform()
	{
		if(document.formDebug){
			if(document.formDebug.txtDebug){
				document.formDebug.txtDebug.value="";				
			}
			if(document.formDebug.txtNumChars){
				document.formDebug.txtNumChars.value = "";
			}
		}
			
	}

	//-------------------------------------------------------------------------------------
	//Cross browser script for getElementById
	function getObject(elementId) { if (document.getElementById) { return document.getElementById(elementId); } else if (document.all) { return document.all[elementId]; } else if (document.layers) { return document.layers[elementId]; } }
