//code to gracefully handle errors
//todo: add logging
//function blockError(){return true;}
//window.onerror=blockError;
            
var URL='';
var state=0;
var position=0.0;
var player=null; //wmplayer
var p=null; //wmplayer.player
// set height and width if they have not been specified previously (allows calling script to override height and width)
if ( typeof( window[ 'width' ] ) == "undefined" ) {
    var width = 356;
    var height = 339;
}
var playcount=0;

function checkDownloadTime(url){
    starttime = new Date().getTime();
    speedtestImage.onload = ImageLoaded;
    speedtestImage.src = url;
}

function ImageLoaded(){
    endtime = new Date().getTime();
    usedtime = endtime-starttime;
}
            
function PluginCheck(name){

    for ( var i in  navigator.plugins ) {
        var n = navigator.plugins[i].name;
         //alert(n);
        if ( n != null && n.indexOf(name) >= 0 ) {
            return true;
        }

    }
    return false;
}    

function fullscreen(){
  if (p && p.playState==3) p.fullScreen=true;
}

            
function beforeunload()
{
	if (window.ActiveXObject && navigator.userAgent.indexOf('Windows') != -1){
			if (p) {
					state=p.PlayState;
					position=p.controls.currentposition;

				}
	}
	//else {
    newvideo('');
    window.onbeforeunload=null;
	//}
}
            
function resume(){
    if (window.ActiveXObject && navigator.userAgent.indexOf('Windows') != -1){
        if (p && state && state>2) {
		    p.controls.currentposition = position;
            p.controls.play();
        }
    }
}

window.onbeforeunload = beforeunload;

            
            
//reloads video and data for selected date/file
function newvideo(filename){
    if  (p) {
            player.stop();
	}
               
    //if (filename==null || filename=="") return;

    //hiorlow = (high!="false"?"H":"L");
    
    
    var pp = document.getElementById("playerparent");
    pp.innerHTML="";
    
    if (filename!=null && filename!="") {
		videosource=filename;
		URL=filename;
		player = new wmplayer(pp,URL,'wmplayer',width,height);
		p = player.wmplayer;
           
		/*
		if (window.ActiveXObject && navigator.userAgent.indexOf('Windows') != -1)
		{
			
			p.width = width;
			p.height = height;
			p.uiMode = "full";
			p.stretchToFit = "true";
			p.settings.setMode("autoRewind", "true");
			p.settings.setMode("showStatusBar", "true");
			p.settings.setMode("showFrame", "true");
			p.settings.autoStart="true";
			p.settings.enableErrorDialogs="false";
			player.load(URL);
			
			
		}
		//else {
			//   player = new wmplayer(pp,URL,'wmplayer',width,height);  
		//}
		*/
	} else {
        //if (typeof(p) != "undefined") { 
		//p.close();
		//}
	}
}
 
	

