 var Url = {

 	// public method for url encoding
 	encode : function (string) {
 		return escape(this._utf8_encode(string));
 	},

 	// public method for url decoding
 	decode : function (string) {
 		return this._utf8_decode(unescape(string));
 	},

 	// private method for UTF-8 encoding
 	_utf8_encode : function (string) {
 		string = string.replace(/\r\n/g,"\n");
 		var utftext = "";

 		for (var n = 0; n < string.length; n++) {

 			var c = string.charCodeAt(n);

 			if (c < 128) {
 				utftext += String.fromCharCode(c);
 			}
 			else if((c > 127) && (c < 2048)) {
 				utftext += String.fromCharCode((c >> 6) | 192);
 				utftext += String.fromCharCode((c & 63) | 128);
 			}
 			else {
 				utftext += String.fromCharCode((c >> 12) | 224);
 				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
 				utftext += String.fromCharCode((c & 63) | 128);
 			}

 		}

 		return utftext;
 	},

 	// private method for UTF-8 decoding
 	_utf8_decode : function (utftext) {
 		var string = "";
 		var i = 0;
 		var c = c1 = c2 = 0;

 		while ( i < utftext.length ) {

 			c = utftext.charCodeAt(i);

 			if (c < 128) {
 				string += String.fromCharCode(c);
 				i++;
 			}
 			else if((c > 191) && (c < 224)) {
 				c2 = utftext.charCodeAt(i+1);
 				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
 				i += 2;
 			}
 			else {
 				c2 = utftext.charCodeAt(i+1);
 				c3 = utftext.charCodeAt(i+2);
 				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
 				i += 3;
 			}

 		}

 		return string;
 	}

}


 function recordVideoPlay(mediaID, mediaTitle, playerSkin, audio, gameid, homeTeamAbbr, visitingTeamAbbr, mediaType, fullDateText) {
 
 	//alert("mediaID: "+mediaID + " mediaTitle: "+mediaTitle +" playerSkin: "+playerSkin+ " audio: "+audio +" gameid: "+gameid + " homeTeamAbbr: " + homeTeamAbbr+ " visitingTeamAbbr: "+ visitingTeamAbbr + " mediaType: "+mediaType + " fullDateText: " + fullDateText);

	 /** Send a micro-call when a video starts.
	 *
	 * (string) mediaID = filename for clip
	 * (string) mediaTitle = title from metadata
	 * (string) playerSkin = team branding or wnba
	 *
	 * Returns true if success & false if any params are invalid
	 */

	 /* ensure variables are passed */
	 playerSkin = playerSkin ? playerSkin : "wnba" ;
	 y = ((mediaID && mediaTitle && playerSkin&&gameid&&homeTeamAbbr&&visitingTeamAbbr&&mediaType&&fullDateText)) ? true : false;
	 if (y != true) {
		 return false;
	 }

	 var s = s_gi(s_account);
	 s.linkTrackVars = "prop29,prop30,prop31,prop32";

	 var url = this.location;


	 index = mediaID.indexOf("arl=");//arl is expected to be last parameter
	 if(index > 0){
	 	mediaID = mediaID.substring(index+4);
	 	mediaID = Url.decode(mediaID);
	 }


       	var playerTeamName = "W-LIVEACCESS";

        if(typeof(site) != "undefined" &&  site != "WNBA"){
            playerTeamName = playerTeamName + site.toUpperCase();
        }
       

	 s.prop4  = gameid;
	 s.prop5  = visitingTeamAbbr + " at "+ homeTeamAbbr + ", " + fullDateText;
	 s.prop6  = playerTeamName;
	 s.prop10 = mediaType;
	 s.prop29 = mediaID;
	 s.prop30 = mediaTitle;
	 if (audio == true) { s.prop30 += " (audio)"; }
	 s.prop31 = playerSkin;
	 s.prop32 = "WNBALIVEACCESS";

	s.evar4 = gameid;
	s.evar5 = visitingTeamAbbr + " at "+ homeTeamAbbr + ", " + fullDateText;
	s.evar6 = playerTeamName;
	s.evar7 = mediaType;
	s.evar11= "WNBA-" + visitingTeamAbbr +"@ WNBA-"+ homeTeamAbbr,
	s.evar16= "WNBALIVEACCESS";

	if(mediaType == "live-video"){
		s.events="event3";
	}
	if(mediaType == "archive-video"){
		s.events="event4";
	}
	
	
	 /* call omniture */
	 //s.tl(true, 'o', url);


	/* call media */
	
	wnbaHandleStreamStart(gameid,mediaTitle,"WNBA-" + homeTeamAbbr, "WNBA-" + visitingTeamAbbr, "unknown",mediaType);
	
         /* reset the s object */
	 s.linkTrackVars = "";
         s.prop4  = "";
	 s.prop5  = "";
	 s.prop6  = "";
	 s.prop10 = "";
	 s.prop29 = "";
	 s.prop30 = "";
	 s.prop31 = "";
	 s.prop32 = "";

	s.evar4 = "";
	s.evar5 = "";
	s.evar6 = "";
	s.evar7 = "";
	s.evar11= "";
	s.evar16= "";
        s.events = "";


	 /* return */
	 return true;

	 
 }
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function unescapeHTML(html) {
	var htmlNode = document.createElement("DIV");
	htmlNode.innerHTML = html;
	if(htmlNode.innerText)
		return htmlNode.innerText; // IE
	return htmlNode.textContent; // FF
}
var LiveAccess = { 




	init : function(){
		try{
			if($$('.date_table').length > 0){
				$$('table.month').invoke('hide');
				$('SEPTEMBER').show();
				$$(".schedule .navigation .september")[0].className = "september_selected";
			}
			//alert("here");
			//if($('popout')){
			//	$('popout').observe('click', LiveAccess.onClick_Popout);
			
			//}
			
			var playerOverlay = $('player-overlay');
			if(playerOverlay){
				playerOverlay.observe('click',LiveAccess.onClick_PlayVideo);
			}
		}catch(e){
			alert("Live Access cannot initialize: "+e);
			document.write("<!-- "+e+"-->");
		}


	},



	onClick_PlayVideo: function(event){
		var a = ActiveGame;  //ActiveGame is an object literal initialized by jstl
		if(a.hasVideo()){//only play when there is something to play
		 	LiveAccess.playVideo(a.gameId,a.desc,a.currentTeamName,a.awayVsHomeMatchUp, a.timeOrArchiveUrl);
		}else if(a.hasAudio()){
			LiveAccess.playAudio(a.audioUrl,a.desc,a.currentTeamName);
		}
	},
	
	onClick_PopoutVideo: function(event){
		var a = ActiveGame;  //ActiveGame is an object literal initialized by jstl
		LiveAccess.popoutVideo(a.gameId,a.desc,a.currentTeamName,a.awayVsHomeMatchUp, a.timeOrArchiveUrl);
		
	},
	

	selectDateByNumber: function(date_table_number) {
		if (date_table_number < 0) { return; }

		var date_tables = $$('table.date_table');
		date_tables.invoke('hide');

		if (date_table_number >= date_tables.length) { return; }

		var date_table = $(date_tables[date_table_number]);
		Element.setOpacity(date_table, 0.0);
		new Effect.Appear(date_table, {duration:0.7, queue: 'end'});
	},

	swapMonth: function(month){
		$$(".schedule .navigation ul li a").each(function(n) {
			n.className = n.className.replace(/_.*$/, "");
		});

		$$(".schedule .navigation ." + month.toLowerCase())[0].className += "_selected";

		$$('table.month').invoke('hide');
		var e = $(month);
		Element.setOpacity(e, 0.0);
		new Effect.Appear(e, {duration:0.7, queue: 'end'});
	},

	playAudio: function(audioUrl, desc, teamName) {
		var isAudio = true;
		var recorded = recordVideoPlay(audioUrl, desc, teamName, isAudio);

		try{
			var mediaplayer = $("mediaplayer");

			var audioplayer = ['<object',
								' id="mediaplayer" name="mediaplayer"',
								' width="600" height="338"',
								' codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,7,1112"',
								' type="application/x-oleobject" standby="Loading Game Video..."',
								' classid="CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95">',
									'<param value="', audioUrl, '" name="filename"/>',
									'<param value="true" name="AutoStart"/>',
									'<param value="true" name="showControls"/>',
									'<param value="2" name="BufferingTime"/>',
									'<param value="true" name="ShowStatusBar"/>',
									'<param value="true" name="AutoSize"/>',
									'<param value="false" name="InvokeURLs"/>',
									'<embed',
										' width="600" height="338"',
										' codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,7,1112"',
										' pluginspage="http://www.microsoft.com/Windows/MediaPlayer/"',
										' showcontrols="1" showdisplay="1" showstatusbar="1"',
										' enabled="1" autostart="1" type="application/x-mplayer2"',
										' src="', audioUrl, '"/>',
								'</object>'].join("");

			if (mediaplayer) {

				if (Prototype.Browser.IE) { $("mediaplayer").Stop(); }

			} else {

				// this should only occur if the game is blacked out

				// adding the element first makes this work in firefox 3.0.x
				//  and doesn't hurt anything in other browsers
				var mediaplayer = new Element("object", {"id" : "mediaplayer", "name": "mediaplayer"});
				$("wmplayer").update("");
				$("wmplayer").insert(mediaplayer);
			}

			$("mediaplayer").replace(audioplayer);

			$$(".active_game .audio")[0].addClassName("audio_playing");
		} catch(e) {
			alert("error " + e);
		}

	},

	displayLoadingVideo : function(element) {
		$(element).replace("Loading...");
	},

	playVideo: function(gameid, desc, teamName, userSelection, gameNo, videoUrl, homeTeamAbbr, visitingTeamAbbr, mediaType){

		var qs = '';
		try{
			//hash the current query string removing gamecode and gameid if given and re-adding gameid only as it is the trigger to the refresh window location with the player
		  var search = window.location.search;
		  if(search != null){
		 	 var qp = $H(search.toQueryParms());
		 	 qp.unset('gamecode');
		 	 qp.unset('gameid');
		 	 qs = "&" + Object.toQueryString(qp);
		  }
		}catch(e){}


		openNewVideoUrl = window.location.pathname + "?gameid=" + gameid + qs;

		try{
		
			//alert("doing qapost");

			if(teamName == null || trim(teamName).length == 0)
				teamName = "wnba";

			var qaUrl = "/wnbalive/qaPost.jsp";
			new Ajax.Request(qaUrl, {
			  method: 'post',
			  parameters: {ui: userId, usm: userSelection, uri: absTarget},
			  onSuccess: function(transport) {

			  },
			  onFailure: function(transport) {
			  },
			  onComplete : function(transport) {
			  	window.location = openNewVideoUrl;
			  }
			});



		}catch(e){
			window.location = openNewVideoUrl;
		}

	},
	
	popoutVideo: function(gameid, desc, teamName, userSelection, gameNo, videoUrl, homeTeamAbbr, visitingTeamAbbr, mediaType){
	
		var qs = '';
		try{
			//hash the current query string removing gamecode and gameid if given and re-adding gameid only as it is the trigger to the refresh window location with the player
		  var search = window.location.search;
		  if(search != null){
		 	 var qp = $H(search.toQueryParms());
		 	 qp.unset('gamecode');
		 	 qp.unset('gameid');
		 	 qs = "&" + Object.toQueryString(qp);
		  }
		}catch(e){}

		try{
		
		var path = window.location.pathname.substring(1,window.location.pathname.lastIndexOf("/") +1);	
		
		
		
		//openNewVideoUrl = window.location.protocol + "//"+ window.location.host + "/" + path + "popout.jsp" + "?gameid="+ gameid + qs;
		openNewVideoUrl = window.location.protocol + "//"+ window.location.host + "/wnbalive/popout.jsp" + "?gameid="+ gameid + qs;
				
				
		}catch(e){
			alert(e);
		}	
		try{
			if(teamName == null || trim(teamName).length == 0)
				teamName = "wnba";

			var qaUrl = "/wnbalive/qaPost.jsp";
			new Ajax.Request(qaUrl, {
			  method: 'post',
			  parameters: {ui: userId, usm: userSelection, uri: absTarget},
			  onSuccess: function(transport) {

			  },
			  onFailure: function(transport) {
			  },
			  onComplete : function(transport) {
				window.open (openNewVideoUrl, "liveAccessPopout","location=0,status=0,scrollbars=1,width=670,height=530"); 					  	
			  }
			});

		}catch(e){
			window.location = openNewVideoUrl;
		}

	}
	

}


