function debug(msg) {
	if($.browser.firefox || $.browser.chrome)
		console.log(msg);
	else
		$('#informations').css('display', 'block')
				.append('<p>' + msg + '</p>');
}

function rand(min, max) {
    var argc = arguments.length;
    if (argc === 0) {
        min = 0;
        max = 2147483647;
    } else if (argc === 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

/*
 * NOTE : le paramètre 'thousands_sep' ne doit pas avoir la valeur ',',
 * car elle engendre des erreurs de calculs suivant le poste de l'internaute.
 */
function number_format(number, decimals, dec_point, thousands_sep) {
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ' ' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

function addError(msg) {
	var randId = rand(1,999999);
	var html = '<p id="errors_' + randId + '" class="error">' + msg + '</p>';
	$("#infos").append(html);
	$("#errors_" + randId).oneTime(5000, "error", function() {
		$(this).fadeOut("slow").remove();
		if($("#infos p").length == 0)
			$("#infos").removeClass("notEmpty");
	});
}

function addWarning(msg) {
	var randId = rand(1,999999);
	var html = '<p id="warnings_' + randId + '" class="warning">' + msg + '</p>';
	$("#infos").append(html);
	$("#warnings_" + randId).oneTime(5000, "warning", function() {
		$(this).fadeOut("slow").remove();
		if($("#infos p").length == 0)
			$("#infos").removeClass("notEmpty");
	});
}

function addMessage(msg) {
	var randId = rand(1,999999);
	var html = '<p id="messages_' + randId + '" class="message">' + msg + '</p>';
	$("#infos").append(html);
	$("#messages_" + randId).oneTime(5000, "message", function() {
		$(this).fadeOut("slow").remove();
		if($("#infos p").length == 0)
			$("#infos").removeClass("notEmpty");
	});
}

function viewAjaxInfos(jsonObj) {
	if(jsonObj != null && jsonObj != undefined) {
		if(jsonObj.errors.length > 0 || jsonObj.warnings.length > 0 || jsonObj.messages.length > 0) {
			$("#infos").addClass("notEmpty");
		}
		// errors
		for(i in jsonObj.errors) {
			addError(jsonObj.errors[i]);
		}
		// warnings
		for(i in jsonObj.warnings) {
			addWarning(jsonObj.warnings[i]);
		}
		// messages
		for(i in jsonObj.messages) {
			addMessage(jsonObj.messages[i]);
		}
	}
}

function initAjax(page) {
//	configuration Ajax
	$.ajaxSetup({
		url : BASE_URL + page + ".php",
		type : "POST",
		beforeSend: function(xhr) {
			xhr.setRequestHeader('Json-Agent', 'Quore/0.2');
		},
		complete: function(xhr) {
			viewAjaxInfos($.parseJSON(xhr.getResponseHeader("JSON-MSG"), true));
		}
	});
//	Pour signaler à l'internate l'exécution d'une requête AJAX
	$("#loading").ajaxStart(
			function() {
				$(this).fadeIn("fast");
			}
	);
	$("#loading").ajaxStop(
			function() {
				$(this).fadeOut("fast");
			}
	);
}

function initAjaxAddToCart(params) {
	var dataObj = $.extend({}, {action: "ajaxAddToCart"}, params);

	$.ajax({
		data: dataObj,
		success: function(s) {
			s = $.trim(s);
			if(s.length > 0)
				$("#shoppingcart").append(s);
			$(".myNumberOfItems").each(
					function() {
						var value = parseInt($(this).text());
						$(this).text(value + 1);
					}
			);
		},
		complete: function(xhr) {
			viewAjaxInfos($.parseJSON(xhr.getResponseHeader("JSON-MSG"), true));
			var item = $.parseJSON(xhr.getResponseHeader("JSON-ITEM"), true);
			if (item != null) {
				$("#row_" + item.id + " .quantity").text(item.quantity);
				$("#row_" + item.id + " .priceItem").text(number_format((item.quantity*item.unitPrice), 2));
			}
			var subTotal = $.parseJSON(xhr.getResponseHeader("JSON-SUBTOTAL"), true);
			var total = parseFloat($("#totalBeforeTax").text());
			$("#totalBeforeTax").text(number_format((total+subTotal), 2));
		}
	});
}

function initAjaxShoppingCart() {
	$("#shoppingcart a.addOne").live('click',
			function(){
				var trId = $(this).parent().parent().attr('id');
				trId = trId.split("_");
				var objectId = trId[1];
				$.ajax({
					url : BASE_URL + "shoppingcart.php",
					type : "POST",
					data: {	action: "ajaxAddOne",
							objectId: objectId },
					success: function(retour) {
						retour = $.parseJSON(retour, true);
						if(retour != undefined) {
							if (retour.quantity == 0){
								$("#row_"+objectId).remove();
							}
							else{
								$("#row_"+objectId+" .quantity").text(retour.quantity);
								$("#row_"+objectId+" .priceItem").text(number_format(retour.priceItem, 2));
							}
							$("#totalBeforeTax").text(number_format(retour.subTotal, 2));
							$(".myNumberOfItems").each(
									function() {
										var value = parseInt($(this).text());
										$(this).text(value + 1);
									}
							);
						}
					}
				});
				return false;
			});
	$("#shoppingcart a.removeOne").live('click',
			function(){
				var trId = $(this).parent().parent().attr('id');
				trId = trId.split("_");
				var objectId = trId[1];
				$.ajax({
					url : BASE_URL + "shoppingcart.php",
					type : "POST",
					data: {	action: "ajaxRemoveOne",
							objectId: objectId },
					success: function(retour) {
						retour = $.parseJSON(retour, true);
						if(retour != undefined) {
							if (retour.quantity == 0){
								$("#row_"+objectId).remove();
								if($('#checkout-button').length > 0 && $('#shoppingcart tr').length < 2)
									$('#checkout-button').hide();
							}
							else{
								$("#row_"+objectId+" .quantity").text(retour.quantity);
								$("#row_"+objectId+" .priceItem").text(number_format(retour.priceItem, 2));
							}
							$("#totalBeforeTax").text(number_format(retour.subTotal, 2));
							$(".myNumberOfItems").each(
									function() {
										var value = parseInt($(this).text());
										$(this).text(value - 1);
									}
							);
						}
					}
				});
				return false;
			});
	$("#shoppingcart a.deleteItem").live('click',
			function() {
				var message = null;
				switch ($('html').attr('lang')) {
				case 'en':
					message = 'Do you really want to delete this item?';
					break;
				case 'fr':
					message = '\u00CAtes-vous sûr de vouloir supprimer cet article?';
					break;
				}
				if(message != null && confirm(message)) {
					var trId = $(this).parent().parent().attr('id');
					trId = trId.split("_");
					var objectId = trId[1];
					$.ajax({
						url : BASE_URL + "shoppingcart.php",
						type : "POST",
						data: {	action: "ajaxDeleteItem",
								objectId: objectId },
						success: function(retour) {
							retour = $.parseJSON(retour, true);
							if(retour != undefined) {
								if (retour.quantity == 0){
									$(".myNumberOfItems").each(
											function() {
												var value = parseInt($(this).text());
												var quantity = parseInt($("#row_"+objectId+" .quantity").text());
												$(this).text(value - quantity);
											}
									);
									$("#row_"+objectId).remove();
									if($('#checkout-button').length > 0 && $('#shoppingcart tr').length < 2)
										$('#checkout-button').hide();
								}
								$("#totalBeforeTax").text(number_format(retour.subTotal, 2));
							}
						}
					});

				}
				return false;
			});
}

function initAjaxCompare(origin) {
	// Liste des produits
	if(origin != undefined) {
		$(".comparaison input").live('click', function() {
			var input = $(this);
			var action = 'ajaxAddProduct';
			if(!input.attr('checked'))
				action = 'ajaxRemoveProduct';
			var productId = input.val();
			$.ajax({
				url : BASE_URL + "compare.php",
				data: {
					action: action,
					productId: productId,
					origin: origin
				},
				success: function(retour) {
					if(action == 'ajaxAddProduct') {
						retour = $.trim(retour);
						if(retour.length > 0)
							$("#compare_list").append(retour);
						else
							input.removeAttr('checked');
					}
					else if(action == 'ajaxRemoveProduct') {
						$("#compareItem_" + origin + "_" + productId).remove();
					}
				},
				complete: function(xhr) {
					viewAjaxInfos($.parseJSON(xhr.getResponseHeader("JSON-MSG"), true));
					var number = $.parseJSON(xhr.getResponseHeader("JSON-SELECTED-NUMBER"), true);
					var max = $.parseJSON(xhr.getResponseHeader("JSON-MAX-SELECTION"), true);
					var label = $.parseJSON(xhr.getResponseHeader("JSON-LABEL"), true);
					if(action == 'ajaxAddProduct') {
						if(number == undefined || max == undefined){
							// Fait rien
						}
						else if(number == max) {
							$(".comparaison input:checked").each(function() {
								$(this).next().css('display', 'none')
												.next().css('display', 'inline')
												.children('span').text('')
												.next().css('display', 'inline');
							});
						}
						else if(number == 1) {
							$(".comparaison input:checked").each(function() {
								if(label != undefined)
									$(this).next().css('display', 'none')
													.next().css('display', 'inline')
													.children('span').text(label)
													.next().css('display', 'none');
							});
						}
						else if(number > 1) {
							$(".comparaison input:checked").each(function() {
								if(label != undefined)
									$(this).next().css('display', 'none')
													.next().css('display', 'inline')
													.children('span').text(label)
													.next().css('display', 'inline');
							});
						}
					}
					else if(action == 'ajaxRemoveProduct') {
						// Current
						input.next().css('display', 'inline')
							.next().css('display', 'none');
						// Les autres dans la page
						$(".comparaison input:checked").each(function() {
							if(label != undefined)
								if(number == 1 || number == max)
									$(this).next().next()
											.children('span').text(label)
											.next().css('display', 'none');
								else
									$(this).next().next()
												.children('span').text(label)
												.next().css('display', 'block');
						});
					}
				}
			});
		});
	}
	// compare box
	$("#compare_list input").live('click', function() {
		var value = $(this).val();
		var arrValue = value.split("_");
		var origin = arrValue[0];
		var productId = parseInt(arrValue[1]);
		$.ajax({
			url : BASE_URL + "compare.php",
			data: {
				action: 'ajaxRemoveProduct',
				productId: productId,
				origin: origin
			},
			success: function(retour) {
				$("#compareItem_" + origin + "_" + productId).remove();
				$("td." + value).each(function() {
					$(this).remove();
				});
				$("#compare_" + productId).removeAttr('checked');
			},
			complete: function(xhr) {
				viewAjaxInfos($.parseJSON(xhr.getResponseHeader("JSON-MSG"), true));
				var number = $.parseJSON(xhr.getResponseHeader("JSON-SELECTED-NUMBER"), true);
				var max = $.parseJSON(xhr.getResponseHeader("JSON-MAX-SELECTION"), true);
				var label = $.parseJSON(xhr.getResponseHeader("JSON-LABEL"), true);// Current
				$("#compare_" + productId).next().css('display', 'inline')
							.next().css('display', 'none');
				// Les autres dans la page
				$(".comparaison input:checked").each(function() {
					if(number == 1 || number == max)
						$(this).next().next()
								.children('span').text(label)
								.next().css('display', 'none');
					else
						$(this).next().next()
								.children('span').text(label)
								.next().css('display', 'inline');
				});
			}
		});
	});
}

function initZoom(numProduct) {
	if(numProduct != undefined) {
		for(var i = 0; i < numProduct; i++)
			$("a.zoom" + i).lightBox({
				overlayBgColor: 		'#222',
				overlayOpacity: 		0.6,
				containerResizeSpeed: 	350});
	}
	else
		$("a.zoom").lightBox({
			overlayBgColor: 		'#222',
			overlayOpacity: 		0.6,
			containerResizeSpeed: 	350,
			fixedNavigation:		true,
			imageLoading:			BASE_URL + 'skin/css/images/lightbox-ico-loading.gif',
			imageBtnPrev:			BASE_URL + 'skin/css/images/lightbox-btn-prev.gif',
			imageBtnNext:			BASE_URL + 'skin/css/images/lightbox-btn-next.gif',
			imageBtnClose:			BASE_URL + 'skin/css/images/lightbox-btn-close.gif',
			imageBlank:				BASE_URL + 'skin/css/images/lightbox-blank.gif'
		});
// TODO à décommenter si on veux faire un lightbox sur des liens textes
//	$("a.zoom_txt").lightBox({
//		overlayBgColor: 		'#222',
//		overlayOpacity: 		0.6,
//		containerResizeSpeed: 	350,
//		fixedNavigation:		true,
//		imageLoading:			BASE_URL + 'skin/css/images/lightbox-ico-loading.gif',
//		imageBtnPrev:			BASE_URL + 'skin/css/images/lightbox-btn-prev.gif',
//		imageBtnNext:			BASE_URL + 'skin/css/images/lightbox-btn-next.gif',
//		imageBtnClose:			BASE_URL + 'skin/css/images/lightbox-btn-close.gif',
//		imageBlank:				BASE_URL + 'skin/css/images/lightbox-blank.gif'
//	});
}

function initAccordion() {
	$('#colonnegauche h5.filter').click(function() {
		$(this).toggleClass('closed');
		if ($(this).next().is(':visible'))
			$(this).next().slideUp('slow');
		else
			$(this).next().slideDown('slow');
		return false;
	});
}

function restoreFilters() {
	$('a.restore-filters').each(function() {
		var href = $(this).attr('href');
		var lang = $('html').attr('lang');
		var reg = new RegExp('.html$', '');
		if ('en' == lang)
			href = href.replace(reg, '/restore-filters.html');
		else if ('fr' == lang)
			href = href.replace(reg, '/restaurer-filtres.html');
		$(this).attr('href', href);
	});
}
