var msie = false;
var cnnPlayStateOn = true;
var cnnForwardStateOn = false;
var cnnReverseStateOn = false;
var isLiveStream = false;
var cnnFlip4mac = false;

function cnnSetBrowser() {
	var agent = navigator.userAgent.toLowerCase();
	if(agent.indexOf('msie')>-1) msie = true;
	//if(window.GeckoActiveXObject) msie = true;

        var wmvPlugins = Plugin.getPluginsForMimeType("video/x-ms-wmv");
        //alert("wmvPlugins " + wmvPlugins);
        if (wmvPlugins) {
            if (wmvPlugins.length >= 0) {
                cnnFlip4mac = wmvPlugins[0].indexOf("Flip4Mac") != -1;
                //alert("flip4mac [" + cnnFlip4mac + "]");
            }
        }
}

function cnnSetVolume() {
	var volume = parent.cnnVideoVolume*6;
	document.getElementById('cnnVideoVolumeBottom').style.width=volume + 'px';
	document.cnnMediaPlayer.settings.volume = parent.cnnVideoVolume*12; 
}

function cnnSetDurationBar() {
	var current = Math.floor(document.cnnMediaPlayer.controls.CurrentPosition) || 0;
	var total = Math.floor(document.cnnMediaPlayer.currentMedia.duration) || 0;
	var time = document.cnnMediaPlayer.controls.CurrentPositionString || '';
	if(total != 0 && current != 0) {
		document.getElementById('cnnVideoPlayheadBottom').style.width = Math.round( (current/total)*100);
		}
	document.getElementById('cnnVideoPlayheadTime').innerHTML = time;
	self.setTimeout('cnnSetDurationBar()',1000);
}

function cnnAdjustVolume(up) {
	if(up) {
		if(parent.cnnVideoVolume<12) parent.cnnVideoVolume++;
		
	} else {
		if(parent.cnnVideoVolume>0) parent.cnnVideoVolume--;
	}
	parent.cnnMuteStateOn = false;
	cnnSetVolume();
}

function cnnLoadVolume() {
	if(parent.cnnMuteStateOn) {
		document.getElementById('cnnVideoVolumeBottom').style.width='0px';
	} else {
		cnnSetVolume();
	}
}

function cnnMute() {
	parent.cnnMuteStateOn = !parent.cnnMuteStateOn;
	document.cnnMediaPlayer.settings.mute = parent.cnnMuteStateOn;
	cnnLoadVolume();
}

function cnnPlay() {
	if(cnnPlayStateOn && !isLiveStream) {
		document.cnnMediaPlayer.controls.Pause();
		cnnPlayStateOn = false;
		document.getElementById('cnnVideoPlay').className='play';
	} else {
		document.cnnMediaPlayer.controls.Play();
		cnnPlayStateOn = true;
		if(!isLiveStream) {
		document.getElementById('cnnVideoPlay').className='pause';
		}
	}
}

function cnnScan(forward) {
	if(!cnnPlayStateOn) {
		cnnPlay();
	}
	if(forward) {
		if(cnnForwardStateOn) {
			document.cnnMediaPlayer.controls.play();
		} else {
			document.cnnMediaPlayer.controls.FastForward();	
		}
		cnnForwardStateOn = !cnnForwardStateOn;
	} else {
		if(cnnReverseStateOn) {
			document.cnnMediaPlayer.controls.play();
		} else {
			document.cnnMediaPlayer.controls.FastReverse();	
		}
		cnnReverseStateOn = !cnnReverseStateOn;
	}
}

function cnnStop() {
	document.cnnMediaPlayer.controls.Stop();
	cnnPlayStateOn = false;
	document.getElementById('cnnVideoPlay').className='play';
	//parent.cnnLoadVideo('content/video/standby');
}

function cnnPlayLiveVideo(url) {
	isLiveStream = true;
	cnnLoadVideo(url);
}

function cnnPlayVideo(url) {
	isLiveStream = false;
	cnnLoadVideo(url);
}