function wmplayer(p, filename, name, width, height) {

    if (!p) return;

    this.id = (name != undefined) ? name : "wmplayer";
    this.className = this.id;
    this.document = p.ownerDocument || p.document;
    this.container = p;
    this.container.player = this;
    this.ended = false;

    this.container.unselectable = "on";
    var html='';
    
    if (window.ActiveXObject && navigator.userAgent.indexOf('Windows') != -1 && navigator.userAgent.indexOf('MSIE') != -1)
    //IE on Windows
        {

        html = '<object width="' + width + '" height="' + height + '" id="' + this.id + 'control" ' +
        'classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" ' +
        'codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,1,52,701" ' + 
        'standby="Loading..." ' +
        'type="application/x-oleobject"> ' +
        '<param name="url" value="' + filename + '">' + 
        '<param name="FileName" value="' + filename + '">' + 
        '<param name="stretchtofit" value="true">' + 
        '<param name="autoStart" value="true">' + 
        '<param name="EnableContextMenu" value="true">' +
        '<param name="ShowStatusBar" value="true">' +
        '<param name="showFrame" value="true">' +
        '<param name="uiMode" value="full">' +
        '</object> ';
        
    }
    else if (navigator.userAgent.indexOf('Macintosh') !=-1 && navigator.userAgent.indexOf('Safari')!=-1)
    {
        /*if (PluginCheck('Flip4Mac')) {*/
         html =  '<embed type="video/x-ms-wmx" ' +
            'pluginspage="http://www.microsoft.com/windows/windowsmedia/player/wmcomponents.mspx" ' +
            'width="' + width + '" height="' + height + '" ' +
            'src="' + filename + '" filename="' + filename + '" ' +
            'allowembedtagoverrides="True"' +
            'bgcolor="#000000"' +
   	        'enablejavascript="True" ' +
	        'id="' + this.id + 'control" ' +
            'autoplay="True" scale="ASPECT"></embed>';
        /*}
        else {
        
         html='<br><br><p class="linkFeatureText">Please <a href="http://www.apple.com/downloads/macosx/video/flip4macwindowsmediacomponentsforquicktime.html" target="_blank" class="linkHelpText">' +
         'download the latest Flip4Mac<br> Plugin for Safari.</a><br>' +
         '(You will need to close and restart <br> Safari after installing the plugin)';
        }*/

        
    } 
    else if (navigator.userAgent.indexOf('Windows') != -1 && navigator.userAgent.indexOf('Firefox') != -1)
    //Windows-FireFox
    {
	
        if (PluginCheck('Windows Media Player Firefox')) {
         html = '<object type="application/x-ms-wmp" ' +
        'codebase="http://port25.technet.com/videos/downloads/wmpfirefoxplugin.exe" ' +
        'data="' + filename + 
        '" width="' + width + '" height="' + height + '">' +
        '<param name="URL" value="' + filename + '">' + 
        '<param name="stretchtofit" value="true">' + 
        '<param name="autoStart" value="true">' + 
        '<param name="EnableContextMenu" value="true">' +
        '<param name="ShowStatusBar" value="true">' +
        '<param name="showFrame" value="true">' +
        '<param name="uiMode" value="full">' +
        '</object> ';
        }
        else {
        
         html='<br><br><p class="linkFeatureText">Please <a href="http://port25.technet.com/pages/windows-media-player-firefox-plugin-download.aspx" target="_blank" class="linkHelpText">' +
         'download the latest Windows Media Player<br> Plugin for FireFox.</a><br>' +
         '(You will need to close and restart <br> Firefox after installing the plugin)';
        }

    }
    else
    {
   	     html =  '<embed type="application/x-mplayer2" ' +
        'pluginspage="http://www.microsoft.com/Windows/Downloads/Contents/MediaPlayer/" ' +
        'width="' + width + '" height="' + height + '" ' +
        'src="' + filename + '" filename="' + filename + '" ' +
	    'enablejavascript="true" ' +
	    'id="' + this.id + 'control" ' +
	    'name="' + this.id + 'control" ' +
        'autostart="True" showcontrols="True" showstatusbar="1" showstatusbar="True" showdisplay="False" autorewind="True" scale="ASPECT"></embed>';
    }
   
    this.container.innerHTML = html;
    this.wmplayer = this.document.getElementById(this.id+"control");
    
    /*
    this.ponlybutton = this.document.createElement("DIV");
    this.ponlybutton.className = "playeronlybutton";
    this.ponlybutton.unselectable = "on";
    this.container.appendChild(this.ponlybutton);
    */
    if (window.ActiveXObject && navigator.userAgent.indexOf('Windows') != -1 && navigator.userAgent.indexOf('MSIE') != -1)
    {
        this.wmplayer.attachEvent("playstatechange",this.eventHandlers.playStateChanged);
    }
    playcount++;
       
}

//Prototype code
player = wmplayer.prototype;
player.className = "player_control";


//Methods
player.load =function(v){
    alert("loading");
    player.wmplayer.URL = v;
}

