//================================================================================
//==			        PalaceNetPlayer.js				==
//==										==
//==	        Javascript function for embedded player				==
//==										==
//==										==
//==	        written By: 	Yariv Glazer					==
//==	        Revision Date:	Nov 23rd, 2007					==
//==										==
//==	Copyrights:	You can use this script as long as give the credits     ==
//================================================================================
    function ShowMetadata()
    {
        var Media = Player.currentMedia;
        
        lines[0] = "Playing"
        // Test whether we have a valid Media object.
        if(!Media)
        {
            lines[1] = "No current media.";
            return;
        }

        // Retrieve the metadata we want to display.
        var Title = Media.getItemInfo("Title");
        var Artist = Media.getItemInfo("WM/AlbumArtist");
        var AlbumTitle = Media.getItemInfo("WM/AlbumTitle");
        var Duration = Media.durationString;

        // Test the duration string value.
        // Streaming media always returns zero.
        if(Duration == "00:00")
        {
           Duration = "No duration available";
        }

        // Display the metadata in the DIV element.
        if ( typeof Metadata != "undefined" )   {
            lines[2] = Title;
            lines[3] = Artist;
            lines[4] = AlbumTitle;
//            lines[4] = "Duration: " + Duration;
        }
    }

    function ShowAd()
    {
        var Media = Player.currentMedia;
        // Test whether a valid Media objec
        // was retrieved.
        if(!Media)
        {
            // No valid media. Cannot update the banner.
            return;
        }

        // Retrieve the banner URL from the 
        // custom PARAM element in the playlist.
        var BannerURL = Media.getItemInfo("BannURL");

        // Set the banner URL for the IMG element.
        if ( typeof imgBanner != "undefined" )   {
            imgBanner.src = BannerURL;
        }
    }

    function BannerClick()
    {
        var Media = Player.currentMedia;
        // Test whether a valid Media objec
        // was retrieved.
        if(!Media)
        {
            // No valid Media object, Do nothing.
            return;
        }

        // Retrieve the URL from the custom PARAM
        // element in the ASX playlist.
        var AdURL = Media.getItemInfo("AdURL");

        // Open a separate browser window to display the 
        // Web page.
        // The following code block contains line breaks for display purposes.
        // The scripting language does not support line breaks.
        // In actual implementation, you must remove the line breaks.
        window.open(AdURL,"", "height=300, width=500, left=300,menubar=no, scrollbars = yes, location=no,titlebar=no, toolbar=no, status=no");
    }

    var CLIP_STOPPED = 1;
    var CLIP_PAUSED = 2;
    var CLIP_PLAYING = 3;
    var CLIP_BUFFERING = 6;
    var CLIP_WAITING = 7;
    var CLIP_READY = 10;
    var CLIP_CONNECTING = 11;

    var MEDIA_OPEN = 13;
    var MEDIA_CONNECTING = 11;
    
    var idI; 
    var MessageTimer;
    var lines = new Array();


    function OpenStateMessage(iState) {
        switch(iState)
        {
            case 0:
                return "Media Player is in an undefined state.";
            case 1:
                return "New playlist is about to be loaded";
            case 2:
                return "Windows Media Player is attempting to locate the playlist";
            case 3:
                return "Connecting to the playlist";
            case 4:
                return "Playlist has been found and is now being retrieved.";
            case 5:
                return "Playlist has been retrieved and is now being parsed and loaded.";
            case 6:
                return "Playlist is open.";
            case 7:
                return "A new playlist has been assigned to currentPlaylist. ";
            case 8:
                return "A new media item is about to be loaded.";
            case 9:
                return "Windows Media Player is locating the media item.";
            case 10:
                return "Connecting to the server that holds the media item.";
            case 11:
                return "Media item has been located and is now being retrieved.";
            case 12:
                return "Media item has been retrieved and is now being opened.";
            case 13:
                return "Media item is now open." + " Media Duration is " + Player.currentMedia.durationString;
            case 14:
                return "Starting codec acquisition.";
            case 15:
                return "Codec acquisition is complete.";
            case 16:
                return "Acquiring a license to play DRM protected content. ";
            case 17:
                return "License to play DRM protected content has been acquired.";
            case 18:
                return "Begin DRM Individualization.";
            case 19:
                return "DRM individualization has been completed.";
            case 20:
                return "Waiting for media item.";
            case 21:
                return "Opening a URL with an unknown type.";
            default:
                return NewState;
        }
    }

