// PRELOAD IMAGES 
if (document.images){
	var skinImg = new Array('skin_livestream2','skin_podcenter','skin_more','skin_webcams','skin_live_baseball','skin_live_basket','skin_live_football','skin_live_golf','skin_live_hockey','skin_live_soccer');
	document.image_chargee = new Array();
	for ( i = 0; i < skinImg.length; i++ )
	{
		document.image_chargee[i] = new Image();
		document.image_chargee[i].src = skinImagePath + skinImg[i] + '.jpg';
	}
}

// HANDLERS 
$(function(){$('#stations').change(swapStation);});
$(function(){$('#states').change(stationsByState);});

/**
* this function is called onload- to populate both select fields. it's also called when the user changes
* the first select (to narrow down stations) and this fn populates the second select- the list of stations.
*
* @param st					the state or timezone that gets passed into this: /stations/player/stations.xml.
* @param loadStream			whether or not this fn should load the first station it finds when
*							parsing through the xml
* @param xml_sid 			the stationId as found in /stations/player/stations.xml. (THIS SHOULD BE
*							DEPENDANT ON THE DATABASE EVENTUALLY).
* @see 						changeStation
*/
function populateStations(st, loadStream, xml_sid){
	
	// DETERMINE THE XML AJX CALL 
	var param = '';
	if ( st.toLowerCase() != 'all' ){ param = '?state='+st.toLowerCase(); }
	stationsXML = '/espnradio/player/stations.xml'+param;

	// PULL IN STATIONS, BASED ON USER'S REQUEST 
	$.ajax({
		url: stationsXML,
		type: 'GET',
		dataType: 'xml', 
		timeout: 3000,
		error: function(){ errorWithRequest() }, 
		success: function(xml){
			$('#stations').html('<option value="">Select Station</option>');
			
			// LOOP THROUGH EACH RETURNED STATION 
			$(xml).find('station').each(function(){
				sel = '';
				if ( $(this).attr('state') == st || st == 'all' ){
					
					if (xml_sid > -1 && loadStream) {
						if ( $(this).attr('id') == xml_sid ){
							changeStation($(this).attr('location'), true);
							sel = 'selected';
						}
					}
					
					// APPEND OPTION TO SELECT 
					$('#stations').append('<option '+sel+' value="'+$(this).attr('location')+'">'+$(this).attr('name')+'</option>');
				}
			});
			$('#stations').attr({ disabled: false });
		}
	});
	$('#drops').show();
}

/**
* this function is called when a new show begins, or when a user changes stations. 
*
* @param loc 		the location of the xml feed of a station's shows that will be parsed.
* @param rerender	true/false, whether or not to rebuild the player swf and check for 
* 					station specific info (a new header image or bgnd). this is only 
*					true when a user changes a station or initally loads the player.
* @see 				parseBuildInfo rebuildPlayer
*/
function changeStation(loc, rerender){
	
	loadRequestTimeout = clearTimeout(loadRequestTimeout);
	
	$.ajax({
		url: loc,
		type: 'GET',
		dataType: 'xml', 
		timeout: 3000,
		error: function(){ errorWithRequest(); }, 
		success: function(xml){

			// REBUILD THE SWF WITH THE CORRECT STATION. 
			if ( rerender ){
				var vars = $(xml).find('station').attr('callsign');
				$('#blurb').html($(xml).find('station').attr('blurb'));
				rebuildPlayer(vars,true);
				// IMAGES 
				$(xml).find('station').find('images').each(function(){
					$(this).find('header').each(function(){
						setStationHeaderImage($(this).attr('value'));
					});
					$(this).find('generic').each(function(){
						generic90Img = $(this).attr('value');
					});
					$(this).find('background').each(function(){
						if ( getCurrentTab == 'tLive' ){
							setBackground($(this).attr("value"));
						}
					});
				});
			}

			// BUILD INFO 
			$('#blurb').html($(xml).find('station').attr('blurb'));
			newShow(xml);
		}
	});

}

