//HTML5 Audio JQuery Plugin
//version 1.1
//dependencies: jquery, swfobject 2
//Ben Pritchard - New Perspective 2011


(function( $ ){
  $.fn.npHTML5Audio = function(args) {

//$.fn.npHTML5Audio = function(args) {
	return this.each(function() {
		var $this = $(this);
		var audioElem = $(this);
		var flashStr = "";
		var sourceStr = "";
		var downloadStr = "";
		var mp4Codec = "";
		var preload = "";
		var manualSeek;
		var touchDevice;
		
		//html5 audio element source tags
		sourceStr = '<source src="'+args.mp3+'" /><source src="'+args.ogg+'" />';
		
		//fall back for browsers that support the audio element but fail
		downloadStr = '<p><a href="'+args.mp3+'"><img src="/images/interior/playMP3.png"/></a></p>';
		
		//check if this device supports touch events
		if(typeof document.body.ontouchstart != "undefined"){
			touchDevice = true;
		}
		
		//flash version
		flashVersionStr = "10.0.0";
		if(args.flashVer){
			flashVersionStr = args.flashVer;
		}
		
		//preload attribute
		if($this.attr("preload") != undefined){
			preload = $this.attr("preload");	
		}
			
		//check if the browser can handle playback via the audio element
		if(swfobject.hasFlashPlayerVersion(flashVersionStr)){		
			  //ie 6 is angry when not provided with an id, attempt to get it from the audio tag, default it to a random string otherwise
			  var _id;
			  if($this.attr('id').length > 0){
				_id = $this.attr('id');
			  }else{
				_id = ("audioPlayer_"+Math.random()*999).toString();
			  }
			 swfobject.embedSWF(args.swf, _id, $this.attr('width'), $this.attr('height'), flashVersionStr,args.swfExpressInstall, {
				  color: args.color,
				  mp3: args.mp3,
				  preload: preload
				},{
				  menu: "false"
				}, {
				  base: args.swfBase,
				  id: _id,
				  name: _id
				});
		  }else{
			  //android 2.2 and lower don't support the audio element - check for and fix
			 var isOlderAndroid = false; 
			 var isAndroid = navigator.userAgent.toLowerCase().indexOf("android") > -1;
			 if(isAndroid){
				var versionRaw = navigator.userAgent.toLowerCase().split("android ")[1].split(";")[0];
				var versionPrimary = parseInt(versionRaw.split(".")[0]);
				var versionSecondary = parseInt(versionRaw.split(".")[1]);
			 }
			 //android 2.2- fallback - provide MP3 for streaming
			 if(isAndroid && ((versionPrimary == 2 && versionSecondary < 3) || (versionPrimary < 2))){
			   $this.replaceWith("<a href='"+args.mp3+"'><img src='/images/interior/playMP3.png'/></a>");
			   isOlderAndroid = true;
			 }
			 if(!document.createElement('audio').canPlayType!=true){
			// if(!!document.createElement('audio').canPlayType && isOlderAndroid != true){
				//skinned audio player string
				 var audioPlayerHTML = '<div id="'+$this.attr("id")+'_player" rel="'+$this.attr("id")+'" class="player">'+
									   '<div id="'+$this.attr("id")+'_playtoggle" class="playtoggle"></div>'+
									   '<div class="divider"></div>'+
									   '<div id="'+$this.attr("id")+'_gutter" class="gutter">'+
									   '<div id="'+$this.attr("id")+'_progress" class="progress"><img src="/audioController/progress.png" width="100%" height="18" /></div>'+
									   '</div>'+
									   '<div id="'+$this.attr("id")+'_timeleft" class="timeleft">00:00/00:00</div>'+
									   '<div class="clear"></div>'+								  
									   '</div>'
				$this.html(sourceStr);
				$this.after(audioPlayerHTML);
				//hide the real player offscreen
				$this.css("position","absolute");
				$this.css("left",-9999);
				//skinned element references
				var playtoggleRef = $("#"+$this.attr("id")+"_playtoggle");
				var gutterRef = $("#"+$this.attr("id")+"_gutter");
				var progressRef = $("#"+$this.attr("id")+"_progress");
				var timeleftRef = $("#"+$this.attr("id")+"_timeleft");
				var audiomuteRef = $("#"+$this.attr("id")+"_audiomute");
				//apply some color
				var progColor = "#b71234";	
				if(args.color){
					progColor = "#"+args.color.split("x")[1];	
				}
				progressRef.css("backgroundColor",progColor);
				//jquery ui slider
				gutterRef.slider({
						  value: 0,
						  step: 0.01,
						  orientation: "horizontal",
						  range: "min",
						  max: $this.duration,
						  animate: true,         
						  slide: function(e,ui) {   
							manualSeek = true;
							progressRef.width(gutterRef.width()*(ui.value/100));
						  },
						  stop:function(e,ui) {
							manualSeek = false;        
							$this.attr("currentTime",audioElem.attr("duration")*(ui.value/100));
						  }
						} );
				//on playhead update event
				$(this).bind('timeupdate', function() {
					var cTime = audioElem.attr("currentTime");
					var tTime = audioElem.attr("duration");
					pos = (cTime / tTime) * 100;
					timeleftRef.text(cmtss(cTime)+"/"+cmtss(tTime));
					if (!manualSeek) { 
						 gutterRef.slider( "option", "value", pos );
						 progressRef.width(pos+'%')
					 }
				});
				//play pause control
				playtoggleRef.click(function() {
										if ($this.attr("paused")) {
										if(touchDevice != true){
											playtoggleRef.css({backgroundPosition: '-117px 0px'});	
										}else{
											playtoggleRef.css({backgroundPosition: '-78px 0px'});	
										}
										$this.trigger("play","");
									}else { 
										if(touchDevice != true){
											  playtoggleRef.css({backgroundPosition: '-78px 0px'});	
										}else{
											playtoggleRef.css({backgroundPosition: '0px 0px'});	
										}
				 						 $this.trigger("pause"); 
									}   
									}); 
				if(touchDevice != true){
					playtoggleRef.mouseover(function(){onPlayPauseOver(playtoggleRef,$this)});
					playtoggleRef.mouseout(function(){onPlayPauseOut(playtoggleRef,$this)})
				}
				//audio mute control binding
				audiomuteRef.click(function(){mute(audiomuteRef,$this)});
				if(touchDevice != true){
					audiomuteRef.mouseover(function(){onAudioOver(audiomuteRef,$this)});
					audiomuteRef.mouseout(function(){onAudioOut(audiomuteRef,$this)});
				}
			 }else{
				 //browser supports the audio element, write the source elements
				$this.replaceWith("Your browser does not support Flash or the HTML5 Audio Tag");
			 }
		  }
		  if(args.debug == true){
			$("body").append("<br />HTML5 Audio JQuery Plugin DEBUG:<br />");
			jQuery.each(jQuery.browser, function(i, val) {
			  $("<div>" + i + " : <span>" + val + "</span>")
				.appendTo(document.body);
			});
			$('body').append(navigator.userAgent.toLowerCase());
		  }
		});
	 };
})( jQuery );
function onPlayPauseOver(playtoggleRef,audioElem){
	if(!audioElem.attr("paused")){
		playtoggleRef.css({backgroundPosition: '-117px 0px'});	
	}else{
		playtoggleRef.css({backgroundPosition: '-39px 0px'});	
	}
}
function onPlayPauseOut(playtoggleRef,audioElem){
	if(!audioElem.attr("paused")){
		playtoggleRef.css({backgroundPosition: '-78px 0px'});		
	}else{
		playtoggleRef.css({backgroundPosition: '0px 0px'});	
	}
}