function CNN_getCookies() {
	//alert("'document.cookie': " + document.cookie);
        var hash = new Array;
        if ( document.cookie ) {
                var cookies = document.cookie.split( '; ' );
                for ( var i = 0; i < cookies.length; i++ ) {
                        var namevaluePairs = cookies[i].split( '=' );
                        hash[namevaluePairs[0]] = unescape( namevaluePairs[1] ) || null;
                }
        }
        return hash;
}



// _____________________________________________________________ WebMonkey code
/*
WM_setCookie(), WM_readCookie(), WM_killCookie()
A set of functions that eases the pain of using cookies.

Source: Webmonkey Code Library
(http://www.hotwired.com/webmonkey/javascript/code_library/)

Author: Nadav Savio
*/

// This next little bit of code tests whether the user accepts cookies.
function WM_browserAcceptsCookies() {
	var WM_acceptsCookies = false;
	if ( document.cookie == '' ) {
		document.cookie = 'WM_acceptsCookies=yes'; // Try to set a cookie.
		if ( document.cookie.indexOf( 'WM_acceptsCookies=yes' ) != -1 ) {
			WM_acceptsCookies = true;
		} // If it succeeds, set variable
	} else { // there was already a cookie
		WM_acceptsCookies = true;
	}
	
	return ( WM_acceptsCookies );
}

function WM_setCookie( name, value, hours, path, domain, secure ) {
	if ( WM_browserAcceptsCookies() ) { // Don't waste your time if the browser doesn't accept cookies.
		var numHours = 0;
		var not_NN2 = ( navigator && navigator.appName
					&& (navigator.appName == 'Netscape')
					&& navigator.appVersion
					&& (parseInt(navigator.appVersion) == 2) ) ? false : true;

		if ( hours && not_NN2 ) { // NN2 cannot handle Dates, so skip this part
			if ( (typeof(hours) == 'string') && Date.parse(hours) ) { // already a Date string
				numHours = hours;
			} else if ( typeof(hours) == 'number' ) { // calculate Date from number of hours
				numHours = ( new Date((new Date()).getTime() + hours*3600000) ).toGMTString();
			}
		}
		
		document.cookie = name + '=' + escape(value) + ((numHours)?(';expires=' + numHours):'') + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:'') + ((secure && (secure == true))?'; secure':''); // Set the cookie, adding any parameters that were specified.
	}
} // WM_setCookie

function WM_readCookie( name ) {
	if ( document.cookie == '' ) { // there's no cookie, so go no further
	    return false;
	} else { // there is a cookie
	    var firstChar, lastChar;
		var theBigCookie = document.cookie;
		firstChar = theBigCookie.indexOf(name);	// find the start of 'name'
		var NN2Hack = firstChar + name.length;
		if ( (firstChar != -1) && (theBigCookie.charAt(NN2Hack) == '=') ) { // if you found the cookie
			firstChar += name.length + 1; // skip 'name' and '='
			lastChar = theBigCookie.indexOf(';', firstChar); // Find the end of the value string (i.e. the next ';').
			if (lastChar == -1) lastChar = theBigCookie.length;
			return unescape( theBigCookie.substring(firstChar, lastChar) );
		} else { // If there was no cookie of that name, return false.
			return false;
		}
	}	
} // WM_readCookie

function WM_killCookie( name, path, domain ) {
	var theValue = WM_readCookie( name ); // We need the value to kill the cookie
	if ( theValue ) {
		document.cookie = name + '=' + theValue + '; expires=Fri, 13-Apr-1970 00:00:00 GMT' + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:''); // set an already-expired cookie
	}
} // WM_killCookie