/**
* this function is called when a new show begins, or when a user changes stations. 
*
* @param xml	the schedule xml with show elements broken down by day.
*
* @return		false, once it's found the current show.
*/
function newShow(xml){

	// PULL SHOWS BY THE CORRECT DAY 
	$(xml).find('schedule').each(function(){

		var timezone = $(this).attr('timezone');

		$(this).find('day').each(function(){

			if ( $(this).attr("value").toLowerCase() == getCurrentDay().toLowerCase() ){

				 log('Today is '+$(this).attr("value")+'.'); 

				nextShow=false;

				$(this).find('show').each(function(){

					if ( nextShow ){
						nextShowInfo($(this).attr('name'),$(this).attr('link'));
						nextShow = false;
						// break; 
						return false;
					}

					ems = parseInt(getETimeMS());
					// local time - client side 
					ms = parseInt(getTimeMS());
					/*ms = ms - timezone;*/

					var start = parseInt($(this).attr("startms")) + ems;
					var end = parseInt($(this).attr("endms")) + ems;
					if ( $(this).attr('multiday') == 'true' ){
						end = end + 86400000;
					}

					 log('Is '+$(this).attr('name')+' the current show? '+start+' < '+ms+' < '+end); 

					if ( ms >= start && (ms < end) ){

						 log('CURRENT SHOW-> '+$(this).attr('name')+ ' <-------'); 

						$('#loadingbox').hide();
						$('#selecthelp').hide();
						$('#showbox').show();
						setShowInfo($(this).attr('name'),$(this).attr('link'));
						setShowImage($(this).attr('graphic'),$(this).attr('link'));

						countdown(Math.abs((end - ms)));
						$('#showThumb').fadeIn('slow');
						$('#showbox').fadeIn('slow');
						$('#timeremain').fadeIn('slow');

						nextShow = true;

					}

				});
			}
		});
	});

}

/**
* this function gets called when the user changes the value of the 
* second select element -- (wants to change the station).
*
* @see changeStation
*/
function swapStation(){
	$('#thumbImg').hide();
	$('#showbox').hide();
	$('#loadingbox').show();
	$('#selecthelp').hide();
	stationXML = $('#stations').val();

	// AD HANDLE 
	eq = stationXML.indexOf('=');
	adName = 'espn'

	if ( eq > -1 ){
		adName = stationXML.substring(eq+1);
	}
	grabAd('live', adName);
	currentStation = adName;
	if ( stationXML != '' ){
		changeStation(stationXML, true);
	}
}

/**
* this function gets called when the user wants to change tabs.
*
* @param c 	the element id of the tab the user wants to switch to.
*
* @see getCurrentTab trackPageView stopAudio stopStreaming stopPodcast
*/
function swapTab(c){
	
	$('#prestitial').hide();

	switch ( getCurrentTab() )
	{
		case "tLive":
			stopStreaming();
			$('#liveTab').hide();
			break;
		case "tCast":
			stopPodcast();
			$('#podcastTab').hide();
			break;
		case "tMore":
			stopAudio();
			$('#espnaudioTab').hide();
			break;
		case "tWebcams":
			stopVideo();
			hideWebcams();
			break;
	}

	var b = "";
	tabs = new Array("tCast","tLive","tMore","tWebcams");

	switch (c){
		case "tCast":
		  b= skinImagePath + "skin_podcenter.jpg";
		  $('#podcastTab').show();
		  trackPageView('podcenter');
		  break;
		case "tLive":
		  b= skinImagePath + "skin_livestream2.jpg";
		  $('#liveTab').show();
		  trackPageView('live');
		  break;
		case "tMore":
		  b= skinImagePath + "skin_more.jpg";
		  $('#espnaudioTab').show();
		  trackPageView('audio');
		  break;
		case "tWebcams":
		  b= skinImagePath + defaultWebcamSkin;
		  showWebcams();
		  trackPageView('webcam');
		  break;
		default:
		  b= skinImagePath + "skin_livestream2.jpg";
		  $('#liveTab').show();
		  trackPageView('live');
	}
	
	try{
		$('body').attr({ style: 'background: #000000 url('+b+') no-repeat scroll 0% 0%;' });
		$('#'+getCurrentTab()).removeClass("realm");
		$('#'+c).toggleClass("realm");
	} catch(e) { errorWithRequest(); }

	setCurrentTab(c);

}

/**
* this recursive function is called every second until a new show begins. it then calls
* newShow() to build the information for the new show, and restarts the recursion.
*
* @param ms		the current number of milliseconds until the next show begins.
*/
function countdown(ms){
		 /*log(ms+' milliseconds until next ajax request.');*/ 
		count = Math.floor(ms / 1000);
		if (count > 0) {
			sec=toSt(count%60);
			count=Math.floor(count/60);
			min=toSt(count%60);
			count=Math.floor(count/60);
			hr=toSt(count%24);
			txt = hr + ":" + min + ":" + sec;
			$("#timeremain").html(txt);
			timeout = clearTimeout(timeout);
			timeout = setTimeout("countdown(" + (ms - 1000) + ")", 1000);
		} else {
			$('#timeremain').fadeOut('slow');
			changeStation($('#stations').val(), false);
		}

}

