var playerElement;

var jsReady = false;

var videoSkinPresent = false;

function isJSReady() {
	return jsReady; 	
}

function isReady() {
	return jsReady;
}

function setJSReady() { 
	jsReady = true;
}

function onCBSIPlayerReady(playerId) {
	var playerElementLocal = document.getElementById(playerId);
	if (playerElementLocal) {
   	    playerElementLocal.addEventJSCallback('onContentStart_cbsi', 'onContentStarted');
		playerElementLocal.addEventJSCallback('onContentEnd_cbsi', 'onContentEnded');
		playerElementLocal.addEventJSCallback("onAdResourcesInfo", "onAdResourcesInfo");
	}
}

function getAdScript(playerId){
	playerElementLocal = document.getElementById(playerId);
	if (playerElementLocal) {
		return playerElementLocal.getAdScript();
	} 
}
		
function setAdScriptURLPage (scriptSource) {
	dhtmlLoadScript(scriptSource);
}

function dhtmlLoadScript(url) {
	var e = document.createElement("script");
	e.src = url;
	e.type="text/javascript";
	document.getElementsByTagName("head")[0].appendChild(e);
}


function onContentStarted(playerId){
	if($("joinSocialRoom")){
		if (!videoSkinPresent) {
			$("joinSocialRoom").show();
		}
	}
}

function onContentEnded(){
	if($("joinSocialRoom")){
		$("joinSocialRoom").hide();
	}
}

function getCompanionAdInfoBySize(w, h, playerId){
	playerElementLocal = document.getElementById(playerId);
	if (playerElementLocal) {
		return playerElementLocal.getCompanionAdInfoBySize(w, h);
	}
}

function getCompanionAdInfo(playerId){
	playerElementLocal = document.getElementById(playerId);
	if (playerElementLocal) {
		return playerElementLocal.getCompanionAdInfo();
	}
}


//set preferred ad type for the page - this will normally be swf.
var preferredAdType = 'swf';

function selectPreferredAd(adArray) {
	
	for (i=0; i<adArray.length; i++) {
		var ad = new Array();
		ad[i] = adArray[i];
	}
	
	if (ad.length > 1) {
		adFiltered = ad.compact(); //compacting the ad array to clean up undefined ad slots
		
		//looping through the compacted ad array to find an ad slot with a preferred ad type, swf or img.
		for (i=0; i<adFiltered.length; i++) {
			if (adFiltered[i][2] == preferredAdType) {
				var adPref = adFiltered[i]	
			} else {
				var adPref = adFiltered[0] //if preferred type is not found, use first ad slot (normally img)
			}
		}
		
	} else {
		
		var adPref = ad[0] //use first ad slot if only one ad slot is available.
		
	}
	
	return adPref;
	
}

function onAdResourcesInfo(params, playerId){
	
	var adScript = getAdScript(playerId);
	if (adScript != null && adScript != "" ){
		playerElement = document.getElementById(playerId);
		setAdScriptURLPage(adScript);
	}
	
	var ads = getCompanionAdInfoBySize(300,60,playerId);
	var ads2 = getCompanionAdInfoBySize(300,250,playerId);
	var ads3 = getCompanionAdInfoBySize(985,90,playerId);
	var ads4 = getCompanionAdInfoBySize(985,130,playerId);
	
	if (ads.length > 0 ) {
		var ad = selectPreferredAd(ads);
		if (ad[3].length > 0) {
			insertTrackingPixel(ad[3])
		}
		setCompanionAd(ad[0],ad[1],ad[2],'300','60');
	} else {
		clearCompanionAd('300','60');
	}
	
	if (ads2.length > 0 ) {
		var ad2 = selectPreferredAd(ads2);
		if (ad2[3].length > 0) {
			insertTrackingPixel(ad2[3])
		}
		setCompanionAd(ad2[0],ad2[1],ad2[2],'300','250');
	} else {
		clearCompanionAd('300','250');
	}
	
	if (ads3.length > 0 ) {
		var ad3 = selectPreferredAd(ads3);
		if (ad3[3].length > 0) {
			insertTrackingPixel(ad3[3])
		}
		videoSkinPresent = true;
		$('centeredPlayerWrapper').setStyle({backgroundColor : '#000'});
		setCompanionAd(ad3[0],ad3[1],ad3[2],'985','90');
	} else {
		videoSkinPresent = false;
		clearCompanionAd('985','90');
	}
	
	if (ads4.length > 0 ) {
		var ad4 = selectPreferredAd(ads4);
		if (ad4[3].length > 0) {
			insertTrackingPixel(ad4[3])
		}
		$('centeredPlayerWrapper').setStyle({backgroundColor : '#000'});
		setCompanionAd(ad4[0],ad4[1],ad4[2],'985','130');
	} else {
		clearCompanionAd('985','130');
	}
	 
}