function mute(audiomuteRef,audioElem){
	if(audioElem.attr("volume") != 0){
		audioElem.attr("volume",0);
		audiomuteRef.css({backgroundPosition: '-117px 0px'});
	}else{
		audioElem.attr("volume",1);
		audiomuteRef.css({backgroundPosition: '-39px 0px'});
	}
}
function onAudioOver(audiomuteRef,audioElem){
	if(audioElem.attr("volume") == 0){
		audiomuteRef.css({backgroundPosition: '-117px 0px'});	
	}else{
		audiomuteRef.css({backgroundPosition: '-39px 0px'});	
	}
}
function onAudioOut(audiomuteRef,audioElem){
	if(audioElem.attr("volume") == 0){
		audiomuteRef.css({backgroundPosition: '-78px 0px'});		
	}else{
		audiomuteRef.css({backgroundPosition: '0px 0px'});	
	}
}
function cmtss(s){//returns mins:seconds
	inputTime = s;
	//Number of Hours
	NoH = Math.floor(inputTime/3600);
	remaining = inputTime-(NoH*3600);
	//Number of Minutes
	NoM = Math.floor(remaining/60);
	remaining = remaining-(NoM*60);
	//Number of Seconds
	NoS = Math.floor(remaining);
	//Check if value is a single digit, if so concatinate with '0' else display value.
	if (NoH<10) {
		hours = "0"+NoH.toString();
	} else {
		hours = NoH.toString();
	}
	if (NoM<10) {
		minutes = "0"+NoM.toString();
	} else {
		minutes = NoM.toString();
	}
	if (NoS<10) {
		seconds = "0"+NoS.toString();
	} else {
		seconds = NoS.toString();
	}
	if(isNaN(minutes)){
		minutes = "00";	
	}
	if(isNaN(seconds)){
		seconds = "00";	
	}
	return minutes + ":" + seconds;
}