/**
* this function is called the user wants to change stations, which requires us to re-write the
* player_swf flash obj to the DOM with differnt flashVars
*
* @param vars		the new flashVars that get passed into the flashObj. these can be found in
* 					the station's shows.xml file, in the root node.
* @param auto		true/false. should the swf autoplay (i think it always does right now).
*
* @see				flash.js
*/
function rebuildPlayer(vars, auto){
	volume_param = '';
	$('#tempControl').hide();
	$('#streaming-player-home').show();
	if ( getStreamVolume() > -1 ){
		volume_param = '&vol='+getStreamVolume();
	}
	streamingPlayer.flashVars=vars+volume_param;
	streamingPlayer.useDOM = true;
	streamingPlayer.targetElement = "streaming-player-home";
	streamingPlayer.render(true);
}

//--------------------------------------
// HELPER FUNCTIONS TO BUILD THE STAGE
//-------------------------------------- 
function setShowImage(img, link){
	 log('Build image for current show; '+img); 
	if ( img != null && img != '' ){
		$('#thumbImg').hide();
		if ( link != null ){
			$('#thumbLink').attr({ onclick: "openURL('"+link+"');" });
		} else {
			$('#thumbLink').attr({ onclick: "void(0);" });
		}
		$('#thumbImg').attr({ src: img });
		$('#thumbImg').fadeIn('slow');
	} else {
		$('#thumbImg').hide();
	}
}

function setShowInfo(showname, showlink){
	 log('Build info for current show; '+showname); 
	$('#currentLink').hide();
	if ( showlink != null ){
		$('#currentLink').attr({ onclick: "openURL('"+showlink+"');" });
	} else {
		$('#currentLink').attr({ onclick: "return false;" });
	}
	$('#currentLink').html(showname);
	$('#currentLink').fadeIn('slow');
}

function nextShowInfo(nextname, nextlink){
	 log('Build info for the next show; '+nextname); 
	$('#nextLink').hide();
	if ( nextlink != null ){
		$('#nextLink').attr({ onclick: "openURL('"+nextlink+"');" });
	} else {
		$('#nextLink').attr({ onclick: "return false;" });
	}
	$('#nextLink').html(nextname);
	$('#nextLink').fadeIn('slow');
}

function setStationHeaderImage(img){
	$("#stationImage").attr({ src: img });
}

function setBackground(img){
	if ( img != '' ){ $('body').attr({ style: 'background: #000000 url('+img+') no-repeat scroll 0% 0%;' }); }
	setLiveVideoSkin(img);
}

//-------------------------------------------
// HELPER FUNCTIONS FOR CALCULATING TIME
//------------------------------------------- 
function getCurrentDay(){

	days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');

	// SET DATE OBJECT TO GET SHOW SCHEDULE FOR TODAY 
	onairdate = new Date();
	onairdate.setHours(0);
	onairdate.setMinutes(0);
	onairdate.setSeconds(0);
	onairdate.setMilliseconds(0);
	mil = onairdate.getTime();	// Get Milliseconds since midnight Jan 1 1970 to onairdate 
	tzone = onairdate.getTimezoneOffset();  // Minutes difference from GMT 
	tzone >= 0 ? gmttime = mil - (tzone * 60 * 1000) : gmttime = mil + (tzone * 60 * 1000);   	// Convert tzone to GMT time in Milliseconds 

	// CONVERT GMT TIME TO EST (ACCOUNT FOR DAYLIGHT SAVINGS TIME) 
	etimems = gmttime + dstOffset;

	// SET DATE AND GET CURRENT TIME EASTERN 
	now = new Date();
	nowmil = now.getTime();
	nowtz = now.getTimezoneOffset();
	nowtz >= 0 ? gmtnow = nowmil - (nowtz * 60 * 1000) : gmtnow = nowmil + (nowtz * 60 * 1000);

	// CONVERT TO DATE OBJECT 
	enow = new Date();
	enow.setTime(nowmil);
	eday = enow.getDay(); // Current day EST 

	return days[eday];
}

function getTimeMS(){
	now = new Date();
	nowmil = now.getTime();
	nowtz = now.getTimezoneOffset();
	nowtz >= 0 ? gmtnow = nowmil - (nowtz * 60 * 1000) : gmtnow = nowmil + (nowtz * 60 * 1000);
	return nowmil;
}