player.stop =function(){
    if (navigator.userAgent.indexOf('Macintosh') !=-1 ){
		    //wmplayercontrol.Stop();
    }
    else if (player.wmplayer.controls) {
      	    player.wmplayer.controls.stop();
    }
}
        
player.eventHandlers = {
   playStateChanged: function (v) {
   
        
        var fullscreenbutton = document.getElementById('fullscreenimage');
        if (!fullscreenbutton){
               var fullscreenbutton = document.getElementById('fullscreenimage_disabled'); 
        }
        
      if (fullscreenbutton){
       if (v==3 ){
                        fullscreenbutton.id = 'fullscreenimage';
        }
        else  
        {
                        fullscreenbutton.id = 'fullscreenimage_disabled';
        }
       }         
   }
}


var highorlow = 'm';
cookieval = getCookie("PlayerSettings");
if (cookieval) {
    highorlow=cookieval.replace('bandwidth=',''); //replace to  handle legacy format
}

function changebandwidth(sSpeed){
    // sSpeed = h or l
    highorlow=sSpeed; //highorlow=='h'?'l':'h');
    videoURL = URL;
    // are we viewing a live channel?
    if  (videoURL.indexOf("/cbn_iptv") >=0) {
        // we are viewing Limelight's CDN for the live channels
        // 1. remove any existing bitrate parameter
        // 2. add the new bitrate parameter
        videoURL= URL.replace(/(\?WMBitrate=\d+)+/, '');
        videoURL= videoURL.replace(/(\?wmbitrate=\d+)+/, '');
        switch (sSpeed) {
            case "m":
                 videoURL = videoURL + '?WMBitrate=500000';
                 break;
            case "l":
                 videoURL = videoURL + '?WMBitrate=200000';        
                 break;
            case 'h':
            default:
                // leave as is without a parameter
        }
    } else if  ((videoURL.indexOf("/cbn_live1") >=0) || (videoURL.indexOf("/cbn-newslive") >=0)) {
        // we are viewing Limelight's CDN for the Live Club or Live News
        // 1. remove any existing bitrate parameter
        // 2. add the new bitrate parameter
        videoURL= URL.replace(/(\?wmbitrate=\d+)+/, '');
        switch (sSpeed) {
            case "m":
                 videoURL = videoURL + '?wmbitrate=500000';
                 break;
            case "l":
                 videoURL = videoURL + '?wmbitrate=200000';        
                 break;
            case 'h':
            default:
                // leave as is without a parameter
        }
    } else {
        // we are viewing a video on demand
        if (sSpeed=='m'){
            videoURL = URL.replace(/_[hH]?[lL]?\.wmv(\?WMBitrate=500000)?/, '_H.wmv?WMBitrate=500000'); 
         } else{
            videoURL = URL.replace(/_[hH]?[lL]?\.wmv(\?WMBitrate=500000)?/, '_' + highorlow.toUpperCase() + '.wmv');
         }
    }
    // do we need to add the prefix to the video
    if (videoURL.indexOf("http://www.cbn.com/media/asx.aspx?VideoPath=") < 0) {
        videoURL = 'http://www.cbn.com/media/asx.aspx?VideoPath=' + videoURL;
    }
    newvideo(videoURL);
    setCookie("PlayerSettings",highorlow,365 );
   
}

function getURL(data){
    // function that is executed once the ajax has returned the formatted link to the video
    // alert("VideoUrlProcessor: " + data);
    // play the video
    newvideo(data);
}


          
function loadvideo(s, b, a, ad){

    if (!b || b=='') b=highorlow;
    if (!a) a='';
    if (!ad) ad='';
            
    var cdata = new ajaxdata("counter.aspx?s=" + s + "&" + timestamp());
    cdata.getData(); 
    var sPageQuery = "VideoURLProcessor.aspx?s=" + s + "&b=" + b + "&a=" + a + "&ad=" + ad
    var adata = new ajaxdata(sPageQuery);
    adata.getData("getURL"); 
}





