/********************************************************************************
*																				*
*																				*
*		FeedMe  - Your News Buddy (tm)											*
*																				*	
*		feedme.js 																*
*																				*
*		Author: Roger Kenny														*
*																				*
*		This file is copyrighted software.										*
*																				*
*		No part may me duplicated, modified, or redistributed in any way		*
*		without express writted permission by the copyright holder.				*
*																				*
*		Copyright (c) 2007 Roger Kenny, Ripped Productions						*
*		All Rights Reserved														*
*																				*
*																				*
*																				*
*********************************************************************************/

var APPNAME = "iTrain";
var PRESCRIPT = "";
var VERSION = "Beta.6";

var CREATOR = "Roger Kenny";
var LICENSE = "Licensed by Ripped Productions";
var COPYRIGHT = "Copyright &copy; 2007 Roger Kenny, Ripped Productions. All rights reserved";

var feedtip = "Click a feed's icon to navigate or delete.<br/>Click a headline to connect to the story";

var openclosesteps = 4;
var openclosebyx = 24/openclosesteps;
var animmills = 60; //default animation milliseconds
var debugdiv;
var currentopenpanel;

var currentscreenwidth = 320;
var safezoneright = currentscreenwidth + 100;
var safezoneleft = -200;

var tickers = [];
var generictickers = [];

var displayads = [

{ name: 'Advertise on iTrain', link: 'http://www.rogerkenny.com/itrain/ads/', color: '#888888' },
{ name: 'Fingers Need Some Action? Try BATTLEFLEET Now!', link: 'http://www.iphonebattlefleet.com', color: '#aaaaaa' },
{ name: 'From the creator of iTrain  comes, Feedme: Your News Buddy', link: 'http://www.itrainnyc.com', color: '#888888' },
{ name: 'ARTISTS! POETS! SOUNDSMITHS! MINDS! It\'s the Buffalo Readings!', link: 'http://www.buffaloreadings.com', color: '#888888' },
{ name: 'Life got you down? Don\'t Kill Yourself Yet... Have you tried Bandito?', link: 'http://www.thebandito.com', color: '#888888' }

];

function loadCookieTickers() {
	
	//Train Tickers
	var count = 0;
	var lastcount = (readCookie('lasttrainfeed')!=null) ?  parseInt(readCookie('lasttrainfeed')) : 8;
	while ( count < lastcount) {
	
		if (readCookie('tickers['+count+']')!=null) {

			var toadd = readCookie('tickers['+count+']');
			eraseCookie('tickers['+count+']');
			addTicker( toadd );
		}
				count++;
	}	
	
	//Generic Tickers
	count = 0;
	lastcount = (readCookie('lastgenericfeed')!=null) ?  parseInt(readCookie('lastgenericfeed')) : 8;
	while ( count < lastcount) {
	
		if (readCookie('generictickers['+count+']url')!=null) {

			var toaddurl = readCookie('generictickers['+count+']url');
			var toaddlogo = readCookie('generictickers['+count+']logo');
			var toaddcolor = readCookie('generictickers['+count+']color');
			eraseCookie('generictickers['+count+']url');
			eraseCookie('generictickers['+count+']logo');
			eraseCookie('generictickers['+count+']color');
			addGeneric( toaddurl, toaddlogo,  toaddcolor );
		}
				count++;
	}
	
	//lirrticker = new Ticker( 'l', tickers.length);
	//addGeneric('getcacherss.php?id=CNN&cachetime=60', 'images/1line.png');
}

function loadCookieTickersOLD() {

	
	//Generic Tickers
	var count = 0;
	var lastcount = (readCookie('lasttrainfeedmefeed')!=null) ?  parseInt(readCookie('lasttrainfeedmefeed')) : 8;
	while ( count < lastcount) {
	
		if (readCookie('tickers['+count+']url')!=null) {

			var toaddurl = readCookie('tickers['+count+']url');
			var toaddlogo = readCookie('tickers['+count+']logo');
			var toaddname = readCookie('tickers['+count+']feedname');
			var toaddcategory = readCookie('tickers['+count+']category');
			var toaddcolor = readCookie('tickers['+count+']color');
			eraseCookie('tickers['+count+']url'); 
			eraseCookie('tickers['+count+']logo');
			eraseCookie('tickers['+count+']feedname');
			eraseCookie('tickers['+count+']category');
			eraseCookie('tickers['+count+']color');
			addGeneric( toaddurl, toaddlogo, toaddname, toaddcategory, toaddcolor );
		}
				count++;
	}
	
	//lirrticker = new Ticker( 'l', tickers.length);
	//addGeneric('getcacherss.php?id=CNN&cachetime=60', 'images/1line.png');
}

function Initialize () { ///alert('gothere');
	//document.getElementById('backdropdiv').style.backgroundImage = 'url("images/back0'+Math.floor(Math.random()*37)+'.jpg")';
	//document.getElementById('version').innerHTML = "v."+VERSION;
	var backimg = document.createElement('img');
	backimg.setAttribute('src', "images/back0"+Math.floor(Math.random()*37)+".jpg");
	backimg.setAttribute('style', 'position:absolute;top:53px;left:0px; width:100%;');
	document.getElementById('backdropdiv').appendChild(backimg);
	debugdiv = document.getElementById('debug');
	setTimeout(function(){window.scrollTo(0, 1);}, 100);
	updateScreenWidth();
	initializeDialogBoxes();
	//loadBrowser();
	fillFooter();
	document.getElementById('feedtipdiv').innerHTML = 'Hello. Please Select from the above options.';
	loadCookieTickers();

	
}