function getETimeMS(){			
	// SET DATE OBJECT TO GET SHOW SCHEDULE FOR TODAY 
	onairdate = new Date();
	onairdate.setHours(0);
	onairdate.setMinutes(0);
	onairdate.setSeconds(0);
	onairdate.setMilliseconds(0);
	mil = onairdate.getTime();	// Get Milliseconds since midnight Jan 1 1970 to onairdate 
	tzone = onairdate.getTimezoneOffset();  // Minutes difference from GMT 
	tzone >= 0 ? gmttime = mil - (tzone * 60 * 1000) : gmttime = mil + (tzone * 60 * 1000);   	// Convert tzone to GMT time in Milliseconds 

	// CONVERT GMT TIME TO EST (ACCOUNT FOR DAYLIGHT SAVINGS TIME) 
	etimems = gmttime + dstOffset;

	return etimems;
}

//------------------------------------
// OPENING NEW LINKS, ADS
//------------------------------------ 
function grabAd(type,name){
	param = '';
	if ( type == 'null' || type == null || name == 'undefined' || name == null || name == 'null' ){
		type = '';
		name = '';
	}
	if ( type != '' ){
		param = '?'+type+'='+name;
	}
	var url = 'http://sports.espn.go.com/espnradio/thisIsAnAd'+param;
	externalAd(url);
}

function openURL(url){
	var newWindowHeight = 500;
	var openedWindow = null;
	if(screen.availHeight){
		newWindowHeight = screen.availHeight;
	}
	var newWindowWidth = 1024;
	if(screen.availHeight && screen.availHeight<1024){
		newWindowWidth = screen.availHeight;
	}
	if(opener){
		try{
			openedWindow=opener.window.open(url);
		}
		catch (e) {
			window.open(url, 'newWindow', 'status=1,toolbar=1,location=1,menubar=1,directories=1,resizable=1,scrollbars=1,top=0,left=0,height='+newWindowHeight+',width='+newWindowWidth);
		}
	}
	else{
		try{
			openedWindow=window.open(url, 'newWindow', 'status=1,toolbar=1,location=1,menubar=1,directories=1,resizable=1,scrollbars=1,top=0,left=0,height='+newWindowHeight+',width='+newWindowWidth);
		}
		catch (e) {
			window.open(url, 'newWindow', 'status=1,toolbar=1,location=1,menubar=1,directories=1,resizable=1,scrollbars=1,top=0,left=0,height='+newWindowHeight+',width='+newWindowWidth);
		}
	}
	if(openedWindow){
		try{
			openedWindow.focus();
		}
		catch (e) {	}
	}
}

function externalAd(url){
	if ( url.indexOf('null') > -1 || url == null ){
		url = "http://sports.espn.go.com/espnradio/thisIsAnAd";
	}
	$("#adFrame").hide();
	$("#adFrame").attr({ src: url });
	$("#adFrame").fadeIn('slow');
}

//------------------------------------
// FUNCTIONS THAT TALK TO FLASH
//------------------------------------ 
function stopVideo(){
    getFlashMovie("stw_video").stopLiveVideo();
}

function setLiveVideoSkin(skin){
	skin = skin.replace('skin_', 'fullscreen_skin_');
	getFlashMovie("stw_video").setSkin(skin);
}

function stopStreaming() {
	try{
		getFlashMovie("streamingPlayer").callTurnOff();
		 log('Successfully turned off streaming with js call to flash.'); 
	} catch (e) {}
}

function setStreamVolume(vol) {
	stream_vol = vol;
	try{
		getFlashMovie("streamingPlayer").callSetStreamVolume(vol);
		 log('successfully set the volume with js call to flash'); 
	} catch (e) {}
}

function getStreamVolume() {
	return stream_vol;
}

function setPodcastVolume(vol) {
	podcast_vol = vol;
}

function getPodcastVolume() {
	return podcast_vol;
}

function hidepreroll(str){
	hidePrestitialTimeout = clearTimeout(hidePrestitialTimeout);
	populateStations('all', true, stationId);
	so.useDOM = true;
	so.targetElement = "webcamFrame";
	so.render(true);
	$('#prestitial').hide();
}

