function add(text) {
	text.value++;
	controlNum(text);
}

function rem(text) {
	text.value--;
	controlNum(text);
}

function controlNum(text) {
	var m = Number(text.value);
	if (isNaN(m))
		text.value = 1;
	else if(text.value>99)
		text.value = 99;
	else if(text.value<0)
		text.value = 0;
}

function panier_add(reference, type, i, key, categorie, oem) {
	var qt = $('#qt'+key).val();
	if (qt <= 0)
		return false;
	var url = "public/panier.php?action=add&type="+type+"&qt="+qt+"&reference="+reference+"&categorie="+categorie+"&oem="+oem;
	//alert(url);
	$.get(url, function(data){
		if (data == "erreur"){
			return false;
			alert("Erreur lors de l'ajout au panier");
		}
		else{
			$('#panier').html(data);
			$("#in_panier_qte").html(qt);

			if($('#but'+key).attr('src').search('magenta') != -1)
				$('#but'+key).attr('src', 'public/images/panier/bouton_modifier_magenta.png');
			else
				$('#but'+key).attr('src', 'public/images/panier/bouton_modifier.png');

			$('#but'+key).attr('onclick', '');
			$('#but'+key).unbind('click');
			$('#but'+key).bind('click', function() { panier_update(reference, type, i, key, categorie); return false; });
			$('#del'+key).css('visibility', 'visible');
			$("#confirm img")[0].src="public/images/dialogue_panier/image_ajout_ok.png";
			confirm("L'article a correctement été ajouté au panier.", function () { window.location.href = 'mon-panier';});
			}
	});
	return true;
}
function panier_update(reference, type, i, key, categorie) {
	var qt = $('#qt'+key).val();
	var url = "public/panier.php?action=update&qt="+qt+"&reference="+reference+"&key="+key+"&categorie="+categorie;
	$.get(url, function(data){
		if (data == "erreur")
			return ;
			//alert("Erreur lors de l'ajout au panier");
		else {
				$('#panier').html(data);
				if (qt == 0) {
					if($('#but'+key).attr('src').search('magenta') != -1)
						$('#but'+key).attr('src', 'public/images/panier/bouton_ajouter_magenta.png');
					else
						$('#but'+key).attr('src', 'public/images/panier/bouton_ajouter.png');

					$('#qt'+key).val(1);
					$('#but'+key).attr('onclick', '');
					$('#but'+key).unbind('click');
					$('#but'+key).bind('click', function() { panier_add(reference, type, i, key, categorie); return false; });
					$('#del'+key).css('visibility', 'hidden');
					$("#in_panier_qte").html(qt);
				}
				else {
					$("#in_panier_qte").html(qt);
					$("#confirm img")[0].src="public/images/dialogue_panier/image_modif_ok.png";
					confirm("L'article a correctement été modifie.", function () { window.location.href = 'mon-panier';});
				}
			}
	});
}

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 get_total_panier() {
	var total = 0;
	$('#catalogue tr.panier_cell').each(function () {
		var prix = new Number($(this).find('td:last span:last').attr('prix'));
		var qt = new Number($(this).find('input:text').val());
		total += qt*prix;
	});
	return total;
}

function add_from_panier(reference, type, i, key) {
	var prix = new Number($('#catalogue tr.panier_cell:eq('+i+') td:last span:last').attr('prix'));
	if (prix == 0)
		return;
	add(document.getElementById('qt'+key));
	var qt = little_panier_update(reference, type, i, key);
	var total = get_total_panier();

	$('#catalogue tr.panier_cell:eq('+i+') td:last span:first').html(number_format( qt*prix*1.196, 2, ',', '' )+' &euro; TTC');
	$('#catalogue tr.panier_cell:eq('+i+') td:last span:last').html(number_format( qt*prix, 2, ',', '' )+' &euro; HT');

	$('#catalogue #total_ht').attr('total', number_format(total, 2, '.', ''));
	$('#catalogue #total_ht').html(number_format(total, 2, ',', '')+'&euro;');
	$('#catalogue #total_ttc').html(number_format(total*1.196, 2, ',', '' )+'&euro;');
}

