// Ticker and UserLogin client
function callClients(){
	displayUserState();
	loadFeed();
}
//tickerClient
function loadFeed(){
	feeder = new XMLDataFeed();

	feeder.setUrl("/.element/js/2.0/sect/leaguepass/LP_Schedule.xml?version=1031");
	try{
		feeder.feedData(onDataLoaded);
	}
	catch (E){
		////console.log("Exception ...: " + E);
	}
}

function onDataLoaded(games){
	var tickerFragment = document.createDocumentFragment();
	// start loading and ticking
	var tickerWrapper = $("tickerWrapper");
	
	var tickObj = document.createElement("div");
	tickObj.id = "tickerContent";
	tickObj.style.width = (126 * games.length) + "px";
	tickObj.style.left = "900px";
	
	var tickerLet = new TickerLet();

	var homeTeamImg = null; 
	var visitingTeamImg = null; 
	var start_time = null;
	var start_date = null;
	var start_time_et = null;
	
	for (var i=0; i<games.length; i++) {

		homeTeamImg 	= games[i].getAttribute("home_abrv");
		visitingTeamImg = games[i].getAttribute("visiting_abrv");
		start_time 		= games[i].getAttribute("start_time");
		start_date 		= games[i].getAttribute("start_date");
		start_time_et 	= games[i].getAttribute("start_time_et");
		
		tickerLet = new TickerLet();
		tickerLet.injectLftDiv(visitingTeamImg + ".gif");
		tickerLet.injectRhtDiv(homeTeamImg + ".gif");
		
		tickerLet.setTickerTime(start_time, start_time_et, start_date);
		tickerLet.setBottom();
	
		tickObj.appendChild(tickerLet.getDiv());
	}
	
	tickerFragment.appendChild(tickObj);
	
	tickerWrapper.appendChild(tickerFragment);

	var objTicker = new ObjectTicker();
	objTicker.setTickerObj(tickObj);
	objTicker.setNumImages(games.length);
	objTicker.init();

	objTicker.start();
}

/***********************************************************************
ObjectTicker.js
CopyRight: NBA Digital, Turner

Description: 
Is a ticker that slowly scrolls object, eg Divs.
Like a news ticker except it accepts objects.

Dependencies: 
prototype and scriptaculous with effects loaded.

Customizations:

Speed: Change the speed variable below giving an inverse velocity in seconds.
Delay: Change the time in seconds for the ticker to start

************************************************************************/

	/** Speed ***********************************************************/
var speed_GLB = 5; // NOTE::The higher the number the Slower the speed
	/** Delay ***********************************************************/
var delay_GLB = 0;


function ObjectTicker(){
	/** number of divs in the slide **********/
	this.numImages = 0;
	/** Image length - constant ************/
	this.imageLength = 126;
	/** Speed **********************/
	this.speed = 0;
	/** Delay **********************/
	this.delay = 0;
	
	this._tickerObj = null;
	
	this._width = 0;
	
	return this;
}

ObjectTicker.prototype = {

	_tickerClone : null,
	
	constructor : ObjectTicker(),
	
	init : function(){
		this.delay = delay_GLB;
		this.speed = speed_GLB * (this.numImages/2);
		this._width = this.numImages * this.imageLength;
	},
	
	setTickerObj : function(tobj){
		this._tickerObj = tobj;
	},
	
	setNumImages : function(numImg){
		this.numImages = numImg;
	},
	
	start : function(){
		var that = this;
		
		tickerFollower = function(){
			var leftPosition = parseInt(that._tickerObj.style.left);
			if (leftPosition < 0){
				that._tickerObj.style.left = "900px";
				that.start();
			}
		};
		
		if (that._tickerObj.style.left == "900px")
			new Effect.Move(this._tickerObj, {transition: Effect.Transitions.linear, fps: 100, delay: this.delay, duration: this.speed, x: -this._width - 900, y: 0});
			
		else
			new Effect.Move(this._tickerObj, {transition: Effect.Transitions.linear, fps: 100, delay: this.delay, duration: this.speed, x: -this._width, y: 0});
		
		setTimeout(tickerFollower, ((this.speed*1000*(this.delay+1)) + 1000));
		
		var newTO = this.clone(this._tickerObj);
		newTO.style.top = this._tickerObj.style.top;
		newTO.style.left = "200px";
		
	},

	clone: function(element) {
  		var clone = new Element(element.tagName);
  		$A(element.attributes).each(function(attribute) { 
					if( attribute.name != 'style' ) 
						clone[attribute.name] = attribute.value; 
					});
  		clone.setStyle( element.getStyles() );
  		clone.update(element.innerHTML);
  		return clone;
	}
};


/***********************************************************************
TickerLet.js
CopyRight: NBA Digital, Turner Broadcasting Systems

Description: 
Create a TickerLet Object
************************************************************************/
Date.prototype.getAMPMTime = function () {
	var h = this.getUTCHours();
 	var m = "0" + this.getMinutes();

	var ap = "AM";

  	if (h >= 12) {
    	ap = "PM";

    	if (h >= 13)
      	h -= 12;
  	}
	else if (h == 0)
		h = 12;

  	return (h + ":" + m.slice(-2) + " " + ap);
}