function showpreroll(str){
	$('#prest-table').attr({ border: "10" });
	prest.flashFile = "http://assets.espn.go.com/swf/espnradio/08/prestitial/prestitial_wgif.swf";
	prest.useDOM = true;
	prest.width = "450";
	prest.height = "358";
	prest.targetElement = "prest-home";
	prest.render(true);
	so.render(false);
	hidePrestitialTimeout = setTimeout("hidepreroll()",30000);
}

//------------------------------------
// TRACKING
//------------------------------------ 
function trackPageView(tab){
	//changeSAcct();
	if ( tab == 'live' ){
		if ( currentStation == 'chicago'){
			tab = 'espnradio1000:live';
			prop5 = 'stations:espnradio1000';
		} else if (currentStation == 'dallas'){
			tab = 'espn1033:live';
			prop5 = 'stations:espnradio1033';
		} else if (currentStation == 'la'){
			tab = '710espn:live';
			prop5 = 'stations:710espn';
		} else if (currentStation == 'nyc'){
			tab = '1050espnradio:live';
			prop5 = 'stations:1050espnradio';
		} else if (currentStation == 'pittsburgh'){
			tab = 'espnradio1250:live';
			prop5 = 'stations:espnradio1250';
		} else if (currentStation == 'espnradio'){
			tab = "live";
			prop5 = 'player';
		} else {
			tab = currentStation+':live';
			prop5 = 'player';
		}
	}
	try {
		anClearVars();
		s_omni.pageName="espnradio:espnradio:player:"+tab;
		s_omni.server = window.location.host;
		s_omni.channel = "espnradio";
		s_omni.prop1 = "espnradio";
		s_omni.prop5 = 'espnradio:'+prop5;
		s_omni.prop17 = "en";
		s_omni.prop25 = "none";
		s_omni.prop30 = "n";
		s_omni.hier1 = 'espnradio:'+prop5;
		var s_code=s_omni.t();if(s_code)document.write(s_code);
	} catch (e) {}
}
/*
function changeSAcct(){
	var new_account = "wdgespradio, wdgespcom";

	if ( currentStation == 'chicago' ){

		new_account="wdgespchicago";
		console.log('changing account');
	}
	s_omni.sa(new_account);
}
*/
//------------------------------------
// GENERIC HELPER FUNCTIONS
//------------------------------------ 
function getCurrentTab(){
	return currentTab;
}

function setCurrentTab(tab){
	currentTab = tab;
}

function log(err){
	try {
		/*console.log(err);*/
	} catch (e) {}
}
		
function toSt(n) {
	s="";
	if(n<10) s+="0";
	return s+n.toString();
}

function errorWithRequest(){
	$('#showThumb').hide();
	$('#showbox').hide();
	$('#loadingbox').html('Sorry, there was an error processing your request. Please try a different station or <a href="">refresh</a> the player<span id="dots_2"></span>');
	$('#loadingbox').show();
}

function stationsByState(){
	populateStations($('#states').val(), false, null);
}

function hideWebcams(){
	$('#scoreboard').show();
	$('#headlines').show();
	$('#webcamsTab').hide();
	$('#webnav').hide();
	$('#webcam_skin').hide();
}

function showWebcams(){
	$('#scoreboard').hide();
	$('#headlines').hide();
	$('#webcamsTab').show();
	$('#webnav').show();
	$('#webcam_skin').show();
}

function startScroll(direction, ivl){
	if (direction == "up"){
		y = -5 - ivl;
		document.getElementById("headlinesScroll").scrollTop += y;
	} else{
		y = 5 + ivl;
		document.getElementById("headlinesScroll").scrollTop += y;
	}
	newInterval = ivl + 1;
	var functionCall = "startScroll(\"" + direction + "\", " + newInterval + ")";
	scrollInterval = setTimeout(functionCall, 50);
	return false;
}

function endScroll(){
	if (scrollInterval != null){
		scrollInterval = clearTimeout(scrollInterval);
	}
	return false;
}

function rescaleApp(){
	window.resizeTo(masterWidth,masterHeight);
}

function flashUpgrade(){
	$('#help').html('Please click <a href="javascript:void(0);" onclick ="openURL(\'http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash\');">here</a> to upgrade your flash player.');
}

function addEvent(obj, evType, fn){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, false);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		return false;
	}
}

function getFlashMovie(flashObjName){
	if( window.document[flashObjName] ){
		return window.document[flashObjName];
	}
	if( navigator.appName.indexOf("Microsoft Internet") == -1 ){
		if( document.embeds&&document.embeds[flashObjName] ){
			return document.embeds[flashObjName];
		}
	} else {
		return document.getElementById(flashObjName);
	}
}