function refreshPrix(){
	$.getJSON(
			__url+'panier.php',
		{
			'action':'getPanier'
		},
		function(panier){
			$(".mon-panier-prix-menu").html('('+panier.nbItems+')&nbsp;&nbsp;&nbsp;'+formatToFloat(panier.prixTotal)+'$');
		}
	);
}

function ajouterLivre(id){
	$.post(
		__url+'panier.php',
		{
			'action':'ajouterLivre',
			'id':id
		},
		function(resultat){
			if(resultat == 1){
				ajouterAvertissement("Votre livre a été ajouté avec succès dans votre panier.");
				refreshPrix();
			}else{
				ajouterErreur("Ce livre est déjà dans votre panier et il est de type PDF. Vous ne pouvez acheter plusieurs fois le même fichier PDF. Pour retélécharger un fichier PDF acheté, veuillez consulter la section <b>Mon Compte</b>.");
			}
		}
	);
}

function ajouterChapitre(id){
	$.post(
		__url+'panier.php',
		{
			'action':'ajouterChapitre',
			'id':id
		},
		function(resultat){
			if(resultat == 1){
				ajouterAvertissement("Votre chapitre a été ajouté avec succès dans votre panier.");
				refreshPrix();
			}else{
				ajouterErreur("Ce chapitre est déjà dans votre panier et il est de type PDF. Vous ne pouvez acheter plusieurs fois le même fichier PDF. Pour retélécharger un fichier PDF acheté, veuillez consulter la section <b>Mon Compte</b>.");
			}
		}
	);
}

function ajouterFormat(id){
	$.post(
		__url+'panier.php',
		{
			'action':'ajouterFormat',
			'id':id
		},
		function(resultat){
			if(resultat == 1){
				ajouterAvertissement("Votre livre a été ajouté avec succès dans votre panier.");
				refreshPrix();
			}else{
				ajouterErreur("Ce livre est déjà dans votre panier et il est de type PDF. Vous ne pouvez acheter plusieurs fois le même fichier PDF. Pour retélécharger un fichier PDF acheté, veuillez consulter la section <b>Mon Compte</b>.");
			}
		}		
	);
}

function changeQuantite(livreId, _quantite, type){
	$.post(
		__url+'panier.php',
		{
			action:'changeQuantite',
			id:livreId,
			quantite:_quantite,
			type:type
		},
		function(quantite){
			if(type=='chapitre'){
				refreshChapitreTotal(livreId);
			}else{
				refreshLivreTotal(livreId);
			}
			refreshPrix();
			if(quantite == 1 && _quantite == 2){
				ajouterErreur('Le livre ou le chapitre que vous voulez ajouter est en format PDF. Vous ne pouvez acheter plusieurs fois le même fichier PDF. Pour retélécharger un fichier PDF acheté, veuillez consulter la section <b>Mon Compte</b>.');
			}
			
			return quantite;
		}
	);
}

function augmenteQuantite(itemId, type){
	var current = $('span#quantite_'+itemId).html();
	var quantite = parseInt(current,10) + 1;
	
	var nouvelleQuantite = this.changeQuantite(itemId, quantite, type);
}

function reduireQuantite(itemId, type){
	var current = $('span#quantite_'+itemId).html();
	var quantite = parseInt(current,10) - 1;
	this.changeQuantite(itemId, quantite, type);
	if(quantite=== 0){
		this.effacerLivre(itemId);
	}
}

function refreshTotaux(){
	$.getJSON(
			__url+'panier.php',
		{
			action:'getPanier'
		},
		function(panier){
			$("#sousTotal").html(formatToFloat(panier.prixTotal));
			$("#totalTaxes").html(formatToFloat(panier.taxesArrondies));
			$("#totalLivraison").html(formatToFloat(panier.fraisLivraison));
			$("#grandTotal").html(formatToFloat(panier.grandTotal));
			refreshPrix();
		}
	);
}

