/**
 * 
 */

function  _timerCallbackHTML5()  {
	$(function(){
		
			var curTimeBox=$("p.counter span")[0];
			var durTimeBox=$("p.counter span")[1];
			var durMin = Math.ceil(window._html5audio.duration / 60);	
			var durSec = Math.ceil(window._html5audio.duration % 60);
			
			var curMin = Math.ceil(window._html5audio.currentTime / 60);	
			var curSec = Math.ceil(window._html5audio.currentTime % 60);
			
			$(durTimeBox).text((durMin<10?"0":"")+durMin+":"+(durSec<10?"0":"")+durSec);	
			$(curTimeBox).text((curMin<10?"0":"")+curMin+":"+(curSec<10?"0":"")+curSec);
			  
			var percent= window._html5audio.currentTime/window._html5audio.duration *100;
			
			$(".html_player_ipad .bar .complete").css("width",percent+"%");
		    $(".html_player_ipad .bar .handler").css("left",percent+"%");
		
	});
		
}	

var MMPlayer = function(config) {

	if ($.isPlainObject(config))
	{
		for (prop in config)
		{
			eval("this."+prop+"=config."+prop+";");
		}
	}
	
	
		 
	this.init();
}



MMPlayer.prototype = {
	isRendered: false,
	targetId: null,
	baseClass: ".html_player_ipad",
	mimeType :"audio/mpeg",
	ipad_player_html: "/static/html/ipad_player.html",
	html5_player: false,
	engine: "flash",
	DDStart: false,
	/* Events stubs */
	onDownload: function(){}, 
	onLike: function(){},
	onFavorite: function(){},
	onShare: function(){},
	onVolumeChange: function (newvol) {},
	onSeek: function(position) {},
	  
	init: function() {
		
	
		if (this.isIOS())  //FIXME:DEBUG
		{ /* loading HTML5 config*/
			//alert("IOS detected");
			this.render(this.baseClass);
			//alert("Player rendered");	
			this.isRendered=true;
			
			
			this.html5_player=this.getHTML5Player();
			//alert("HTML5 audio created");
			this.engine="html5";
			
			this.onVolumeChange= function(vol)
			{
				this.html5_player.volume=(vol/100);
			}
			
			this.onSeek = function(pos)
			{
				var dur= this.html5_player.duration;
				var newpos=(dur*(pos/100));
				this.html5_player.currentTime=newpos;
				
			}
			
			
	
			
		}
		
		/*window.setInterval(window._timerCallbackHTML5);
		window.setInterval(window._timerCallbackHTML5);*/	
			
		return this;
		
	},
	render: function(targetId) {
		
		$(targetId).load(this.ipad_player_html,function(){
			var obj=window._mmplayer;
			obj.setEventHandlers();
			//alert("event handlers init():");
						
			if (typeof obj.onReady == "function")	
				obj.onReady();
			
			
		});
		return this;
	},
	hide: function(){
		$(this.baseClass).hide();
		return this;
	},
	show: function()
	{
		$(this.baseClass).show();
		return this;
	},
	
	getFlashPlayer: function()
	{
		//TODO: FLash player implementation
		
	},
	seek: function(percent)
	{
		$(this.baseClass+" .bar .complete").css("width",percent+"%");
		$(this.baseClass+" .bar .handler").css("left",(percent-4)+"%");
		this.onSeek(percent);
		
	},
	setTitle: function(str)
	{
		$(this.baseClass+" .info").html("<p>"+str+"</p>");
		return this;
	},
	setEventHandlers: function()
	{
		
	 /** PROGRESS BAR SLIDER CONTROL EVENTS  **/
						
		
		$(this.baseClass+" .bar")[0].ontouchstart= function(e)
		{
			
			//alert("touchstart");
			window._mmplayer.DDStart=true;
			e.preventDefault();
			
			return false;
			
		}
		$(this.baseClass+" .bar")[0].ontouchmove=function(event){
			
			
			if (window._mmplayer.DDStart)
			{
			
			    

    
    					
				
				var progress=Math.ceil((event.targetTouches[0].clientX-this.offsetLeft)/$(this).width()*100);
				if (progress<=100 && progress>=0)
					window._mmplayer.seek(progress);
					
					
			}
			event.preventDefault();
			return false;
		};
		
		$(this.baseClass+" .bar").click(this,function(event){
			var progress=Math.ceil((event.clientX-this.offsetLeft)/$(this).width()*100);
			
				if (progress<=100 && progress>=0)
					event.data.seek(progress);	
		});
		
		$(document.body)[0].ontouchend=function(e){
			
		//1	alert("touchend");	
			
			window._mmplayer.DDStart=false;
			e.preventDefault();	
				
			
		};
		
		
		/** VOLUME SLIDER CONTROL EVENTS **/
		 
		$(this.baseClass+" .volume .handler")[0].ontouchstart=function(event){
			window._mmplayer.DDStart=true;
			event.preventDefault();
			
		};
		$(this.baseClass+" .volume")[0].ontouchmove=function(event){
			
			if (window._mmplayer.DDStart)
			{
			
				
				var perc=100-Math.ceil((event.targetTouches[0].clientY-$(this).offset().top)/$(this).height()*100);
					
				if (perc<=100 && perc>=0)
					window._mmplayer.setVolume(perc);
					
				window._html5audio.volume=perc/100;	
				
					
			}
			
		};
		
		//this.html5_player.addEventListener("loadedmetadata", this.onPlayerReady, false);
		
					
	 	// PLAY BUTTON CONTROL EVENTS
		
		$(".play.pause")[0].ontouchstart=function(event){
			  if (window._html5audio.paused)
			  {
			  		this.className="play pause";
			  		window._mmplayer.handlePlay();
			  }
			  else {
			  	    this.className="play";
			  		window._mmplayer.handlePause();
			  }
			  	 		
			event.preventDefault();	
		};	
		
		function _setPlayerPosition()
		{
			switch(window.orientation)
			{
				case 0:
				
					$(".html_player_ipad").css("top",window.scrollY+$(window).height());		
				break;
				case -90:
				
					$(".html_player_ipad").css("top",window.scrollY+$(window).height()-20);
				break;
				case 90:
					$(".html_player_ipad").css("top",window.scrollY+$(window).height()-20);
				break;
				case 180:
					$(".html_player_ipad").css("top",window.scrollY+$(window).height());
				break;
	
		    }
		}
		window.onorientationchange = function(e)
		{
		
			_setPlayerPosition();

			
		}
		window.onscroll= function(event)
		{
			
			_setPlayerPosition();
			
			
			event.preventDefault();
			return false;
		}
		
				
		$(".html_player_ipad").css("width","1107px");
		_setPlayerPosition();
		
		// SPEC BUTTON CONTROL EVENTS
		
		
		$(this.baseClass+" .btn_1") //share
					.mouseover(function(){$(this).toggleClass("inactive")})
					.mouseout(function(){$(this).toggleClass("inactive")})
					.click(this,function(event){event.data.onShare();});
					
		$(this.baseClass+" .btn_2") //download
					.mouseover(function(){$(this).toggleClass("inactive")})
					.mouseout(function(){$(this).toggleClass("inactive")})
					.click(this,function(event){event.data.onDownload();});
		$(this.baseClass+" .btn_3") //like
					.mouseover(function(){$(this).toggleClass("inactive")})
					.mouseout(function(){$(this).toggleClass("inactive")})
					.click(this,function(event){event.data.onLike();});
		$(this.baseClass+" .btn_4") //favorite
					.mouseover(function(){$(this).toggleClass("inactive")})
					.mouseout(function(){$(this).toggleClass("inactive")})
					.click(this,function(event){event.data.onFavorite();});
		
		
										
								
					
	},
	handlePause: function()
	{
		
		if (this.engine=="html5")
			this.html5_player.pause();
			
		this.stopPlayerTimer();	
		this.timer=false;
	},
	handlePlay: function()
	{
		
		if (this.engine=="html5")
			this.html5_player.play();
			
		this.initPlayerTimer();	
		
	},
	setMediaUrl: function(url)
	{
		switch (this.engine)
		{
			case "html5" :
				
				this.html5_player.src=url;
				
				
			break;
		}
	},
	setVolume: function(percent)
	{          
		
		$(this.baseClass+" .volume .complete").css("height",percent+"%");
		$(this.baseClass+" .volume .handler").css("top",(100-percent)-4+"%");
		this.onVolumeChange(percent);
	},
	isHTML5AudioSupported: function()
	{
		
		var aud= document.createElement("AUDIO");
				
		if (typeof aud.canPlayType == "function") {
			
			return aud.canPlayType(this.mimeType)	!=	"";
			
		} else {
			return false;
		}
		
	},
	isIOS: function(){
		return ((navigator.userAgent.match(/iPad/i) != null)||(navigator.userAgent.match(/iPhone/i) != null));
 	},
 	
 	getHTML5Player: function()
 	{
 		if (!this.isHTML5AudioSupported()) 
 		{
 			throw Error("HTML5 AUDIO NOT SUPPORTED");
 			return false;
 		}
 		if ($.isPlainObject(window._html5audio) )
 		{
 			var aud= window._html5audio;
 		} else {
 			var aud= document.createElement("audio");
 			var src= document.createElement("source");
 			
 			$(src).attr("type",this.mimeType);
 			//$(aud).attr("controls",true)
 			$(aud).append($(src));
 			$(document.body).append($(aud));
 			window._html5audio=aud;
 			
 			
 			
 		}
 		
 		return aud;
 	},
 	initPlayerTimer: function() {
	   this.timer= setInterval(_timerCallbackHTML5,1000);
	      
	  // alert(this.timer);
	},
	stopPlayerTimer: function() {
		window.clearInterval(this.timer);
	}
	
		
}	