function fillFooter () {
	var info = "<a href='http://www.rogerkenny.com'>"+APPNAME +" version: "+ VERSION + "<br/>"+ COPYRIGHT+"</a>";
	document.getElementById('footinfo').innerHTML = ''+info;
}

var lineselector;
var mapviewer;
var hopstop;
var greeting;
var readroom;

function initializeDialogBoxes() {
	lineselector = new DialogBox(  'alerts', 380, 'alertsbutton' ,'alertsclosebutton', 'alertbullet');
	lineselector.initialize();
	mapviewer = new DialogBox(  'mapviewer', 369, 'mapbutton' ,'mapclosebutton', 'mapsbullet' );
	mapviewer.initialize();	
	hopstop = new DialogBox(  'hopstop', 180, 'directionsbutton' ,'directionsclosebutton', 'directionsbullet' );
	hopstop.initialize();	
	readroom = new DialogBox(  'readroom', 380, 'readbutton' ,'readclosebutton', 'readbullet' );
	readroom.initialize();	

}


function Debugalert ( message ) {
	debugdiv.innerHTML = ''+message;
}
/**************** Dialog Box Object Declaration ****************/
function openPanel ( who ) {
	//if (who.percentopen == 0) { who.openclosex = -24; }
	if (who.openclosex < 0) {
		if ( who.ismoving == false ){ who.ismoving = true; }
		who.openclosex += openclosebyx;
		who.percentopen = openCloseF( who.openclosex );
		var nexttop = 0 - (who.height - ( who.height * who.percentopen/100 ));
		who.div.style.top = Math.floor(nexttop)+"px";
		who.movetimer = setTimeout ( function() { openPanel( who ); }, animmills );
	} else {
		who.showCloseDiv();
		clearTimeout(who.movetimer);
		if ( who.ismoving == true ){ who.ismoving = false; }
		who.openclosex = 0;
		who.percentopen = 100;
	}
}

function closePanel ( who ) {
	//if (who.percentopen == 100) { who.openclosex = 0; }
	if (who.openclosex <= 24) {
		if ( who.ismoving == false ){ who.ismoving = true; }
		who.openclosex += openclosebyx;
		who.percentopen = openCloseF( who.openclosex );
		who.movetimer = setTimeout ( function() { closePanel( who ); }, animmills );
		var nexttop = 0 - (who.height-( who.height*who.percentopen/100));
		who.div.style.top = Math.floor(nexttop)+"px";
	} else {
		who.hideCloseDiv();
		clearTimeout(who.movetimer);
		if ( who.ismoving == true ){ who.ismoving = false; }
		who.openclosex = -24;
		who.percentopen = 0;
	}
}

function showGreeting() {
	//greeting.open(); 
}

function closeMe () {
	closePanel(this);
	//this.bullet.setAttribute('class', 'shown');
	currentopenpanel = null;

}

function openMe () {
	if (currentopenpanel!=null) { currentopenpanel.close(); }
	openPanel(this);
	currentopenpanel = this;
	//this.bullet.setAttribute('class', 'shown');

}

function showCloseDiv () {
	this.closediv.setAttribute('class', 'shown');	
}

function hideCloseDiv () {
	this.closediv.setAttribute('class', 'hidden');	

}

function openCloseF( x ) {
	//return (Math.cos(x/7.6)*50)+50;
	return (-0.1736111*(x*x))+100;
}

function initializeDialog () {
	//this.opendiv.onclick = this.open;
	//this.closediv.onclick = this.close;
}

function DialogBox (  divid, height, opendiv, closediv ) {
	this.divid = divid;
	this.div = document.getElementById(divid);
	this.height = height;
	this.opendiv = document.getElementById(opendiv);
	this.closediv = document.getElementById(closediv);
	//this.bullet = document.getElementById(mybullet);
	this.percentopen = 0;
	this.ismoving = false;
	this.currenttop = -1 * this.height;
	this.openclosex = -24; 
	this.movetimer;
	
	//methods
	this.close = closeMe;
	this.open = openMe;
	this.initialize = initializeDialog;
	this.showCloseDiv = showCloseDiv;
	this.hideCloseDiv = hideCloseDiv;
}

/****************** RSS Tickers Code **********************/
// global flag
var isIE = false;
var opentickers = 0;

function addTicker( train ) {
	if (opentickers == 0) { playAllFeeds(); }
	var isalreadyopen = false;
	for (var count=0; count<tickers.length; count++) {
		if (tickers[count].train == train) {
			isalreadyopen = true;
			count = tickers.length+1;
		} else {
		}
	}
	
	if (opentickers < 10 && isalreadyopen == false) {
		tickers[tickers.length] = new Ticker( train, tickers.length );
		tickers[tickers.length-1].initialize();
		document.getElementById('feedtipdiv').innerHTML = feedtip;
		createCookie('tickers['+(tickers.length-1)+']', train, 2048);
		createCookie('lasttrainfeed', tickers.length);
		opentickers++;
	} else if (opentickers >= 10) {
		alert('Maximum Alert Feeds Reached');
	} else {
	
	}
}

