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 = '';
    if (typeof thousands_sep === 'undefined') {
    	switch ($('html').attr('lang')) {
    	case 'fr':
    		sep = ' ';
    		break;
    	case 'en':
    		sep = ',';
    		break;
    	}
    }
    else {
    	sep = 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>';
	$('#informations').append(html);
	$('#errors_' + randId).oneTime(5000, 'error', function() {
		$(this).fadeOut('slow').remove();
		if($('#informations p').length == 0)
			$('#informations').css('display', 'none');
	});
}

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

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

function viewAjaxInfos(jsonObj) {
	if(jsonObj != null && jsonObj != undefined) {
		if(jsonObj.errors.length > 0 || jsonObj.warnings.length > 0 || jsonObj.messages.length > 0) {
			$('#informations').css('display', 'block');
		}
		// 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);
			$(".number-of-items").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 + ' .price-item').text(number_format((item.quantity*item.unitPrice), 2));
			}
			var subTotal = $.parseJSON(xhr.getResponseHeader('Json-Subtotal'), true);
			var total = parseFloat($('#total-before-tax').text().replace(/[\s,]+/g, ''));
			$('.total-before-tax').text(number_format((total+subTotal), 2));
		}
	});
}

function initAjaxShoppingCart() {
	$('#shoppingcart a.add-one').live('click',
			function(){
				var lineId = $(this).parent().parent().attr('id');
				lineId = lineId.split('-');
				var objectId = lineId[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+' .price-item').text(number_format(retour.priceItem, 2));
							}
							$('.total-before-tax').text(number_format(retour.subTotal, 2));
							$(".number-of-items").each(
									function() {
										var value = parseInt($(this).text());
										$(this).text(value + 1);
									}
							);
						}
					}
				});
				return false;
			});
	$('#shoppingcart a.remove-one').live('click',
			function(){
				var lineId = $(this).parent().parent().attr('id');
				lineId = lineId.split('-');
				var objectId = lineId[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();
							}
							else{
								$('#row-'+objectId+' .quantity').text(retour.quantity);
								$('#row-'+objectId+' .price-item').text(number_format(retour.priceItem, 2));
							}
							$('.total-before-tax').text(number_format(retour.subTotal, 2));
							$(".number-of-items").each(
									function() {
										var value = parseInt($(this).text());
										$(this).text(value - 1);
									}
							);
						}
					}
				});
				return false;
			});
	$('#shoppingcart a.delete-item').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 lineId = $(this).parent().parent().attr('id');
					lineId = lineId.split('-');
					var objectId = lineId[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){
									$(".number-of-items").each(
											function() {
												var value = parseInt($(this).text());
												var quantity = parseInt($("#row-"+objectId+" .quantity").text());
												$(this).text(value - quantity);
											}
									);
									$('#row-'+objectId).remove();
								}
								$('.total-before-tax').text(number_format(retour.subTotal, 2));
							}
						}
					});
				}
				return false;
			});
}

function initAjaxCompare(origin) {
	// Liste des produits
	if(origin != undefined) {
		$('input[id^=compare]').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') {
						$('#compare-item-' + 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) {
							$('input[id^=compare]:checked').each(function() {
								$(this).next().css('display', 'none')
												.next().css('display', 'inline')
												.children('span').text('')
												.next().css('display', 'inline');
							});
						}
						else if(number == 1) {
							$('input[id^=compare]: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) {
							$('input[id^=compare]: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
						$('input[id^=compare]: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) {
				$('#compare-item-' + 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
				$('input[id^=compare]: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++)
			if($('a.zoom' + i).length) {
				$('a.zoom' + i).lightBox({
					overlayBgColor: 		'#222',
					overlayOpacity: 		0.6,
					containerResizeSpeed: 	350,
					imageBtnClose:			BASE_URL + 'skin/css/images/lightbox-btn-close.gif'});
			}
	}
	else {
		if($('a.zoom').length) {
			$('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'
			});
		}
	}
}

function initAccordion() {
	$('#specifications h5.filter').click(function() {
		$(this).toggleClass('closed')
				.next().toggle('slow');
		return false;
	});
}
function initAjaxCheckProductAvailability() {
	$('.check-product-availability').live('click', function() {
		var href = $(this).attr('href');
		var productId = null;
		var productOrigin = null;
		var regProductId = null;
		if(URL_REWRITE) {
			regProductId = new RegExp('(availability|disponibilite)-p([0-9]+)', '');
			if(href.indexOf('liquidation-center') > 0) {
				productOrigin = 'liquidation-center';
			}
			else {
				productOrigin = 'product';
			}
		}
		else {
			regProductId = new RegExp('(productId)=([0-9]+)', '');
			var regProductOrigin = new RegExp('productOrigin=([a-z\-]+)', '');
			var resultProductOrigin = regProductOrigin.exec(href);
			if(resultProductOrigin) {
				productOrigin = resultProductOrigin[1];
			}
		}
		var resultProductId = regProductId.exec(href);
		if(resultProductId) {
			productId = resultProductId[2];
		}
		$.ajax({
			url : BASE_URL + 'forms.php',
			type : 'POST',
			data: {	action: 'ajaxDisplayProductAvailability',
					productId: productId,
					productOrigin: productOrigin
					},
			success: function(retour) {
				$('body').append(retour);
				$("#product-availability-dialog-form").hide();
			},
			complete: function(xhr) {
				viewAjaxInfos($.parseJSON(xhr.getResponseHeader('Json-Msg'), true));
				var buttons = $.parseJSON(xhr.getResponseHeader('Json-Buttons-Name'), true);
				// On définit les actions des boutons
				var buttonFunctions = {};
				buttonFunctions[buttons.send] = function() {
					$.ajax({
						url : BASE_URL + 'forms.php',
						type : 'POST',
						data: {	action: 'ajaxSendProductAvailability',
								productavailability_name: $("#productAvailabilityName").val(),
								productavailability_email: $("#productAvailabilityEmail").val(),
								productavailability_subject: $("#productAvailabilitySubject").val(),
								productavailability_message: $("#productAvailabilityMessage").val()
							},
						complete: function(xhr) {
							var jsonObj = $.parseJSON(xhr.getResponseHeader('Json-Msg'), true);
							if(jsonObj != null && jsonObj != undefined) {
								if(jsonObj.errors.length != 0) {
									for(i in jsonObj.errors) {
										var randId = rand(1,999999);
										var html = '<p id="errors_' + randId + '" class="error">' + jsonObj.errors[i] + '</p>';
										$('#product-availability-dialog-form div').append(html);
										$('#errors_' + randId).oneTime(5000, 'error', function() {
											$(this).fadeOut('slow').remove();
										});
									}
								}
								else {
									viewAjaxInfos(jsonObj);
									$("#product-availability-dialog-form").dialog('close');
								}
							}
						}
					});
				};
				buttonFunctions[buttons.cancel] = function() {
					$(this).dialog('close');
				};
				// On crée la boîte de dialogue
				$("#product-availability-dialog-form").dialog({
						autoOpen: false,
						draggable: false,
						resizable: false,
						height: 420,
						width: 420,
						modal: true,
						buttons: buttonFunctions,
						close: function() {
							$(this).remove();
						}
				}).dialog('open');
			}
		});

		return false;
	});
}

function restoreFilters() {
	$('a.restore-filters').each(function() {
		var href = $(this).attr('href');
		if(URL_REWRITE) {
			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);
		}
		else {
			$(this).attr('href', href + "&restore=1");
		}
	});
}
