/**
 *  Class: $.Video2
 *  Scrollbar is used when the content on the application is bigger than the screen
*/
(function($) {
    var PlayerPlugin = new Object();
    var AudioPlugin = new Object();
    var TVPlugin = new Object();
    var objVideo2_controller = new Object();         //Progressbar needs to work together with Video plugin

    var urlMedia = "";
    var iTime = 0;
    var contentDuration = 0;
    var startTime = 0;
    var currentStreamTime = 0;
    var currentStreamDuration = 0;
	var buffers = {};
	var defaultBuffers = {
		totalBuffer: 512,
		initialBuffer: 512,
		pendingBuffer: 256
	};
    
    //constant for size of screen
    MAX_HEIGHT_SCREEN = 540;
    MAX_WIDTH_SCREEN = 960;
    JUMP_SECONDS = 0;
    
    //constants for status of media    
    PLAYING 	 = 1;
    PAUSED  = 2;
    STOPPED 	 = 3;
    RESUME = 4;
    //initial value for status
    var status = STOPPED;
    // total time of video
    this.totalTime = 0;
    
    var timeSecondHidden = 0;               // variable used to be hidden the progress bar after request to change for full screen
    var timeFullScreen = 0;                      // variable to get the value of time when the full screen is requested
    var boolFullScreen = false;               // variable used for indicating full screen is requested 
    var boolMarkTime = false;               // variable indicating if the time was marking when Full Screen called
    var boolBeginVideo = false;             // variable used to prohibit to press key pause, play, stop, forward, backward before the Video begins
    
    /**
	  * Video2 function is responsible for showing the video or for listening music
	  * Options parameter can to receive an object value or string value. When receive object value is to
	  * create the Video, and otherwise to do some behavior
      *
	  */
	 $.fn.sfVideo2 = function(options, opt) {
		 
		 //Verifies whether the stored data "sfui" have definition equals "Video"
		 if (!($(this).data('sfui') == 'Video2')) {
		             
			$(this).data('sfui', 'Video2');
			
			var contents = [
                '<div id="Video2Div" ></div>'
			].join('');
			
            //insert the video tag
			$(this).html(contents);
        }
        /*******************************************/
        // The urlMedia is a parameter to indicate where the media file stayed
        if ( options.urlMedia != undefined) {
            urlMedia = options.urlMedia;
        }
        
        if ( options.duration != undefined) {
            contentDuration = options.duration;
        }        
        
        if ( options.startTime != undefined) {
            startTime = options.startTime * 1000;
        }
        
        // The jumpSeconds is a parameter to indicate how many secods can forward or backward
        if ( options.jumpSeconds != undefined) {
            JUMP_SECONDS = options.jumpSeconds;
        }
        // get the Progressbar component to work together with video plugin
        if ( options.idVideo2_controller != undefined ) {
                objVideo2_controller = $("#"+ options.idVideo2_controller);
        }
		if (options.buffers) {
			buffers = options.buffers;
		}
        /*******************************************/
        
        if (typeof options == 'object') {
            load($(this));
        } else if (typeof options =='string') {
            switch (options) {
				case 'stop':
                    runStop();
                    break;
                case 'pause':
                    runPause();
                    break;
                case '_pause':
                    runPluginPause();
                    break;
                case 'resume':
                    PlayerPlugin.Resume();
                    break;
                case 'play':
                    if( (opt != undefined) && (opt.urlMedia != undefined)) {
                        urlMedia = opt.urlMedia;
                    }
                    runPlay();
                    break;
				case 'resumePlay':
					if (!opt) {
						return;
					}
					runResumePlay(opt);
					break;
                case 'setFullScreen':
                    //define how second progressbar going to hidden
                    timeSecondHidden = opt;
                    boolFullScreen = true;
                    boolMarkTime = true;
                    //*******************************************************
                    // process to change the video screen size
                    PlayerPlugin.ClearScreen( );
                    PlayerPlugin.SetDisplayArea(0, 0, MAX_WIDTH_SCREEN, MAX_HEIGHT_SCREEN);
                    $("#pluginPlayer").css('top', '0px');
                    $("#pluginPlayer").css('left', '0px');
                    
                    $(this).css('top', '0px');
                    $(this).css('left', '0px');
                    
                    $("#pluginPlayer").css('width', MAX_WIDTH_SCREEN + 'px');
                    $("#pluginPlayer").css('height', MAX_HEIGHT_SCREEN + 'px');
                    //*******************************************************
                    //If the status of Video is PAUSED and the video size is called then the video is playing automatic but in this case it´s need  
                    //to verify the status to change for use play button otherwise the button stay with button pause. 
                    //Maybe the method SetDisplayArea start the video
                    if (status == PAUSED) {
                        status = PLAYING;
                        objVideo2_controller.changeButton('play');
                    }
                    break;
				case 'SetVideoScreen':
                    boolFullScreen = false;
                     //*******************************************************
                    // process to change the video screen size
                    PlayerPlugin.ClearScreen( );
                    PlayerPlugin.SetDisplayArea(opt.left, opt.top, opt.width, opt.height);
                    
                    $("#pluginPlayer").css('width', opt.width+'px');
                    $("#pluginPlayer").css('height', opt.height+'px');
                    
                    $(this).css('width', opt.width+'px');
                    $(this).css('height', opt.height+'px');
                    $(this).css('left', opt.left+'px');
                    $(this).css('top', opt.top+'px');
                    //*********************************************************
                    //If the status of Video is PAUSED and the video size is called then the video is playing automatic but in this case it´s need  
                    //to verify the status to change for use play button otherwise the button stay with button pause. 
                    //Maybe the method SetDisplayArea start the video
                     if (status == PAUSED) {
                        status = PLAYING;
                        objVideo2_controller.changeButton('play');
                    }
                    break;
                case 'backward':
                    runJumpBackward(JUMP_SECONDS);
                    break;
                case 'forward':
                    runJumpForward(JUMP_SECONDS);
                    break;
                case 'setMute':
                    runMute(AudioPlugin);
                    break;
                case 'RCKeyDefined':
                    if ( boolFullScreen ) {
                        objVideo2_controller.setVisible('visible');
                        boolMarkTime = true;
                    }
                    switch (opt) {
                        case $.sfKey.PLAY:
                            runPlay();
                            break;
                         case $.sfKey.STOP:
                            // verify locked the video control, if the boolBeginVideo is false then do nothing when stop is pressed
                            if ( boolBeginVideo ) {
                                runStop();
                            }
                            break;
                         case $.sfKey.PAUSE:
                            // verify locked the video control, if the boolBeginVideo is false then do nothing when pause  is psressed
                            if ( boolBeginVideo ) {
                                runPause();
                            }
                            break;
                         case $.sfKey.RW:
                            // verify locked the video control, if the boolBeginVideo is false then do nothing when backward  is pressed
                            if ( boolBeginVideo ) {
                                runJumpBackward(JUMP_SECONDS);
                            }
                            break;
                        case $.sfKey.FF:
                            // verify locked the video control, if the boolBeginVideo is false then do nothing when forward is pressed
                            if ( boolBeginVideo ) { 
                                runJumpForward(JUMP_SECONDS);
                            }
                            break;
                        case $.sfKey.VOL_UP:
                            runVolumeUp();
                            break;
                        case $.sfKey.VOL_DOWN:
                            runVolumeDown();
                            break;   
						case $.sfKey.MUTE:
							Logger.write("KEY_MUTE", "video2", true);
							runMute();
							break;
                        default:         
                            widgetAPI.blockNavigation(event);
                            break;
                    }
                    break;
                case 'getTotalTime':
                    currentStreamDuration = PlayerPlugin.GetDuration();
                    return currentStreamDuration;
                case 'getPlayedTime':
                    return iTime;
                case 'setTotalTime':
                    setTotalTime();
                case 'getStatus':
                    return status;
                case 'show':
                    $(this).show();
                    break;
                case 'hide':
                    $(this).hide();
                    break;
				case 'setBuffers':
					if (!opt || typeof(opt) != "object") {
						return;
					}
					buffers = opt;
					setBuffers();
					break;
            }
        }
        
	    return this;
	};  

     $.fn.sfVideo2SetUrl = function(url){
            urlMedia = url;            
      }     
      
     $.fn.sfVideo2SetDuration = function(duration){
            contentDuration = duration || 0;
      }     
      
     $.fn.sfVideo2FF = function(sec){
            var startTime = sec * 1000 || 0;
            jump(startTime);
      }
     
     $.fn.sfVideo2SecondsJump = function(url, seconds){
            PlayerPlugin = document.getElementById('pluginPlayer');
            seconds = Math.ceil(seconds);
            PlayerPlugin.ResumePlay(url, seconds);
     }
     
     $.fn.sfVideoGetCurrentTime = function(){
            return currentStreamTime;
     }    
     
     $.fn.sfVideoGetContentDuration = function(){
            return ASXLoader.hasPlayList ? contentDuration : currentStreamDuration;          
     }    
      
    /**
     *  Run the progressbar
     */
   function runProgressbar() {
        if (objVideo2_controller != undefined) {
            //reference for function to calculate time and the bar for progress
            PlayerPlugin.OnCurrentPlayTime =  'setOnCurrentPlayTime';
        } else {
            Logger.write("PROGRESSBAR NOT FOUND", "video2");
        }
    }	
    
    /**
     * Executing mute on the media
     */
    function runMute() {
            if (!checkAudio())
            return;

        var isMute = AudioPlugin.GetSystemMute();
        if ($.sf.define.PLR_TRUE == isMute ) {
            AudioPlugin.SetSystemMute($.sf.define.PLR_FALSE);
        } else if ($.sf.define.PLR_FALSE == isMute ) {
            AudioPlugin.SetSystemMute($.sf.define.PLR_TRUE);
        } else {
             Logger.write("#### ERROR IN THE MUTE FUNCTION #####", "video2");
        }
    }
    
    /**
     * Executing stop on the media
     */
     function runStop() {
        status = STOPPED;
        PlayerPlugin.Stop();
        
        //send state for Progressbar component to update the button  displayed
        //the values of changeButton accept are: stop, pause, play
        if(objVideo2_controller != undefined) {
             objVideo2_controller.changeButton('stop');
        }
        //locked the video controls(pause, forward, backward)
        boolBeginVideo = false;
    }
     
     /**
      * Executing play on the media
      */
    function runPlay() {
			Logger.write("runPlay()", "video2");
            var ret = false;        
            
            if (status == PAUSED) {
				Logger.write("status == PAUSED", "video2");
                status = RESUME;
                ret = PlayerPlugin.Resume();
            } else if (status == STOPPED) {
				Logger.write("status == STOPPED", "video2");
                status = PLAYING;
                var timeToResume = ASXLoader.getCurrentStartTime();
                if (timeToResume > 0)
                {     
                     Logger.write("[Player] playing using STARTTIME = " + timeToResume + "; url = " + urlMedia, "video2");
                     ret = PlayerPlugin.ResumePlay(urlMedia, timeToResume);
                }
                else
                {
                    Logger.write("[Player] playing url = " + urlMedia, "video2");
                    ret = PlayerPlugin.Play(urlMedia);
                }
            } 
           
             //send state for Progressbar component to update the button  displayed
            //the values of changeButton accept are: stop, pause, play
           if(objVideo2_controller != undefined) {
                objVideo2_controller.changeButton('play');
            }
            return ret;
    }  
	
	function runResumePlay(time) {
		PlayerPlugin.Stop();
		status = RESUME;
		ret = PlayerPlugin.ResumePlay(urlMedia, time);
	}
    
    /**
      * Executing play on the media
      */
    function jump(startTime) {
            var ret = false;
            Logger.write("[Player] status = " + status, "video2");
            if (status == PLAYING || status == PAUSED)
            {
                var curDuration = ASXLoader.hasPlayList ? ASXLoader.getCurrentDuration() : this.totalTime;
                var curStartTime = (ASXLoader.hasPlayList ? ASXLoader.getCurrentStartTime() : 0) * 1000;
                
                var timeToJump =  (iTime + startTime)/1000;
   
                if ((timeToJump - curStartTime/1000) > 0)
                {
                     if (timeToJump * 1000 <= curDuration)
                     {
						 Logger.write("FF without playlist stuff", "video2", true);
                         PlayerPlugin.Stop();
                         Logger.write("[Player] ff to ="+startTime, "video2");
                         Logger.write("[Player] new time to jump = " + Helpers.intTimeToString(timeToJump*1000), "video2");        
                         timeToJump = Math.ceil(timeToJump);
                         ret = PlayerPlugin.ResumePlay(urlMedia, timeToJump);
                         iTime = timeToJump;
                         startTime = 0;
                         status = PLAYING;
                     }
                     else if (ASXLoader.hasPlayList && ASXLoader.hasNext)
                     {
						Logger.write("FF with playlist stuff", "video2", true);
						
						var duration = curDuration;
						
						while (timeToJump * 1000 > duration) {
							urlMedia = ASXLoader.getNextUrl();
							timeToJump -= duration/1000;
							duration = ASXLoader.getCurrentDuration();
							
							if (!ASXLoader.hasNext)
                                break;
						}
						
                         PlayerPlugin.Stop();
                         Logger.write("[Player] ff to ="+startTime, "video2");
                         timeToJump = Math.ceil(timeToJump);
                         ret = PlayerPlugin.ResumePlay(urlMedia, timeToJump);    
                         iTime = timeToJump;
                         status = PLAYING;
                     }
                }
                else if (ASXLoader.hasPlayList && ASXLoader.hasPrev)
                {   
                     while(timeToJump < 0)
                     {
                         urlMedia = ASXLoader.getPrevUrl();
                         var duration = ASXLoader.getCurrentDuration();
                         Logger.write("[Player] new duration = " + Helpers.intTimeToString(duration), "video2");
                         timeToJump += duration/1000;
                         Logger.write("[Player] new time to jump = " + timeToJump, "video2");
                     }
                    
                     PlayerPlugin.Stop();
                     timeToJump = Math.ceil(timeToJump);
                     ret = PlayerPlugin.ResumePlay(urlMedia, timeToJump);    
                     iTime = timeToJump;
                     startTime = 0;
                     status = PLAYING;
                }
            } 
            return ret;
    }   
    
    /**
      * Executing pause on the media and control the status of video
      */
    function runPause() {
        var state = 'pause';    //use to change the button
                Logger.write("run paused", "video2");
        if( status == PLAYING || status == RESUME || status == PAUSED ) {
                Logger.write("plagin before paused", "video2");
                PlayerPlugin.Pause();
                Logger.write("plagin after paused", "video2");
                status = PAUSED;
            }

          //send state for Progressbar component to update the button  displayed
            //the values of changeButton accept are: stop, pause, play
           if(objVideo2_controller != undefined) {
                objVideo2_controller.changeButton(state);
            }
    }
    
     /**
      * Executing pause on the media and control the status of video
      */
    function runPluginPause() {
        var state = 'pause';    //use to change the button
        PlayerPlugin.Pause();
                //send state for Progressbar component to update the button  displayed
            //the values of changeButton accept are: stop, pause, play
           if(objVideo2_controller != undefined) {
                objVideo2_controller.changeButton(state);
            }
    }
    
    /**
     * Executing backward on the media
     */
     function runJumpBackward(seconds) {
        objVideo2_controller.changeButton('backward');
        PlayerPlugin.JumpBackward(seconds);
    }
    
    /**
     * Executing forward on the media
     */
     function runJumpForward(seconds) {
        objVideo2_controller.changeButton('forward');
        PlayerPlugin.JumpForward(seconds);
    }
    
    /**
     * Executing volume up on the media
     */
     function runVolumeUp() {
        if (!checkAudio())
            return;

       AudioPlugin.SetVolumeWithKey($.sf.define.PL_AUDIO_VOLUME_KEY_UP);
       //set up value of Volume
       objVideo2_controller.setVolume(AudioPlugin.GetVolume());
    }
    
    /*
    * Checks for device type
    */
   function checkAudio() {
        tvPlugin = document.getElementById('pluginObjectTV');
        if (tvPlugin.GetProductType() == 2)
        {
            $("#Video2_controllerVolume").css({"visibility":"hidden"});
            $("#iconVolume").css({"visibility":"hidden"});
            return false;
        }
        return true;
    }


    /**
     * Executing volume down on the media
     */
     function runVolumeDown() {
      if (!checkAudio())
            return;

       AudioPlugin.SetVolumeWithKey($.sf.define.PL_AUDIO_VOLUME_KEY_DOWN);
       //set up value of Volume
       objVideo2_controller.setVolume(AudioPlugin.GetVolume());
    }
    
    /*
    *Sets total time
    */
    function setTotalTime() {
         this.totalTime = PlayerPlugin.GetDuration();
         currentStreamDuration = this.totalTime;         
         Logger.write("[player] total time =" + this.totalTime, "video2");
    }
	
	function setBuffers () {
		var initialBuffer, totalBuffer, pendingBuffer;
		if (buffers) {
			initialBuffer = parseInt(buffers.initialBuffer || defaultBuffers.initialBuffer);
			totalBuffer = parseInt(buffers.totalBuffer || defaultBuffers.totalBuffer);
			pendingBuffer = parseInt(buffers.pendingBuffer || defaultBuffers.pendingBuffer);
		}
		Logger.write("Buffers:: initial: " + initialBuffer + "; total: " + totalBuffer + "; pending: " + pendingBuffer, "video2", true);
		PlayerPlugin.SetTotalBufferSize(totalBuffer * 1024);
		PlayerPlugin.SetInitialBuffer(initialBuffer * 1024);
		PlayerPlugin.SetPendingBuffer(pendingBuffer * 1024);
	}
    /**
     * This method is responsible for load the plugins of video / audio and configure the basic values for run media
     */
    function load(self) {
        
        var tagObject = "<object id='pluginPlayer' classid='clsid:SAMSUNG-INFOLINK-PLAYER' class='videoConfiguration'></object>";
        tagObject += "<object id='audioPlayer' classid='clsid:SAMSUNG-INFOLINK-AUDIO' ></object>";

        document.getElementById('Video2Div').innerHTML = tagObject ;
        //variable to control some events of  player and audio plugins
        PlayerPlugin = document.getElementById('pluginPlayer');         
        
        if (checkAudio())          
            AudioPlugin = document.getElementById('audioPlayer');

        TVPlugin = document.getElementById('pluginObjectTVMW');
             
        /**************EVENTS*****************************/
        PlayerPlugin.OnStreamInfoReady = 'ScenePlayer.onPlayerStreamReady';     
        PlayerPlugin.OnRenderingComplete = 'ScenePlayer.onRenderingComplete';     
        PlayerPlugin.OnBufferingStart = 'ScenePlayer.onBufferingStart';     
        PlayerPlugin.OnBufferingComplete = 'ScenePlayer.onBufferingComplete';     
        PlayerPlugin.OnConnectionFailed = 'ScenePlayer.onConnectionFailed';      
        PlayerPlugin.OnRenderError = 'ScenePlayer.onRenderError';      
        PlayerPlugin.OnStreamNotFound = 'ScenePlayer.onStreamNotFound';      
        PlayerPlugin.OnNetworkDisconnected = 'ScenePlayer.onNetworkDisconnected';
        
        /************* CONFIGURATIONS **********************/
		setBuffers();
        PlayerPlugin.SetInitialTimeOut(30); // сколько максимально ждать, прежде чемa начинать проигрывание (через это время стартуется проигрывание, даже если initial buffer не заполнен; время в секундах)
        PlayerPlugin.ClearScreen();
        
        // Take the values of css parameter has into Scene1.css.index This values is declared in the Visual Editor
        var objectWidth = $(self).css('width').replace('px','');
        var objectHeight = $(self).css('height').replace('px','');
        var objectLeft = $(self).css('left').replace('px','');
        var objectTop = $(self).css('top').replace('px','');
        
        //Define values of video for definitions above 
        $("#pluginPlayer").css('width',objectWidth +'px');
        $("#pluginPlayer").css('height',objectHeight +'px');
        
        //Method to modified the position and size of Video
        PlayerPlugin.SetDisplayArea(objectLeft, objectTop, objectWidth, objectHeight);
        /************* CONFIGURATIONS **********************/
              
		  this.isMadness = false;
		  this.isSparta = true;
        //execute play on the video set up
        runPlay();
        
        //variable used in the setOnCurrentPlayTime function
        this.totalTime = PlayerPlugin.GetDuration();
        //execute event current time
        runProgressbar();
    }
        /**
         * calculate time to show in the progress
         * this function is used with Progressbar component
         */
        setOnCurrentPlayTime = function(time) {
            if (ScenePlayer.playingInfo == "begin")
            {
                ScenePlayer.playingInfo +=time + "; stt=" + (parseInt(ASXLoader.getCurrentStartTime(), 10) * 1000) +"; prd=" + (parseInt(ASXLoader.getPrevDuration(), 10) * 1000); 
                Logger.write("pI="+ScenePlayer.playingInfo, "video2");
            }
			
            iTime = parseInt(time, 10)/1;
			Logger.write("iTime: " + iTime, "video2", true);
            var prevDuration = parseInt(ASXLoader.getPrevDuration(), 10) * 1000;
            time = iTime + prevDuration;         
            
            currentStreamTime = time; 

            this.totalTime = PlayerPlugin.GetDuration();
			var displayTime = time;
			var displayDuration = contentDuration > 0 ? contentDuration : this.totalTime;
            var timeHTML = "";
            
            if (status == PLAYING ||  status == PAUSED ||status == RESUME ) {
                //send state for Progressbar component to update the button  displayed
                //the values of changeButton accept are: stop, pause, play
                if ( objVideo2_controller != undefined && status != PAUSED ) {
                    status = PLAYING;
                    objVideo2_controller.changeButton('play');
                } else if (objVideo2_controller != undefined && status == PAUSED ) {
                    objVideo2_controller.changeButton('pause');
                }
					
				if (ASXLoader.hasPlayList) {
					var section = ASXLoader.getCurrentSection(currentStreamTime / 1000);
					if (section) {
						displayTime -= section.start * 1000;
						displayDuration = section.duration * 1000;
					} else {
						displayDuration = ASXLoader.getTotalDuration();
					}
				}
				
				timePercent = (100 * displayTime) / displayDuration;
                    
                //set the time of percent for  progressbar                
                 if (timePercent <= 100)
                    objVideo2_controller.setProgress(timePercent);
                //set up value of Volume
                if (checkAudio())
                    objVideo2_controller.setVolume(AudioPlugin.GetVolume());
                
                timeHTML = Helpers.intTimeToString(displayTime) +"/"+Helpers.intTimeToString(displayDuration);
                boolBeginVideo = true;
                
            } else if ( status == STOPPED) {
                timeHTML = "0:00:00/0:00:00";
            }
            
            //set value of time on the div           
            objVideo2_controller.setTime(timeHTML);
       
            //unlocked the key control of video(pause, forward, backward)
            boolBeginVideo = true;
            
            //get the time of begin full screen displayed
            if (  boolFullScreen && boolMarkTime ) {
                timeFullScreen = timeSecond;
                boolMarkTime = false;
            } 
            
            //calculate the time after full screen showing for hide the progress bar
            if (boolFullScreen && boolMarkTime ==false) {
                if ( timeSecond == (timeSecondHidden+timeFullScreen) ) {
                    objVideo2_controller.setVisible('hidden');
                }
            }           
            
            if ((time >= contentDuration) && (contentDuration > 0))
            {
                    Logger.write("[Player] Stream time over; duration ="+contentDuration, "video2");
                    ScenePlayer.stopAndReturn();
                    return;
            }
		}  
    
})(jQuery);

               