//--fonctions diverses et variable global
function disabledButton(e){Event.stop(e)}
function addZero(n){return n.toString().length<2?'0'+n.toString():n}
function durationConvert(p){
 var pos=Math.floor(p / 1000);
 var min=Math.floor(pos / 60);
 var sec=addZero(pos % 60);
 return min+':'+sec;
}

var bddPlaylist;

Event.observe(window, 'load',initBddPlaylist, false);
function initBddPlaylist(){
 bddPlaylist=new lecteur();
}

var lecteur=Class.create({
 volume:80,
 oldVolume:0,
 timerMsg:false,
 status:-1,//-1: stop 0:pause 1:lecture
 nowPlayingSongID:0,//l'id du son charger
 nowPlayingSongInfos:{},//l'objet contenant les infos du son charger
 comingSongInfos:{},//l'objet contenant les infos du son a venir

//--constructeur:
 initialize:function(){
  setInterval(function(){bddPlaylist._monitor()},10000);
  //on éteint les boutons
  this.gestionButton('off');
  //on récupère la playlist
  this.setPlaylist('recovery',0);
  //initialisation des boutons volume
  Buttons.audio('audio-icon');
  $('controls').observe('selectstart',disabledButton).unselectable='on';
  $('volume-control').observe('mousedown',this.volumeEnable.bind(this)).observe('mouseup',this.volumeDisable.bind(this)).observe('click',this.volumeSlide.bind(this));
  $('audio-icon').observe('click',function(){if(this.volume>0)this.setVolume(0);else this.setVolume(this.oldVolume);}.bind(this));
  //reglage volume par défaut
  this.setVolume(this.volume);
  //Message Notice début
  this.message('noticeDebut');
 },

//--gestion des boutons de navigations
 gestionButton:function(m){
  var arg=this.gestionButton.arguments;
  if(m=='off'){
   //play
   if(arg[1]=='play'||arg[1]==null){
    Buttons.play('playpause',0);
    $('playpause').stopObserving().observe('mouseup',disabledButton).observe('mousedown',disabledButton);
   }
   //next
   if(arg[1]=='skip'||arg[1]==null){
    Buttons.skip('skip',0);
    $('skip').stopObserving().observe('mouseup',disabledButton).observe('mousedown',disabledButton);
   }
   //previous
   if(arg[1]=='prev'||arg[1]==null){
    Buttons.prev('prev',0);
    $('prev').stopObserving().observe('mouseup',disabledButton).observe('mousedown',disabledButton);
   }
   /*//forward
   if(arg[1]=='forward'||arg[1]==null){
    Buttons.forward('forward',0);
    $('forward').stopObserving().observe('mouseup',disabledButton).observe('mousedown',disabledButton);
   }
   //rewind
   if(arg[1]=='rewind'||arg[1]==null){
    Buttons.rewind('rewind',0);
    $('rewind').stopObserving().observe('mouseup',disabledButton).observe('mousedown',disabledButton);
   }*/
  }
  else if(m=='on'){
   //play
   if(arg[1]=='play'||arg[1]==null){
    Buttons.play('playpause',1);
    $('playpause').stopObserving().observe('mouseup', function(){bddPlaylist.commande('playPause')}).observe('mousedown',function(){if(bddPlaylist.status==0)Buttons.play('playpause',2);
     else Buttons.pause('playpause',2)});
   }
   if(arg[1]=='skip'||arg[1]==null){
    Buttons.skip('skip',1);
    $('skip').stopObserving().observe('mouseup',function(){Buttons.skip('skip',1);bddPlaylist.commande('skip')}).observe('mousedown',Buttons.skip.bind(Buttons,'skip',2));
   }
   if(arg[1]=='prev'||arg[1]==null){
    Buttons.prev('prev',1);
    $('prev').stopObserving().observe('mouseup',function(){Buttons.prev('prev',1);bddPlaylist.commande('prev')}).observe('mousedown',Buttons.prev.bind(Buttons,'prev',2));
   }
   /*//forward
   if(arg[1]=='forward'||arg[1]==null){
    Buttons.forward('forward',0);
    $('forward').stopObserving().observe('mouseup',disabledButton).observe('mousedown',disabledButton);
   }
   //rewind
   if(arg[1]=='rewind'||arg[1]==null){
    Buttons.rewind('rewind',0);
    $('rewind').stopObserving().observe('mouseup',disabledButton).observe('mousedown',disabledButton);
   }*/
  }
 },

//--les commandes des boutons de navigation
 commande:function(m){
  switch(m){
  case 'playPause':
   songObj=this.nowPlayingSongInfos;
   if(this.status==0){
    Buttons.pause('playpause',1);
    this.status=1;
    $('play-status').innerHTML='Lecture';
    soundManager.togglePause(songObj.id);
   }else if(this.status==-1){
    this.status=1;
    this.loadSong(true);
   }else{
    Buttons.play('playpause',1);
    this.status=0;
    $('play-status').innerHTML='Pause';
    if(songObj.id)soundManager.togglePause(songObj.id);
    else this.loadSong(true);
   }
  break;
  case 'skip':case 'prev':
   this.loadSong(true,m);
  break;
  }
 },

 _monitor: function(){
  if(this.status==1){
   var currentSongID=this.nowPlayingSongInfos.id;
   var ObjSong=soundManager.getSoundById(currentSongID);
   if(this._lastPos==ObjSong.position){
    this.songFinish();
    this._lastPos=-1;
   }else this._lastPos = ObjSong.position;
  }
 },

//--vérifie que le sons chargé est bien le prochain
 songFinish:function(){
  var key=this.nowPlayingSongInfos.key;
  new Ajax.Request(_urlPhPBddPlaylist,{method: 'get',parameters: {'action':'getSongTooLoad','mode':'skip','key':key},
   onSuccess:function(xhr,j){
    if(bddPlaylist.comingSongInfos.key!=j.key){
     bddPlaylist.comingSongInfos=j;
     soundManager.createSound(j.id,j.filepath);
    }
    bddPlaylist.playNewSong();
   },
   onCreate: function(){$('play-status').innerHTML='Chargement...'}
  });
 },

 loadSong:function(){
  var arg=this.loadSong.arguments;
  var playNow=(arg[0]!=null)?arg[0]:false;
  var key=(arg[2]!=null)?arg[2]:this.nowPlayingSongInfos.key;
  new Ajax.Request(_urlPhPBddPlaylist,{method: 'get',parameters: {'action':'getSongTooLoad','mode':(arg[1]!=null)?arg[1]:'','key':key?key:''},
   onSuccess:function(xhr,j){
    bddPlaylist.comingSongInfos=j;
    soundManager.createSound(j.id,j.filepath);
    if(playNow)bddPlaylist.playNewSong();
   }
  });
 },

 playNewSong:function(){
  Buttons.pause('playpause',1);
  this.status=1;
  $('play-status').innerHTML='Lecture';
  var oldObj=this.nowPlayingSongInfos;
  var newObj=this.nowPlayingSongInfos=this.comingSongInfos;
  if(oldObj.id)soundManager.stop(oldObj.id);
  soundManager.play(newObj.id);
  this.setVolume(this.volume,true);
  this.showMessage(newObj.titre,2500);
  //
  new Ajax.Updater('stream-info',_urlPhPBddPlaylist,{method: 'get',parameters: {'action' : 'getInfosMorceau','id':newObj.id},
   onCreate: function(){Element.show('chargement-streamInfo');},
   onComplete: function(){Element.hide('chargement-streamInfo');}
   });
  //
  if(oldObj.key){
   $('sup'+oldObj.key).show();
   $(oldObj.key).removeClassName('currentTrack').addClassName('trackReaded');
  }
  $(newObj.key).addClassName('currentTrack').removeClassName('trackReaded');
  $('sup'+newObj.key).hide();
 },
//--volume
 volumeEnable:function(e){$('volume-control').observe('mousemove',bddPlaylist.volumeSlide)},

 volumeDisable:function(e){$('volume-control').stopObserving('mousemove',bddPlaylist.volumeSlide)},

 volumeSlide: function(e){
  var audioIconWidth=$('audio-icon').getWidth();
  var mouseX=Event.pointerX(e)-$('audio-icon').viewportOffset().left-audioIconWidth;
  if(mouseX>-1){
   var per=Math.ceil((mouseX / ($('volume-control').getWidth()-audioIconWidth))*10);
   bddPlaylist.setVolume(per*10);
  }
 },

 setVolume:function(v){
  var arg=this.setVolume.arguments;
  this.oldVolume=this.volume;
  var per=v/10;
  if(per>=0&&per<=10){
   for(i=1;i<=per;i++)$('vol-'+i).addClassName('volume-active');
   for(j=per+1;j<=10;j++)$('vol-'+j).removeClassName('volume-active');
   this.volume=v;
   if(!arg[1])this.showMessage('Volume à '+(per*10)+'%',3500);
   var SongID=this.nowPlayingSongInfos.id;
   if(SongID)soundManager.setVolume(SongID,this.volume);
  }
 },
//--gestion message et message
 showMessage:function(msg,tps){
  if(this.timerMsg)clearTimeout(this.timerMsg);
  $('message').show();
  $('message').innerHTML=msg;
  this.timerMsg=setTimeout(function(){$('message').hide();this.timerMsg=false},tps);
 },

 message:function(c){
  switch(c){
   case 'aproposde':
    this.showMessage('-Version 1.00 RC1: 15/07/2009<br/>-Version BETA: 29/01/2009<br/>Développer et coder par McGeRo(V. Jérémiah)<br/>Copyright Bddmusics.com',30000);
   break;
   case 'remerciements':
    this.showMessage('Spécial Remerciement à :<br/>Fab, RDK971, M2O et K-Flex<br/>',30000);
   break;
   case 'noticeDebut':this.showMessage('Pour commencer choisir vos morceaux à écouter ci-dessous...',30000);break;
   case 'help':this.showMessage('-<b>Pour jouer immédiatement</b> Double Clique<br/>-<b>Pour supprimer</b> Cliquer sur <b>|x|</b>',30000);break;
  }
 },

 resetPlaylist:function(){
  this.gestionButton('off');
  this.comingSongInfos=this.nowPlayingSongInfos={};
  this.status=-1;
  soundManager.stopAll();
  $('playlist').innerHTML=$('stream-info').innerHTML='';
  $('play-status').innerHTML='Stop';
  $('current-position').innerHTML=$('duration').innerHTML='0:00';
 },

 //--Gestion Playlist
 setPlaylist:function(m,id){
  new Ajax.Request(_urlPhPBddPlaylist,{method: 'get',parameters: {'action':'setplaylist','id':id,'mode':m},
   onCreate: function(){Element.show('chargement-playlist')},
   onSuccess:function(xhr,j){
     switch(m){
      case 'add':case 'alea':case 'recovery':
       if(j.error=='none'){
        $('playlist').innerHTML+=xhr.responseText;
        bddPlaylist.showMessage('Ajouter à la playlist...',1500);
       }
      break;
      case 'rm':
       bddPlaylist.showMessage('Supprimer de la playlist...',1500);
       $(id).remove();
      break;
     }
     if(j.numTrack==0)bddPlaylist.resetPlaylist()
     if(j.numTrack>0)bddPlaylist.gestionButton('on','play');
     if(j.numTrack<=1){
      bddPlaylist.gestionButton('off','prev');
      bddPlaylist.gestionButton('off','skip');
     }
     if(j.numTrack>1){
      bddPlaylist.gestionButton('on','prev');
      bddPlaylist.gestionButton('on','skip');
     }
    },
    onComplete: function(){Element.hide('chargement-playlist')}
  });
 }
});