function cnnLoadVideo(url) {

        if (url.indexOf("http://") == -1) {
            // missing protocol, domain, port
            url = "http://" + location.host + url;
        }

        var nsfg = WM_readCookie('nsfg');
        if (!nsfg) {
            nsfg = "";
        }

        var cnnid = WM_readCookie('CNNid');
        if (!cnnid) {
            cnnid = "";
        }

        url += "?nsfg=" + nsfg + "&CNNid=" + cnnid;

//alert("url=" + url);
//alert("?nsfg=" + nsfg + "&CNNid=" + cnnid);

	cnnSetBrowser();
	var videoString = "";
	if(msie) {
        videoString += '<OBJECT ID="cnnMediaPlayer" height="260" width="464" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" MAYSCRIPT>';
        videoString += '  <PARAM name="URL" value="'+url+'"/>';
        videoString += '  <PARAM NAME="uiMode" VALUE="none"/>';
        videoString += '  <PARAM NAME="enableContextMenu" value="false" />';
        videoString += '  <param name="windowlessVideo" value="false"/>';      

if (parent.cnnMuteStateOn) {
        videoString += '  <param name="volume" value="0"/>';
}


        videoString += '</OBJECT>';
	videoString +='<div id="cnnVideoControls">\n';
	if(!isLiveStream) {
	videoString +='<a id="cnnVideoRewind" onClick="cnnScan(false);"></a>\n';
	}
	videoString +='<div id="cnnVideoPlayhead"><div id="cnnVideoPlayheadTop"></div><img id="cnnVideoPlayheadBottom" src="http://i.a.cnn.net/cnn/video/portable/images/video/playhead_bottom.gif" /><div id="cnnVideoPlayheadTime">00:00</div></div>\n';
	if(!isLiveStream) {
	videoString +='<a id="cnnVideoForward" onClick="cnnScan(true);"></a>\n';
	}
	if(isLiveStream) {
	videoString +='<a id="cnnVideoPlay" class="play" onClick="cnnPlay();"></a>\n';
	} else {
	videoString +='<a id="cnnVideoPlay" class="pause" onClick="cnnPlay();"></a>\n';
	}
	videoString +='<a id="cnnVideoStop" onClick="cnnStop();"></a>\n';
	videoString +='<a id="cnnVideoMute" onClick="cnnMute();"></a>\n';
	videoString +='<div id="cnnVideoVolume"><div id="cnnVideoVolumeTop"></div><img id="cnnVideoVolumeBottom" src="http://i.a.cnn.net/cnn/video/portable/images/video/volume_bottom.gif" /></div>\n';
	videoString +='<a id="cnnVideoSoundUp" onClick="cnnAdjustVolume(true);"></a>\n';
	videoString +='<a id="cnnVideoSoundDown" onClick="cnnAdjustVolume(false);"></a>\n';
	videoString +='</div>\n';
	videoString +='<div id="cnnVideoControlsBlank"></div>\n';
        
/*
        videoString +='<script for="cnnMediaPlayer" event="PlayStateChange(newState)">\n';
        videoString +='alert("!!");\n';
        videoString +='if (typeof(newState) != "undefined") {\n';
        videoString +='if (newState == 1) {\n';
        videoString +='alert("video has stopped (by user or end of stream)");\n';
        videoString +='}\n';
        videoString +='if ((newState == 1) && (cnnSalesVideoPlaying)) {\n';
        videoString +='alert("reload the frameset with landing page");\n';
        videoString +='}\n';
        videoString +='}\n';
        videoString +='</script>\n';
*/

	} 


        else {
            if (cnnFlip4mac) {
                videoString +='<OBJECT ID="cnnMediaPlayer" WIDTH=464 HEIGHT=280\n';
            } else {
                videoString +='<OBJECT ID="cnnMediaPlayer" WIDTH=464 HEIGHT=330\n';
            }

	videoString +='CLASSID="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95\n"'; 
	videoString +='STANDBY="Loading Windows Media Player components..."\n'; 
	videoString +='TYPE="application/x-oleobject">\n'; 
	videoString +='<PARAM NAME="FileName" VALUE="' + url + '">\n';
	videoString +='<param name="ShowStatusBar" value="true">\n'; 
	videoString +='<EMBED TYPE="application/x-mplayer2"\n'; 
	videoString +='SRC="' + url + '"\n'; 
        videoString +='NAME="cnnMediaPlayer"\n';
            if (cnnFlip4mac) {
        videoString +='HEIGHT=280\n';
            } else {
        videoString +='HEIGHT=330\n';
            }
        videoString +='WIDTH=464\n';
	videoString +='HEIGHT=330\n'; 
	videoString +='showstatusbar="1">\n'; 
	videoString +='</EMBED>\n'; 
	videoString +='</OBJECT>\n';
	}
	document.write(videoString);
//alert(videoString);
	if(msie) {
		cnnLoadVolume();
		cnnSetDurationBar();
	}
}
