var player = null;
var currentItem = 0;
var previousItem = -1;
var selectedIndexInPlaylist;
var myPlaylistFileSuffix = 'playlist.asx';
var currentPlaylist;
var pausedProgrammatically;
var currentState;
var isNewFileLoaded;
var previouslyPlayedVideo;
var startPlaying;
var previousRowClass;
var previousPlayingImg;
var isNextOrPrevious = false;
var requiredMajor = '9';
var requiredMinor = '0';
var requriedRelease = '115';

function playerReady(thePlayer) {
    player = window.document[thePlayer.id];
    addListeners();
    if (playlistNeedsModification() && selectedIndexInPlaylist != undefined) {
        playFileOfPlaylist(0);
    }
    else {
        setMetaData(0);
    }
}
function createPlayer(theFile) {
            if(player==undefined)
            {
                var flashvars = {
                    'file': theFile,
                    'autostart': "false",
                    'shuffle': "false",
                    'playlistsize': "150",
                    'playlist': "none",
                    'bufferlength': 5,
                    'plugins': 'captions-1,http://videos.realization.com/results/player/player_plugin_flimp.swf',
                    'captions.fontsize': '11',
                    'logo': 'Images/logo.png'
                }
                var params = {
                        allowfullscreen:"true", 
                        allowscriptaccess:"always"
                }
                var attributes = {
                        id:"player",  
                        name:"player"
                    }
                    var requiredPlayerVersion = requiredMajor + "." + requiredMinor + "." + requriedRelease;
                    var playerVersion = swfobject.getFlashPlayerVersion(); // returns a JavaScript object
                    //var output = "You have Flash player " + playerVersion.major + "." + playerVersion.minor + "." + playerVersion.release + " installed";
                                   //alert(output);
                    document.getElementById(hdFlashPlayerVersionId).value = playerVersion.major + "." + playerVersion.minor + "." + playerVersion.release;
                    if (playerVersion.major > requiredMajor||(playerVersion.major==requiredMajor&&playerVersion.minor>=requiredMinor&&playerVersion.release>=requriedRelease)) {
                        swfobject.embedSWF("player/player-licensed.swf", "divPlayer", "680px", "350px", requiredPlayerVersion, false, flashvars, params, attributes);
                        isNewFileLoaded = true;
                        currentPlaylist = getCurrentPlaylistFileName(theFile);
                        document.getElementById(window.hdPlaylistId).value = getCurrentPlaylistFileName(theFile);
                    }
                    else {
                        document.getElementById('divPlayer').innerHTML = "Sorry, you have an older version of Adobe Flash Player. To view these videos, you need the latest version of flash player which can be downloaded <a href=\"http://get.adobe.com/flashplayer/\" target=\"_blank\"> here</a>";
                        hideDownload();
                    }
            }
}
function addListeners() {
	if (player) {
	    player.addControllerListener("ITEM", "itemListener");
	    player.addControllerListener("PLAYLIST", "playlistListener");
	    player.addModelListener("STATE", "stateListener");
	    player.addViewListener("NEXT", "nextListener");
	    player.addViewListener("PREV", "previousListener");
	   
	} else {
		setTimeout("addListeners()",100);
	}
}
function nextListener(obj) {
    if (playlistNeedsModification()) {
        setTimeout("player.sendEvent(\"STOP\")", 0);
        manipulatePlaylist("Next");
        isNextOrPrevious = true;
    }
}

function previousListener(obj) {
    if (playlistNeedsModification()) {
        setTimeout("player.sendEvent(\"STOP\")", 0);
        manipulatePlaylist("Previous");
        isNextOrPrevious = true;
    }
}
function playlistListener(obj) {
    var indexOfFile = selectedIndexInPlaylist == undefined ? 0 : selectedIndexInPlaylist;
    if (selectedIndexInPlaylist != undefined&&startPlaying)
        playFileOfPlaylist(selectedIndexInPlaylist);
    else {
        setMetaData(indexOfFile);
    }

}

function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
    currentState = obj.newstate;
    previousState = obj.oldstate;
    if (currentState == 'COMPLETED') {
        if (playlistNeedsModification()) {
            manipulatePlaylist("Playlist");
        }
        else {
            playNextUpTillEnd();
        }
    }


}
function playNextUpTillEnd() {
    var playlist = player.getPlaylist();
    if (playlist) {
        if (playlist.length > currentItem + 1) {
            setTimeout("player.sendEvent(\"Next\")", 0);
        }
    }
}

function manipulatePlaylist(isPrevious) {
    currentItemBeforeReloadingFile = currentItem;
    previousItemBeforeReloadingFile = previousItem;
    try {
        document.getElementById(window.hdPlaylistClickEventId).value = isPrevious;
        __doPostBack(window.hdCurrentPlaylistId, previouslyPlayedVideo);
    }
    catch (e) {
    }
}

function IsPreviousItemUndefined() {
    if (previousItem == undefined || previousItem == -1)
        return true;
    return false;
}


