/**
 * ****************************************************************************
 *  - TDMSound By TDM   - TEAM DEV MODULE FOR XOOPS
 *  - Licence PRO Copyright (c)  (http://www.tdmxoops.net)
 *
 * Cette licence, contient des limitations!!!
 *
 * 1. Vous devez posséder une permission d'exécuter le logiciel, pour n'importe quel usage.
 * 2. Vous ne devez pas l' étudier,
 * 3. Vous ne devez pas le redistribuer ni en faire des copies,
 * 4. Vous n'avez pas la liberté de l'améliorer et de rendre publiques les modifications
 *
 * @license     TDMFR PRO license
 * @author		TDMFR ; TEAM DEV MODULE 
 *
 * ****************************************************************************
 */
 
    var _playingid = "";
    var _playlist = [];
    var _volume = 0.6;
    var flag = 0;
    var status = '';
    //var releaseClick;
    function gObj(nom){
		if (navigator.appName.indexOf("Microsoft")!=-1){
			return window[nom];
		} else  { 
			return document.getElementById(nom);
		}
	}
	
    function PlayerCallback(what, who)
    {
		if(what=='initialized')
		{
			//alert("Player Initialized");
		} 
		
		var theme = $("#theme").val();

        if(typeof(who) != 'undefined' && who != null && who.length > 0 && who != 'null')
        {
            var link = document.getElementById(who);
            if(link != null)
            {
				switch(what)
                {
                    case 'play':
                    {
						$("div.btncontrol a.play img").attr("src", document.location + "images/theme/"+ theme + "/pause_big.png");
						player_up.update(_playingid);
						status = "playing";
						UpdatePosition();
                        break;
                    }
                    case 'error': {}
                    case 'stop':
					{
						$("div.btncontrol a.play img").attr("src", document.location + "images/theme/" + theme + "/play_big.png");
						//$("a#playAll img").attr("src","./images/playlist.png");
						$("a#playAll img").css("opacity",1);
						$(currTab+" span.nametract a").each(function(){
						$("table.gallery_title").css("opacity",1);
						$ ("a.titletrack img").attr("src", document.location + "images/theme/" + theme + "/play_big.png");
						});
					  

						if($("#playing").length > 0)	
							$("#playing").remove();
						status = "stop";
						break;
					}
                    case 'pause':
                    {
                        
                        link.onclick = function(eventArgs)
                        {
                            PlayMedia(eventArgs, link);
                        };
                        $("div.btncontrol a.play img").attr("src", document.location + "images/theme/" + theme + "/play_big.png");
						$("a#playAll img").css("opacity",1);
						if($("#playing").length > 0)	
							$("#playing").remove();
                        status = "pause";
                        UpdatePosition();
                        break;
                    }
                    case 'finished':
                    {
                        
                        if(_playlist != null && _playlist.length > 0)
                        {
                            var next = _playlist.shift();
                            _playingid = $(next).attr("id");
                            gObj('audioPlayer').LoadSong(next.attr("href"), next.attr("id"));
                            if($(currTab+" a#"+who).parent("span").siblings("span.pricetrack").children("a.pricetrack").length > 0)
								$(currTab+" a#"+who).parent("span").siblings("span.pricetrack").children("a.pricetrack").prepend("<div id='playing' style='float:left;margin-right:5px'><img src='../img/decos/playing.gif' alt='playing' /></div>");
                            //$("div.toutalbum a.listenAll img").attr("src","./images/playliston.png");
							$("a#playAll img").css("opacity",0.5);
                            $("div.btncontrol a.play img").attr("src",document.location + "images/theme/" + theme + "/pause_big.png");
							status = "playing";	
							player_up.update(_playingid);
                        } else {
							$("div.btncontrol a.play img").attr("src", document.location + "images/theme/" + theme + "/play_big.png");
							status = "finished";
						}
						if($("#playing").length > 0)
							$("#playing").remove();
                        flag = 0;
                        
                        break;
                    }
                }
            }
        }
    }

    function PlayMedia(eventArgs, who)
    {
        
        if(status != "playing" || _playingid != $(who).attr("id"))
        {
			try
			{
			   if(gObj('audioPlayer') != null)
				{
					_playlist = [];
					_playingid = $(who).attr("id");
					gObj('audioPlayer').LoadSong($(who).attr("href"), $(who).attr("id"));
			
				}
				CancelEventDefault(eventArgs);
			}
			catch(e)
			{}
		} else {
			StopMedia(eventArgs, who);
		}
	}

    function PlayList(eventArgs, who)
    { 
	
	var theme = $("#theme").val();

        try
        {
			if(gObj('audioPlayer') != null)
            {
                _playlist = [];
                
				
				 
                $(currTab+" span.nametract").each(function(i){
					_playlist[i] = $(this).children("a");
				});
                var first = _playlist.shift();
                _playingid = $(first).attr("id");
                
                $("div.btncontrol a.play img").attr("src",document.location + "images/theme/" + theme + "/pause_big.png");
                $("a#playAll img").css("opacity",0.5);
				
				player_up.update(_playingid);
				gObj('audioPlayer').LoadSong($(first).attr("href"), $(first).attr("id"));
            }
         CancelEventDefault(eventArgs);
		 $("a#playAll img").css("opacity",0.5);
        }
        catch(e)
        {}
        return false;
    }

    function StopMedia(eventArgs, who)
    {
        try
        {
            if(gObj('audioPlayer') != null)
            {
                gObj('audioPlayer').StopSong($(who).attr("id"));
            }
        }
        catch(e)
        {}
        CancelEventDefault(eventArgs);
    }

    function CancelEventDefault(eventArgs)
    {
        if(! eventArgs)
        {
            eventArgs = window.event;
        }
        if(eventArgs.preventDefault)
        {
            eventArgs.preventDefault();
        }
        eventArgs.returnValue = false;
    }
	