function addGeneric( url, logo, color ) {
	if (opentickers == 0) { playAllFeeds(); }
	var isalreadyopen = false;
	for (var count=0; count<generictickers.length; count++) {
		if (generictickers[count].url == url) {
			isalreadyopen = true;
			count = generictickers.length+1;
		} else {
		}
	}
	var name = 'generic';
	var category = 'generic';
	
	if (opentickers < 10 && isalreadyopen == false) {
		generictickers[generictickers.length] = new Ticker( 'generic', generictickers.length );
		generictickers[generictickers.length-1].initializeGeneric( url, logo, name, category, color );
		document.getElementById('feedtipdiv').innerHTML = feedtip; 
		document.getElementById('alertcontrols').style.display = 'block'; 
		createCookie('generictickers['+(generictickers.length-1)+']url', generictickers[generictickers.length-1].url, 2048);
		createCookie('generictickers['+(generictickers.length-1)+']logo', generictickers[generictickers.length-1].logographic, 2048);
		createCookie('generictickers['+(generictickers.length-1)+']color', generictickers[generictickers.length-1].color, 2048);
		createCookie('lastgenericfeed', generictickers.length);
		opentickers++;
		updateScreenWidth();
	} else if (opentickers >= 10) {
		alert('Maximum Alert Feeds Reached');
	} else {
	
	}
}

var feedspaused; 

function pauseAllFeeds () {
	clearTimeout (allfeedrotatetimer);
	//lastdistance = feeddistance;
	//feeddistance = 0;
}

function playAllFeeds () {
	//feeddistance = lastdistance;
	//lastdistance = (readCookie('feeddistance')!=null) ?  parseInt(readCookie('feeddistance')) : 2;
	rotateAllFeeds( );
}

function coverTop() {
	document.getElementById('topcover').setAttribute('class', 'coverdiv');
}

function uncoverTop() {
	document.getElementById('topcover').setAttribute('class', 'hidden');

}

function coverAllFeeds() {
		var count=0;
	while (count<tickers.length) {
		tickers[count].cover();
		count++;
	}
		count=0;
	while (count<generictickers.length) {
		generictickers[count].cover();
		count++;
	}
}

function uncoverAllFeeds() {
		var count=0;
	while (count<tickers.length) {
		tickers[count].uncover();
		count++;
	}
	count=0;
	while (count<generictickers.length) {
		generictickers[count].uncover();
		count++;
	}
}

function deselectAllFeeds() {

	var count=0;
	while (count<tickers.length) {
		tickers[count].deselect();
		count++;
	}
	count=0;
	while (count<generictickers.length) {
		generictickers[count].deselect();
		count++;
	}

}
/****** Ticker Object *****/

function setColor() {
	switch (this.train) {
		case 'b':
		case 'd':
		case 'f':
		case 'v':
			this.color = "#ff8c21";
			break;
		case '1':
		case '2':
		case '3':
			this.color = "#ff0000";
			break;
		case '4':
		case '5':
		case '6':
		case '6express':
			this.color = "#008442";
			break;
		case '7':
			this.color = "#940063";
			break;
		case 'a':
		case 'c':
		case 'e':
		case 's2':
			this.color ="#106ba5";
			break;
		case 'n':
		case 'q':
		case 'r':
		case 'w':
			this.color ="#ffde00";
			break;
		case 'j':
		case 'm':
		case 'z':
			this.color ="#a57300";
			break;
		case 'l':
		case 's':
			this.color ="#9c9c9c";
			break;
		case 'g':
		default:
			this.color ="#00e90e";
	}
	
}

function initializeFeed() {
	this.setColor();
	this.drawFeed();
	this.url += "?id="+this.feedid+"&cachetime=60";
	
	loadXMLDoc( this );
}

function drawFeed() {

	this.holderdiv = document.createElement('div');
	this.holderdiv.setAttribute('class', 'ticker');
	this.holderdiv.setAttribute('style', 'width: '+currentscreenwidth+'px;');
	
	this.feeddiv = document.createElement('div');
	this.feeddiv.setAttribute('class', 'tickerfeed');
	this.holderdiv.appendChild(this.feeddiv);
	
	this.pubdatediv = document.createElement('div');
	this.pubdatediv.setAttribute('class', 'pubdatediv');
	this.holderdiv.appendChild(this.pubdatediv);
	
	this.coverdiv = document.createElement('div');
	this.coverdiv.setAttribute('class', 'hidden');
	this.holderdiv.appendChild(this.coverdiv);
		
	this.logobackdiv = 	this.logodiv = document.createElement('div');
	this.logobackdiv.setAttribute('class', 'tickerlinelogo');
	
	this.logodiv = document.createElement('div');
	//this.logodiv.setAttribute('class', 'tickerlinelogo');
	this.logodiv.setAttribute('style', 'position: absolute; top: 0px; left: 0px; width: 35px; height: 35px;');
	this.logodiv.style.backgroundImage = "url('"+this.logographic+"')";
	var thisfeed = this;
	
	this.logodiv.onmouseover = function () { this.style.cursor='pointer'; };
	this.logodiv.onmouseout = function () { this.style.cursor='auto'; };
	this.logodiv.onclick = function () { selectAFeed( thisfeed )  };/*removeThisFeed( thisfeed )*/

	this.logobackdiv.appendChild(this.logodiv);

	this.holderdiv.appendChild(this.logobackdiv);
	
		this.drawControls();	
	
	var mainfeedsdiv = document.getElementById("alerttickers");
	mainfeedsdiv.appendChild(this.holderdiv);
	this.feeddiv.innerHTML = 'Loading Feed...';
	
		
}