//    function ShowOpenState(NewState){
//        switch(NewState)
//        {
//            // Media object open.
//            case MEDIA_OPEN:
//                ShowMetadata();
////                getVolume();
//    //            ShowAd();
//                break;
//            
//            default:
//                    ShowMessage( OpenStateMessage(NewState) );
//                break;
//        }
//    }

    function startPlay() {
	    if(Player.playState != CLIP_PLAYING) {
		    Player.controls.play();
	    }
    }

    function pausePlay() {
        if (Player.controls.isAvailable('Pause')) {
            Player.controls.pause();
        }
    }

    function stopPlay() {
        Player.controls.stop();
    }

    function setFullScreen() {
	    if(Player.playState == CLIP_PLAYING) { Player.fullScreen = 'true'; }
    }

    function muteSound(oBtnMute) {
	    try {
		    if(Player.settings.mute) {
			    Player.settings.mute = false;
			    rollOverButton(oBtnMute, "off");
		    } else {
			    Player.settings.mute = true;
			    rollOverButton(oBtnMute, "on");
		    }
		    getVolume();
	    } catch (e){}
    }
    //=====================================================================
    //========================== Auxillary functions ======================
    //=====================================================================

    var arrButtons = new Array();
	    arrButtons["buttonPlay_off"] = new Image();
	    arrButtons["buttonPlay_off"].src = "images/Play_off.gif";
    	
	    arrButtons["buttonPlay_on"] = new Image();
	    arrButtons["buttonPlay_on"].src = "images/Play_on.gif";
    	
	    arrButtons["buttonPause_off"] = new Image();
	    arrButtons["buttonPause_off"].src = "images/Pause_off.gif";
    	
	    arrButtons["buttonPause_on"] = new Image();
	    arrButtons["buttonPause_on"].src = "images/Pause_on.gif";
    	
	    arrButtons["buttonStop_off"] = new Image();
	    arrButtons["buttonStop_off"].src = "images/Stop_off.gif";
    	
	    arrButtons["buttonStop_on"] = new Image();
	    arrButtons["buttonStop_on"].src = "images/Stop_on.gif";
    	
	    arrButtons["buttonMute_off"] = new Image();
	    arrButtons["buttonMute_off"].src = "images/Mute_off.gif";
    	
	    arrButtons["buttonMute_on"] = new Image();
	    arrButtons["buttonMute_on"].src = "images/Mute_on.gif";
    	
    //=========================================================================

    function rollOverButton(oButton, mode) {
	    try {
	        oButton.src = arrButtons[oButton.name + "_" + mode].src;
	    } catch (e){}
    }
    
    function switchPlayPause(NewState) {
	    switch(NewState) {
		    case CLIP_PLAYING:
			    Player.style.visibility = "visible";
			    break;
            case CLIP_PAUSED:
    		    buttonPlay.width = 21 ;
			    buttonPause.width = 0 ;
                break;

		    default:
    		    buttonPlay.width = 21 ;
			    buttonPause.width = 0 ;
			    Player.style.visibility = "hidden";
			    break;
	    }
    }
    
    function ShowPlayState(NewState){
        var FriendlyMessage;
        
        switchPlayPause(NewState);
        window.clearInterval(idI);
        window.clearInterval(MessageTimer);
        LineUp.style.visibility = "visible";
                
        switch (NewState){
            case 1:
                loading.style.visibility = "hidden";
                FriendlyMessage = "Stopped";
                findTimeLeft();
                moveSlider(0);              
                break;

            case 2:
                FriendlyMessage = "Paused";
                break;

            case 3:
//                FriendlyMessage = "Playing";
                loading.style.visibility = "hidden";
                LineUp.style.visibility = "hidden";
		buttonPlay.width = 0 ;
                if (Player.controls.isAvailable('Pause')) { buttonPause.width = 21; }
                idI = window.setInterval("UpdateDuration()", 200);  
                getVolume();
                ShowMetadata();
                MessageTimer = window.setInterval("loopLines()", 2000);  
                return;

            case 6:
                loading.style.visibility = "visible";
                FriendlyMessage = "Buffering";
                idI = window.setInterval("UpdateBP()", 50);
                break;

            case 7:
                loading.style.visibility = "visible";
                FriendlyMessage = "Waiting";
                break;

            case 10:
                loading.style.visibility = "hidden";
                FriendlyMessage = "Ready";
                break;

            case 11:
                loading.style.visibility = "visible";
                FriendlyMessage = "Connecting";
                break;

            // Other cases go here.

            default:
                FriendlyMessage = "";
        }
        ShowMessage( FriendlyMessage );
    }
    
    function UpdateBP(){
        ShowMessage( "Buffering " + Player.network.bufferingProgress + "%" );
    }
    
    //=====================================================================
    //================== Slider & Progress functions ======================
    //=====================================================================
    function UpdateDuration(){
        // Store the current position of the current media item.
        var TimeNow = Player.controls.currentPosition;

        timepass.innerHTML = FormatTime(TimeNow);
        if (Player.currentMedia.duration > 0) {
            timeleft.innerHTML = FormatTime(Player.currentMedia.duration - TimeNow);
            moveSlider( TimeNow / Player.currentMedia.duration );
        }
        else {
            moveSlider( 0 );
            timeleft.innerHTML = "Live";
        }
    }

    function FormatTime(seconds){
        var minutes = Math.floor(seconds / 60)
        seconds = Math.floor(seconds - minutes * 60);
        if (minutes == 0) { minutes = "00"; }
        if (seconds < 10) { seconds = "0" + seconds; }
        return minutes + ":" + seconds;
    }

    function findTimeLeft(){
        if (Player.currentMedia.duration == 0) {
            timeleft.innerHTML = "";
        }
        else {
            timeleft.innerHTML = FormatTime(Player.currentMedia.duration);
        }        
    }
    
    function leaveMovieSlider() {
        setPosition();
    }

    function grabMovieSlider() {
        nX = window.event.clientX ;
	    if ( nX < ProgressBar.offsetLeft + 5) {
	        nX = ProgressBar.offsetLeft + 5;
	    }
	    else if ( nX > ProgressBar.offsetLeft + ProgressBar.offsetWidth - 3 ) {
	        nX = ProgressBar.offsetLeft + ProgressBar.offsetWidth - 3;
	    }
//	    Handle.style.left = nX - ProgressBar.offsetLeft;
	    ProgressBarDone.style.width = nX - ProgressBar.offsetLeft - 5;
    }
    
    function moveSlider(Percentage) {
        var pos = Math.floor(Percentage * ProgressBar.offsetWidth);
        if ( pos < (ProgressBar.offsetWidth - 8) ) { 
            ProgressBarDone.style.width = pos; 
        }
    }

    function setPosition() {
        nX = window.event.clientX - ProgressBar.offsetLeft ;
        if ((nX < ProgressBar.offsetWidth) && ( nX > 0)) {
            if (Player.currentMedia.duration > 0) {
                nX = nX / ProgressBar.offsetWidth ;
                Player.controls.currentPosition = nX * Player.currentMedia.duration ;
                UpdateDuration();
            }
        }
    }

    //=====================================================================
    //========================= Volume functions ==========================
    //=====================================================================
    function setVolume() {
        nX = window.event.clientX - volumePlace.offsetLeft ;
        Player.settings.volume = 100 * nX / volumePlace.offsetWidth;
        getVolume();
    }

    function getVolume() {
        if ( Player.settings.mute ) {
            volHandle.style.width = 0 ;
            buttonMute.src = arrButtons["buttonMute_on"].src;
        }
        else {
            volHandle.style.width = (Player.settings.volume / 100) * 17 ;
            buttonMute.src = arrButtons["buttonMute_off"].src;
        }
    }

    var Path_name = "http://s01wm.mhsvideonetwork.com/";
    
    function PlayClip(ClipURL) {
        if ( ClipURL.indexOf("://") < 0 ) { ClipURL = Path_name + ClipURL; }
        
        if ( navigator.appVersion.indexOf("MSIE") < 0 ) {
            if ( ClipURL.indexOf(".wmv") > 0 ) {
                embPlayer( ClipURL );                
            }
            else {
                embPlayer( Path_name + "PalaceLive.wmv" );
            }
        }
        else {
            Player.URL = ClipURL;
        }
    }

    function initPalyer() {
        //============================= File to Play ===============================
        var full_file_name = "";

        lines[1] = "";
        if (location.search) {
            full_file_name = Path_name + location.search.substring(1);
        } 
        else {
            full_file_name = "http://www.mhsvideonetwork.com/Palace/PalaceLive.asx" ;//Live Feed
        }
        
        // Fit the palyer to the browser 
        PlayClip(full_file_name);
        
        // get the related clips
        startTimer(15,'GetRelatedClips()');
//	        RelatedClips.style.visibility = "visible";
    }

    function embPlayer( sURL ) { 
       var oVideo = document.getElementById("Video");
      
       var vText = "<object id='Player'><EMBED TYPE='application/x-mplayer2' ";
       vText += "SRC='" + sURL;
       vText += "' autostart='true' width=400 height=355 ShowControls=1 ShowDisplay=0 ShowStatusBar=0></EMBED></object>";
       oVideo.innerHTML = vText ;
    }

    function ShowMessage( text ){
        if ( typeof Metadata != "undefined" )  {
            if ( text != "" ) {
                Metadata.style.visibility = "visible";
                Metadata.innerHTML = text;
            }
            else {
                Metadata.style.visibility = "hidden";
            }
        }
    }

    var lineNumber = -1 ;
    function loopLines(){
        if (lineNumber > lines.length - 2) { 
            lineNumber = 0;
        }
        else {            lineNumber += 1;
        }
        
        if ((lines[lineNumber] != "undefined") && (lines[lineNumber] != "")) { 
            ShowMessage(lines[lineNumber]);
        }
    }

    //=====================================================================
    //=================== Related Clips functions =========================
    //=====================================================================
    var responseText = "";
    var timer;
    var url = "http://www.mhsvideonetwork.com/Palace/RelatedClips.html";
    var RelatedId;
    var xmlhttp;

    function getFile(pURL) {
        try
        {
	        if (!xmlhttp) {
                xmlhttp= new XMLHttpRequest;; 
	        }
		        xmlhttp.open('POST', pURL, true);
		        xmlhttp.onreadystatechange = postFileReady;
		        xmlhttp.send();
         }
         catch(e)
         {
         }
    }

    // function to handle asynchronous call
    function postFileReady() {
        if (xmlhttp.readyState==4) { 
            if (xmlhttp.status==200) {
                responseText = xmlhttp.responseText;
            }
        }
    }

    function GetDivInnerHtml( id, tmpStr ) {
        if (tmpStr.indexOf(id) > 0) {
            //  Cut the string to start at the location of the 'id'
            tmpStr = tmpStr.substring(tmpStr.indexOf(id));
            //  Move the start to after the '>' character
            tmpStr = tmpStr.substring(tmpStr.indexOf(">") + 1);
            //  cut the end of the string 
            tmpStr = tmpStr.substr(0, tmpStr.indexOf("</DIV"));
        }
        else {
            tmpStr = "";
        }
        return( tmpStr );
    }

    function GetRelatedClips() {
	    getFile(url);
	    if ( responseText != "" ) {
	        RelatedClips.style.visibility = "visible";
	        if ( GetDivInnerHtml('RelatedId',responseText) != RelatedId ) {
	            RelatedClips.innerHTML = GetDivInnerHtml('RelatedClips',responseText);
	            RelatedId = GetDivInnerHtml('RelatedId',responseText);
    	        LineUp.innerHTML = BuildLineupSlide();
	        }
	    }
	    else {
	        RelatedClips.style.visibility = "hidden";
	        RelatedClips.innerHTML = "";
	        LineUp.innerHTML = "<img border='0' src='images/pistons.gif'>";
	    }
    }

    function startTimer(slideTime, timeFunction) {
	    clearInterval(timer);
	    timer = setInterval(timeFunction, slideTime * 1000);
    }

    function highlightText(obj, Action ) {
        if ( Action == 'on' ) {
            obj.style.color = 'Aqua';
            obj.style.cursor = 'hand';
        }
        else {
            obj.style.color = 'Yellow';            
            obj.style.cursor = 'auto';
        }
    }

    function SwitchClips(objLine) {
        var tmp = lines[1];
        if ( tmp == "" ) {
            tmp = lines[2];
        }
        
        // switch the name of the clip
        lines[1] = objLine.innerText;
	    objLine.innerText = tmp;
	    
        // switch the Path of the clip
        tmp = Player.URL;
	    PlayClip( objLine.id );
	    objLine.id = tmp;
    }

    function BuildLineupSlide() {
	    //var tmp = GetDivInnerHtml('RelatedClips',responseText);
	    //tmp = "<DIV class=textYellow10>" + tmp + "</DIV>";
	    return GetDivInnerHtml('GameName',responseText) ;//+ tmp;
    }

