function SoundPlayer() {
  var self = this;
  // var pl = this;
  var sm = soundManager; // SoundManager
  var vslider = fdSliderController; // Volume Slider Controller
  var btnBackward = document.getElementById('backward');
  var btnForward = document.getElementById('forward');
  var btnPlayPause = document.getElementById('play_pause');
  var btnMute = document.getElementById('mute');
  var btnHighest = document.getElementById('highest');
  var volumeHolder = document.getElementById('volume_holder');
  var tc = document.getElementById("time_counter"); // Le compteur de secondes
  var artistediv = document.getElementById("artistediv"); // Le compteur de secondes
  var playlistdiv = document.getElementById("playlist-track"); // Le compteur de secondes
  var panierdiv = document.getElementById("cart"); // Le compteur de secondes
  var coverdiv = document.getElementById("cover"); // Le compteur de secondes
  var facebookshare = document.getElementById("facebookshare"); // Le compteur de secondes
  var twittershare = document.getElementById("twittershare"); // Le compteur de secondes
  var wave = document.getElementById("wave");
  var loadingProg = document.getElementById("loading_progress");
  var playingProg = document.getElementById("playing_progress");
  
  var artistename="";
  var titrename="";
  var versionname="";
  var urlPochette="";
  var paniercontent="";
  var session = false;
  
  var playlist = new Array();
  
  this.extractUrl = 'extraitmp3.php'; // Chemin du fichier php extrait mp3
  this.soundsByURL = [];
  this.lastSound = null;
  this.soundCount = 0;
  this.actVol = 100; // Volume actuel, par défaut 100
  this.extrSoundLength = 45;
  this.waveformLength = 278;
  this.minVolume = 0;
  this.maxVolume = 100;
  this.oneSecond = 1000; // Une seconde
  
  var isIE = (navigator.userAgent.match(/msie/i));

  this.config = {
    playNext: false, // Lire les mp3 successivement
    autoPlay: false  // Lecture le premier mp3 automatique
  }

  this.css = { // CSS classe ajoutée à bouton Play_Pause
    cPlay: 'play',
    cPause: 'pause'
  }

  this.labels = {
    lBackward: 'Retourne',
    lForward: 'Avance',
    lPlay: 'Lecture',
    lPause: 'Pause',
    lMute: 'Muet',
    lHighest: 'Plus haut'
  }
  
  this.playPause = function() {
    if(self.lastSound == null) return false;
    self.lastSound.setVolume(self.actVol);
    self.lastSound.togglePause();
  }
  
  this.backward = function() {
    if(self.lastSound == null) {
      timer = null;
      return false;
    }
    if(self.lastSound.playState && !self.lastSound.paused) { // S'il est en lecture
      self.lastSound.setPosition(self.lastSound.position - self.oneSecond); // On recule d'une seconde
      timer = setTimeout(self.backward,120); // On relance la fonction
    }
  }
  
  this.forward = function() {
    if(self.lastSound == null) {
      timer = null;
      return false;
    }
    if(self.lastSound.playState && !self.lastSound.paused) { // S'il est en lecture
      self.lastSound.setPosition(self.lastSound.position + self.oneSecond); // On avance d'une seconde
      timer = setTimeout(self.forward,120); // On relance la fonction
    }
  }
  
  this.setPlayPauseButton = function(toPlayButton) { // Appellé par les Events : loading, playing etc
    if (toPlayButton == true) {
      // Le bouton "pause" devient "play"
      self.removeClass(btnPlayPause, btnPlayPause.className); 
      self.addClass(btnPlayPause, self.css.cPlay); 
      self.setTitle(btnPlayPause, self.labels.lPlay);
    } else {
      // Le bouton "play" devient "pause"
      self.removeClass(btnPlayPause, btnPlayPause.className); 
      self.addClass(btnPlayPause, self.css.cPause); 
      self.setTitle(btnPlayPause, self.labels.lPause);
    }
  }
  
  this.setStartPoint = function(e) {
    if(self.lastSound == null) return false;
    o_info = ''+self.lastSound.id3['COMM'];
    o_arr = o_info.split('*');
    if(o_info != '' && o_arr.length == 2) {
      oSoundLength = parseFloat(o_arr[1]);
      newStartPoint = parseInt(((e.clientX-self.getOffX(wave))*oSoundLength)/self.waveformLength);
      shref = self.lastSound.url;
      pfileID = '?id=';
      pstart = '&st=';
      fileID = shref.substring(shref.indexOf(pfileID)+pfileID.length, shref.indexOf(pstart));
      self.playSound(fileID, newStartPoint, artistename, titrename, versionname);
    } else {
      return false;
    }
  }
  
  this.initVolume = function(vol) { // Initialiser le volume
    volumeHolder.value = vol;
    vslider.updateSlider('volume_holder');
  }

  this.volumeButton = function(isMute) {
    if(isMute) { // Si appui sur "mute"
      volumeHolder.value = self.minVolume;
    } else { // Si appui sur "highest"
      volumeHolder.value = self.maxVolume;
    }
    vslider.updateSlider('volume_holder');
    self.updateVolume();
  }

  this.updateVolume = function() { // Mise à jour le volume et le cookie. 
    self.actVol = parseInt(volumeHolder.value);
    if(self.lastSound != null) self.lastSound.setVolume(self.actVol);
    var date = new Date();
    // Le cookie va être stocké en un mois
    setCookie('act_vol', self.actVol, date.getFullYear(), date.getMonth()+1, date.getDay());
  }
  
  this.addEventHandler = function(o,evtName,evtHandler) {
    typeof(attachEvent)=='undefined'?o.addEventListener(evtName,evtHandler,false):o.attachEvent('on'+evtName,evtHandler);
  }

  this.removeEventHandler = function(o,evtName,evtHandler) {
    typeof(attachEvent)=='undefined'?o.removeEventListener(evtName,evtHandler,false):o.detachEvent('on'+evtName,evtHandler);
  }

  this.classContains = function(o,cStr) {
    return (typeof(o.className)!='undefined'?o.className.match(new RegExp('(\\s|^)'+cStr+'(\\s|$)')):false);
  }

  this.addClass = function(o,cStr) {
    if (!o || !cStr || self.classContains(o,cStr)) return false;
    o.className = (o.className?o.className+' ':'')+cStr;
  }

  this.removeClass = function(o,cStr) {
    if (!o || !cStr || !self.classContains(o,cStr)) return false;
    o.className = o.className.replace(new RegExp('( '+cStr+')|('+cStr+')','g'),'');
  }

  this.setTitle = function(o,cStr) {
    if (!o || !cStr) return false;
    o.title = cStr;
  }

  this.getSoundByURL = function(sURL) {
    return (typeof self.soundsByURL[sURL] != 'undefined'?self.soundsByURL[sURL]:null);
  }

  this.isChildOfNode = function(o,sNodeName) {
    if (!o || !o.parentNode) {
      return false;
    }
    sNodeName = sNodeName.toLowerCase();
    do {
      o = o.parentNode;
    } while (o && o.parentNode && o.nodeName.toLowerCase() != sNodeName);
    return (o.nodeName.toLowerCase() == sNodeName?o:null);
  }
  
  this.fireClickEvent = function(element) {
    if (element.click) {
      element.click();
      return true;
    } else if (document.createEvent) {
      var e = document.createEvent('MouseEvents');
      e.initEvent('click', true, true);
      return !element.dispatchEvent(e);
    } else {
      return false;
    }
  }
  
  this.getOffX = function(o) {
    var curleft = 0;
    if (o.offsetParent) {
      while (o.offsetParent) {
        curleft += o.offsetLeft;
        o = o.offsetParent;
      }
    }
    else if (o.x) curleft += o.x;
    return curleft;
  }
  
  this.events = {
    // Handlers pour sound events
    loading: function() {
      o_info = ''+this.id3['COMM'];
      o_arr = o_info.split('*');
      if(o_info != '' && o_arr.length == 2) {
        oSoundLength = parseFloat(o_arr[1]);
        extrStartPoint = parseFloat(o_arr[0]);
        leftPosition = extrStartPoint/oSoundLength * self.waveformLength;
        loadingProg.style.left = leftPosition + 'px';
        if(!this.bytesTotal) {
          loadingProg.style.width = '1px';
        } else {
          loadingProgWidth = this.bytesLoaded/this.bytesTotal * this.duration/(oSoundLength*1000) * self.waveformLength;
          extrWidth = self.extrSoundLength/oSoundLength * self.waveformLength;
          if (extrWidth > self.waveformLength-leftPosition)
            extrWidth = self.waveformLength-leftPosition;
          if(loadingProgWidth > extrWidth) {
            loadingProg.style.width = extrWidth + 'px'; // Fix SoundManager
          } else {
            loadingProg.style.width = loadingProgWidth + 'px';
          }
        }
      } else {
        loadingProg.style.left = '0px'
        if(!this.bytesTotal) {
          loadingProg.style.width = '1px';
        } else {
          loadingProg.style.width = (this.bytesLoaded/this.bytesTotal * self.waveformLength) + 'px';
        }
      }
    },
    
    playing: function() {
      o_info = ''+this.id3['COMM'];
      o_arr = o_info.split('*');
      if(o_info != '' && o_arr.length == 2) {
        oSoundLength = parseFloat(o_arr[1]);
        extrStartPoint = parseFloat(o_arr[0]);
        leftPosition = extrStartPoint/oSoundLength * self.waveformLength;
        playingProg.style.left = leftPosition + 'px';
        playingProgWidth = this.position/(oSoundLength*1000) * self.waveformLength;
        if (extrWidth > self.waveformLength-leftPosition)
          extrWidth = self.waveformLength-leftPosition;
        if(playingProgWidth > extrWidth) {
          playingProg.style.width = extrWidth + 'px';  // Fix SoundManager
        } else {
          playingProg.style.width = playingProgWidth + 'px';
        }
        act_sec = parseInt((this.position/1000 + extrStartPoint) % 60,10); // Calcul du nb de secondes écoulées
        if(act_sec<10) { act_sec = "0"+act_sec; } // (Ajout d'un 0 si <10)
        act_min = parseInt((this.position/1000 + extrStartPoint)/60,10); // Calcul du nb de minutes écoulées
        tot_sec = parseInt(oSoundLength % 60,10); // Calcul du nb de secondes total du son
        if(tot_sec<10) { tot_sec = "0"+tot_sec; } // (Ajout d'un 0 si <10)
        tot_min = parseInt(oSoundLength/60,10); // Calcul du nb de minutes total du son
      } else {
        playingProg.style.left = '0px'
        playingProg.style.width = (this.position/this.duration * self.waveformLength) + 'px';
        act_sec = parseInt(this.position/1000 % 60,10); // Calcul du nb de secondes écoulées
        if(act_sec<10) { act_sec = "0"+act_sec; } // (Ajout d'un 0 si <10)
        act_min = parseInt(this.position/1000/60,10); // Calcul du nb de minutes écoulées
        tot_sec = parseInt(this.duration/1000 % 60,10); // Calcul du nb de secondes total du son
        if(tot_sec<10) { tot_sec = "0"+tot_sec; } // (Ajout d'un 0 si <10)
        tot_min = parseInt(this.duration/1000/60,10); // Calcul du nb de minutes total du son
      }
      tc.innerHTML = act_min+"'"+act_sec+" / "+tot_min+"'"+tot_sec; // On affiche ces valeurs dans le div "tc"
    },
    
    play: function() {
      self.setPlayPauseButton(false);
    },
    
    stop: function() {
      self.setPlayPauseButton(true);
    },
    
    pause: function() {
      self.setPlayPauseButton(true);
    },
    
    resume: function() {
      self.setPlayPauseButton(false);
    },
    
    finish: function() {
      self.setPlayPauseButton(true);
    },
    
    id3: function() { }
  }

  this.stopEvent = function(e) {
    if (typeof e != 'undefined' && typeof e.preventDefault != 'undefined') {
      e.preventDefault();
    } else if (typeof event != 'undefined' && typeof event.returnValue != 'undefined') {
      event.returnValue = false;
    }
    return false;
  }

  this.getLink = (isIE)?function(e) {
    return (e && e.target?e.target:window.event.srcElement);
  }:function(e) {
    return e.target;
  }

  this.playSound = function(fileID, start, artiste, titre, version) {
	document.getElementById("player").style.display="block"; 
	document.getElementById("header_cache").style.display="none"; 
	
	artistename=artiste;
	titrename=titre;
	versionname=version;
	  
    var soundURL = '../../extraitmp3.php?id=' + fileID + '&st=' + start;
	
	// Affichage de la pochette
	var xhr_object = null;
	if(window.XMLHttpRequest) // Firefox
	   xhr_object = new XMLHttpRequest();
	else if(window.ActiveXObject) // Internet Explorer
	   xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
	else { // XMLHttpRequest non supporté par le navigateur
	   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
	   return;
	}
	xhr_object.open("GET", "../../pochette.php?id=" + fileID, true);

	xhr_object.onreadystatechange = function() {
	   if(xhr_object.readyState == 4) {
			urlPochette = xhr_object.responseText;
			coverdiv.innerHTML = '<a href="#" class="cover_link"><img width="74" height="74" src="' + urlPochette + '"/></a>';
	   }
	}	
	xhr_object.send(null);
	
	// Partage facebook et twitter
	var xhr_partage = null;
	if(window.XMLHttpRequest) // Firefox
	   xhr_partage = new XMLHttpRequest();
	else if(window.ActiveXObject) // Internet Explorer
	   xhr_partage = new ActiveXObject("Microsoft.XMLHTTP");
	else { // XMLHttpRequest non supporté par le navigateur
	   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
	   return;
	}
	xhr_partage.open("GET", "../../partage.php?id=" + fileID, true);

	xhr_partage.onreadystatechange = function() {
	   if(xhr_partage.readyState == 4) {
			urlmorceau = xhr_partage.responseText;
			facebookshare.innerHTML = '<a class="facebook" target="_blank" href="http://www.facebook.com/share.php?u=' + urlmorceau + '"><img border="0" src="../../images/facebook.png"/></a>';
			twittershare.innerHTML = '<a class="twitter" target="_blank" href="http://twitter.com/share?url=' + urlmorceau + '"><img border="0" src="../../images/twitter.png"/></a>';
	   }
	}	
	xhr_partage.send(null);

	// Ajouter au panier
	var xhr_panier = null;
	if(window.XMLHttpRequest) // Firefox
	   xhr_panier = new XMLHttpRequest();
	else if(window.ActiveXObject) // Internet Explorer
	   xhr_panier = new ActiveXObject("Microsoft.XMLHTTP");
	else { // XMLHttpRequest non supporté par le navigateur
	   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
	   return;
	}
	xhr_panier.open("GET", "../../ajouterpanier.php?id=" + fileID, true);

	xhr_panier.onreadystatechange = function() {
	   if(xhr_panier.readyState == 4) {
			paniercontent = xhr_panier.responseText;
			panierdiv.innerHTML = paniercontent;
	   }
	}	
	xhr_panier.send(null);
	
	// Waveform
	var xhr_waveform = null;
	if(window.XMLHttpRequest) // Firefox
	   xhr_waveform = new XMLHttpRequest();
	else if(window.ActiveXObject) // Internet Explorer
	   xhr_waveform = new ActiveXObject("Microsoft.XMLHTTP");
	else { // XMLHttpRequest non supporté par le navigateur
	   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
	   return;
	}
	xhr_waveform.open("GET", "../../waveform.php?id=" + fileID, true);

	xhr_waveform.onreadystatechange = function() {
	   if(xhr_waveform.readyState == 4) {
			waveformbg = xhr_waveform.responseText;
			wave.style.backgroundImage = "url(" + waveformbg + ")";
	   }
	}	
	xhr_waveform.send(null);
	
    
    var thisSound = self.getSoundByURL(soundURL);
    if (thisSound) {
      // Existe
      if (thisSound == self.lastSound) {
        // En lecture ou en pause
        self.stopSound(self.lastSound);
        thisSound.setVolume(self.actVol);
        thisSound.togglePause();
      } else {
        if (self.lastSound) self.stopSound(self.lastSound);
        // Mp3 différent
        thisSound.setVolume(self.actVol);
        thisSound.togglePause(); // Lecture
        sm._writeDebug('sound different than last sound: '+self.lastSound.sID);
		
		
      }
    } else {
      // Créer un son	
	  thisSound = sm.createSound({
        id:'sound'+(self.soundCount++),
        url:soundURL,
        whileloading:self.events.loading,
        whileplaying:self.events.playing,
        onplay:self.events.play,
        onstop:self.events.stop,
        onpause:self.events.pause,
        onresume:self.events.resume,
        onfinish:self.events.finish,
        onid3:self.events.id3
      });
      self.soundsByURL[soundURL] = thisSound;
	  
	  
	  
      // Stopper le dernier son
      if (self.lastSound) self.stopSound(self.lastSound);
      thisSound.setVolume(self.actVol);
      thisSound.play();
    }
    
	//gestion de la playlist	
	var track = new Array();
	
	var ajout = true;
	
	// ajout des tracks en session dans le js		
	if(!session) {
		// Ajouter au panier
		var xhr_session = null;
		if(window.XMLHttpRequest) // Firefox
		   xhr_session = new XMLHttpRequest();
		else if(window.ActiveXObject) // Internet Explorer
		   xhr_session = new ActiveXObject("Microsoft.XMLHTTP");
		else { // XMLHttpRequest non supporté par le navigateur
		   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
		   return;
		}
		xhr_session.open("GET", "../../checksession.php", true);
		
		var contsession = "";
		var textesession = "";	
		xhr_session.onreadystatechange = function() {
		   if(xhr_session.readyState == 4) {
				session_texte = xhr_session.responseText;
				var sessionaarray = session_texte.split("<br/>");
				var sessionsize = parseInt((sessionaarray.length)/5);
				for (i=0; i<sessionsize; i++) {
					var j= i*5;
					var tracksession = new Array();
					tracksession.push(sessionaarray[j], sessionaarray[j+1], sessionaarray[j+2], sessionaarray[j+3], sessionaarray[j+4]);	
					// alert("sessionaarray : " + sessionaarray[j]);	
					playlist.push(tracksession);
					// alert(" - session : " + sessionaarray[j] + "   playlist : " + playlist[i][0]);
				}
				
				// alert("sessionsize : " + sessionsize + "    playlist : " + playlist.length);
				for (i=sessionsize-1; i>0; i--) {
					if(i>=0) {
						
						// textesession = '<li style="width:179px; height:20px; overflow:hidden;">' + playlist[i][0] + ' - ' + playlist[i][1] + '</li>';
						textesession = '<li style="width:260px; height:20px; overflow:hidden;"><a href="#" onclick="playSound(' + playlist[i][3] + ', ' + playlist[i][4] + ', \'' + playlist[i][0] + '\', \'' + playlist[i][1] + '\', \'' + playlist[i][2] + '\'); return false;" class="playable"><img src="http://www.myclubbingstore.com/images/carre.png" border=0/> ' + playlist[i][0] + ' - ' + playlist[i][1] + '</a></li>';
						contsession=contsession + textesession;
						// alert(textesession);
					}
				}
				playlistdiv.innerHTML = contsession;
		   }
		}	
		xhr_session.send(null);	
		session = true;
	}
	
	// on check que le track n'est pas déjà en playlist
	for (i=playlist.length-1; i>playlist.length-6; i--) {
		if (i>=0 && artiste == playlist[i][0] && titre == playlist[i][1] && version == playlist[i][2]) {
			ajout = false;
		}
	}
	
	if (ajout) {
		track.push(artiste, titre, version, fileID, start);	
		playlist.push(track);
		
		// ajout en session
		var xhr_playlist = null;
		if(window.XMLHttpRequest) // Firefox
		   xhr_playlist = new XMLHttpRequest();
		else if(window.ActiveXObject) // Internet Explorer
		   xhr_playlist = new ActiveXObject("Microsoft.XMLHTTP");
		else { // XMLHttpRequest non supporté par le navigateur
		   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
		   return;
		}
		xhr_playlist.open("GET", "../../playlistsession.php?id=" + fileID, true);	
		xhr_playlist.send(null);
	}
	
	var cont = "";
	var texte = "";	  
	  
	for (i=playlist.length-2; i>=playlist.length-6; i--) {
		if(i>=0) {
			texte = '<li style="width:260px; height:20px; overflow:hidden;"><a href="#" onclick="playSound(' + playlist[i][3] + ', ' + playlist[i][4] + ', \'' + playlist[i][0] + '\', \'' + playlist[i][1] + '\', \'' + playlist[i][2] + '\'); return false;" class="playable"><img src="http://www.myclubbingstore.com/images/carre.png" border=0/> ' + playlist[i][0] + ' - ' + playlist[i][1] + '</a></li>';
			cont=cont + texte;
		}
	}
	
	
	playlistdiv.innerHTML = cont;
	
    self.lastSound = thisSound;
    
	artistediv.innerHTML = artistename + " - " + titrename + " (" + versionname + ")";
	
	
	
    return false;
  }

  this.stopSound = function(oSound) {
    soundManager.stop(oSound.sID);
    soundManager.unload(oSound.sID);
  }

  this.init = function() {
    sm._writeDebug('soundPlayer.init()');

    self.actVol = getCookie('act_vol') || self.maxVolume; // On lit le volume stocké dans le cookie, si null on le met à 100
    self.initVolume(self.actVol); // Initialisation de volume
    
    sm._writeDebug('soundPlayer.init(): OK.');
  }

  this.init();
}