function dateHMS(time) {
  var addZero = function(v) { return v<10 ? '0' + v : v; };
  var d = new Date(time * 1000); // js fonctionne en milisecondes
  var t = [];
  //t.push(addZero(d.getHours()));
  t.push(addZero(d.getMinutes()));
  t.push(addZero(d.getSeconds()));
  return t.join(':');
}


    function UpdatePosition()
    {
	
        try
        {
		
            if(gObj('audioPlayer') != null && _playingid != null && _playingid != "")
            {
	
                var playratio = gObj('audioPlayer').GetSongPosition(_playingid);
				var downloadratio = gObj('audioPlayer').GetSongProgress(_playingid);
				var vwidth = document.getElementById('divratio').clientWidth;
                document.getElementById('divloadratio').style.width = Math.round(downloadratio * vwidth) + 'px';
                document.getElementById('divplayratio').style.width = Math.round(playratio * vwidth) + 'px';
			   var position = gObj('audioPlayer').GetSongTime(_playingid);
			   var time = dateHMS(position);
			   $("div.playcontrol span.position").html(time);
			   var playduration = gObj('audioPlayer').GetSongDuration(_playingid);
			  var timeduration = dateHMS(playduration);
			$("div.playcontrol span.ratio").html(timeduration);
			   setTimeout(UpdatePosition, 100);
			}
        }
        catch(e)
        {}
    }
	
	function modifSound(variant)
    {
		//le son est au max ?
        if(gObj('audioPlayer') != null)
		{
			if(variant == "moins" && _volume>0.1)
			{
				_volume = _volume-0.1;
				if(_volume<=0) return;
				gObj('audioPlayer').SetSongVolume(_playingid, _volume);
			}
			if(variant == "plus" && _volume<1)
			{
				_volume = _volume+0.1;
				if(_volume>=1) return;
				gObj('audioPlayer').SetSongVolume(_playingid, _volume);
			}
		}
    }
	

 
  	var morceaux = new Array();  
  
  function cAudio(command, id, e)
  {

	if(!id) var id = _playingid;
	if(typeof(id) != "undefined" || id != null || id != "")
	{
		var index;
	
		for(var i=0;i<morceaux.length;i++)
		{
			if(id == morceaux[i].attr("id"))
			{
				index = i;
				break;
			}
		}
		switch(command)
		{
			case 'prev':
			{
				index = index-1;
				if(morceaux[index])
				{
					$("div.btncontrol a.prec img").css("opacity",1);
					_playingid = morceaux[index].attr("id");
					gObj('audioPlayer').LoadSong($("a#"+_playingid).attr("href"),_playingid);
					player_up.update(_playingid);
					break;
				} else {
					// on grise le bouton prev
					$("div.btncontrol a.prec img").css("opacity",0.5);
				}
			}
			case 'next':
			{
				index = index+1;
				
				if(morceaux[index])
				{
				
					$("div.btncontrol a.suiv img").css("opacity",1);
					_playingid = morceaux[index].attr("id");
					
					gObj('audioPlayer').LoadSong($("a#"+_playingid).attr("href"),_playingid);
					player_up.update(_playingid);
					break;
				} else {
					// on grise le bouton suiv
					$("div.btncontrol a.suiv img").css("opacity",0.5);
				}
			}
		}
	}
  }
  var player_up = {
	init : function(){
		
		if(morceaux[0])
		{
			var url = morceaux[0].attr("href");
			

			var titre = morceaux[0].html();
		
			_playingid = morceaux[0].attr("id");
		
			$("div.playcontrol div.btncontrol a.prec img").css("opacity",0.5);
			
			$("div.playcontrol div.btncontrol a.play").attr("href",url);
		
			if(morceaux[1])
			{
				
				$("div.playcontrol div.btncontrol a.suiv").attr("title","suivant");
			} else {
				$("div.playcontrol div.btncontrol a.suiv img").css("opacity",0.5);
			}
			$("div.playcontrol p.titre").html(titre);
		}
	},
	update : function(id){
		
		var theme = $("#theme").val();
		// on passe le nom du titre et le boutton en play
		 //alert(currTab);
		//$(currTab+" span.nametract a#"+id).each(function(){
			$("table#gallery_"+id).css("opacity",0.5);
			$ ("a.titletrack img."+id).attr("src",document.location + "images/theme/" + theme + "/pause_big.png");
		//});
		// changer la face du bouton player_up en bouton pause
		$("div.btncontrol a.play img").attr("src", document.location + "images/theme/" + theme + "/pause_big.png");
		//updater le titre
		$("div.playcontrol p.titre").html($("#"+id).html());
		//upload l'image
		$("div.playcontrol div.contcover img").attr("src", $("#cover_"+id).attr("src"));
		//mis ajour de la base + 1 lecture
		var pid =  $("span.nametract a#"+id).parent("span").attr("id");
		AddHits(pid);
		//check s'il y a un prev et un next
		for(var i=0;i<morceaux.length;i++)
		{
			if(morceaux[i].attr("id") == id)
			{
				(morceaux[i-1]) ? $("div.btncontrol a.prec img").css("opacity",1) : $("div.btncontrol a.prec img").css("opacity",0.5); 
				(morceaux[i+1]) ? $("div.btncontrol a.suiv img").css("opacity",1) : $("div.btncontrol a.suiv img").css("opacity",0.5);
			}
		}
	}
  }
  
  function initShowUpPlayer(tab){


  
	if(morceaux.length > 0)
		morceaux = [];
	$("div" + tab + " span.nametract").each(function(i){
		morceaux[i] = $(this).children("a");
		
	});
	try {
		gObj("audioPlayer").StopSong(_playingid);
	} catch(e){};
	_playingid = $(morceaux[0]).attr("id");
	player_up.init();	
	$("div.btncontrol a.play").unbind();
	$("div.btncontrol a.play").click(function(e){
		var source = $(this).children("img").attr("src");
		
		if(status != "playing" && _playingid != null)
		{
				gObj("audioPlayer").LoadSong($("a#"+_playingid).attr("href"),_playingid);
				player_up.update(_playingid);
				CancelEventDefault(e);
				
				
		} else if(status != "stop" || status != "finished")
		{
				gObj("audioPlayer").StopSong(_playingid);
				CancelEventDefault(e);
				
		}
		return false;
	});
	
	$(currTab+" span.playtrack a", currTab+" span.nametract a").click(function(){
		if(_playingid)
		{
			player_up.update(_playingid);
		}
		return false;
	});
	
  }
  setTimeout(UpdatePosition, 100);
  
