/**
 * POKE Youtube Chromless Player Plugin for Virgin Racing
 * SWFObject Required
 * Auth: Chris Reeves, POKE, 9/2/2010
 */

/**
 * We are going to have to store references to each player so we can
 * run the onReady method for eachplayer instance (youtube api not allowing us to define our own on ready call back)
 */
var PokeYouTubePlayers = Array();

/**
 * Required youtube callback when video is ready
 */
function onYouTubePlayerReady(playerId) {
  var key = parseInt(playerId.replace('pokeytplayer', ''));
  PokeYouTubePlayers[key].onReady(document.getElementById("pokeytplayerapi"+key));
}

/**
 * JQuery function
 */ 
(function($) {

  /**
   * JQuery plugin function
   * $(elment).youtube(ops);
   */
  $.fn.youtube = function(ops) {
    var elmn = this[0];
    var node = elmn.nodeName;
    
    var staticURL = '/media/images/buttons/';
    if(ops.staticURL) {
      staticURL = ops.staticURL;
    }
    
    // make sure we are collaing on a div    
    if(node == 'DIV') {
      var defaultOps = {
        width     : '100%',
        height    : '100%',
        staticURL : staticURL,
        params    : { 
          allowScriptAccess : "always", 
          bgcolor           : "#000", 
          wmode             : 'transparent' },
        atrbs     : { 
          id                : "pokeytplayerapi" },
        controls  : {
          restart           : {   
            html  : $('<img/>').attr('src', staticURL+'btn-video-restart.png').addClass('pngfix'),
            css   : 'restart',
            fn    : function(elmn) {
              this.restart(elmn);
            } },
          playToggle        : { 
            html  : $('<img/>').attr('src', staticURL+'btn-video-pause.png').addClass('pngfix'),
            css   : 'playToggle',
            fn    : function() {
              this.playToggle();
            } },
          stop              : { 
            html  : $('<img/>').attr('src', staticURL+'btn-video-stop.png').addClass('pngfix'),
            css   : 'stop',
            fn    : function() {
              this.stop();
            } },
          soundToggle       : { 
            html  : $('<img/>').attr('src', staticURL+'btn-video-soundOn.png').addClass('pngfix'),
            css   : 'soundToggle',
            last  : true,
            fn    : function() {
              this.soundToggle();
            } 
          }
        }
      }
      var ops = $.extend(defaultOps, ops);
      return PokeYTPlayer(this, ops);
    } else {
      alert('You must apply the youtube player to a div element');
    }
  }

  /**
   * Poke Youtube Player function
   * @param obj element
   * @param obj options
   */
  function PokeYTPlayer(elmn, ops) {
    return this instanceof PokeYTPlayer ? this.init(elmn, ops) : new PokeYTPlayer(elmn, ops);
  }
  
  /**
   * PokeYTPlayer Instance Counter
   */
  PokeYTPlayer.counter = 0;
  
  /**
   * PokeYTPlayer Class
   */
  $.extend(PokeYTPlayer.prototype, {
    
    id: null,             // instance id
    elmn: null,           // element plugin called on
    parent: null,         // plugin elements parent
    playerapi: null,      // youtube player api
    objectID: null,       // <object> element id attribute
    controls: null,       // injected controls element
    timer: null,          // injected timer element
    intervalID: null,     // interval ID
    duration: null,       // video duration
    currTime: null,       // current video play time
    ops: {},              // supplied options object
    
    /**
     * Init method (constructor)
     * Fired when the plugin is called, should take care of some basic setup and embed the video player
     * @param obj plugin dom element
     * @param obj options
     */
    init: function(elmn, ops) {
      this.id = PokeYTPlayer.counter;
      this.elmn = $(elmn);
      this.parent = this.elmn.parent();
      this.ops = ops || {};
      ops.atrbs.id = ops.atrbs.id+PokeYTPlayer.counter;
      this.objectID = ops.atrbs.id;
      var playerID = "pokeytplayer"+PokeYTPlayer.counter;
			swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid="+playerID, 
				this.elmn.attr('id'), this.ops.width, this.ops.height, "8", null, null, this.ops.params, this.ops.atrbs);
			PokeYouTubePlayers.push(this);
      PokeYTPlayer.counter++;
    },
    
    /**
     * On ready callback
     * Fired when the youtube video is ready, should load the video and start playing
     * @param obj player api element
     */
    onReady: function(playerapi) {
      var self = this;
      this.playerapi = playerapi;
      this.playerapi.loadVideoById(this.ops.videoID, 0);
      this.ops.placeholder.hide();
      this.ops.playBtn.hide();
      this.intervalID = setInterval(function() {
        self.duration = self.playerapi.getDuration();
        self.currTime = self.playerapi.getCurrentTime();
        self.updateCurrentTime();
      }, 250);
      this.buildControls();
      this.buildTimer();
    },
    
    /**
     * Build player controls
     * Builds the players controls as defined in this.ops.controls
     */
    buildControls: function() {
      this.controls = $('<ul/>').addClass('controls');
      var self = this;
      for(name in this.ops.controls) {
        var control = this.ops.controls[name];
        var li = $('<li/>').addClass(control.css).addClass('pngfix').append($('<a>').attr('href', '#'+name).addClass(control.css).addClass('pngfix').bind('click', function() {
          var control = self.ops.controls[$(this).attr('href').replace('#', '')];
          if(control.fn) {
            control.fn.apply(self);
          }
          $(this).blur();
          return false;
        }).append(control.html));
        if(control.last) {
          li.addClass('last');
        }
        li.appendTo(this.controls);
      }
      this.parent.append(this.controls);
      this.ie6ObjectFix();
      // remove blur from links
      this.parent.find('a').focus(function() {
        $(this).blur();
      });
    },
    
    /**
     * Build Timer
     * Builds the elements to hold the player duration and current time
     */
    buildTimer: function() {
      var self = this;
      var currTimeElmn = $('<div/>').addClass('currTime').append('00:00');
      var slash = $('<div/>').addClass('slash').append('/');
      var durationElmn = $('<div/>').addClass('duration').append('00:00');
      this.timer = $('<div/>').addClass('timer').addClass('pngfix');
      var times = $('<div/>').addClass('times').append(currTimeElmn).append(slash).append(durationElmn)
      this.timer.append(times);
      var share = $('<div/>').addClass('share').append($('<a/>').attr('target', '_blank').attr('href', this.playerapi.getVideoUrl()).append('SHARE').click(function() {
        self.playToggle();
      }));
      this.timer.append(share);
      this.controls.after(this.timer);
      Cufon.set('fontFamily', 'Gotham Rounded').replace('.timer .times').replace('.timer .share', {
        hover: true
      });
    },
    
    /**
     * IE 6 Fixes 
     * If IE6 (you know, that 10 year old browser that people STILL support), 
     * fix css positioning of the object 
     */
    ie6ObjectFix: function() {
      if($.browser.msie && $.browser.version == '6.0') {
        $('#'+this.objectID).css({
          'z-index': 1,
          'position': 'absolute',
          'top': 0,
          'left': 0
        });
      }
    },
    
    /**
     * Restart Video
     * Sends the player head back to the start of the video
     */
    restart: function() {
      this.playerapi.seekTo(0);
    },
    
    /**
     * Play toggle
     * Pauses / Plays the video acording to video state
     */
    playToggle: function() {
      elmn = this.controls.find('a[href="#playToggle"]');
      var state = this.playerapi.getPlayerState();
      if(state == 1) {
        this.playerapi.pauseVideo();
        elmn.find('shape').remove();
        elmn.find('img').remove();
        elmn.append($('<img/>').attr('src', this.ops.staticURL+'btn-video-play.png').addClass('pngfix'));
      } else if(state == 2) {
        this.playerapi.playVideo();
        elmn.find('shape').remove();
        elmn.find('img').remove();
        elmn.append($('<img/>').attr('src', this.ops.staticURL+'btn-video-pause.png').addClass('pngfix'));
      }
    },
    
    /**
     * Stop Video
     * Should destroy the swf object and resotre the old element
     */
    stop: function() {
      // more ie6 specific issues, yeyness :D
      if($.browser.msie && $.browser.version == '6.0') {
        this.timer.prev().remove();
      }
      $('#'+this.objectID).remove();
      this.controls.remove();
      this.timer.remove();
      this.ops.placeholder.show();
      this.ops.playBtn.show();
      this.elmn.appendTo(this.parent);
      clearInterval(this.intervalID);
    },
    
    /**
     * Sound Toggle
     * Toggles the sound on or off depending on current mute status
     */
    soundToggle: function() {
      elmn = this.controls.find('a[href="#soundToggle"]');
      if(this.playerapi.isMuted()) {
        this.playerapi.unMute();
        elmn.find('img').remove();
        elmn.find('shape').remove();
        elmn.append($('<img/>').attr('src', this.ops.staticURL+'btn-video-soundOn.png').addClass('pngfix'));
      } else {
        this.playerapi.mute();
        elmn.find('img').remove();
        elmn.find('shape').remove();
        elmn.append($('<img/>').attr('src', this.ops.staticURL+'btn-video-soundOff.png').attr({'height': '20', 'width': '19'}).addClass('pngfix'));
      }
    },
    
    /**
     * Update Timer
     * Updates the timer elements with the currect duration and current time
     */
    updateCurrentTime: function() {
      if(this.playerapi.getPlayerState() > 0) {
        this.timer.find('.duration').html(this.secsToMins(this.duration));
        this.timer.find('.currTime').html(this.secsToMins(this.currTime));
        Cufon.set('fontFamily', 'Gotham Rounded').replace('.timer .times');
      } else {
        this.stop();
      }
    },
    
    /**
     * Seconds to Minutes 
     * Converts a string of seconds into minutes, eg 304.00 becomes 5:07
     * @param string seconds
     */
    secsToMins: function(secs) {
      var time = parseFloat(secs);
      time = Math.round(secs);
      if(time > 59) {
        mins = Math.floor(time/60);
        secs = time % 60; 
        time = (mins < 10 ? '0'+mins : mins)+':'+((time % 60) < 10 ? '0'+(time % 60): time % 60);
      } else {
        time = '00:'+(time < 10 ? '0'+time : time);
      }
      return time;
    }
    
  });

})(jQuery);