/**
 * YouTube Player (youtube_player.js)
 * Copyright (c) 2008 Jack Szwergold. All rights reserved.
 *
 * w: http://www.runwork.com
 * e: me@runwork.com
 *
 * Created: 2008-03-29
 * Version: 2009-03-01
 *
 */

  GoogleAPIKey = 'AI39si5LVbFeyaF-sP7TOM6CWZKJPQ6BjKVKolpKwK868JsD7W1ucWQPCopRggKmCet2VIbSJcMxRB1CJWvAllTxZyY3pwdVOw';

  Event.observe(window, 'load', function () {
    YouTube = new YouTubeJSPlayer();
  });

  var YouTubeJSPlayer = Class.create();

  YouTubeJSPlayer.prototype = {

    initialize: function() {
      this.yourDevKey = GoogleAPIKey;

      // my stuff
      PlayerSwitch = this.playerswitch.bind();
      PlayTheVideo = this.playthevideo.bind();
      Activate = this.activate.bind(this);

      // youtube/google specific
      youTubeStateChange = this.statechange.bind(this);
      youTubeError = this.error.bind(this);
    },

    // ready the player
    activate: function(videoInfoJSON) {
      var videoInfo = videoInfoJSON.evalJSON();
      var videoID = videoInfo.videoID;
      var playerID = videoInfo.playerID;
      var showControls = videoInfo.showControls;
      var quality = (typeof(videoInfo.quality) == 'number') ? Math.abs(videoInfo.quality) : 0;

      this.params = { allowScriptAccess: 'always', bgcolor: '000000', wmode: 'window' };
      this.atts = { id: playerID };
      this.url = 'http://www.youtube.com/apiplayer?key=' + this.yourDevKey + '&enablejsapi=1&playerapiid=' + playerID;
      if ($('SWFOverlay'+playerID)) {
        this.ytWidth = $('SWFOverlay'+playerID).getWidth();
        this.ytHeight = $('SWFOverlay'+playerID).getHeight();
      }

      swfobject.embedSWF(this.url, 'SWFPlayer'+playerID, this.ytWidth, this.ytHeight, '8', null, null, this.params, this.atts);

      this.videoID = videoID;
      this.showControls = showControls;
      this.quality = quality;

      this.SWFPlayer = 'SWFPlayer'+playerID;
      this.SWFOverlay = 'SWFOverlay'+playerID;
      this.SWFError = 'SWFError'+playerID;

      this.PlayButton = 'PlayButton'+playerID;
      this.PauseButton = 'PauseButton'+playerID;
      this.Playback = 'Playback'+playerID;
      this.Volume = 'Volume'+playerID;

      this.track_playback = 'track_playback'+playerID;
      this.handle_playback = 'handle_playback'+playerID;
      this.bar_playback = 'bar_playback'+playerID;

      this.track_volume = 'track_volume'+playerID;
      this.handle_volume = 'handle_volume'+playerID;
      this.bar_volume = 'bar_volume'+playerID;

      var parent = this;
      onYouTubePlayerReady = function (ytPlayer) {
        this.ytPlayerActive = ytPlayer;
            this.ytPlayer = $(ytPlayer);

        this.SWFPlayer = parent.SWFPlayer;
        this.SWFOverlay = parent.SWFOverlay;
        this.SWFError = parent.SWFError;

        this.PlayButton = parent.PlayButton;
        this.PauseButton = parent.PauseButton;
        this.Playback = parent.Playback;
        this.Volume = parent.Volume;

        this.track_playback = parent.track_playback ;
        this.handle_playback = parent.handle_playback;
        this.bar_playback = parent.bar_playback;

        this.track_volume = parent.bar_playback;
        this.handle_volume = parent.handle_volume;
        this.bar_volume = parent.bar_volume;

            if(null != this.ytPlayer) {
              if(typeof(parent.volumeSliders) == 'object') {
                parent.volumeSliders.setDisabled();
              }
              if(typeof(parent.controlSliders) == 'object') {
                parent.controlSliders.setDisabled();
              }
              this.peControls = new PeriodicalExecuter(function () { parent.updateinfo(); }, .25);
              this.ytPlayer.addEventListener('onError', 'youTubeError');
              this.ytPlayer.addEventListener('onStateChange', 'youTubeStateChange');
              this.ytPlayer.setStyle( { visibility: 'hidden' } );
              this.ytPlayer.setSize(parent.ytWidth, parent.ytHeight);
              this.PlayTheVideo(videoID, parent.quality);
              parent.sliders();
            }
          }
    },

    // Controls based on player state
    playerswitch: function(videoInfo) {
      var videoInfoJSON = Object.toJSON(videoInfo);
      Activate(videoInfoJSON);
      var videoInfo = videoInfoJSON.evalJSON();
      var videoID = videoInfo.videoID;
      var playerID = videoInfo.playerID;
      var showControls = videoInfo.showControls;

      // This kills off any currently active player.
      if (this.ytPlayerActive != videoInfo.playerID && (typeof(this.ytPlayerActive) != 'undefined')) {
        this.peControls.stop();
        $(this.ytPlayerActive).stopVideo();
        $(this.ytPlayerActive).clearVideo();
        swfobject.removeSWF(this.ytPlayerActive);

        var new_player = new Element('div', { 'class' : 'SWFPlayer', 'id' : 'SWFPlayer' + this.ytPlayerActive } );
        Element.insert($('SWFOverlay'+this.ytPlayerActive), { after: new_player } );
        $('SWFPlayer'+this.ytPlayerActive).update('<!-- SWF placeholder -->');

        // Why do I need to do this for FireFox?!?!?!
        setTimeout( function() { $('SWFOverlay'+this.ytPlayerActive).show(); }, 0 );
        $('PauseButton'+this.ytPlayerActive).hide();
        $('PlayButton'+this.ytPlayerActive).show();
        if (!showControls) {
          $('Playback'+this.ytPlayerActive).hide();
          $('Volume'+this.ytPlayerActive).hide();
        }
      }

      if(null != this.ytPlayer) {
        switch(this.ytPlayer.getPlayerState()) {
              case -1: // unstarted
                this.PlayTheVideo(videoID);
                break;
              case 0: // ended
              case 2: // pause
                if (this.Playing != videoID)
                  this.PlayTheVideo(videoID);
                else
                  this.ytPlayer.playVideo();
                break;
              case 1: // playing
                if (this.Playing != videoID)
                  this.PlayTheVideo(videoID);
                else
                  this.ytPlayer.pauseVideo();
                break;
              case 3: // buffering
                if (this.Playing != videoID)
                  this.PlayTheVideo(videoID);
                else
                  this.ytPlayer.pauseVideo();
                break;
        }
      }
    },

    // play the video
    playthevideo: function(videoID, quality) {
          if(null != this.ytPlayer) {
        this.playQuality = (quality > 0) ? '&fmt=' + Math.abs(quality) : '';
            this.Playing = videoID;
            $(this.SWFOverlay).hide();
                this.ytPlayer.setStyle( { visibility: 'visible' } );
            this.ytPlayer.stopVideo();
            this.ytPlayer.clearVideo();
            this.ytPlayer.loadVideoById(videoID + this.playQuality, 0);
                this.ytPlayer.playVideo();
                this.ytPlayer.unMute();
          }
        },

    // stop the video
    stopthevideo: function() {
      $(this.SWFError).show();
      $(this.PlayButton).hide();
      $(this.PauseButton).hide();
      $(this.Playback).hide();
      $(this.Volume).hide();
        },

    // error catch
    error: function(errorCode) {
      switch(errorCode) {
        case 2: // not found (???)
          this.stopthevideo();
              break;
            case 100: // not found
          if (this.quality > 0)
            parent.ytPlayer.loadVideoById(this.videoID, 0);
          else
            this.stopthevideo();
              break;
        case 101: // no embedding
          this.stopthevideo();
              break;
        case 150: // no embedding (???)
          this.stopthevideo();
              break;
      }
    },

    // player state
    statechange: function(newStateRAW) {
      var newState = (typeof(newStateRAW) != "number") ? 0 : newStateRAW;
      switch(newState) {
        case -1: // unstarted
              break;
        case 0: // ended
          $(this.SWFOverlay).show();
          $(this.PlayButton).show();
          $(this.PauseButton).hide();
          if (!this.showControls) {
            $(this.Playback).hide();
            $(this.Volume).hide();
          }
          $(parent.ytPlayer).setStyle( { visibility: 'hidden' } );
              break;
        case 2: // pause
          $(this.PlayButton).show();
          $(this.PauseButton).hide();
              break;
            case 1: // playing
          $(this.SWFOverlay).hide();
          $(this.SWFError).hide();
          $(this.PlayButton).hide();
          $(this.PauseButton).show();
          $(this.Playback).show();
          $(this.Volume).show();
          $(parent.ytPlayer).setStyle( { visibility: 'visible' } );
              break;
            case 3: // buffering
          $(this.SWFOverlay).hide();
          $(this.SWFError).hide();
          $(this.PlayButton).hide();
          $(this.PauseButton).show();
          $(this.Playback).show();
          $(this.Volume).show();
          $(parent.ytPlayer).setStyle( { visibility: 'visible' } );
              break;
      }
    },

    // sliders
    sliders: function() {
      var parent = this;

      // This controls the video playback head
      this.controlSliders = new Control.Slider(this.handle_playback, this.track_playback, {
            sliderValue:1,
            onSlide:function(current) {
              $(parent.handle_playback).setStyle({left: parent.seek_offset(current)+'px'});
              $(parent.bar_playback).setStyle({width: parent.seek_offset(current)+'px'});
              ytPlayer.pauseVideo();
            },

            onChange:function(current) {
              $(parent.handle_playback).setStyle({left: parent.seek_offset(current)+'px'});
              $(parent.bar_playback).setStyle({width: parent.seek_offset(current)+'px'});
              ytPlayer.seekTo(current*ytPlayer.getDuration(), true);
              ytPlayer.playVideo();
            }
      });

          // controls the audio volume
      this.volumeSliders = new Control.Slider(this.handle_volume, this.track_volume, {
            sliderValue:1,
            onSlide:function(volume) {
              parent.adjust_volume(volume*100);
              $(parent.handle_volume).setStyle({left: parent.volume_offset()+'px'});
              $(parent.bar_volume).setStyle({width: parent.volume_offset()+'px'});
            },
            onChange:function(volume) {
              parent.adjust_volume(volume*100);
            }
          });

    },

    // adjust volume
    adjust_volume: function(value) {
      parent.ytPlayer.unMute();
      parent.ytPlayer.setVolume(value);
    },

    // update info
    updateinfo: function() {
      if ($('debugYouTube')) { debugYouTube(); }
          $(parent.handle_playback).setStyle({left: this.play_offset()+'px'});
          $(parent.bar_playback).setStyle({width: this.play_offset()+'px'});
          $(this.handle_volume).setStyle({left: this.volume_offset()+'px'});
          $(this.bar_volume).setStyle({width: this.volume_offset()+'px'});
        },

    // volume offset
    volume_offset: function() {
      return (parent.ytPlayer.getVolume()*($(this.track_volume).getWidth()/100));
    },

    // playback offset
    play_offset: function() {
      return (($(this.track_playback).getWidth()/parent.ytPlayer.getDuration())*parent.ytPlayer.getCurrentTime());
    },

    // seek offset
    seek_offset: function(current) {
          return (($(this.track_playback).getWidth()/parent.ytPlayer.getDuration())*(current*parent.ytPlayer.getDuration()));
    }

  }