function updateVolume() { // Cette fonction est appellée par Silder
  soundPlayer.updateVolume();
}
function playPause() { // Appui sur le bouton "play" ou "pause"
  soundPlayer.playPause();
}
function backward() { // Appui sur le bouton "Retourne"
  soundPlayer.backward();
}
function forward() { // Appui sur le bouton "Avance"
  soundPlayer.forward();
}
function setStartPoint(e) { // Nouveau point d'extrait
  soundPlayer.setStartPoint(e);
}
function volumeButton(isMute) { // Boutton "Muet" ou "Le plus haut"
  soundPlayer.volumeButton(isMute);
} 
function playSound(fileID, start, artiste, titre, version) { // Lecture de mp3
  soundPlayer.playSound(fileID, start, artiste, titre, version);
  document.getElementById("play_pause").onclick = playPause;
  
	// mise à jour du compteur d'écoute
	var xhr_nb_ecoutes = null;
	if(window.XMLHttpRequest) // Firefox
	   xhr_nb_ecoutes = new XMLHttpRequest();
	else if(window.ActiveXObject) // Internet Explorer
	   xhr_nb_ecoutes = new ActiveXObject("Microsoft.XMLHTTP");
	else { // XMLHttpRequest non supporté par le navigateur
	   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
	   return;
	}
	xhr_nb_ecoutes.open("GET", "../../js/nb_ecoutes.php?id=" + fileID, true);	
	xhr_nb_ecoutes.send(null);
}

var soundPlayer = null;

soundManager.url = '../../swf/'; // Chemin du dossier "swf"
soundManager.debugMode = false; // DebugMode désactivé
soundManager.useFlashBlock = false;

soundManager.flashVersion = 9;
soundManager.useMovieStar = false; // optional: enable MPEG-4/AAC support (requires flash 9)

soundManager.onready(function() {
  if (soundManager.supported()) {
    soundPlayer = new SoundPlayer();
  }
});