function insertTrackingPixel(trackingPixelsArray) {
	for (i=0;i<trackingPixelsArray.length;i++) {
		if (trackingPixelsArray[i]!='') {
			$('page').insert('<img src="' + trackingPixelsArray[i] + '" width="1" height="1" border="0" style="position:absolute; bottom:0; right:0"/>')
		}
	}
}

function setCompanionAd (strSource, strLink, strType, strWidth, strHeight)  {

	var containerId = 'ad' + strWidth + 'x' + strHeight;
	
	var adLabelHTML = '';
	
	if ((strWidth == '300')&&(strHeight == '250')) {
		containerId = 'ad2';
		adLabelHTML = '<p>Advertisement</p>';
	}
	
	if ((strWidth == '300')&&(strHeight == '60')) {
		adLabelHTML = '<p>Advertisement</p>';
	}

	if (strType == 'img') {
		if ($(containerId) != null) {
			if (strLink != '') {
				$(containerId).update(adLabelHTML + '<a href="'+ strLink +'" target="_blank"><img src="'+ strSource +'" border="0" width="' + strWidth + '" height="'+ strHeight +'" /></a>');
			} else {
				$(containerId).update('<img src="'+ strSource +'" border="0" width="' + strWidth + '" height="'+ strHeight +'" />');
			}
			$(containerId).show()
		}
	}
	else if (strType == 'swf') {
		
		swfContainerId = 'swfAdContainer'+ strWidth +'x' + strHeight;
		
		if ($(containerId) != null) {
			$(containerId).update(adLabelHTML + '<div id="'+ swfContainerId +'"></div>');
			var so = new SWFObject(strSource, swfContainerId, strWidth, strHeight, "6", "#000000");
			so.addParam("quality", "high");
			so.addParam("scale", "noscale");
			so.addParam("menu", "false");
			so.addParam("salign", "tl");
			so.addParam("allowScriptAccess", "always");
			so.addParam("wmode", "transparent");
			so.addVariable("clickTag", strLink);
			so.write(swfContainerId);
			$(containerId).show()
		}
	}

}

function clearCompanionAd (strWidth, strHeight)  {

	var containerId = 'ad' + strWidth + 'x' + strHeight;
	
	if ((strWidth == '300')&&(strHeight == '250')) {
		containerId = 'ad2'
	}

	if ($(containerId) != null) {
		$(containerId).update();
		$(containerId).hide();
	}
	
	$('centeredPlayerWrapper').setStyle({backgroundColor : 'transparent'});

}


/*bc support functions*/
var pauseInterval;

function pauseHelper() {
	if (playerState == '1') {
		playerElement.htmlForcePause();
		if (playerState == '2') {
			clearInterval(pauseInterval);
		}
	}
}

function publisherPlayerPause() {
	if (playerElement) {
		try
		{
			playerElement.exitFullScreen();
		}
		catch(err)
		{
		}
		playerElement.htmlForcePause();
		if (playerState != '2') {
			pauseInterval = setInterval("pauseHelper()", 1000);
		}
	}
}


function publisherPlayerResume(){
	clearInterval(pauseInterval);
    if (playerElement) {
        playerElement.htmlReleasePause();
    }
}

function publisherPlayerGetContentDuration () {
	if (playerElement) {
		return playerElement.getContentDuration();
	}
}

function onCanPlayerStateChange(newState) {
	setCanPlayerState(newState);
}

var playerState = "";

function setCanPlayerState(newState) {
	playerState = newState;
}

/*END bc support functions*/



/* player embed support functions */

function getPreviewImageURL(pid) {
	var strResponse = '';
	new Ajax.Request('http://www.cbs.com/sitecommon/includes/video/qvf_metadata.php',
   {
	asynchronous: false,   
    method:'get',
	parameters: {pid:pid, getPreviewImageURL:'yes'},
    onSuccess: function(transport){
     strResponse = transport.responseText || "no response text";

    }
	
  });
	
	return strResponse;
}