/* Plalist  */
function AddPlayList(id)
{
    // Utilisation d'Ajax / jQuery pour l'envoie
     $.ajax({
       type: "POST",
       url: "./include/jquery.php",
	   data: "op=add&pl_file="+id,
	   success: function(msg){
		alert(msg);
	}
     });

    // Nous retournons "false" au navigateur afin que la page ne soit pas actualisé
    return false;
}

function RemovePlayList(id)
{
    // Utilisation d'Ajax / jQuery pour l'envoie
     $.ajax({
       type: "POST",
       url: "./include/jquery.php",
	   data: "op=remove&pl_file="+id,
	   success: function(msg){
		alert(msg);
		
		//reload la playlist
		funct_PlayList();
	}
     });

    // Nous retournons "false" au navigateur afin que la page ne soit pas actualisé
    return false;
}

function funct_PlayList()
{
    // Utilisation d'Ajax / jQuery pour l'envoie
     $.ajax({
       type: "POST",
       url: "./include/jquery.php",
	   data: "op=playlist",
	   success: function(msg){
		//var $tabs = $('#tabs').tabs();
		//$tabs.tabs('select', 1);
		$('#TDMPlaylist').html(msg);
		
	//reint le lecteur
	currTab = "#TDMPlaylist";
	initShowUpPlayer(currTab);
	
	}
     });

    // Nous retournons "false" au navigateur afin que la page ne soit pas actualisé
    return false;
}