function refreshLivreTotal(livreId){
	$.post(
		__url+'panier.php',
		{
			action:'getLivreTotal',
			id:livreId
		},
		function(info){
			total = formatToFloat(info.total);
			$("#total_"+livreId).html(formatToFloat(total));
			$("#quantite_"+livreId).html(info.quantite);
			refreshTotaux();
		},
		'json'
	);
}


function refreshChapitreTotal(chapitreId){
	$.post(
			__url+'panier.php',
			{
				action:'getChapitreTotal',
				id:chapitreId
			},
			function(info){
				total = formatToFloat(info.total);
				$("#total_"+chapitreId).html(formatToFloat(total));
				$("#quantite_"+chapitreId).html(info.quantite);
				refreshTotaux();
			},
			'json'
	);
}

function effacerLivre(livreId){
	$.post(
			__url+'panier.php',
			{
				action:'effacerLivre',
				id:livreId
			},
			function(){
				$("tr#ligne_"+livreId).remove();
				if($("#bodyProduits tr").size()==0){
					$("table#lstProduits tfoot").remove();
					$("#bodyProduits").html('<tr><td colspan="4">Vous n\'avez aucun produit dans votre panier présentement.</td></tr>');
					$("#linkTransaction").hide();
					refreshPrix();
				}else{
					refreshTotaux();
				}
			}
		);
}

function effacerChapitre(chapitreId){
	$.post(
			__url+'panier.php',
			{
				action:'effacerChapitre',
				id:chapitreId
			},
			function(){
				$("tr#ligne_"+chapitreId).remove();
				if($("#bodyProduits tr").size()==0){
					$("table#lstProduits tfoot").remove();
					$("#bodyProduits").html('<tr><td colspan="4">Vous n\'avez aucun produit dans votre panier présentement.</td></tr>');
					$("#linkTransaction").hide();
				}else{
					refreshTotaux();
				}
			}
		);
}

function trier(page){
	$("#frmTrier").submit();
}

function trierCategories(idCategorie, nomCategorie){
	$("#frmTrier").submit();
}

function formatToFloat(str){
	return formatFrenchNumber(str, true, 2, 10, false);
}