function TickerLet(){
	this._div = document.createElement("div");
	this._div.className = "nbaLPTickerComponent";
	
	this.lftDiv = document.createElement("div");
	this.lftDiv.className = "lftTop";

	this.rhtDiv = document.createElement("div");
	this.rhtDiv.className = "rhtTop";
	
	this.lftSpan = document.createElement("span");
	this.lftSpan.className = "bDate";

	this.rhtSpan = document.createElement("span");
	this.rhtSpan.className = "bTime";
	
	this._div.appendChild(this.lftDiv);
	this._div.appendChild(this.rhtDiv);
	this._div.appendChild(this.lftSpan);
	this._div.appendChild(this.rhtSpan);
	
	this.time = null;
	this.dispTime = null;
	this.dispDate = null;
	
	return this;
}
TickerLet.prototype = {
	constructor: TickerLet,
	
	imageBase: "/.element/img/2.0/sect/gameinfo/teamlogos/small/",
	
	months: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
	
	setTickerTime: function(time, displayTime, displayDate){
		this.time = new Date(Number(time));
		this.dispTime = displayTime;
		this.dispDate = displayDate;
	},
	
	getDiv: function(){
		return this._div;
	},
	
	setImageBase: function(base){
		this.imageBase = base;
	},
	
	injectLftDiv: function(imgName){
		this.lftDiv.style.backgroundImage = "url(" + this.imageBase + imgName + ")";
	},
	
	injectRhtDiv: function(imgName){
		this.rhtDiv.style.backgroundImage = "url(" + this.imageBase + imgName + ")";
	},
	
	setBottom: function(){
		this.setLftSpan();
		this.setRhtSpan();
	},
	
	setLftSpan: function(){
		//var dateTxt = this.months[this.time.getUTCMonth()] + ", " + this.time.getUTCDate() + " " + this.time.getFullYear();		
		var dateTxt = this.dispDate;
		this.lftSpan.innerHTML = dateTxt;
	},
	
	setRhtSpan: function(){
		//var timeTxt = this.time.getAMPMTime();
		//this.rhtSpan.innerHTML = timeTxt + " ET";

		var timeTxt = this.dispTime;
		this.rhtSpan.innerHTML = timeTxt
	}

};

/***********************************************************************
XMLDataFeed.js
CopyRight: NBA Digital, Turner Broadcasting Systems

Description: 
Read xml data from an http url

Dependencies:
Prototype.js
************************************************************************/
function XMLDataFeed(){
	this.XMLdata = "No data received";
	this.dataFed = false;
	this.games = null;

	this.url = null;
	this.ajaxer = null;
}

XMLDataFeed.prototype = {
	
	constructor: XMLDataFeed,
	
	feedData: function(callbackfn){
		if (this.url == null){
			throw new Exception("Please set the url of the Feed first");
			return;
		}
		
		Ajax.Responders.register({
				onException: function(request, exception){
    				throw new Exception('exception occurred...: ' + exception);
  				}
		});
		this.ajaxer = new Ajax.Request(this.url,{
    			method:'get',
				onSuccess: function(transport){
					this.XMLdata = transport.responseXML;
					this.dataFed = true;

					if (window.DOMParser){
						this.games = this.XMLdata.getElementsByTagName("game");
					}
					else{
						//Create a xml tag in run time and inject it for IE
						var xmlFrag = document.createElement('xml');

						xmlFrag.innerHTML = transport.responseText;
						xmlFrag.id = 'xmlFragId';
						document.body.appendChild(xmlFrag);

						xmlDoc = document.getElementById('xmlFragId');
						this.games = xmlDoc.getElementsByTagName("game");
						document.body.removeChild(document.getElementById('xmlFragId'));
					}
					callbackfn(this.games);
    			}
		});
	},
	
	setUrl: function(url){
		this.url = url;
	}
};
//user
var lpWindow = "";
function launchLP(debug){
  lpPage = "http://premium.nba.com/pr/leaguepass/app/current/console.html";
  lpPage += (debug && debug.indexOf("true")>-1)?"?debug=true":"?debug=false";
  if (lpWindow.closed || lpWindow==""){
    lpWindow = window.open(lpPage,"lpWindow","width=1010,height=685,top=0,left=0,status=no")
    if (lpWindow.opener == null) lpWindow.opener=self;
  }
  lpWindow.focus();
}
function displayUserState(){
	var cout = null;

	var userLi = document.getElementById("nbaLPULoggedIn");
	
	var isLoggedIn = false;
	if (getCookie("authid") != null)
		isLoggedIn = true;
		
	if (isLoggedIn){
		cout = "Welcome, ";
		var username = getCookie("AA-Member");
		username = username.split("|")[0];
		cout += username;
		userLi.innerHTML = cout;
		document.getElementById("nbaLPLaunch").innerHTML = '<a href="javascript:launchLP()"><img src="http://i.cdn.turner.com/nba/nba/.element/img/1.1/sect/leaguepass/launch_btn.jpg" alt="Launch" width="100" height="25"></a>';
		document.getElementById("nbaLPManageAccount").innerHTML = '<a href="https://audience.nba.com/services/msib/flow/index ">Manage Account</a>';
	}
}


function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
