var cnnActivePlayer = null;
var cnnPlayers = [];
var cnnCheckForExpired = false;

/**
 * Expand video tries to expand. If it cannot find the playerDiv, then it inserts the player.
 */
function expandVideo(index)
{
	if(typeof(storyVidPlayers) == 'undefined') {

		var id = 'player'+index;

		//if player div is found, then expand it
		if($(id)) {
			try { $(id).contentWindow.expandVideo(); }
			catch(e){}
		}
		else {
			//if div not found, then insert it
			if($('vid'+index)) { insertPlayer(index, ('vid'+index)); }
		}
	}
}

/**
 * Pulls the video config for a player
 */
function getVidConfig(index) { return vidConfig[index]; }

/**
 * Recursively displays the vids' titles and attaches a click event
 */
function loadVidTitles(x) {
	if (x == null)x=0;
	if( $("vid"+x+"Title") ) {
		//show this vid div
		if( $("vid"+x+"Title").style.display=="none" ) $("vid"+x+"Title").style.display="";
		Event.observe("vid"+x+"Title", 'click', function(event){ expandVideo(x); Event.stop(event); } );
		loadVidTitles(++x);
	}
	else {
		return false;
	}
}

/**
 * Begins the video
 */
function initializeVideo()
{
	//assume that all videos are collapsed from the start
	var setLazyLoad = false;

	//display video titles and attach click events to them
	loadVidTitles();

	/*For Loop finds valid videos + determines if lazyloading should take place
		1) If a story has a non-collapsed video, it should lazyload the video.
		2) if a story has one collapsed video and one non-collapsed video, only the non-collapsed video should lazyload.
		3) If a story only has collapsed videos, there should be no lazyloading at all.*/
	for(var i = 0; i < vidConfig.length; i++) {
		//clear out expired videos
		var jsonList = [];
		for(var j = 0; j < vidConfig[i].videoArray.length; j++) {
			if(isVideoExpired(vidConfig[i].videoArray[j]) == false) {
				jsonList.push(vidConfig[i].videoArray[j]);
			}
		}
		vidConfig[i].videoArray = jsonList;
		//if valid videos to play
		if(vidConfig[i].videoArray.length > 0) {
			if(vidConfig[i].collapsed != true) {
				setLazyLoad = true;
				if($('vid'+i)) {
					//if effects.js is not included, just insert the player without lazyloading
					if( (typeof storyVidPlayers== 'undefined') || (storyVidPlayers.length == 0 ) ) {
						try{ insertPlayer(i, ('vid'+i)); }catch(e){ Effect.Fade($('vid'+x+'title')); }
					}
				}
			}
		}
		//no valid videos to play
		else {
			$("vid"+i+"Title").getElementsByTagName("span")[3].innerHTML = "This video is no longer available.";
			$("vid"+i+"Title").addClassName('expired');
			Effect.Fade( $("vid"+i+"Title"),{ duration: 1.5 });
		}
	}  //end of for-loop

	if( (typeof storyVidPlayers != 'undefined') && (storyVidPlayers.length > 0 ) && ( setLazyLoad == true ) ) {
		//videos will be loaded when the screen has been paint
		var loadVideos = new PaintScreen().init();
	}

}

/**
 * Inserts player into target div
 */
function insertPlayer(index, videoTargetDivId)
{
	//generate random so we dont cache.
	//TODO:
	// - check to see if we need this random hack
	var rnd = Math.floor(Math.random()*101010101);

	//player iframe
	var str = '<iframe id="player'+index+'" src="/.element/ssi/video/3.0/story.player.html?p='+index+'&d='+(rnd)+'" width="384" height="272" frameborder="0" scrolling="no"></iframe>';

	//show the player div
	$('vid'+index).show();

	//hide the inline story div
	if( (typeof storyVidPlayers!= 'undefined') && (storyVidPlayers.length > 0) ) {
		$('vid'+i+'Title').addClassName('collapsed');
	}
	else {
		$('vid'+index+'Title').hide();
	}

	//insert player iframe into div
	$(videoTargetDivId).update(str);

	//Register cnn player
	cnnPlayers[index] = index;
}

/**
 *
 */
function isVideoExpired(jsonId)
{
	if(!cnnCheckForExpired) { return false; }

	var root = location.protocol+ "//" +location.hostname + ((location.port == '') ? ('') : (':'+location.port) )
	var videoRoot = '/video/data/2.0';
	var videoURI = root + videoRoot + jsonId;

	var conn = getXMLHTTPRequest();
	if(conn == null) { return true; }

	conn.open("GET", videoURI, false);
	conn.send(null);

	try { eval('var data = ' +conn.responseText); }
	catch(e) { return true; }

	if(data.isExpired == 'Expired') { return true; }

	return false;
}

/**
 * Sets the current player as active. Pausing all other players
 */
function setActivePlayer(index)
{
	for(var i = 0; i < cnnPlayers.length; i++) {
		if(cnnPlayers[i] == index) { continue; }
		try { $('player'+cnnPlayers[i]).contentWindow.pausePlayer(); }
		catch(e){}
	}
}

/*Start the First Video*/
function rewind2zero()
{
	CNNPlaylistManager.getInstance().advanceTo(CNNPlaylistManager.getInstance().activePlaylist, 0);
}