function getVideoPageURL(pid) {
	var strResponse = '';
	new Ajax.Request('http://www.cbs.com/sitecommon/includes/video/qvf_metadata.php',
   {
	asynchronous: false,   
    method:'get',
	parameters: {pid:pid, getVideoPageURL:'yes'},
    onSuccess: function(transport){
     strResponse = transport.responseText || "no response text";
    }
  });
	return strResponse;
}

var strInitTime = '';

function cbsEmbedVideo (videoEmbedParams) {
	
	//var previewImageURL = getPreviewImageURL(pid);
	var videoPageURL = getVideoPageURL(videoEmbedParams.pid);
	
	var strTime = new Date().getTime();
	
	if ((videoEmbedParams.pid == '')||(typeof(videoEmbedParams.pid) == 'undefined')) alert('You must specify a pid!');
	if ((videoEmbedParams.autoPlay == '')||(typeof(videoEmbedParams.autoPlay) == 'undefined')) videoEmbedParams.autoPlay = 'false';
	if ((videoEmbedParams.playerWidth == '')||(typeof(videoEmbedParams.playerWidth) == 'undefined')) videoEmbedParams.playerWidth = '640';
	if ((videoEmbedParams.playerHeight == '')||(typeof(videoEmbedParams.playerHeight) == 'undefined')) videoEmbedParams.playerHeight = '360';
	if (typeof(videoEmbedParams.previewImage) == 'undefined') previewImage = '';
	if ((videoEmbedParams.playerURL == '')||(typeof(videoEmbedParams.playerURL) == 'undefined')) videoEmbedParams.playerURL = 'http://www.cbs.com/thunder/player/1_0/partner/cbs/cbs.swf';
	if ((videoEmbedParams.partner == '')||(typeof(videoEmbedParams.partner) == 'undefined')) videoEmbedParams.partner = 'cbs';
	if (typeof(videoEmbedParams.parentDivId) == 'undefined') videoEmbedParams.parentDivId = '';
	if ((videoEmbedParams.replacePlayer == '')||(typeof(videoEmbedParams.replacePlayer) == 'undefined')) videoEmbedParams.replacePlayer = 'no';
	if ((videoEmbedParams.parentDivId!='')&&(strInitTime == '')) strInitTime = strTime;
	
	var soVideo = new SWFObject(videoEmbedParams.playerURL + "?t=" + strTime, "rcpHolder" + strTime, videoEmbedParams.playerWidth, videoEmbedParams.playerHeight, "9", "#000000");
	
	//soVideo.addVariable("prevImg", escape(previewImageURL));
	if (videoEmbedParams.previewImage!='') soVideo.addVariable("prevImg", escape(videoEmbedParams.previewImage));	
	soVideo.addParam("quality", "high");
	soVideo.addParam("scale", "noscale");
	soVideo.addParam("menu", "true");
	soVideo.addParam("salign", "tl");
	soVideo.addParam("allowScriptAccess", "always");
	soVideo.addParam("wmode", "opaque");
	soVideo.addParam("allowFullScreen", "true");
	soVideo.addVariable("autoPlayVid", videoEmbedParams.autoPlay);
	soVideo.addVariable("link", escape("http://"+ document.location.host + videoPageURL));
	soVideo.addVariable("pid", videoEmbedParams.pid);
	soVideo.addVariable("partner", videoEmbedParams.partner);
	if ((videoEmbedParams.configXML != '')&&(typeof(videoEmbedParams.configXML) != 'undefined')) soVideo.addVariable("config", videoEmbedParams.configXML);
	
	if (videoEmbedParams.replacePlayer == 'yes') {
		embedPlayer(soVideo, videoEmbedParams.parentDivId, strInitTime)
	} else {
		embedPlayer(soVideo, videoEmbedParams.parentDivId, strTime)
	}
}

function embedPlayer(playerObj, parentDivId, strTime) {
	
	if (jsReady == false) setJSReady();
	
	if ((parentDivId != '')&&(typeof(parentDivId) != 'undefined')) {
		
			if (!$(parentDivId + 'PlayerDiv' + strTime)) {
				$(parentDivId).insert('<div id="' + parentDivId + 'PlayerDiv' + strTime + '"></div>');
			}

	} else {
		
		document.write('<div id="' + parentDivId + 'PlayerDiv' + strTime + '"></div>')
		
	}
	
	playerObj.write(parentDivId + "PlayerDiv" + strTime);

	
}

/* END player embed support functions */