var isVisible=false; // La variable i nous dit si la bulle est visible ou non
var Size = new Array();
var TotalTime = new Date;
TotalTime.setSeconds(0);
TotalTime.setMinutes(0);
TotalTime.setHours(0);
deplacement = 44;
var download_limit = 1000;
var download_ok = true;

document.onmousemove=move; // dès que la souris bouge, on appelle la fonction move pour mettre à jour la position de la bulle. 
	
function Duration(timeToAdd, AddSubstract) {

	
	var parenthese_debut = timeToAdd.indexOf("(");
	var parenthese_defin = timeToAdd.indexOf(")");
	var time_tot = timeToAdd.substr(parenthese_debut + 1, parenthese_defin - parenthese_debut - 1);

	var time1 = new Array;
	var time1 = time_tot.split(':');

	var minutesAjouter = time1[0] * 60 * 1000; // nombre de minutes en millisecondes. * 60 = 60 secondes par minutes. Puis * 1000 pour les millisecondes. 
	var secondesAjouter = time1[1] * 1000; 
	
	// on multiplie par -1 s'il s'agit d'une soustraction
	if (AddSubstract != "add") {
		heuresAjouter = heuresAjouter * (-1);
		minutesAjouter = minutesAjouter * (-1);
		secondesAjouter = secondesAjouter * (-1);
	}
		
	var heureActuelle = TotalTime.getTime(); // l'heure accumulée actuelle
	var heuresAjouter = heureActuelle + minutesAjouter + secondesAjouter; // On ajoute au cumul actuel, les heures, minutes, secondes du morceau de musique.
	TotalTime.setTime(heuresAjouter);
}

function ResetDuration() {
	TotalTime.setSeconds(0);
	TotalTime.setMinutes(0);
	TotalTime.setHours(0);
}

