/*
 ======================================================================
 RSS JavaScript Ticker object
 Original Author: George at JavaScriptKit.com/ DynamicDrive.com
 Modified for MorganHillWeather.com by Rainman
 Version: 36   Date: July 5th 2010
 ======================================================================
*/

function createAjaxObj(){
	var httprequest=false
	if (window.XMLHttpRequest){ // if Mozilla, Safari etc
		httprequest=new XMLHttpRequest()
		if (httprequest.overrideMimeType)
			httprequest.overrideMimeType('text/xml')
	}
	else if (window.ActiveXObject){ // if IE
		try {
			httprequest=new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e){
			try{
				httprequest=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	}
	return httprequest
}

// ----------------------------------------------------------------------------------------
// Main RSS Ticker Object function
// rss_ticker(RSS_id, cachetime, divId, divClass, delay, mode, label, age, optionalswitch)
// ----------------------------------------------------------------------------------------

function rss_ticker(RSS_id, cachetime, divId, divClass, delay, mode, label, age, optionalswitch){
	this.RSS_id=RSS_id 		// Array key indicating which RSS feed to display
	this.cachetime=cachetime 	// Time to cache feed, in minutes. 0=no cache.
	this.tickerid=divId 		// ID of ticker div to display information
	this.tickerclass=divClass	// Class of ticker div
	this.delay=delay 		// Delay between msg change, in miliseconds.
	this.mode=mode 			// "scroll" if scrolling ticker mode required
	this.label=label 		// text description of feed e.g. BBC News...
	this.age=age			// age limit for feed items in days
	this.logicswitch=(typeof optionalswitch!="undefined")? optionalswitch : -1
	this.mouseoverBol=0 //Boolean to indicate whether mouse is currently over ticker (and pause it if it is)
	this.pointer=0
	this.validfeed=false		// v28: set to true if valid feed data found
	this.ajaxobj=createAjaxObj()

//	document.write('<div id="'+divId+'" class="'+divClass+'" style="overflow:hidden; width:760px"'+'>Initializing ticker...</div>')
	if( mode != "scroll") {
		document.write('<div id="'+divId+'" class="'+divClass+'" style="overflow:hidden"'+'>Initializing ticker...</div>')
	}

	this.getAjaxcontent()
}

// -------------------------------------------------------------------
// getAjaxcontent()- Makes asynchronous GET request to "rssfetch.php" with the supplied parameters
// -------------------------------------------------------------------

rss_ticker.prototype.getAjaxcontent=function(){
	if (this.ajaxobj){
		var instanceOfTicker=this
		var parameters="id="+encodeURIComponent(this.RSS_id)+"&cachetime="+this.cachetime+"&bustcache="+parseInt(new Date().getTime() / 1000)  // v17: tweak cache bust
		this.ajaxobj.onreadystatechange=function(){instanceOfTicker.initialize()}
		this.ajaxobj.open('GET', "rssfetch.php?"+parameters, true)
		this.ajaxobj.send(null)
	}
}

// -------------------------------------------------------------------
// initialize()- Initialize ticker method.
// -Gets contents of RSS content and parse it using JavaScript DOM methods 
// -------------------------------------------------------------------

rss_ticker.prototype.initialize=function(){ 
	if (this.ajaxobj.readyState == 4){ //if request of file completed
		if (this.ajaxobj.status==200){ //if request was successful
			var xmldata=this.ajaxobj.responseXML
			var instanceOfTicker=this

			if(xmldata){

				if(xmldata.getElementsByTagName("item").length==0){ //if no <item> elements found in returned content
					this.validfeed=false
				}
				else {  //v21: only attempt to parse data if RSS feed available
					this.validfeed=true
					this.feeditems=xmldata.getElementsByTagName("item")

					//Cycle through RSS XML object and store each peice of the item element as an attribute of the element
					for (var i=0; i<this.feeditems.length; i++){
						if ( (this.feeditems[i].getElementsByTagName("title")) && (this.feeditems[i].getElementsByTagName("title").length) ) {
							if (this.feeditems[i].getElementsByTagName("title")[0].firstChild){
							this.feeditems[i].setAttribute("ctitle", this.feeditems[i].getElementsByTagName("title")[0].firstChild.nodeValue)
							}
						}
						if ( (this.feeditems[i].getElementsByTagName("link")) && (this.feeditems[i].getElementsByTagName("link").length) ) {
							if (this.feeditems[i].getElementsByTagName("link")[0].firstChild){
							this.feeditems[i].setAttribute("clink", this.feeditems[i].getElementsByTagName("link")[0].firstChild.nodeValue)
							}
						}
						if ( (this.feeditems[i].getElementsByTagName("description")) && (this.feeditems[i].getElementsByTagName("description").length) ) {
							if (this.feeditems[i].getElementsByTagName("description")[0].firstChild){
							this.feeditems[i].setAttribute("cdescription", this.feeditems[i].getElementsByTagName("description")[0].firstChild.nodeValue)
							}
						}
						if ( (this.feeditems[i].getElementsByTagName("pubDate")) && (this.feeditems[i].getElementsByTagName("pubDate").length) ) { // added in v7 & v11
							this.feeditems[i].setAttribute("cpubdate", this.feeditems[i].getElementsByTagName("pubDate")[0].firstChild.nodeValue)
						}
					}


					var filter = new RegExp("Morgan Hill")
					for (var i=0; i<this.feeditems.length; i++){
					//	if(filter.test(this.feeditems[i].getAttribute("ctitle")) || filter.test(this.feeditems[i].getAttribute("cdescription"))) {
					//		this.feeditems[i].setAttribute("ctitle", '<font color="#FF0000">'+this.feeditems[i].getAttribute("ctitle")+'</font>')
					//	}
			
						// Special handling for National Weather Service (NWS) feed
						// Different for scrolling ticker (mode="scroll") versus rotating message box
						// v24: changes to accommodate NWS feed as a ticker... NEEDS TIDYING UP with CSS!

						if( (this.RSS_id == "NWS") && (this.mode != "scroll") ) {
							var pattern  =  new RegExp("no active watches")
							var nwsTitle =  this.feeditems[i].getAttribute("ctitle")

							if(pattern.test(nwsTitle)) { // if we have NWS alert feed message we want then change it

								// v22: redundant... made this message hidden so only a red alert gets displayed
								nwsTitle = '<font color="#00CC00">There are no active watches, warnings or advisories</font>'

								// v23: Make "no active watches" message disappear if alert state changes on-the-fly
								document.getElementById(this.tickerid).style.visibility="hidden"
							}
							else { // fix truncated San Jose if found and change to alert color bold(v25) RED
							 
								nwsTitle = '<font color="#FF0000"><b>'+nwsTitle.replace(/San \x28California\x29/, 'San Jose')+'</b></font>'
								nwsTitle = nwsTitle.replace(/ - /, '<br />')

								// v22: Make weather alert message appear by changing visibility state
								document.getElementById(this.tickerid).style.visibility="visible"
							}

							this.feeditems[i].setAttribute("ctitle", '<center>'+nwsTitle+'</center>')
						}

						// v31: include both NWS and NWS-BRW in this statement
						if( ((this.RSS_id == "NWS") || (this.RSS_id == "NWS-BRW")) && (this.mode == "scroll") ) {
							var pattern  =  new RegExp("no active watches")
							var nwsTitle =  this.feeditems[i].getAttribute("ctitle")
							var nwsDesc  =  this.feeditems[i].getAttribute("cdescription")
							var tmpDesc  =  new Array()
	
							if(pattern.test(nwsTitle)) { // if we have NWS alert feed message we want then change it

								// Replace title with custom message for no active alerts
								// nwsTitle = 'There are no active watches, warnings or advisories'

								// v27: Kill the display of this scrolling ticker if no alert messages
								nextTicker()
								return
							}
							else { 
								// fix truncated "San Jose" if found in NWS message only
								if( this.RSS_id == "NWS"  ) nwsTitle = nwsTitle.replace(/San \x28California\x29/, 'San Jose')

								// v26:	Split description at timestamp to remove non-informative preamble
								var d = new Date()
								var year = d.getUTCFullYear()

								nwsDesc=nwsDesc.replace(/<br>/gi, " ")
								// tmpDesc=nwsDesc.split(/(\d{3,4} (AM)|(PM) (PDT)|(PST))/)   // matching eg. "209 AM PDT MON OCT 12 2009"
								tmpDesc=nwsDesc.split(year)

								// v31: only use split message if we found the year... sometimes not there at all!
								if( tmpDesc[1] ) this.feeditems[i].setAttribute("cdescription", tmpDesc[1])					
							}

							this.feeditems[i].setAttribute("ctitle", nwsTitle)
						}

						// Special handling to fix "County County" string annoyance in CDF titles
						if( this.RSS_id == "CDF") {
							var nwsTitle =  this.feeditems[i].getAttribute("ctitle")

							nwsTitle = nwsTitle.replace(/ County County\x29 /, ' County\x29<br />')
					
							this.feeditems[i].setAttribute("ctitle", nwsTitle)
						}
					}
				}

			} else this.validfeed=false

			document.getElementById(this.tickerid).onmouseover=function(){instanceOfTicker.mouseoverBol=1}
			document.getElementById(this.tickerid).onmouseout=function(){instanceOfTicker.mouseoverBol=0}

			this.startTime = new Date().getTime()	// v18: init a start time for each ticker instance	

			if( this.mode=="scroll" ) {
				this.scrollmsg()
			}
			else {
				this.rotatemsg()
			}
		}
	}
}

// -------------------------------------------------------------------
// rotatemsg()- Rotate through RSS messages and display them
// -------------------------------------------------------------------

rss_ticker.prototype.rotatemsg=function(){
	var instanceOfTicker=this
	var tickerDiv=document.getElementById(this.tickerid)

	if (this.mouseoverBol==1) { //if mouse is currently over ticker, do nothing (pause it)
		setTimeout(function(){instanceOfTicker.rotatemsg()}, 100)
	}
	else {
		var todaysDate = new Date()
		var newsDate   = new Date()

		if( this.validfeed ) {
			// if there was a pub date for the item then use it else use todays as default
			if ( this.feeditems[this.pointer].getAttribute("cpubdate") ) {
				newsDate = Date.parse( this.feeditems[this.pointer].getAttribute("cpubdate") )
			}

			// if news item is less than this.age days old then display it
			// intended to filter out CDF incidents from long ago
			if ( Math.round( (todaysDate - newsDate) / 86400000 ) < this.age ) {


				var tickercontent='<a href="'+this.feeditems[this.pointer].getAttribute("clink")+'" target="_blank">'+this.feeditems[this.pointer].getAttribute("ctitle")+'</a>'

				tickercontent=tickercontent.replace(/<br>/gi, " ")		// v34: filter title... replace line break with space
				tickercontent=tickercontent.replace(/(<br([^>]+)>)/gi, " ")	// v34: filter title... remove all line breaks

				if (this.logicswitch=="showdescription") {
					var tickerdesc=this.feeditems[this.pointer].getAttribute("cdescription")
					if (tickerdesc) {
						tickerdesc=tickerdesc.replace(/<br>/gi, " ")		// v33: replace line break with space
						tickerdesc=tickerdesc.replace(/(<br([^>]+)>)/gi, " ")	// v33: replace line break with space
						tickerdesc=tickerdesc.replace(/<p>/gi, "")		// v14: remove leading para tag
						tickerdesc=tickerdesc.replace(/<\/p>/gi, "")		// v14: remove trailing para tag
						tickerdesc=tickerdesc.replace(/(<img([^>]+)>)/gi, "")	// v14: remove all img tags
						tickerdesc=tickerdesc.replace(/\n/gi, "")		// v15: remove all \n line feeds
						tickerdesc=tickerdesc.replace(/(<img)/gi, "")		// v15: remove all stray img... tags

						tickercontent+="<br />"+tickerdesc
					}
				}
		
				// my hack to highlight Morgan Hill reference in title or description
				tickercontent=tickercontent.replace(/Morgan Hill/g, '<font color="#FFFFFF">Morgan Hill</font>')

				tickerDiv.innerHTML=tickercontent

				this.pointer=(this.pointer<this.feeditems.length-1)? this.pointer+1 : 0
			}
			else {
				// skip to next feed item
				this.pointer=(this.pointer<this.feeditems.length-1)? this.pointer+1 : 0
			}
		}
		else tickerDiv.innerHTML="RSS news feed not available"

		// v18: attempt to refresh ticker content after cache time has expired, sync with beginning of item list
		if( (this.startTime + (this.cachetime * 60000) >  (new Date().getTime())) || (this.pointer != 0) ) {
			setTimeout(function(){instanceOfTicker.rotatemsg()}, this.delay) //update container every "delay" number of seconds
		}
		else {  // try to get new content from server
			this.getAjaxcontent()
		}
	}
}

// -------------------------------------------------------------------
// scrollmsg()- Scroll all RSS messages
// 
// Scrolling Ticker Support
// Origins from WebTicker by Mioplanet http://www.mioplanet.com/rsc/newsticker_javascript.htm
// 
// -------------------------------------------------------------------

rss_ticker.prototype.scrollmsg=function(){
	var instanceOfTicker=this
	var tickerDiv=document.getElementById(this.tickerid)

	TICKER_WIDTH = tickerDiv.style.width
	TICKER_SPEED = 1
	TICKER_STYLE = "font-family:Verdana; font-size:12px; color:#999999"

	var tickerSupported = false
	var tickerItems = 0     //v28: if zero after building ticker, do a nextTicker() call as there's nothing to read e.g. all feed items might be aged
	var img = "<img src=images/ticker_space.gif width="+TICKER_WIDTH+" height=0>"
	var pad = '<span onclick="nextTicker();">'+" « « « « « « « « "+'</span>' //v20:add onlick() event handler
	var clickMsg = '<span onclick="nextTicker();">'+" « « « « [click here to change ticker] « « « « "+'</span>' //v20:add onclick() event handler
	var fulltickermsg='<b>'+this.label+'</b>'+clickMsg

	if ( this.validfeed ) { //v21: Only populate ticker content if valid feed items
		while( this.pointer<this.feeditems.length) {
			// Build content string

			var todaysDate = new Date()
			var newsDate   = new Date()

			// if there was a pub date for the item then use it else use todays as default
			if ( this.feeditems[this.pointer].getAttribute("cpubdate") ) {
				newsDate = Date.parse( this.feeditems[this.pointer].getAttribute("cpubdate") )
			}

			// if news item is less than this.age days old then include it
			if ( Math.round( (todaysDate - newsDate) / 86400000 ) < this.age ) {

				var tickercontent='<a href="'+this.feeditems[this.pointer].getAttribute("clink")+'" target="_blank">'+this.feeditems[this.pointer].getAttribute("ctitle")+'</a>'

				tickercontent=tickercontent.replace(/<br>/gi, " ")		// v33: filter title... replace line break with space
				tickercontent=tickercontent.replace(/(<br([^>]+)>)/gi, " ")	// v33: filter title... remove all line breaks

				if (this.logicswitch=="showdescription") {
					var tickerdesc=this.feeditems[this.pointer].getAttribute("cdescription")
					if (tickerdesc) {
						tickerdesc=tickerdesc.replace(/<br>/gi, " ")		// v33: replace line break with space
						tickerdesc=tickerdesc.replace(/(<br([^>]+)>)/gi, " ")	// v33: replace line break with space
						tickerdesc=tickerdesc.replace(/<p>/gi, "")		// v14: remove leading para tag
						tickerdesc=tickerdesc.replace(/<\/p>/gi, "")		// v14: remove trailing para tag
						tickerdesc=tickerdesc.replace(/(<img([^>]+)>)/gi, "")	// v14: remove all full img tags
						tickerdesc=tickerdesc.replace(/\n/gi, "")		// v15: remove all \n line feeds
						tickerdesc=tickerdesc.replace(/(<img)/gi, "")		// v15: remove all stray img... tags

						tickercontent=tickercontent+'&nbsp;'+tickerdesc
					}
				}
		
				// my hack to highlight Morgan Hill reference in title or description
				tickercontent=tickercontent.replace(/Morgan Hill/g, '<font color="#FFFFFF">Morgan Hill</font>')

				fulltickermsg=fulltickermsg+tickercontent+pad

				tickerItems++
			}

			this.pointer += 1
		}

		if ( tickerItems == 0 ) { //v28: If no items within age range, skip to next ticker
			nextTicker()
			return
		}
	}
	else fulltickermsg=fulltickermsg+"RSS news feed not available"+pad  //v21: if no valid feed, set "unavailable" msg

	// Firefox
	if (navigator.userAgent.indexOf("Firefox")!=-1 || navigator.userAgent.indexOf("Safari")!=-1) {
		tickerDiv.innerHTML = "<TABLE  cellspacing='0' cellpadding='0' width='100%'><TR><TD nowrap='nowrap'>"+img+"<SPAN style='"+TICKER_STYLE+"' ID='TICKER_BODY' width='100%'>&nbsp;</SPAN>"+img+"</TD></TR></TABLE>"
		tickerSupported = true
	}
	// IE
	if (navigator.userAgent.indexOf("MSIE")!=-1 && navigator.userAgent.indexOf("Opera")==-1) {
		tickerDiv.innerHTML = "<DIV nowrap='nowrap' style='width:100%;'>"+img+"<SPAN style='"+TICKER_STYLE+"' ID='TICKER_BODY' width='100%'></SPAN>"+img+"</DIV>"
		tickerSupported = true
	}
	if(!tickerSupported) {
		tickerDiv.outerHTML = ""
	}
	else {
		tickerDiv.scrollLeft = 0
		document.getElementById("TICKER_BODY").innerHTML = fulltickermsg
		tickerDiv.style.display="block"

		TICKER_ALIVE = true // V15: added ticker kill switch to allow new ticker selection
				    //      required to prevent multiple timers running and scroll speed-up
				    //  NB. Not instance-aware so only one ticker can be active on a page
		this.ticker_tick()
	}
}


rss_ticker.prototype.ticker_tick=function(){
	var instanceOfTicker=this
	var tickerDiv=document.getElementById(this.tickerid)

	if(!this.mouseoverBol) tickerDiv.scrollLeft += TICKER_SPEED

	if(tickerDiv.scrollLeft >= tickerDiv.scrollWidth - tickerDiv.offsetWidth) {
		// was... tickerDiv.scrollLeft = 0
		// v32: if the ticker has run it's course once then switch to next ticker instead or replaying
		TICKER_ALIVE = false
		nextTicker()
	}
	else {
		// v18: attempt to refresh ticker content after cache time has expired, sync with beginning of item list
		if( (this.startTime + (this.cachetime * 60000) >  (new Date().getTime())) || (tickerDiv.scrollLeft != 0) ) {
			if(TICKER_ALIVE) setTimeout(function(){instanceOfTicker.ticker_tick()}, 15)
		}
		else {  // try to get new content from server
			TICKER_ALIVE = false
			this.pointer=0
			this.getAjaxcontent()
		}
	}

}