project = window.project || {};
project.video_players = [];

/*
 * Extend video.js functions
 */
project.ExtendedVideoJs = JRClass.extend.apply(VideoJS, [{
    /*
     * overwritten to build custom controls
     */
    buildAndActivateControlBar: function()
    {
        
    	if (!VideoJS.isIOS())
        {
    		jQuery(this.video).parent().append(jQuery("<div class=\"vjs-controls\"><div class=\"vjs-controls-holder\"><div class=\"vjs-play-control\"><span></span></div><div class=\"vjs-fullscreen-control\"></div><div class=\"vjs-volume-control\"><span class=\"vjs-volume-mute\"></span><span class=\"vjs-volume-down\"></span><div><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span></div><span class=\"vjs-volume-up\"></span></div></div><div class=\"vjs-time-control\"><span class=\"vjs-duration-display\">00:00</span></div><div class=\"vjs-progress-control\"><span class=\"vjs-current-time-display\">00:00</span><div class=\"vjs-progress-holder\"><div style=\"width: 100%;\" class=\"vjs-load-progress\"></div><div style=\"width: 0%;\" class=\"vjs-play-progress\"><span class=\"vjs-play-progress-bar\"></span></div></div></div></div>"));
        } else 
        {
        	jQuery(this.video).parent().append(jQuery("<div class=\"vjs-controls\"><div class=\"vjs-controls-holder\"><div class=\"vjs-play-control\"><span></span></div><div class=\"vjs-fullscreen-control\"></div><div style=\"opacity: .3\" class=\"vjs-volume-control\"><span class=\"vjs-volume-mute\"></span><span class=\"vjs-volume-down\"></span><div><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span><span class=\"vjs-volume-level-on\"></span></div><span class=\"vjs-volume-up\"></span></div></div><div class=\"vjs-time-control\"><span class=\"vjs-duration-display\">00:00</span></div><div class=\"vjs-progress-control\"><span class=\"vjs-current-time-display\">00:00</span><div class=\"vjs-progress-holder\"><div style=\"width: 100%;\" class=\"vjs-load-progress\"></div><div style=\"width: 0%;\" class=\"vjs-play-progress\"><span class=\"vjs-play-progress-bar\"></span></div></div></div></div>"));
        }
        
        var controls = jQuery(this.video).parent().find('.vjs-controls').first();

        this.controls = controls[0];
        this.playControl = controls.find('.vjs-play-control')[0];
        this.progressControl = controls.find('.vjs-progress-control')[0];
        this.progressHolder = controls.find('.vjs-progress-holder')[0];
        this.loadProgressBar = controls.find('.vjs-load-progress')[0];
        this.playProgressBar = controls.find('.vjs-play-progress')[0];
        this.timeControl = controls.find('.vjs-time-control')[0];
        this.currentTimeDisplay = controls.find('.vjs-current-time-display')[0];
        this.durationDisplay = controls.find('.vjs-duration-display')[0];
        
        if (!VideoJS.isIOS())
        {
        this.volumeControl = controls.find('.vjs-volume-control div')[0];
        this.volumeControlParent = controls.find('.vjs-volume-control')[0];
        this.volumeDisplay = this.volumeControl;
        }
        
        this.fullscreenControl = controls.find('.vjs-fullscreen-control')[0];

        this.activateElement(this.controls, "controlBar");
        this.activateElement(this.controls, "mouseOverVideoReporter");
        this.activateElement(this.playControl, "playToggle");
        this.activateElement(this.progressHolder, "currentTimeScrubber");
        this.activateElement(this.loadProgressBar, "loadProgressBar");
        this.activateElement(this.playProgressBar, "playProgressBar");
        this.activateElement(this.currentTimeDisplay, "currentTimeDisplay");
        this.activateElement(this.durationDisplay, "durationDisplay");
        
        if (!VideoJS.isIOS())
        {
        	this.activateElement(this.volumeControl, "volumeScrubber");
            this.activateElement(this.volumeDisplay, "volumeDisplay");
        }
        
        this.activateElement(this.fullscreenControl, "fullscreenToggle");
    },

    /*
     * overwritten to force custom controls on mobiles
     */
    
    html5Init: function()
    {
        this.element = this.video;

        this.fixPreloading(); // Support old browsers that used autobuffer
        this.supportProgressEvents(); // Support browsers that don't use 'buffered'

        // Set to stored volume OR 85%
        this.volume((localStorage && localStorage.volume) || this.options.defaultVolume);

        // Update interface for device needs
        if (VideoJS.isIOS())
        {
          //this.options.useBuiltInControls = true;
          this.iOSInterface();
        }
        else if (VideoJS.isAndroid())
        {
          //this.options.useBuiltInControls = true;
          this.androidInterface();
        }

        // Add VideoJS Controls
        if (!this.options.useBuiltInControls)
        {
          this.video.controls = false;
          if (this.options.controlsBelow)
          {
              _V_.addClass(this.box, "vjs-controls-below");
          }

          // Make a click on th video act as a play button
          this.activateElement(this.video, "playToggle");

          // Build Interface
          this.buildStylesCheckDiv(); // Used to check if style are loaded
          this.buildAndActivatePoster();
          this.buildBigPlayButton();
          this.buildAndActivateSpinner();
          this.buildAndActivateControlBar();
          this.loadInterface(); // Show everything once styles are loaded
          this.getSubtitles();
        }
    }
    
}]);