function loadFile(theFile, index, playFile) {
    isNextOrPrevious = false;
    selectedIndexInPlaylist = index;
    currentPlaylist = getCurrentPlaylistFileName(theFile);
    document.getElementById(window.hdPlaylistId).value = getCurrentPlaylistFileName(theFile);
    //alert(currentPlaylist);
    startPlaying = playFile == undefined ? true : playFile;
    if (player == undefined) createPlayer(theFile);
    else {
        currentItem = 0; previousItem = -1;
        isNewFileLoaded = true;
        setTimeout("player.sendEvent('LOAD','" + theFile + "')", 0);
    }
}

function getCurrentPlaylistFileName(theFile) {
    var indexOfQuestionMark = theFile.toString().indexOf("?");
    if (indexOfQuestionMark >= 0) {
        return theFile.toString().substr(0, indexOfQuestionMark);
    }
    else {
        return theFile;
    }
}

function itemListener(obj) {
    previousItem = currentItem;
    currentItem = obj.index;
    setMetaData(currentItem);
}
	

	
	function setMetaData(theIndex) {
	var plst = null;
	plst = player.getPlaylist();
    
	if (plst) 
	{
	     var Company = plst[theIndex].title;
                var text = plst[theIndex].description;
                var source = plst[theIndex].file
                //alert(source);
                previouslyPlayedVideo = source;
                var index=source.lastIndexOf("/");
                var sourceURl=source.substring(index);
                var Beforetext;
                var AfterText;
                if(text!="")
                {
                    var textSplit=text.split("[==]");
                    
                    Beforetext=textSplit[0];
                    Beforetext=Beforetext.replace(/==br==/g, "<br />");
                    
                    AfterText=textSplit[1];
                    AfterText=AfterText.replace(/==br==/g, "<br />");
                    
                }
                if (currentState == 'BUFFERING' || currentState == 'PLAYING') {
                    document.title = Company + " Video (Critical Chain) ";
                }
                document.getElementById(window.lblUserNameId).innerHTML =Company;
                document.getElementById(window.lblBeforeId).innerHTML=Beforetext;
                document.getElementById(window.lblAfterId).innerHTML=AfterText;
                document.getElementById(window.hdsrcId).value = source;
                if (!playlistNeedsModification()||!isNextOrPrevious)
                    changeNowPlayingStyleInPlaylist(theIndex);
       }
   }

   function playFileOfPlaylist(videoIndex) {
       isNextOrPrevious = false;
       if (player != undefined) {
           setTimeout("player.sendEvent('ITEM',"+ videoIndex+")", 0);
       }
       
   }

   function playlistNeedsModification() {
       if (!currentPlaylist)
           return false;
       return currentPlaylist.endsWith(myPlaylistFileSuffix);

   }



   function changeNowPlayingStyleInPlaylist(indexOfCurrentVideo) {

       var wholePlaylistBlock = document.getElementById(playlistBlockId);
       var repeaterRowElements = getElementsByClassName("nowPlayingRow", wholePlaylistBlock);
       var idOfCurrentlyPlayingRow;
       if (playlistNeedsModification()) {
           idOfCurrentlyPlayingRow = rptPlaylistId +'_ctl' + zeroPad(indexOfCurrentVideo, 2) + '_nowPlayingRow';
       }
       else {
           idOfCurrentlyPlayingRow = rptNextUpId + '_ctl' +zeroPad(indexOfCurrentVideo, 2) + '_nowPlayingRow';
       }
       if (!IsArrayUndefinedOrOfZerolength(repeaterRowElements)) {
           for (k = 0; k < repeaterRowElements.length; ++k) {
               repeaterRowElements[k].className = previousRowClass;
           }
       }
       var nowPlayingRow = document.getElementById(idOfCurrentlyPlayingRow);

       if (nowPlayingRow != undefined) {
           previousRowClass = nowPlayingRow.className;
           nowPlayingRow.className = "nowPlayingRow";
       }
   }
   
   function IsArrayUndefinedOrOfZerolength(arr) {
       if (arr == undefined || arr.length == 0)
           return true;
       else
           return false;
   }

   function zeroPad(num, count) {
       var numZeropad = num + '';
       while (numZeropad.length < count) {
           numZeropad = "0" + numZeropad;
       }
       return numZeropad;
   }
   

function getElementsByClassName(className, container) {
    container = container || document;
    var allElements = container.all || container.getElementsByTagName('*');
    var arr = [];
    for (var k = 0; k < allElements.length; ++k) {
        if (allElements[k].className == className) {
            arr[arr.length] = allElements[k];
        }
    }
    return arr;
}



function ShowNowPlaying(currentVideoIndexInMyPlaylistTab) {
    var currentVideoIndexInRightTab = currentVideoIndexInMyPlaylistTab == undefined ? currentItem : currentVideoIndexInMyPlaylistTab;
    changeNowPlayingStyleInPlaylist(currentVideoIndexInRightTab);
    var plst = null;
	plst = player.getPlaylist();

	if (plst) {
	    var Company = plst[currentItem].title;
	    document.title = Company + " Video (Critical Chain) ";
	}
    
}