function formatFrenchNumber(num, allowDecimal, maxDecimal, maxUnit, allowNegative) {
	if(num === undefined){
		return('');
	}
	
	if (num.length == 0) {
		return('');
	}

	// On force le type en string.
	str = num.toString();

	// On prend note si le nombre est negatif
	neg = 0;
	if (str.charAt(0) === '-') {
		neg = 1;
	}

	// On strip toutes les chars AUTRES que les chiffres, le point et la virgule. 
	str2 = str;
	str = '';
	for (k = 0; k < str2.length; k++) {
		if (
			((str2.charAt(k) === ',' || str2.charAt(k) === '.') && allowDecimal)
			|| str2.charAt(k) === '0' || str2.charAt(k) === '1'
			|| str2.charAt(k) === '2' || str2.charAt(k) === '3'
			|| str2.charAt(k) === '4' || str2.charAt(k) === '5'
			|| str2.charAt(k) === '6' || str2.charAt(k) === '7'
			|| str2.charAt(k) === '8' || str2.charAt(k) === '9'
		) {
			str = str + str2.charAt(k);
		}
	}
	
	// Si, apres la transformation, la string ne contient plus de chars, alors inutile de continuer plus loin.
	if (str.length == 0) {
		return('');
	}

	// Si on permet les decimales, on supprime toutes les points et virgules que contient la string SAUF le/la dernier(e).
	if (allowDecimal) {
		str2 = str;
		str = '';
		sep = false;
		for (j = str2.length-1; j >= 0; j--) {
			if (str2.charAt(j) === ',' || str2.charAt(j) === '.') {
				if (!sep) {
					str = str2.charAt(j) + str;
				}
				sep = true;
			} else {
				str = str2.charAt(j) + str;
			}
		}
	}
	
	// On change le point pour une virgule
	str2 = str;
	str = '';
	for (k = 0; k < str2.length; k++) {
		if (str2.charAt(k) === '.') {
			str = str + ',';
		} else {
			str = str + str2.charAt(k);
		}
	}

	// Si, apres la transformation, la string ne contient plus de chars, alors inutile de continuer plus loin.
	if (str.length == 0) {
		return('');
	}

	// On ajuste le nombre de décimales authorisées selon maxDecimal
	if (allowDecimal) {
		a = str.split(',');
		x = a[0];
		y = a[1];
		z = '';
		if (y !== undefined) {
			if (y.length < maxDecimal) {
				diff = 1 * maxDecimal - y.length;
				fill = '';
				for (var d = 1; d <= diff; d++) {
					fill = fill + '0';
				}
				z = str + fill;
			} else {
				if (y.length > maxDecimal) {
					z = x + ',' + y.substr(0, maxDecimal);
				}
			}
		
		// S'il n'y avait pas de décimales, on les ajoute selon maxDecimal
		} else {
			fill = '';
			for (var d = 1; d <= maxDecimal; d++) {
				fill = fill + '0';
			}
			z = str + ',' + fill;
		}
		if (z.length > 0) {
			str = z;
		}
	}

	// On ajuste le nombre d'unités authorisées selon maxUnit
	if (maxUnit > 0) {
		a = str.split(',');
		x = a[0];
		y = a[1];
		z = '';
		if (x !== undefined && x.length > maxUnit) {
			z = x.substr(0, maxUnit) + ',' + y;
		}
		if (z.length > 0) {
			str = z;
		}
	}

	// On sépare les milles par une espace
	a = str.split(',');
	if (typeof(a[1]) === 'undefined') {
		a = str.split('.');
	}

	x = a[0];
	y = a[1]; 
	z = '';
	
	if (typeof(x) != 'undefined') {
		for (i = x.length-1; i >= 0; i--) {
			if (x.charAt(i) != ',' && x.charAt(i) != ' ') {
				z += x.charAt(i);
			}
		}

		x = '';

		for (i = z.length-1; i >= 0; i--) {
			if (i%3 == 0) {
	 			x += z.charAt(i) + ' ';
	 		} else {
				x += z.charAt(i);
			}
		}

		if (typeof(y) == 'undefined') { 
			y = '00';
		}

		if (y.length == 1) {
			y = y + '0';
		}

		if (allowDecimal) { 
			x = x.slice(0, (x.length-1)) + ',' + y;
		} else {
			x = x.slice(0, (x.length-1));
		}

		str = x;
	}

	// On trim les zéros et espaces inutiles à gauche
	tocut = 0;
	for (k = 0; k < str.length; k++) {
		if (str.charAt(k+1) != ',' && (str.charAt(k) === '0' || str.charAt(k) === ' ')) {
			tocut++;
		} else {
			break;
		}
	}
	if (tocut > 0) {
		str = str.substr(tocut, 1*str.length-tocut);
	}

	// Si le nombre était negatif et qu'on permet qu'il le soit, on lui remet son signe
	if (neg && allowNegative) {
		str = '-' + str;
	}

 	return str;
}

function ajouterAvertissement(str){
	var time = new Date();
	var id = "avertissement_"+time.getTime();
	
	$("#avertissementsGeneraux").append("<p id=\""+id+"\"><span class=\"ui-icon ui-icon-alert\"></span><span style=\"float:left;\"<strong>Avertissement : </strong>"+str+"</span>&nbsp;</p>");
	$("#msg-avertissement").show();
	
	$(this).oneTime(7000,function(){ 
		$("#"+id).fadeOut(1000, function(){
			$("#"+id).remove();
			if($("#avertissementsGeneraux p").length==0){
				$("#msg-avertissement").hide();
			}
		});
	});
}

function ajouterErreur(str){
	var time = new Date();
	var id = "avertissement_"+time.getTime();

	$("#erreursGenerales").append("<p id=\""+id+"\"><span class=\"ui-icon ui-icon-alert\"></span><strong>Erreur : </strong>"+str+"</p>");
	$("#msg-erreurs").show();
	
	$(this).oneTime(7000,function(){ 
		$("#"+id).fadeOut(1000, function(){
			$("#"+id).remove();
			if($("#erreursGenerales p").length==0){
				$("#msg-erreurs").hide();
			}
		});
	});
}