function AddPlayLists(id)
{
    // Utilisation d'Ajax / jQuery pour l'envoie
     $.ajax({
       type: "POST",
       url: "./include/jquery.php",
	   data: "op=adds&alb_id="+id,
	   success: function(msg){
		alert(msg);
		
	}
     });

    // Nous retournons "false" au navigateur afin que la page ne soit pas actualisé
    return false;
}

/* ajoute lecture d'un fichier  */
function AddHits(id)
{

//trouver le moyen de le faire depuis la fonction update du lecteur
    // Utilisation d'Ajax / jQuery pour l'envoie
     $.ajax({
       type: "POST",
       url: "./include/jquery.php",
	   data: "op=hits&file_id="+id,
	   	success: function(msg){
	}
     });

    // Nous retournons "false" au navigateur afin que la page ne soit pas actualisé
    return false;
}

/* ajoute un album pour la lecture  */
function AddPlays(id)
{

//trouver le moyen de le faire depuis la fonction update du lecteur
    // Utilisation d'Ajax / jQuery pour l'envoie
     $.ajax({
       type: "POST",
       url: "./include/jquery.php",
	   data: "op=plays&alb_id="+id,
	   	success: function(msg){
		var $tabs = $('#tabs').tabs();
		$tabs.tabs('select', 2);
		$('#TDMSound2').html(msg);
		
	//reint le lecteur
	currTab = "#TDMSound2";
	initShowUpPlayer(currTab);
	PlayList('play', currTab);
			
	}
     });

    // Nous retournons "false" au navigateur afin que la page ne soit pas actualisé
    return false;
}

$(function(){
//reinsilise les tabs a chaque click:
$("#tbs0").click(function() { // bind click event to link
currTab = "#TDMSoundDirect";
initShowUpPlayer(currTab);
});

$("#tbs1").click(function() { // bind click event to link
currTab = "#TDMPlaylist";
initShowUpPlayer(currTab);
});

$("#tbs2").click(function() { // bind click event to link
currTab = "#TDMSound2";
initShowUpPlayer(currTab);
});

});

function AddVote(id, url)
{

//trouver le moyen de le faire depuis la fonction update du lecteur
    // Utilisation d'Ajax / jQuery pour l'envoie
     $.ajax({
       type: "POST",
       url: "./include/jquery.php",
	 data: "op=addvote&vote_url="+url+"&vote_id="+id,
	   success: function(msg){
	   alert(msg);
	}
     });

    // Nous retournons "false" au navigateur afin que la page ne soit pas actualisé
    return false;
}

function RemoveVote(id, url)
{

//trouver le moyen de le faire depuis la fonction update du lecteur
    // Utilisation d'Ajax / jQuery pour l'envoie
     $.ajax({
       type: "POST",
       url: "./include/jquery.php",
	 data: "op=removevote&vote_url="+url+"&vote_id="+id,
	   success: function(msg){
		alert(msg);
	}
     });

    // Nous retournons "false" au navigateur afin que la page ne soit pas actualisé
    return false;
}