(function() {
  var Bar, FlashMediaPlayer, HtmlMediaPlayer, MediaPlayer, MediaPlayerControls, MediaPlayerFactory, MediaSource, Plugin, Scrubber, Util, VolumeControl, i;
  var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

  Number.prototype.padLeft = function(width, char) {
    if (char == null) char = " ";
    if (("" + this).length >= width) return "" + this;
    return arguments.callee.call(char + this, width, char);
  };

  if (window.jQuery) {
    $.fn.mediaPlayer = function(options) {
      this.each(function() {
        return MediaPlayerFactory.create(this, options || {});
      });
      return this;
    };
  }

  MediaPlayerFactory = {
    create: function(element, options) {
      var browserCanPlayVideo, flash, player, videoEl;
      videoEl = document.createElement('video');
      browserCanPlayVideo = !!videoEl.canPlayType && (videoEl.canPlayType('video/mp4') || videoEl.canPlayType('video/webm'));
      if (browserCanPlayVideo) {
        player = new HtmlMediaPlayer(element, options);
      } else {
        flash = new Plugin('flash');
        $(element).addClass('fallback');
        if (flash.isInstalled || flash.version.major < 10) {
          $(element).addClass('fallback');
          player = new FlashMediaPlayer(element, options);
        }
      }
      $(element).data('controller', player);
      return player;
    }
  };

  Util = {
    getRelativePosition: function(x, relativeElement) {
      return Math.max(0, Math.min(1, (x - this.findPosX(relativeElement)) / relativeElement.offsetWidth));
    },
    findPosX: function(element) {
      var curleft;
      curleft = element.offsetLeft;
      while ((element = element.offsetParent)) {
        curleft += element.offsetLeft;
      }
      return curleft;
    },
    blockTextSelection: function() {
      document.body.focus();
      return document.onselectstart = function() {
        return false;
      };
    },
    unblockTextSelection: function() {
      return document.onselectstart = function() {
        return true;
      };
    }
  };

  MediaSource = (function() {

    function MediaSource(model) {
      this.url = model.url;
      this.type = model.type;
    }

    MediaSource.prototype.isPlayableBy = function(player) {
      return player.canPlayType(this.type);
    };

    MediaSource.prototype.toElement = function() {
      return $('<source />', {
        src: this.url,
        type: this.type
      });
    };

    return MediaSource;

  })();

  i = 0;

  MediaPlayer = (function() {

    function MediaPlayer(element, options) {
      var s, _i, _len, _ref;
      this.options = options;
      this.element = $(element);
      this.index = i++;
      this.initialized = false;
      this.autoPlay = false;
      this.duration = 0;
      this.currentTime = 0;
      this.bufferedTime = 0;
      this.volume = localStorage.volume || 0.8;
      this.played = false;
      this.paused = true;
      this.ended = false;
      this.isFullScreen = false;
      this.width = this.element.width();
      this.height = this.element.height();
      this.sources = [];
      _ref = this.element.find('source');
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        s = _ref[_i];
        this.sources.push(new MediaSource({
          url: s.getAttribute('src'),
          type: s.getAttribute('type')
        }));
      }
      this.controls = new MediaPlayerControls(this);
    }

    MediaPlayer.prototype.setPoster = function(poster) {
      return this.element.find('.poster').css('backgroundImage', 'url(' + poster.url + ')');
    };

    MediaPlayer.prototype.setSources = function(sources) {
      return this.sources = sources;
    };

    MediaPlayer.prototype.reset = function() {
      this.currentTime = 0;
      this.bufferedTime = 0;
      this.duration = 0;
      this.paused = true;
      this.element.removeClass('played playing paused').addClass('waiting');
      return this.controls.reset();
    };

    MediaPlayer.prototype.onPlay = function() {
      this.paused = false;
      this.ended = false;
      this.played = true;
      this.element.removeClass('paused ended').addClass('played playing');
      return this.element.trigger('play');
    };

    MediaPlayer.prototype.onPause = function() {
      this.paused = true;
      this.element.removeClass('playing').addClass('paused');
      return this.element.trigger('pause');
    };

    MediaPlayer.prototype.onEnded = function() {
      this.ended = true;
      this.paused = true;
      this.element.removeClass('playing').addClass('ended');
      return this.element.trigger('ended');
    };

    MediaPlayer.prototype.onDurationChange = function(duration) {
      this.duration = duration;
      return this.element.trigger('durationChange', duration);
    };

    MediaPlayer.prototype.onTimeUpdate = function(timeInSeconds) {
      this.element.removeClass('waiting');
      this.currentTime = timeInSeconds;
      return this.element.trigger('timeUpdate', timeInSeconds);
    };

    MediaPlayer.prototype.onBufferedTimeChange = function(bufferedTime) {
      this.bufferedTime = bufferedTime;
      return this.element.trigger('bufferedTimeChange', bufferedTime);
    };

    MediaPlayer.prototype.onVolumeChange = function(volume) {
      this.volume = volume;
      localStorage.volume = volume;
      if (volume > 0) {
        this.element.removeClass('muted');
        this.element.find('.volume').removeClass('muted');
        this.muted = false;
      }
      return this.element.trigger('volumeChange', volume);
    };

    MediaPlayer.prototype.mute = function() {
      this.volumeBeforeMute = this.volume;
      this.setVolume(0);
      this.muted = true;
      this.element.trigger('muted');
      this.element.addClass('muted');
      return this.element.find('.volume').addClass('muted');
    };

    MediaPlayer.prototype.unmute = function() {
      this.setVolume(this.volumeBeforeMute);
      this.muted = false;
      this.element.removeClass('muted');
      return this.element.find('.volume').removeClass('muted');
    };

    MediaPlayer.prototype.onError = function(error) {
      return this.element.trigger('error', error);
    };

    MediaPlayer.prototype.onSeeking = function() {
      this.element.addClass('waiting');
      return this.element.trigger('seeking');
    };

    MediaPlayer.prototype.onSeeked = function() {
      this.element.removeClass('waiting');
      return this.element.trigger('seeked');
    };

    MediaPlayer.prototype.onWaiting = function() {
      return this.element.trigger('waiting');
    };

    return MediaPlayer;

  })();

  HtmlMediaPlayer = (function() {

    __extends(HtmlMediaPlayer, MediaPlayer);

    function HtmlMediaPlayer(element, options) {
      this.head = $(element).find('video')[0];
      this.head.controls = false;
      HtmlMediaPlayer.__super__.constructor.call(this, element, options);
      $(this.head).on({
        'loadedmetadata': this.onLoadedMetadata.bind(this),
        'ended': this.onEnded.bind(this),
        'timeupdate': this.onTimeUpdate.bind(this),
        'volumechange': this.onVolumeChange.bind(this),
        'progress': this.onProgress.bind(this),
        'seeking': this.onSeeking.bind(this),
        'seeked': this.onSeeked.bind(this),
        'waiting': this.onWaiting.bind(this),
        'error': this.onError.bind(this),
        'webkitfullscreenchange': this.onFullScreenChange.bind(this)
      });
    }

    HtmlMediaPlayer.prototype.canPlay = function(type) {
      return this.head.canPlayType(type);
    };

    HtmlMediaPlayer.prototype.play = function() {
      this.head.play();
      return this.onPlay();
    };

    HtmlMediaPlayer.prototype.pause = function() {
      this.head.pause();
      return this.onPause();
    };

    HtmlMediaPlayer.prototype.seek = function(timeInSeconds) {
      if (this.initialized) return this.head.currentTime = timeInSeconds;
    };

    HtmlMediaPlayer.prototype.setVolume = function(volume) {
      return this.head.volume = volume;
    };

    HtmlMediaPlayer.prototype.setSources = function(sources) {
      var source, _i, _len, _ref;
      HtmlMediaPlayer.__super__.setSources.call(this, sources);
      $(this.head).children('source').remove();
      _ref = this.sources;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        source = _ref[_i];
        new MediaSource(source).toElement().appendTo($(this.head));
      }
      return this.reload();
    };

    HtmlMediaPlayer.prototype.reload = function() {
      if (!this.paused) this.pause();
      this.reset();
      return this.head.load();
    };

    HtmlMediaPlayer.prototype.enterFullscreen = function() {
      this.isFullscreen = true;
      this.element.addClass('fullscreen');
      if (this.supportsFullscreen) return this.head.webkitEnterFullScreen();
    };

    HtmlMediaPlayer.prototype.exitFullscreen = function() {
      this.isFullscreen = false;
      if (this.supportsFullscreen) this.head.webkitExitFullscreen();
      return this.element.removeClass('fullscreen');
    };

    HtmlMediaPlayer.prototype.onError = function(e) {
      console.log(e);
      return HtmlMediaPlayer.__super__.onError.call(this, e);
    };

    HtmlMediaPlayer.prototype.onFullScreenChange = function(e) {
      this.isFullscreen = document.webkitIsFullScreen;
      if (this.isFullscreen) {
        this.element.addClass('fullscreen');
      } else {
        this.element.removeClass('fullscreen');
      }
      return this.head.controls = false;
    };

    HtmlMediaPlayer.prototype.onLoadedMetadata = function(e) {
      console.log('metadata loaded');
      this.initialized = true;
      this.onDurationChange(e.target.duration);
      this.supportsFullscreen = this.head.webkitSupportsFullscreen;
      if (this.supportsFullscreen) this.element.addClass('supportsFullscreen');
      return this.setVolume(this.volume);
    };

    HtmlMediaPlayer.prototype.onProgress = function(e) {
      var buffered, bufferedTime;
      buffered = this.head.buffered;
      if (!(buffered && buffered.length >= 1)) return;
      bufferedTime = buffered.end(0);
      return this.onBufferedTimeChange(bufferedTime);
    };

    HtmlMediaPlayer.prototype.onPlay = function(e) {
      return HtmlMediaPlayer.__super__.onPlay.call(this);
    };

    HtmlMediaPlayer.prototype.onPause = function(e) {
      return HtmlMediaPlayer.__super__.onPause.call(this);
    };

    HtmlMediaPlayer.prototype.onVolumeChange = function(e) {
      return HtmlMediaPlayer.__super__.onVolumeChange.call(this, e.target.volume);
    };

    HtmlMediaPlayer.prototype.onTimeUpdate = function(e) {
      return HtmlMediaPlayer.__super__.onTimeUpdate.call(this, e.target.currentTime);
    };

    return HtmlMediaPlayer;

  })();

  FlashMediaPlayer = (function() {

    __extends(FlashMediaPlayer, MediaPlayer);

    function FlashMediaPlayer(element, options) {
      FlashMediaPlayer.__super__.constructor.call(this, element, options);
      this.pluginPlaceholder = this.element.find('.fallback');
      this.movieName = 'player_1';
      this.element.find('video').remove();
      window.player = this;
      this.pluginPlaceholder.html(this.getPluginHTML());
      this.plugin = document.getElementById(this.movieName);
    }

    FlashMediaPlayer.prototype.play = function() {
      this.callFlash('_play');
      return this.onPlay();
    };

    FlashMediaPlayer.prototype.pause = function() {
      this.callFlash('_pause');
      return this.onPause();
    };

    FlashMediaPlayer.prototype.reload = function() {
      this.reset();
      return this.callFlash('_loadUrl', this.sources[0].url);
    };

    FlashMediaPlayer.prototype.setVolume = function(volume) {
      return this.callFlash('_setVolume', volume);
    };

    FlashMediaPlayer.prototype.seek = function(time) {
      return this.callFlash('_seek', time);
    };

    FlashMediaPlayer.prototype.setSources = function(sources) {
      FlashMediaPlayer.__super__.setSources.call(this, sources);
      return this.reload();
    };

    FlashMediaPlayer.prototype.callFlash = function(functionName, arg) {
      try {
        if (arg) {
          return this.plugin[functionName](arg);
        } else {
          return this.plugin[functionName]();
        }
      } catch (ex) {
        return this.onDebug("Exception calling flash function '" + functionName + "': " + ex.message);
      }
    };

    FlashMediaPlayer.prototype.callback = function(functionName, arg) {
      try {
        this[functionName].bind(this)(arg);
      } catch (error) {
        this.onDebug(error);
      }
      return false;
    };

    FlashMediaPlayer.prototype.getPluginHTML = function() {
      var params, pluginSrc;
      params = {
        url: this.sources[0].url,
        backgroundColor: '0x000000',
        width: this.width,
        height: this.height,
        autoPlay: this.autoPlay,
        playerRef: 'player'
      };
      pluginSrc = 'http://s.cmcdn.net/scripts/player/2011-02-01.swf';
      if ($.browser.msie) pluginSrc += '?' + new Date().getTime();
      return ['<object', ' id="', this.movieName, '"', ' name="', this.movieName, '"', ' type="application/x-shockwave-flash"', ' data="', pluginSrc, '"', ' width="', this.width, '"', ' height="', this.height, '"', '>', '<param name="wmode" value="windowless" />', '<param name="movie" value="', pluginSrc, '" />', '<param name="menu" value="false" />', '<param name="quality" value="autohigh" />', '<param name="allowScriptAccess" value="always" />', '<param name="flashvars" value="' + jQuery.param(params) + '" />', '</object>'].join('');
    };

    FlashMediaPlayer.prototype.onComplete = function() {
      return this.onEnded();
    };

    FlashMediaPlayer.prototype.onVolumeChange = function(volume) {
      return FlashMediaPlayer.__super__.onVolumeChange.call(this, volume);
    };

    FlashMediaPlayer.prototype.onDurationChange = function(duration) {
      return FlashMediaPlayer.__super__.onDurationChange.call(this, duration);
    };

    FlashMediaPlayer.prototype.onCurrentTimeChange = function(time) {
      return this.onTimeUpdate(time);
    };

    FlashMediaPlayer.prototype._onLoadProgress = function(progress) {
      return this.onLoadProgress(progress);
    };

    FlashMediaPlayer.prototype.onLoadProgress = function(progress) {
      return this.onBufferedTimeChange(this.duration * progress);
    };

    FlashMediaPlayer.prototype.onJsReady = function() {
      return this.initialized = true;
    };

    FlashMediaPlayer.prototype.onPlayerStateChange = function(state) {
      return this.onDebug('state change:' + state);
    };

    FlashMediaPlayer.prototype.onDebug = function(message) {
      try {
        return console.write(message);
      } catch (error) {

      }
    };

    FlashMediaPlayer.prototype.onMediaError = function(error) {
      var errStr;
      errStr = 'errorID: ' + error.errorID + '<br /> - message: ' + error.message + '<br /> - detail: ' + error.detail;
      alert(errStr);
      return this.onDebug('onMediaError: ' + errStr);
    };

    FlashMediaPlayer.prototype.onBufferingChange = function(buffering) {
      if (buffering) return this.onWaiting();
    };

    return FlashMediaPlayer;

  })();

  MediaPlayerControls = (function() {

    function MediaPlayerControls(player) {
      var _this = this;
      this.player = player;
      this.element = this.player.element.find('.controls');
      this.hidden = false;
      this.scrubber = new Scrubber(this.element.find('.scrubber'), this);
      this.volume = new VolumeControl(this.element.find('.volume'), this);
      this.element.find('.box').click(function(e) {
        return false;
      });
      this.element.find('.fullscreenToggle').click(function(e) {
        if (_this.player.isFullscreen) {
          return _this.player.exitFullscreen();
        } else {
          return _this.player.enterFullscreen();
        }
      });
      this.bufferedBar = new Bar(this.element.find('.bufferedBar'));
      this.playedBar = new Bar(this.element.find('.playedBar'));
      this.currentTime = $('.currentTime');
      this.totalTime = $('.totalTime');
      this.player.element.on({
        play: function(e) {},
        muted: function(e) {},
        pause: function(e) {},
        timeUpdate: function(e, time) {
          var minutes, playedValue, seconds;
          if (_this.scrubber.dragging) return;
          playedValue = time / _this.player.duration;
          _this.playedBar.setValue(playedValue);
          minutes = parseInt(time / 60);
          seconds = parseInt(time % 60);
          return _this.currentTime.text("" + (minutes.padLeft(1, '0')) + ":" + (seconds.padLeft(2, '0')));
        },
        durationChange: function() {
          var minutes, seconds;
          minutes = parseInt(_this.player.duration / 60);
          seconds = parseInt(_this.player.duration % 60);
          return _this.totalTime.text("" + (minutes.padLeft(1, '0')) + ":" + (seconds.padLeft(2, '0')));
        },
        bufferedTimeChange: function(e, bufferedTime) {
          var bufferedValue;
          bufferedValue = bufferedTime / _this.player.duration;
          return _this.bufferedBar.setValue(bufferedValue);
        },
        click: function(e) {
          if (_this.player.paused) {
            _this.player.play();
          } else {
            _this.player.pause();
          }
          return false;
        },
        mousemove: this.mouseMove.bind(this),
        mouseenter: this.mouseMove.bind(this),
        mouseleave: this.mouseOut.bind(this)
      });
      this.element.find('.playToggle').click(function() {
        if (_this.player.paused) {
          return _this.player.play();
        } else {
          return _this.player.pause();
        }
      });
    }

    MediaPlayerControls.prototype.reset = function() {
      this.playedBar.setValue(0);
      return this.bufferedBar.setValue(0);
    };

    MediaPlayerControls.prototype.hoverIdle = function(e) {
      return this.player.element.addClass('hoverIdle');
    };

    MediaPlayerControls.prototype.mouseOut = function(e) {
      return this.player.element.removeClass('hovering hoverIdle');
    };

    MediaPlayerControls.prototype.mouseMove = function(e) {
      this.player.element.addClass('hovering').removeClass('hoverIdle');
      if (this.mouseMoveTimeout) clearInterval(this.mouseMoveTimeout);
      return this.mouseMoveTimeout = setTimeout(this.hoverIdle.bind(this), 3000);
    };

    return MediaPlayerControls;

  })();

  Scrubber = (function() {

    function Scrubber(element, controls) {
      this.element = element;
      this.controls = controls;
      this.player = this.controls.player;
      this.dragging = false;
      this.wasPlaying = false;
      this.element.find('.track').on({
        'mousedown': this.startScrub.bind(this),
        'mouseup': this.stopScrub.bind(this)
      });
      this.element.click(function() {
        return false;
      });
    }

    Scrubber.prototype.startScrub = function(e) {
      Util.blockTextSelection();
      this.wasPlaying = !this.player.paused;
      this.dragging = true;
      this.player.element.addClass('scrubbing');
      this.scrubTo(e);
      if (this.wasPlaying) this.player.pause();
      return $(document).on({
        'mousemove': this.scrubTo.bind(this),
        'mouseup': this.stopScrub.bind(this)
      });
    };

    Scrubber.prototype.stopScrub = function(e) {
      Util.unblockTextSelection();
      this.dragging = false;
      this.scrubTo(e);
      if (this.wasPlaying) this.player.play();
      this.player.element.removeClass('scrubbing');
      return $(document).off('mousemove mouseup');
    };

    Scrubber.prototype.scrubTo = function(e) {
      var position;
      position = Util.getRelativePosition(e.pageX, this.element[0]);
      return this.setPosition(position);
    };

    Scrubber.prototype.setPosition = function(position) {
      var minutes, seconds, seekTime;
      this.controls.playedBar.setValue(position);
      seekTime = this.player.duration * position;
      minutes = parseInt(seekTime / 60);
      seconds = parseInt(seekTime % 60);
      $('.currentTime').html("" + (minutes.padLeft(1, '0')) + ":" + (seconds.padLeft(2, '0')));
      return this.player.seek(seekTime);
    };

    return Scrubber;

  })();

  VolumeControl = (function() {

    function VolumeControl(element, controls) {
      var _this = this;
      this.element = element;
      this.controls = controls;
      this.player = this.controls.player;
      this.volumeButton = this.element.find('.volumeButton');
      this.track = this.element.find('.track');
      this.bar = new Bar(this.track.find('.bar'));
      this.dragging = false;
      this.player.element.on({
        volumeChange: function(e, volume) {
          if (!_this.dragging) return _this.setValue(volume);
        }
      });
      this.element.on({
        'mouseover': this.mouseOver.bind(this),
        'mouseout': this.mouseOut.bind(this)
      });
      this.track.on({
        'mousedown': this.startDrag.bind(this),
        'mouseup': this.endDrag.bind(this)
      });
      this.setValue(this.player.volume);
      this.volumeButton.on('click', this.toggleMute.bind(this));
    }

    VolumeControl.prototype.setValue = function(volume) {
      this.bar.setValue(volume);
      if (volume === 0) {
        return this.element.addClass('silent').removeClass('low high');
      } else if (volume < 0.80) {
        return this.element.addClass('low').removeClass('silent high');
      } else {
        return this.element.addClass('high').removeClass('silent low');
      }
    };

    VolumeControl.prototype.toggleMute = function() {
      if (this.player.muted) {
        return this.player.unmute();
      } else {
        return this.player.mute();
      }
    };

    VolumeControl.prototype.mouseOver = function(e) {
      return this.element.addClass('hovering');
    };

    VolumeControl.prototype.mouseOut = function(e) {
      return this.element.removeClass('hovering');
    };

    VolumeControl.prototype.startDrag = function(e) {
      Util.blockTextSelection();
      this.dragging = true;
      this.scrubTo(e);
      this.element.addClass('dragging');
      return $(document).on({
        'mousemove': this.scrubTo.bind(this),
        'mouseup': this.endDrag.bind(this)
      });
    };

    VolumeControl.prototype.endDrag = function(e) {
      Util.unblockTextSelection();
      this.dragging = false;
      this.element.removeClass('dragging');
      this.scrubTo(e);
      return $(document).off('mousemove mouseup');
    };

    VolumeControl.prototype.scrubTo = function(e) {
      var position;
      position = Util.getRelativePosition(e.pageX, this.track[0]);
      return this.setPosition(position);
    };

    VolumeControl.prototype.setPosition = function(position) {
      this.setValue(position);
      return this.player.setVolume(position);
    };

    return VolumeControl;

  })();

  Bar = (function() {

    function Bar(element) {
      this.element = element;
    }

    Bar.prototype.setValue = function(value) {
      return this.element.css('width', (value * 100) + '%');
    };

    Bar.prototype.width = function() {
      return this.element.width();
    };

    return Bar;

  })();

  Plugin = (function() {

    function Plugin(name) {
      this.name = name;
      this.version = {
        text: '',
        major: -1,
        minor: -1
      };
      this.setVersion();
      this.isInstalled = this.version.major > -1;
    }

    Plugin.prototype.setVersion = function() {
      if (window.ActiveXObject) {
        return this.setActiveXVersion();
      } else {
        return this.setNavigatorVersion();
      }
    };

    Plugin.prototype.getNavigatorPlugin = function() {
      try {
        if (this.name === 'flash') return navigator.plugins['Shockwave Flash'];
      } catch (error) {
        return null;
      }
      return null;
    };

    Plugin.prototype.getActiveXObject = function() {
      try {
        if (this.name === 'flash') {
          return new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
        }
      } catch (error) {
        return null;
      }
    };

    Plugin.prototype.setActiveXVersion = function() {
      var activeXObject, versionArray, versionText;
      try {
        activeXObject = this.getActiveXObject();
        if (activeXObject) {
          if (this.name === 'flash') {
            versionText = activeXObject.GetVariable('$version');
            versionArray = versionText.split(',');
            this.version.text = versionText;
            this.version.major = parseInt(versionArray[0].split(' ')[1], 10);
            return this.version.minor = parseInt(versionArray[1], 10);
          }
        }
      } catch (error) {
        return null;
      }
    };

    Plugin.prototype.setNavigatorVersion = function() {
      var descParts, majorMinor, navigatorPlugin, versionParts, versionText;
      try {
        navigatorPlugin = this.getNavigatorPlugin();
        if (navigatorPlugin) {
          versionText = navigatorPlugin.description;
          this.version.text = versionText;
          if (versionText.startsWith('Shockwave')) {
            descParts = versionText.split(/ +/);
            majorMinor = descParts[2].split(/\./);
            this.version.major = parseInt(majorMinor[0], 10);
            return this.version.minor = parseInt(majorMinor[1], 10);
          } else {
            versionParts = versionText.split('.');
            this.version.major = parseInt(versionParts[0], 10);
            return this.version.minor = parseInt(versionParts[1], 10);
          }
        }
      } catch (error) {
        return null;
      }
    };

    return Plugin;

  })();

}).call(this);