function showFullFeed(who) {
	who.showFullFeed();
}

function showMyFullFeed() {
	this.fullfeedview.innerHTML = '';
	for (var i = 0; i < this.feeditems.length; i++) { //load the display array
		var title = this.feeditems[i].getAttribute('ctitle');
		var link = this.feeditems[i].getAttribute('clink') ;
		this.fullfeedview.innerHTML += "<div ><a href='"+link+"' style='color: "+this.color+";' >"+title+"</a></div>";
		if ((i % 3) == 0 && i > 1 && Math.random() > 0.65) {
			var adpickindex = Math.floor(Math.random()*displayads.length);
			var adpick = displayads[adpickindex];
			this.fullfeedview.innerHTML += "<div ><a href='"+adpick.link+"' style='color: "+adpick.color+";' >"+adpick.name+"</a></div>";
		}
	}
	
	var thisfeed = this;
	this.fullfeedview.setAttribute('class', 'fullfeedview');
	this.xmlbuttondiv.innerHTML = 'hide all';
	this.xmlbuttondiv.onclick = function( ) { 	hideFullFeed(thisfeed); };
}
function hideFullFeed(who) {
		who.hideFullFeed();

}

function hideMyFullFeed() {
	this.fullfeedview.setAttribute('class', 'hidden');
	var thisfeed = this;
	this.xmlbuttondiv.innerHTML = 'show all';
	this.xmlbuttondiv.onclick = function( ) { 	showFullFeed(thisfeed); };
}

function drawFeedControls() {
	var thisfeed = this;
	this.controldiv = document.createElement('div');
	this.controldiv.setAttribute('class', 'fchidden');
	this.controldiv.setAttribute('style', 'width: '+currentscreenwidth+'px;');

	this.buttontab = document.createElement('div');
	this.buttontab.setAttribute('class', 'buttontab');
	
	this.xmlbuttondiv = document.createElement('div');
	this.xmlbuttondiv.setAttribute('class', 'xmlbuttondiv');
	this.xmlbuttondiv.onclick = function() { showFullFeed(thisfeed); };
	this.xmlbuttondiv.onmouseover = function () { this.style.cursor='pointer'; };
	this.xmlbuttondiv.onmouseout = function () { this.style.cursor='auto'; };
	this.buttontab.appendChild(this.xmlbuttondiv);
	this.xmlbuttondiv.innerHTML = "show all";
	
	this.fastforwarddiv = document.createElement('div');
	this.fastforwarddiv.setAttribute('class', 'fastforwarddiv');
	this.fastforwarddiv.onclick = function() { fastForwardFeed( thisfeed, seekdistance/1.5 ) };
	this.fastforwarddiv.onmouseover = function () { this.style.cursor='pointer'; };
	this.fastforwarddiv.onmouseout = function () { this.style.cursor='auto'; };
	this.buttontab.appendChild(this.fastforwarddiv);
	
	this.rewinddiv = document.createElement('div');
	this.rewinddiv.setAttribute('class', 'rewinddiv');
	this.rewinddiv.onclick = function () { rewindFeed( thisfeed, seekdistance/1.5 ) };
	this.rewinddiv.onmouseover = function () { this.style.cursor='pointer'; };
	this.rewinddiv.onmouseout = function () { this.style.cursor='auto'; };
	this.buttontab.appendChild(this.rewinddiv);
	

	
	this.leftbook = document.createElement('div');
	this.leftbook.setAttribute('class', 'leftbook');
	this.buttontab.appendChild(this.leftbook);
	
	this.deletediv = document.createElement('div');
	this.deletediv.setAttribute('class', 'deletediv');
	this.buttontab.appendChild(this.deletediv);
		
		if (this.train == 'generic' ) {
			this.deletediv.onclick = function () { removeThisGenericFeed( thisfeed ) };
		}else {
			this.deletediv.onclick = function () { removeThisFeed( thisfeed ) };
		}
		
		this.deletediv.onmouseover = function () { this.style.cursor='pointer'; };
		this.deletediv.onmouseout = function () { this.style.cursor='auto'; };

	/*this.refreshdiv = document.createElement('div');
	this.refreshdiv.setAttribute('class', 'refreshdiv');
	this.buttontab.appendChild(this.refreshdiv);*/

	this.rightbook = document.createElement('div');
	this.rightbook.setAttribute('class', 'rightbook');
	this.buttontab.appendChild(this.rightbook);
	
//full feed view
	this.fullfeedview = document.createElement('div');
	this.fullfeedview.setAttribute('class', 'hidden');

	this.controldiv.appendChild(this.buttontab);
	this.controldiv.appendChild(this.fullfeedview);

	var maincontroldiv = document.getElementById('alertcontrols');
	maincontroldiv.appendChild(this.controldiv);
	
}