function GetXhr(){

	/* Création d'une instance XMLHttpRequest */
	var xhr = null; 
	if(window.XMLHttpRequest) // Firefox et autres
	   xhr = new XMLHttpRequest(); 
	else if(window.ActiveXObject){ // Internet Explorer 
		   try {
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		else { // XMLHttpRequest non supporté par le navigateur 
		   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
		   xhr = false; 
		} 
	return xhr;
}

function Telecharge() {
	
	if (download_ok==false) {
		alert('You cannot select more than ' + download_limit + ' MB');
		return;
	}

	// AJAX
	var xhr = GetXhr();
	xhr.open("POST","library_mp3/audio_download.php",false);
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	
	// Mise en table des lignes sélectionnées
	var donneesTableResult = '';
	var trouve = false;
	var pointvirgule = "";
	var fichier_avec_timing = "";
	var position_mp3 = 0;
	x=0;
	while (checkbox_line = parent.frames['AudioFilesList'].document.getElementById('CBT' + x)) {
		if (checkbox_line.checked) {
			theTable = parent.frames['AudioFilesList'].document.getElementById('TableListing' + x)		
			trouve = true;
			// Récupère le nom du fichier sans le timing
			fichier_avec_timing = theTable.rows[0].cells[2].innerHTML;
			position_mp3 = fichier_avec_timing.indexOf('.mp3');
			fichier_avec_timing = fichier_avec_timing.substring(0, position_mp3 + 4);
			donneesTableResult = donneesTableResult + pointvirgule + fichier_avec_timing;
			pointvirgule = ";";
		}
		x++;
	}
	if (trouve) {
		fenetre = window.open("", "mapopup", "width=500,height=200,directories=no,location=no,menubar=no,resizable=yes,scrollbars=no,status=no,toolbar=no");
		fenetre.document.write('<body style="background-color: #9F0101; color:white; font-weight: bold;">');
		fenetre.document.write('<div style="text-align:center;font-size:22px; padding-bottom:10px;">Preparing zip file... please wait...<br><br><br>');
		fenetre.document.write('<input type="button" value="Click here to stop download" onClick="self.close()" name="button"></div>');
		fenetre.document.location.href = "library_mp3/audio_download_window.php?basedir=" + directory_mp3 + "&dir=" + RepertoireSelectionne;
//		fenetre.document.write('<script language="javascript" type="text/javascript" src="library_mp3/audio_library.js"></script>');
//		fenetre.document.write('<script>var xhr = GetXhr(); xhr.open("POST","library_mp3/audio_download.php",false); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");');
//		fenetre.document.write('var param_send = "dir=" + RepertoireSelectionne + "&fichiers=" + donneesTableResult + "&basedir=" + directory_mp3;');
//		fenetre.document.write('document.location.href = "library_mp3/audio_forcedownload.php";');
//		fenetre.document.write('xhr.send(param_send);</script>');
		
//		var param_send = "dir=" + RepertoireSelectionne + "&fichiers=" + donneesTableResult + "&basedir=" + directory_mp3;
//		var param_send = "library/audio_download.php?dir=" + RepertoireSelectionne + "&fichiers=" + donneesTableResult + "&name=mp3_list.zip&basedir=" + directory_mp3;
//		var param_send = "dir=" + RepertoireSelectionne + "&fichiers=" + donneesTableResult + "&name=Wma_list.zip";
//		xhr.send(param_send);
		
//		fenetre.document.write('<script>document.location.href = "library_mp3/audio_forcedownload.php";</script>');
//		fenetre.document.write('self.onfocus = function() { alert("salut"); self.onblur = function() { alert (finiself.onfocus = function { self.close(); }}};</script>');

//		alert(xhr.responseText); // affiche que les fichiers ont été envoyés.

//		if (window.onblur) { alert ("salut"); document.location.href = "library_mp3/audio_forcedownload.php";}
//		document.location.href = "library_mp3/audio_forcedownload.php";
//		fenetre.window.onload = function () { fenetre.document.location.href = "library_mp3/audio_forcedownload.php" };
	}
}

function GetId(id) {
	return document.getElementById(id);
}

function move(e) {
	if(isVisible) {  // Si la bulle est visible, on calcul en temps reel sa position ideale
		if (navigator.appName!="Microsoft Internet Explorer") { // Si on est pas sous IE
			GetId("curseur").style.left=e.pageX + 20+"px";
			GetId("curseur").style.top=e.pageY + 20+"px";
		}
 		else { // Modif proposé par TeDeum, merci à  lui
			if(document.documentElement.clientWidth>0) {
				GetId("curseur").style.left=20+event.x+document.documentElement.scrollLeft+"px";
				GetId("curseur").style.top=10+event.y+document.documentElement.scrollTop+"px";} 
			else {
				GetId("curseur").style.left=20+event.x+document.body.scrollLeft+"px";
				GetId("curseur").style.top=10+event.y+document.body.scrollTop+"px";}
		}
	}
}

 
function montre(text) {
	if(isVisible==false) {
		GetId("curseur").style.visibility="visible"; // Si il est caché (la verif n'est qu'une securité) on le rend visible.
		GetId("curseur").innerHTML = text; // on copie notre texte dans l'élément html
		isVisible=true;
	}
}

function cache() {
	if(isVisible==true) {
		GetId("curseur").style.visibility="hidden"; // Si la bulle est visible on la cache
		isVisible=false;
	}
}

function SelectUnselectAll(Select){ 
	y = 0;
	if (Select) {
		var Couleur = '#FFCC99';}
	else {
		Couleur = '#FFF09D';
	}
//	au_moins_un_checke = false;
	var checkbox_size_tot = 0;
	ResetDuration();
	while (checkbox_line = parent.frames['AudioFilesList'].document.getElementById('CBT' + y)) {
		
		theTable = parent.frames['AudioFilesList'].document.getElementById('TableListing' + y)		
		checkbox_line.checked = Select;

		if (Select) {
			checkbox_size_tot = checkbox_size_tot + parseInt(parent.Size[y]); // mise à jour de la taille totale
			Duration(theTable.rows[0].cells[2].innerHTML, "add"); // Mise à jour de la durée totale
		}
		theTable.rows[0].cells[0].setAttribute('bgColor', Couleur);
		theTable.rows[0].cells[1].setAttribute('bgColor', Couleur);
		theTable.rows[0].cells[2].setAttribute('bgColor', Couleur);
		y++;
	}

	if (Select) {
		// Mise à jour Taille et Duration
		Down = parent.document.getElementById('Download'); // rallume le download de la toolbox
		Mega = parent.document.getElementById('Megabytes');
		Dura = parent.document.getElementById('Duration');
		var size_tot = checkbox_size_tot/1000000;
		size_tot = size_tot.toFixed(2);
		Mega.innerHTML = '<div class="Mega"><b>Size: </b>' + size_tot + ' MB</div>';
		
		if (size_tot > download_limit) {
			download_ok = false;
		} else {download_ok = true;}
			
		var	HoursString = TotalTime.getHours();
		if (HoursString < 10) HoursString = "0" + HoursString;
		var MinutesString = TotalTime.getMinutes();
		if (MinutesString < 10) MinutesString = "0" + MinutesString;
		var SecondesString = TotalTime.getSeconds();
		if (SecondesString < 10) SecondesString = "0" + SecondesString;
		var Stringfinale = HoursString + ":" + MinutesString + ":" + SecondesString;
		
		Dura.innerHTML = '<div class="Mega"><b>Length: </b>' + HoursString + ':' + MinutesString + ':' + SecondesString + '</div>';

		Down.style.display = 'block';} // rallume le Download de la toolbox
	else {
		Down.style.display = 'none'; // on éteint le Download de la toolbox
	}
}

function CloseWindowAudio() {
//	document.getElementById("audio_wma").contentWindow.document.getElementById('mediaPlayer').stop();
	parent.frames.audio_mp3.document.location.href = 'library/audio_playmp3.php?sound=';
	document.getElementById('Mp3Player').style.display="none";
	hauteur = document.getElementById("AudioDirectory").height;
	document.getElementById("AudioDirectory").height = parseInt(hauteur) - deplacement;
}

function DimensionFrames() {
 var windowHeight = 0;
   if (typeof(window.innerHeight) == 'number') {
        windowHeight = window.innerHeight;
   }
        else {
          if (document.body && document.body.clientHeight) {
            windowHeight = document.body.clientHeight;
        }
        else {
          if (document.documentElement && document.documentElement.clientHeight) {
            windowHeight = document.documentElement.clientHeight;
          }
        }
   }
	document.getElementById('AudioFilesList').style.height = windowHeight - 160;
	document.getElementById('AudioDirectory').style.height = windowHeight - 50;
}

function ChangeWmaMp3(type) {
	document.getElementById('AudioDirectory').src='library/audio_directories.php?WmaMp3=' + type; 
	document.getElementById('AudioFilesList').src = 'library/audio_files.php?nomdir='; 
	document.getElementById('SelectAll').checked = false; 
	document.getElementById('SelectAll').disabled = true; 
	document.getElementById('Download').style.display = 'none'
}