function rem_from_panier(reference, type, i, key) {
	rem(document.getElementById('qt'+key));
	var qt = little_panier_update(reference, type, i, key);
	var prix = new Number($('#catalogue tr.panier_cell:eq('+i+') td:last span:last').attr('prix'));
	var total = get_total_panier();

	$('#catalogue tr.panier_cell:eq('+i+') td:last span:first').html(number_format( qt*prix*1.196, 2, ',', '' )+' &euro; TTC');
	$('#catalogue tr.panier_cell:eq('+i+') td:last span:last').html(number_format( qt*prix, 2, ',', '' )+' &euro; HT');

	$('#catalogue #total_ht').attr('total', number_format(total, 2, '.', ''));
	$('#catalogue #total_ht').html(number_format(total, 2, ',', '')+'&euro;');
	$('#catalogue #total_ttc').html(number_format(total*1.196, 2, ',', '' )+'&euro;');
}

function update_from_panier(reference, type, i, key) {
	var prix = new Number($('#catalogue tr.panier_cell:eq('+i+') td:last span:last').attr('prix'));
	if (prix == 0) {
		$('#qt'+key).val(1);
		return;
	}

	controlNum(document.getElementById('qt'+key));
	var qt = little_panier_update(reference, type, i, key);
	var total = get_total_panier();

	$('#catalogue tr.panier_cell:eq('+i+') td:last span:first').html(number_format( qt*prix*1.196, 2, ',', '' )+' &euro; TTC');
	$('#catalogue tr.panier_cell:eq('+i+') td:last span:last').html(number_format( qt*prix, 2, ',', '' )+' &euro; HT');

	$('#catalogue #total_ht').attr('total', number_format(total, 2, '.', ''));
	$('#catalogue #total_ht').html(number_format(total, 2, ',', '')+'&euro;');
	$('#catalogue #total_ttc').html(number_format(total*1.196, 2, ',', '' )+'&euro;');
}

function del_from_panier(reference, type, i, key) {

	confirm("L'article a correctement été modifie.", function () {
		$('#qt'+key).val(0);
		little_panier_update(reference, type, i, key);
	}, '#confirm');
}


function little_panier_update(reference, type, i, key) {
	var qt = $('#qt'+key).val();
	var url = "public/panier.php?action=update&qt="+qt+"&reference="+reference+"&key="+key;
	$.get(url, function(data){
		if (data == "erreur")
			return ;
			//alert("Erreur lors de l'ajout au panier");
		else {
				$('#panier').html(data);
				if (qt == 0) {
					window.location.reload();
				}
				else {
					$("#in_panier_qte").html(qt);
				}
			}
	});
	return qt;
}

function confirm(message, div, callback) {
	$(div).modal({
		close:false,
		position: ["30%",],
		overlayId:'confirmModalOverlay',
		containerId:'confirmModalContainer',
		onShow: function (dialog) {
			dialog.data.find('.message').append(message);

			// if the user clicks "yes"
			dialog.data.find('.yes').click(function () {
				var a = 1;
				// call the callback
				if ($.isFunction(callback)) {
					//alert('YES');
					callback.apply();
				}
				// close the dialog
				$.modal.close();
			});
		}
	});
}