function selectThisFeed() {
	
	pauseAllFeeds();
	deselectAllFeeds();
	coverTop();
	this.uncover();
	this.holderdiv.style.borderBottom = "1px solid #00e90e";
	//this.namediv.style.opacity = "1.0";
	this.controldiv.setAttribute('class', 'tickercontrols');
	
	this.logodiv.onclick = function () { 
				deselectAllFeeds(); 
				uncoverAllFeeds(); 
				uncoverTop();
				playAllFeeds(); 
				document.getElementById('feedtipdiv').innerHTML = feedtip;
	};
	document.getElementById('feedtipdiv').innerHTML = 'Click the arrows to scroll.<br/> Click the delete button to remove feed.<br/>Click the feed icon to deselect.';

}

function deselectThisFeed() {
	this.cover();
	this.controldiv.setAttribute('class', 'fchidden');
	this.fullfeedview.setAttribute('class', 'hidden');
	var thisfeed = this;
	this.xmlbuttondiv.innerHTML = 'show all';
	this.xmlbuttondiv.onclick = function( ) { 	showFullFeed(thisfeed); };
	this.holderdiv.style.borderBottom = "1px solid #005705";//alert('deselectingb');
	//this.namediv.style.opacity = "0.5";
	var thisfeed = this;
	this.logodiv.onclick = function () { selectAFeed( thisfeed ) };

}

function coverFeed() {
	this.coverdiv.setAttribute('class', 'coverdiv');

}

function uncoverFeed() {
	this.coverdiv.setAttribute('class', 'hidden');
}

function removeFeed() {
	//clearTimeout(this.rotatetimer);
	this.holderdiv.style.display = 'none';
	this.controldiv.style.display = 'none';
	this.ispaused = true;
	 deselectAllFeeds(); uncoverAllFeeds(); uncoverTop(); playAllFeeds(); 	

}

function removeThisFeed( who ) {
	who.remove();
	eraseCookie( 'tickers['+who.pointer+']' );
	who.train="none";
	opentickers--;
	if (opentickers == 0) { document.getElementById('feedtipdiv').innerHTML = 'Hello. Please Select from the above options.'; }
}

function selectAFeed( who ) {
	who.select(); 
}

function removeThisGenericFeed( who ) {
	who.remove();
	eraseCookie( 'generictickers['+who.pointer+']url' );
	eraseCookie( 'generictickers['+who.pointer+']logo' );
	eraseCookie( 'generictickers['+who.pointer+']color' );
	eraseCookie( 'generictickers['+who.pointer+']category' );
	who.url="none";
	opentickers--;
	if (opentickers == 0) { 
		document.getElementById('feedtipdiv').innerHTML = 'Hello. Please Select from the above options.'; 
		pauseAllFeeds();
	}
}

function loadXMLDoc( who ) {

    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        who.req = new XMLHttpRequest();

        who.req.onreadystatechange = function() { processReqChange( who ); };  
        who.req.open("GET", who.url, true);

        who.req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        isIE = true;
        who.req = new ActiveXObject("Microsoft.XMLHTTP");
        if (who.req) {
            who.req.onreadystatechange = function() { processReqChange( who ); };
            who.req.open("GET", who.url, true);
            who.req.send();
        }
    }
}

// handle onreadystatechange event of req object
function processReqChange( who ) {
    // only if req shows "loaded"

    if (who.req.readyState == 4) {
        // only if "OK"
        if (who.req.status == 200) {
            //alert(req.responseXML);
            who.xmlLoaded();
         } else {
            alert("There was a problem retrieving the XML data:\n" +
                who.req.statusText);
         }
    }
}

function feedxmlLoaded() {

	var xmldata=this.req.responseXML;
	if (xmldata.getElementsByTagName("item").length==0){ //if no <item> elements found in returned content
		this.feeddiv.innerHTML="<b>Error</b> fetching remote RSS feed!<br />"+this.req.responseText;
		this.build();
		return;
	}

	this.feeditems=xmldata.getElementsByTagName("item");

	//Cycle through RSS XML object and store each piece of the item element as an attribute of the element
	for (var i=0; i<this.feeditems.length; i++){
		this.feeditems[i].setAttribute("ctitle", this.feeditems[i].getElementsByTagName("title")[0].firstChild.nodeValue);
		this.feeditems[i].setAttribute("clink", this.feeditems[i].getElementsByTagName("link")[0].firstChild.nodeValue);
		this.feeditems[i].setAttribute("cpubDate", this.feeditems[i].getElementsByTagName("pubDate")[0].firstChild.nodeValue);
		//this.feeditems[i].setAttribute("cdescription", this.feeditems[i].getElementsByTagName("description")[0].firstChild.nodeValue);

	}
	this.build();
}