/* Volume Display Behaviors
================================================================================ */
VideoJS.player.newBehavior("volumeDisplay", function(element){
    if (!this.volumeDisplays) {
      this.volumeDisplays = [];
      this.onVolumeChange(this.updateVolumeDisplays);
    }
    this.volumeDisplays.push(element);
    this.updateVolumeDisplay(element); // Set the display to the initial volume
  },{
    // Update the volume control display
    // Unique to these default controls. Uses borders to create the look of bars.
    updateVolumeDisplays: function(){
      if (!this.volumeDisplays) { return; }
      this.each(this.volumeDisplays, function(dis){
        this.updateVolumeDisplay(dis);
      });
    },
    updateVolumeDisplay: function(display){
      var volNum = Math.ceil(this.volume() * 8);
        if(volNum === 0)
        {
            jQuery(this.volumeControlParent).addClass('vjs-volume-muted');
        }
        else
        {
            jQuery(this.volumeControlParent).removeClass('vjs-volume-muted');
        }
        this.each(display.children, function(child, num){
            if (num < volNum) {
                _V_.addClass(child, "vjs-volume-level-on");
            } else {
                _V_.removeClass(child, "vjs-volume-level-on");
            }
        });
    }
  }
);

/* Play Progress Bar Behaviors
================================================================================ */
VideoJS.player.newBehavior("playProgressBar", function(element){
    if (!this.playProgressBars)
    {
      this.playProgressBars = [];
      this.onCurrentTimeUpdate(this.updatePlayProgressBars);
    }
    this.playProgressBars.push(element);
    this.playProgressBars.push(this.currentTimeDisplay);
  },{
    // Ajust the play progress bar's width based on the current play time
    updatePlayProgressBars: function(newTime)
    {
        var progress = (newTime !== undefined) ? newTime / this.duration() : this.currentTime() / this.duration();
        if (isNaN(progress))
        {
          progress = 0;
        }

        var progress_percent_string = _V_.round(progress * 100, 2) + "%";
        this.playProgressBars[1].style.left = progress_percent_string;
        this.playProgressBars[0].style.width = progress_percent_string;
    }
  }
);

/*
 * Player Behaviour Class 
 */
(function($)
{
    project.PlayerBehaviour = function(dom_element, options)
    {
        this.dom_element = dom_element;
        this.video_element = this.dom_element.find('video');
		this.object_element = this.dom_element.find('object');
        this.video_id = this.video_element.attr('id');
        //this.embed_element = this.dom_element.find('embed');
        options.player_id = project.video_players.length;
		
        project.video_players.push(this);
        options.autoplay = options.autoplay || false;

        this.options = {
                "autoplay" : options.autoplay
        };

        $.extend(this.options, options);

        this.initialize();
    };
    project.PlayerBehaviour.prototype.initialize = function()
    {	
        this.player = new project.ExtendedVideoJs(this.video_id, {
            autoplay: false,
            preload: false,
            useBuiltInControls: false, // Use the browser's controls (iPhone)
            controlsBelow: false, // Display control bar below video vs. in front of
            controlsAtStart: false, // Make controls visible when page loads
            controlsHiding: true, // Hide controls when not over the video
            defaultVolume: 0.75, // Will be overridden by localStorage volume if available
           // playerFallbackOrder: ["flash","html5"], // Players and order to use them
			playerFallbackOrder: ["html5"], // Players and order to use them
            flashPlayerVersion: 10 // Required flash version for fallback
        });
		
		this.player._is_flash = true;

        if (!this.player.flashSupported())
        {
            this.player._is_flash = false;
            this.controls = jQuery(this.player.controls);
            this.initializeCustomButtons();
			this.initializePlayerState();
        }
    };
	
    project.PlayerBehaviour.prototype.initializeCustomButtons = function()
    {
        var that = this;
        var btn_volume_up = this.controls.find('.vjs-volume-up');
        var btn_volume_down = this.controls.find('.vjs-volume-down');

        btn_volume_up.click(function()
        {
            var volume = that.player.volume();
            var volNum = 1 / 8;
            var new_vol = volume + volNum;
            if (new_vol < 1)
            {
                that.player.volume(new_vol);
            }
            else
            {
                that.player.volume(1);
            }
        });

        btn_volume_down.click(function()
        {
            var volume = that.player.volume();
            var volNum = 1 / 8;
            var new_vol = volume - volNum;
            if (new_vol > 0)
            {
                that.player.volume(new_vol);
            }
            else
            {
                that.player.volume(0);
            }
        });

        var mute_button = this.controls.find('.vjs-volume-mute');

        mute_button.click(function()
        {
            var volume = that.player.volume();

            if (volume != 0)
            {
                that.temp_volume = volume;
                that.player.volume(0);
            }
            else
            {
                that.player.volume(that.temp_volume || that.player.options.defaultVolume);
            }
        });
    };

	
	//Add player state change events for communication with javascript
	project.PlayerBehaviour.prototype.initializePlayerState = function()
	{
		this.player.onEnded(function(){ updatePlayerStateInGui('videoOnEnd'); });
		this.player.onPlay(function(){ updatePlayerStateInGui('playVideo'); });
		this.player.onPause(function(){ updatePlayerStateInGui('pauseVideo'); });

	}
	
    JsBehaviourToolkit.registerHandler("video_player", project.PlayerBehaviour);

})(jQuery);
