(function($){

window.ButtonPlayer = function(audio, container) {
    var id7play = "";
    var id7pause = "";
    var id7stop ="";
    var isId7= false;
    var timeExtent = 0;

    if($('main').length > 0) {
        id7play = '<button class="btn btn-default" aria-label="Play"><i class="fa fa-play fa-lg fa-fw" aria-hidden="true"></i></button>';
        id7pause = '<button class="btn btn-default active" aria-label="Pause"><i class="fa fa-pause fa-lg fa-fw" aria-hidden="true"></i></button>';
        id7stop = '<button class="btn btn-default" aria-label="Rewind"><i class="fa fa-fast-backward fa-fw" aria-hidden="true"></i></button>';
        isId7 = true;
    }

  this.$container = $('#' + container);

    if(isId7){
        this.$container.append('<button style="width:0; display: none;" class="btn btn-default time-indicator"><span class="time-elapsed"></span><span class="time-duration"></span></button>');
    }

  this.basename = audio.getBasename();
  this.$container.attr('title', this.basename + " | Click to play");

  this.$container.addClass('buttonPlayer');

  this.$playButton = $('<div class="play button"><div class="glyph">' + id7play +'</div></div>');
  this.$container.append(this.$playButton);

  this.$pauseButton = $('<div class="pause button"><div class="glyph">' + id7pause +'</div></div>');
  this.$container.append(this.$pauseButton);

  this.$progressContainer = $('<div class="progressContainer" />');
  this.$container.append(this.$progressContainer);

  this.$progressLoading = $('<div class="progressLoading" />');
  this.$progress = $('<div class="progress" />');
  this.$progressLoading.append(this.$progress);
  this.$progressContainer.append(this.$progressLoading);

  this.$stopButton = $('<div class="stop button"><div class="glyph">' + id7stop +'</div></div>');
  this.$container.append(this.$stopButton);



  this.$pauseButton.hide();

  this.audio = audio;
  this.duration = null;
  this.executor = null;


  this.$playButton.click($.proxy(function() {
    this.$playButton.hide();
    this.$pauseButton.show();
    this.audio.play();
    if (this.executor == null) {
    	// delay wiring up anything until first play, or we might
    	// not have created the audio element yet.
    	this.executor = setTimeout($.proxy(function() {
    		var v = this.audio.a;
    		var soFar = 0;
            if (v.buffered.length > 0) {
            	soFar = parseInt(((v.buffered.end(0) / v.duration) * 100));
            }

            this.$progressLoading.css({width: soFar + '%'});
    	}, this), 400);



    	this.$pauseButton.click($.proxy(function() {
    		this.$pauseButton.hide();
            this.$playButton.show();
            this.audio.pause();
    	}, this));

    	this.$stopButton.click($.proxy(function() {
    		this.$pauseButton.hide();
            this.$playButton.show();
            this.audio.stop();

            clearTimeout(this.executor);
    	}, this));

    	this.audio.observeEnd($.proxy(function() {
    		this.$pauseButton.hide();
			this.$playButton.show();
			this.$progress.css({ width: '0%' });

            clearTimeout(this.executor);
		}, this));

    	this.audio.observeDurationchange($.proxy(function(d){
    		this.duration = d;
    		if (d != NaN && d != Infinity) {
    			var x = parseInt(d);
    			var dur = '';
    			jQuery.each(new Array('s','m','h'), function(i, u){
    				v = x % 60;
    				dur = "" + v + u + " " + dur;
    				x = (x-v) / 60;
                    timeExtent++;
    				if (x <= 0) return false;
    			});
    			this.$container.attr('title', this.basename + " | Duration: " + dur);
                if(isId7){
                    this.$container.find('.time-elapsed').text(makeTime(0));
                    this.$container.find('.time-duration').text("/" + dur);
                    this.$container.find(".time-indicator").css({display: "block"}).animate({ width: 38 * timeExtent * 2 }, 850);
                }
    		}
    	}, this));

      this.audio.observeTimeupdate($.proxy(function(s){
        if (this.duration != null) {
          //console.log("Time update: " + s + " / " + this.duration);
          if(isId7) { this.$container.find('.time-elapsed').text(makeTime(s))}
          var ratio = (s*100) / this.duration;
          this.$progress.css({'width': ratio+"%"});
        }
      }, this));
    }
  }, this));

  function makeTime(x){
      var dur = '';
      var blankTime = timeExtent;

      jQuery.each(new Array('s','m','h'), function(i, u){
          v = x % 60;
          dur = "" + ((v < 10) ? "0" : "") + Math.floor(v) + u + " " + dur;
          x = (x-v) / 60;
          blankTime--;
          if (blankTime <= 0) return false;
      });

      return dur;
  }
};



window.LongPlayer = function(audio, container) {
  var $ = jQuery;
  this.$container = $('#' + container);
  this.$container.addClass('longPlayer');
  this.added = false;
  var clicker = $('<div class="clicktoplay"><div class="playicon"></div></div>');
  this.$container.append(clicker);

  clicker.click($.proxy(function(e) {
	  clicker.hide();
	  if (!this.added) audio.addSelf(this.$container);
	  audio.a.controls = true;
	  audio.play();
  }, this));
};

var NativeAudio = function(src) {
	this.delayedSrc = src;
};

NativeAudio.prototype.lazyInit = function() {
  if (!this.a) {
    this.a = document.createElement('audio');
    if (this.delayedSrc) {
      this.a.src = this.delayedSrc;
      this.delayedSrc = null;
    }
  }
};

NativeAudio.prototype.play = function() {
  this.lazyInit();
  this.a.play();
};

NativeAudio.prototype.getBasename = function() {
  var src = this.delayedSrc || this.a.src;
  var slash = src.lastIndexOf('/');
  if (slash > -1 && slash < src.length) {
    src = src.substring( slash + 1 );
  }
  return src;
};

NativeAudio.prototype.pause = function() {
  this.lazyInit();
  this.a.pause();
};

NativeAudio.prototype.stop = function() {
  this.a.pause();
  this.a.currentTime = 0;
};

NativeAudio.prototype.seek = function(seconds) {
  this.lazyInit();
  this.a.currentTime = seconds;
};

NativeAudio.prototype.observeTimeupdate = function(fn) {
	$(this.a).bind('timeupdate', $.proxy(function() {
		fn(this.a.currentTime);
	}, this));
};

NativeAudio.prototype.observeDurationchange = function(fn) {
	$(this.a).bind('durationchange', $.proxy(function() {
		fn(this.a.duration);
	}, this));
};

NativeAudio.prototype.observeEnd = function(fn) {
	$(this.a).bind('ended', fn);
	$(this.a).bind('timeupdate', $.proxy(function() {
		if (this.a.currentTime == this.a.duration) {
			fn();
		}
	}, this));
};

NativeAudio.prototype.addSelf = function ($element) {
	this.lazyInit();
	$element.append(this.a);
};

NativeAudio.canPlayType = function(typeString) {
	var a = document.createElement('audio');
	var userAgent = navigator.userAgent;
	var winSafari = userAgent.match(/Windows.+Safari/) && ! userAgent.match(/Chrome/);
	return !!(!winSafari && a.canPlayType && a.canPlayType(typeString).replace(/no/, ''));
};

NativeAudio.canPlayMp3 = function() {
	return NativeAudio.canPlayType('audio/mpeg;');
};

window.NativeAudio = NativeAudio;

})(jQuery);