function buildFeed() {
	this.feeddiv.innerHTML = '';
	this.feeddiv.style.left = this.startx+"px";
	this.insertpointright = 0;
	
	for (var i = 0; i < this.feeditems.length; i++) { //load the display array
		var title = this.feeditems[i].getAttribute('ctitle');
		var link = this.feeditems[i].getAttribute('clink') ;
		this.displayitems.push( new DisplayItem ( title, link, this.color, i ));
		if ((i % 3) == 0 && i > 1 && Math.random() > 0.25) {
			var adpickindex = Math.floor(Math.random()*displayads.length);
			var adpick = displayads[adpickindex];
			this.displayitems.push( new DisplayAdItem ( adpick.name, adpick.link, adpick.color, adpickindex ));
		}
	}
	
	if ( this.feeditems.length < 3 ) {
		this.displayitems[1] = new DisplayItem ( this.feeditems[0].getAttribute('ctitle'), this.feeditems[0].getAttribute('clink'), this.color, i );
		this.displayitems[2] = new DisplayItem ( this.feeditems[0].getAttribute('ctitle'), this.feeditems[0].getAttribute('clink'), this.color, i );
		this.displayitems[3] = new DisplayItem ( this.feeditems[0].getAttribute('ctitle'), this.feeditems[0].getAttribute('clink'), this.color, i );
		this.displayitems[4] = new DisplayItem ( this.feeditems[0].getAttribute('ctitle'), this.feeditems[0].getAttribute('clink'), this.color, i );
	}
	
	for (var count = 0; count < 3; count++ ) { //draw the first 3 items
		this.displayitems[count].drawitem( this.insertpointright, this.feeddiv ); 
		this.insertpointright += this.displayitems[count].div.offsetWidth; 
	}
	
	 
	this.pubdatediv.innerHTML = "<span style='color:"+this.color+";'>"+this.feeditems[0].getAttribute('cpubDate')+"</span>";
	this.firstdrawnitem = 0;
	this.lastdrawnitem = 2;
	
	this.ispaused = false;
}


var feedspeed = 30; //milliseconds
var feeddistance = 2; //pixels
var maxdistance = 50; //pixels
var mindistance = 1;
var lastdistance = (readCookie('feeddistance')!=null) ?  parseInt(readCookie('feeddistance')) : 2;

function speedUp() {
	if (feeddistance == maxdistance) { alert('Max speed reached.');}
	feeddistance = (feeddistance == 2 && lastdistance != 2) ? lastdistance : (feeddistance < maxdistance) ? ++feeddistance : maxdistance;
	createCookie('feeddistance', feeddistance, 2048);
	lastdistance = feeddistance;
}

function speedDefault() {
	feeddistance = (feeddistance==2) ? lastdistance : 2;
	//createCookie('feeddistance', feeddistance, 2048);
}

function slowDown() {
	feeddistance = (feeddistance > mindistance) ? --feeddistance : mindistance;
	createCookie('feeddistance', feeddistance, 2048);
	lastdistance = feeddistance;
}

function updateScreenWidth() {
	if (window.innerWidth != currentscreenwidth) {
		currentscreenwidth = (window.innerWidth <= 1500) ? window.innerWidth : 1500;
		safezoneright = currentscreenwidth + 100;
		document.body.style.maxWidth = currentscreenwidth + "px";
		document.getElementById('backdropdiv').style.width =  currentscreenwidth + "px";
		document.getElementById('backcontent').style.width =  currentscreenwidth + "px";
		document.getElementById('contentarea').style.width =  currentscreenwidth + "px";
		//var feeddivs = document.getElementsByClassName('ticker');
		for (var f = 0; f < tickers.length; f++) {
			tickers[f].updateWidth();
		}
		for (var f = 0; f < generictickers.length; f++) {
			generictickers[f].updateWidth();
		}

	}
}

function updateTickerWidth() {
	this.holderdiv.style.width = currentscreenwidth + "px";
	this.controldiv.style.width = currentscreenwidth + "px";
	
}

var allfeedrotatetimer;

function rotateAllFeeds(  ) {
	
	for ( var feedcount = 0; feedcount < tickers.length; feedcount++ ) {
	
		if (tickers[feedcount].ispaused != true) {
		
			tickers[feedcount].updateDisplayItems( feeddistance );
			
			if (tickers[feedcount].insertpointright < safezoneright) {
				tickers[feedcount].buildForward();
			}
		}
	}
	for ( var gfeedcount = 0; gfeedcount < generictickers.length; gfeedcount++ ) {
	
		if (generictickers[gfeedcount].ispaused != true) {
		
			generictickers[gfeedcount].updateDisplayItems( feeddistance );
			
			if (generictickers[gfeedcount].insertpointright < safezoneright) {
				generictickers[gfeedcount].buildForward();
			}
		}
	}
	updateScreenWidth();
	allfeedrotatetimer = setTimeout( rotateAllFeeds, feedspeed );

}

function updateDisplayItems ( distance ) {
	
	for (var count = 0; count < this.displayitems.length; count++) {
		if (this.displayitems[count].state == "drawn") {
			var newx = this.displayitems[count].currentx - distance;
			this.displayitems[count].updatepos( newx );
		}
	}
	
	this.insertpointright = this.displayitems[this.lastdrawnitem].currentx + this.displayitems[this.lastdrawnitem].div.offsetWidth ;
	this.insertpointleft = this.displayitems[this.firstdrawnitem].currentx ;
}

function findFirstandLast() {
	this.firstdrawnitem = 0;
	while (this.displayitems[this.firstdrawnitem].state != "drawn") {
		this.firstdrawnitem++;
	}
	
	this.lastdrawnitem = this.displayitems.length-1;
	while (this.displayitems[this.lastdrawnitem].state != "drawn") {
		this.lastdrawnitem--;
	}
	
}

function feedBuildForward() {
	//this.findFirstandLast();
	
	if (this.displayitems[this.firstdrawnitem].endxpos <= safezoneleft) {
		this.displayitems[this.firstdrawnitem].erase();
		this.firstdrawnitem = (this.firstdrawnitem == this.displayitems.length-1 ) ? 0 : this.firstdrawnitem+1;
		//var removed = this.displayitems.shift();
	}
	//firstdrawn = displayitems.length+1;
	
	var oldlast = this.lastdrawnitem;
	this.lastdrawnitem = (this.lastdrawnitem == this.displayitems.length-1) ? 0 : this.lastdrawnitem+1;
	
	this.displayitems[this.lastdrawnitem].drawitem( this.insertpointright, this.feeddiv );
	this.indsertpointright = this.displayitems[this.lastdrawnitem].endxpos;
}