function check_promo() {
	//error = false;
	jQuery.getScript( 'code-promo-'+$('#code_promo input:text').val()+'-'+$('#code_promo').attr('liv')+'.html', function(data, textStatus) {
			if (error == false) {
				if (type == 'avoir') {
					var total_ttc = $('#total_ttc').attr('prix');
					var net = total_ttc-prix;
					if (net < 0)
						net = 0;

					var html = '<tr class="c" >';
					html += '<td style="text-align:left;color:#01aef8;font-size: 17px;font-weight:500;">Avoir :</td>';
					html += '<td style="width: 110px;text-align:right;padding: 0 20px 0 0;color:#ED008C;font-size:16px;">'+number_format(prix, 2, ",", "")+' &euro;</td>';
					html += '</tr>';
					html += '<tr class="c" >';
					html += '<td style="text-align:left;color:#01aef8;font-size: 17px;font-weight:500;">Net a payer:</td>';
					html += '<td style="width: 110px;text-align:right;padding: 0 20px 0 0;font-weight:bold;color:#ED008C;font-size:18px;">'+number_format(net, 2, ",", "")+' &euro;</td>';
					html += '</tr>';

					$('#soustotal').append(html);
					confirm("code avantage valide.",'#confirm',function () {});
				} else {
					var html = '<tr>';
					var prix_afficher = '';

					var total_ht = $('#total_ht').attr('prix');
					var total_tva = $('#total_tva').attr('prix');
					var total_ttc = $('#total_ttc').attr('prix');

					if (type == 'prix') {
						if (prix < 0)
							prix = 0;
						prix_afficher = number_format(prix, 2, ",", "")+'&euro;';
						total_ttc -= prix;
						total_ht = total_ttc/1.196;
						total_tva = total_ttc-total_ht;

					} else if (type == 'pourcentage') {
						var prix_afficher = number_format(prix, 2, ",", "")+'%';
						total_ttc -= total_ttc*(prix/100);
						total_ht = total_ttc/1.196;
						total_tva = total_ttc-total_ht;
					}
					html += '<td>'+designation+'</td>';
					html += '<td>-'+prix_afficher+'</td>';
					html += '<td>1</td>';
					html += '<td>-'+prix_afficher+'</td>';
					html += '</tr>';

					$('#catalogue #panier_detail').append(html);

					$('#total_ht').html(number_format(total_ht, 2, ",", "")+' &euro;');
					$('#total_tva').html(number_format(total_tva, 2, ",", "")+' &euro;');
					$('#total_ttc').html(number_format(total_ttc, 2, ",", "")+' &euro;');

					confirm("code avantage valide.",'#confirm',function () {});
				}
			}else {
				if (etape == 5 || etape == 9)
					confirm("Le montant de votre panier est insuffisant.",'#error_valeur',function () {});
				else
					confirm("code avantage non valide.",'#error',function () {});
			}
				//alert('code promo non valide');
	});
}

function add_prix_livraison_to_panier(panier, coup_livraison)
{
	$('#panier tr:last td:last').html(number_format((panier+coup_livraison)*1.196, 2, ",", "")+' &euro; TTC')
}

$(document).ready(function(){

	if ($('.expedition_selector input:checked').size()>0) {
		var coup_livraison = parseFloat($('.expedition_selector input:checked').parent().attr('prix'));
		var panier = parseFloat($('#total_ht').attr('total'));
		add_prix_livraison_to_panier(panier, coup_livraison);
	}else if($($('form[id=paiement]')).size()>0) {
		$('#panier tr:last td:last').html(number_format(parseFloat($('#total_ht').attr('prix'))*1.196, 2, ",", "")+' &euro; TTC')
	}

	$('.expedition_selector').click(function() {
		$(this).children().attr('checked', 'checked');
		$('.expedition_selector:not(this)').css('background', "white url('./public/images/commande/choix_cyan.png') no-repeat");
		$(this).css('background', "white url('./public/images/commande/choix_vert.png') no-repeat");

		var coup_livraison = parseFloat($(this).attr('prix'));
		var panier = parseFloat($('#total_ht').attr('total'));

		$('#total_ht').html(number_format(panier+coup_livraison, 2, ",", "")+'&euro;');
		$('#total_ttc').html(number_format((panier+coup_livraison)*1.196, 2, ",", "")+'&euro;');

		add_prix_livraison_to_panier(panier, coup_livraison);
	});

	$('.paiement_icone').click(function() {
		$(this).children('input:radio').attr('checked', 'checked');

		$('.paiement_icone:not(this)').css('backgroundImage','url(./public/images/commande/cadre_cyan.png)');
		$(this).css('backgroundImage','url(./public/images/commande/cadre_vert.png)');

		$('#description_paiement').html($('#description_'+$(this).attr('id')).html());
	});

	$('#code_promo input:image').click(function() {
		check_promo();
	});
	$('#code_promo input:text').keypress(function (e) {
		if (e.which == 13)
			check_promo();
	});
});

function ajouter_prefere(ref, cat, type)
{
	jQuery.get('./public/ajouter_prefere.php?ref='+ref+'&cat='+cat+'&type='+type, function(data, textStatus) {
		if (data=='OK')
			confirm("L'article a &eacute;t&eacute; ajouter mes pr&eacute;f&eacute;r&eacute;s.", '', '#prefere_ok');
	});
}