function feedBuildReverse() {
	//this.findFirstandLast();
	
	if (this.displayitems[this.lastdrawnitem].currentx >= safezoneright ) {
		this.displayitems[this.lastdrawnitem].erase();
		this.lastdrawnitem = (this.lastdrawnitem == 0) ? this.displayitems.length-1 : this.lastdrawnitem-1;
	}
	
	var oldfirst = this.firstdrawnitem;
	this.firstdrawnitem = (this.firstdrawnitem == 0) ? this.displayitems.length-1 : this.firstdrawnitem-1;
	
	this.displayitems[this.firstdrawnitem].drawitem( safezoneright , this.feeddiv);
	var newinsertpoint = this.displayitems[oldfirst].currentx - this.displayitems[this.firstdrawnitem].div.offsetWidth; //insert it it's width before the first feed item
	
	this.displayitems[this.firstdrawnitem].updatepos( newinsertpoint );
	this.insertpointleft = newinsertpoint;
}

var seekdistance = 400/16;

function setNextSeeks() {
	this.myendpos = this.currentx + this.endx;
	this.nextseekxff = (this.myendpos <= 640) ? (-1*this.endx)+320 :  this.currentx-320;
	this.nextseekxr = (this.currentx >= -320) ? 42 : this.currentx + 320;
}




function fastForwardFeed( who, countdown ) {
	if (countdown > 0) {
		who.updateDisplayItems( seekdistance );
		
		
		var nextcount = --countdown;
		who.rotatetimer = setTimeout( function() { fastForwardFeed( who, nextcount ) }, 50);
	} else {
		if (who.insertpointright < safezoneright+20) {
				who.buildForward();
			}
		clearTimeout( who.rotatetimer );
	}
}

function rewindFeed ( who, countdown ) {
	if (countdown > 0) {
		who.updateDisplayItems( -1*seekdistance );
		
		var nextcount = --countdown;
		who.rotatetimer = setTimeout( function() { rewindFeed( who, nextcount ) }, 50);
	} else {
		if (who.insertpointleft > safezoneleft-50 ) {
				who.buildReverse();
			}
		clearTimeout( who.rotatetimer );
	}
}

function initializeGeneric ( url, logo, name, category, color ) {
	//this.setCategory(category);
	this.color = (color==null||color==undefined) ? this.color : color;
	this.url = url;
	//this.feedname = name;
	this.logographic = logo;
	this.drawFeed();

	loadXMLDoc( this );

}

function setColorGeneric( color ) {
	this.color = (color==null) ? "#ff0000" : color;
}

function setFeedCategory ( category ) {
	this.category = category;
	switch (category) {
		case 'entertainment':
			this.color = "#dd891c";
			this.logoback = "images/dd891c.png";
			break;
		case 'business':
			this.color = "#ddd61c";
			this.logoback = "images/ddd61c.png";
			break;
		case 'technology':
			this.color = "#2add1c";
			this.logoback = "images/2add1c.png";
			break;
		case 'science':
			this.color = "#1cddad";
			this.logoback = "images/1cddad.png";
			break;
		case 'other':
			this.color = "#1c57dd";
			this.logoback = "images/1c57dd.png";
			break;
		case 'news':
		default:
			this.color = "#dd1c1d";
			this.logoback = "images/dd1c1d.png";
	}
}

function Ticker( train, yourpointer ) { 
	this.pointer = yourpointer;
	this.train = train;
	this.logographic = 'images/'+train+'line.png';
	this.logoback = 'images/dd1c1d.png';
	this.feedid = train+'line';
	this.req; //xml request
	this.url='getcacherss.php';
	this.feedname = 'custom';
	this.category;
	this.textcolor;
	this.holderdiv;
	this.namediv;
	this.logodiv;
	this.logobackdiv;
	this.feeddiv;
	this.feeditems;
	this.displayitems = [];
	this.firstdrawnitem; //leftmost visible item
	this.lastdrawnitem; //rightmost visible item
	this.startx = 42;
	this.currentx = 42;
	this.nextseekxff = -320;
	this.nextseekxr = 42;
	this.endx;
	this.myendpos;
	this.rotatetimer;
	this.color = "#00e90e";
	this.controldiv;
	this.coverdiv;
	this.deletediv;
	this.refreshdiv;
	this.xmlbuttondiv;
	this.fastforwarddiv;
	this.rewinddiv;
	this.buttontab;
	this.leftbook;
	this.rightbook;
	this.fullfeedview;
	this.isseeking = false;
	this.ispaused = true;
	this.insertpointright; //place to add next feeditem;
	this.insertpointleft; //place to add prev feeditem' endpoint (from the left);

	//Methods
	this.xmlLoaded = feedxmlLoaded;
	this.initialize = initializeFeed;
	this.build = buildFeed;
	this.setColor = setColor;
	this.remove = removeFeed;
	this.drawFeed = drawFeed;
	this.updateDisplayItems = updateDisplayItems;
	this.drawControls = drawFeedControls;
	this.initializeGeneric = initializeGeneric;
	this.setColorGeneric = setColorGeneric;
	this.select = selectThisFeed;
	this.deselect = deselectThisFeed;
	this.cover = coverFeed;
	this.uncover = uncoverFeed;
	this.setNextSeeks = setNextSeeks;
	this.setCategory = setFeedCategory;
	this.buildForward = feedBuildForward;
	this.buildReverse = feedBuildReverse;
	this.findFirstandLast = findFirstandLast;
	this.updateWidth = updateTickerWidth;
	this.showFullFeed = showMyFullFeed;
	this.hideFullFeed = hideMyFullFeed;
}


/****** Display Item Object *******/

function displayItemDraw( startx, holderdiv ) {
	if (this.state == "new") {
		this.div = document.createElement('div');
		this.div.setAttribute('class', 'tickerfeeditem');
		this.updatepos( startx );
		
		var divlength = ((this.title.length+20)/2);
		this.div.style.width = (divlength*15)+"px";
		//this.div.style.left = startx + "px";
		
		this.div.innerHTML += "<a href='"+ this.link + "' style='color:"+this.color+";' target='_top' >"+ this.title  + "</a>&nbsp;<img src='images/logo.png' width='106' height='34' border='0' style='margin-left: 10px; margin-right: 10px;' >&nbsp;";
		
		this.endxpos = this.currentx + this.div.offsetWidth;
		holderdiv.appendChild( this.div );
	
		this.div.style.opacity = 0.0;
		//alert(this.div.offsetHeight);
		while (this.div.offsetHeight < 60) {
			this.div.style.width = (this.div.offsetWidth - 50)+"px";
		}
		
		while (this.div.offsetHeight > 60) {
			this.div.style.width = (this.div.offsetWidth + 10)+"px";
		}
		this.div.style.opacity = 1.0;
	} else {
		this.updatepos( startx );
		this.endxpos = this.currentx + this.div.offsetWidth;
		this.div.style.display = 'block';
	}
	this.state = "drawn";
}

function displayItemErase() {
	this.div.style.display = 'none';
	//this.div.innerHTML = '';
	this.state = "hidden";
}

function updateItemPos( newx ){
	this.currentx = newx;
	this.endxpos = this.currentx + this.div.offsetWidth;
	this.div.style.left = newx+"px";
}

function DisplayItem ( title, link, color, feeditemindex ) {
	this.title = title;
	this.link = link;
	this.color = color;
	this.index = feeditemindex;
	this.currentx;
	this.endxpos;
	this.div;
	this.state = 'new';
	
	this.drawitem = displayItemDraw;
	this.erase = displayItemErase;
	this.updatepos = updateItemPos;
}

function displayAdItemDraw( startx, holderdiv ) {
	if (this.state == "new") {
		this.div = document.createElement('div');
		this.div.setAttribute('class', 'tickerfeeditem');
		this.updatepos( startx );
		
		var divlength = ((this.title.length+20)/2);
		this.div.style.width = (divlength*15)+"px";
		//this.div.style.left = startx + "px";
		
		this.div.innerHTML += "<img src='images/sponsor.png' width='27' height='34' ><a href='"+ this.link + "' style='color:"+this.color+";' target='_top' >"+ this.title  + "</a><img src='images/sponsor.png' width='27' height='34' >&nbsp;<img src='images/logo.png' width='106' height='34' border='0' style='margin-left: 10px; margin-right: 10px;' >&nbsp;";
		
		this.endxpos = this.currentx + this.div.offsetWidth;
		holderdiv.appendChild( this.div );
	
		this.div.style.opacity = 0.0;
		//alert(this.div.offsetHeight);
		while (this.div.offsetHeight < 60) {
			this.div.style.width = (this.div.offsetWidth - 50)+"px";
		}
		
		while (this.div.offsetHeight > 60) {
			this.div.style.width = (this.div.offsetWidth + 10)+"px";
		}
		this.div.style.opacity = 1.0;
	} else {
		this.updatepos( startx );
		this.endxpos = this.currentx + this.div.offsetWidth;
		this.div.style.display = 'block';
	}
	this.state = "drawn";
}

function DisplayAdItem (  title, link, color, aditemindex ) {
	this.title = title;
	this.link = link;
	this.color = color;
	this.index = aditemindex;
	this.currentx;
	this.endxpos;
	this.div;
	this.state = 'new';
	this.parent = DisplayItem;
	this.adlabel;
	
	this.drawitem = displayAdItemDraw;

}


DisplayAdItem.prototype = new DisplayItem;

/******************** browse panel ********************/
function showdiv ( divid ) {
	document.getElementById(divid).style.display = 'block';
}

function hidediv ( divid ) {
	document.getElementById(divid).style.display = 'none';

}

/******************** Cookie Code ********************/
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else {var expires = "";}
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}



/******************** Start it up *********************/
window.onresize = function() {
	updateScreenWidth();
}

window.onload = function() {
	//updateScreenWidth();
	
	 if(navigator.appName == "Microsoft Internet Explorer")
	{
		 window.location = "explorerhome.html";
	 }
	Initialize();
};

function mod(divisee,base) {
	// Created 1997 by Brian Risk.  http://members.aol.com/brianrisk
	return Math.round(divisee - (Math.floor(divisee/base)*base));
}