var timerUpdatePanier  = null;
var lastInput = null;

function startTimeout(input){ 
	lastInput = input;
	if (timerUpdatePanier !== null){
		clearTimeout(timerUpdatePanier);
	}
	timerUpdatePanier = setTimeout('timeoutUpdatePanier();',1000);
	
}

function timeoutUpdatePanier(){
	modifProduit(lastInput);
	lastInput = null;
	timerUpdatePanier = null;
	
}

function modifProduit(even, message) {
    var quantite = even.value;
    var reference = even.name;
    var idFocus = even.id;

    var re = /^\d*$/; 
    quantite = $.trim(quantite.toString());
    
    if (timerUpdatePanier !== null){
        clearTimeout(timerUpdatePanier);
    }
    
    if (quantite.match(re) && even.defaultValue != quantite && !quantite.match(/^[0 ]*$/)) {
        bloquer(message);
        $.ajax({
            type: 'post', 
            url: '/commande/recapitulatif/update/',
            data: '&idProduitVente=' + reference + '&quantite=' + quantite,
            async: true,
            dataType: 'json',
            success: function(data){
        		renderResults(data);
        		if (window.focus){
        			var elementInFocus = document.getElementById(idFocus);
        			if (elementInFocus){
        				if (elementInFocus.focus){
        					try {
        						
        						elementInFocus.focus();
        						elementInFocus.select();
        					}catch(err){
        						
        					}
        				}
        			}
        		}
        	}
        });
    }
}

function supprProduit(reference) {
    $.ajax({
        type: 'post', 
        url: '/commande/recapitulatif/update/',
        data: '&idProduitVente=' + reference + '&quantite=0',
        async: true,
        dataType: 'json',
        success: renderResults
    });
}

function changerQuantite(difference, id, message) {
	document.getElementById(id).value = parseInt(document.getElementById(id).value) + parseInt(difference);
	modifProduit(document.getElementById(id), message);
}

function modifService(idServiceVente, active, titre, texte, bouton) {
    var myAjax = $.ajax({
        type: 'post',
        url: '/commande/recapitulatif/update/',
        data: '&idServiceVente=' + idServiceVente + '&active=' + active,
        async: true,
        dataType: 'json',
        success: function(response) {
            renderResults(response);
            
            if(active == 0) {
                options = new Array();
                options["picto"] = "avertissement";
                messageBox(titre, texte, bouton, options);
            }
        }
    });
}

function modifServiceByCheckBox(idServiceVente, titre, texte, bouton) {
//    var idServiceVente = even.name;
    var active = 0;
    if(document.getElementById('checkboxGarantie' + idServiceVente).checked) {
        active = 1;
    }
    modifService(idServiceVente, active, titre, texte, bouton);
}

function modifierReduction(even) {
    var id = even.name;
    var url = '/commande/recapitulatif/update/';
    var parametre = '&idReduction=' + id;
    var myAjax = $.ajax({
        type: 'post',
        url: url,
        data: parametre,
        async: true,
        dataType: 'json',
        success: renderResults
    });
}

function renderResults(response, options){
    if(response['formRecapitulatifCommande'] != undefined) {
        $('#idFormRecap').html(response['formRecapitulatifCommande']);
    }
    $('#menuPanier').html(response['contenuPanier']);
    $('#panierClient').html(response['indexPanier']);

    if(response['message'] != null && response['message'] != '') {
        messageBox(response['message']['titre'], response['message']['message'], response['message']['bouton'], options);
    }
}

function ajouterCodePromo(nomCodePromo) {
    if(nomCodePromo != '') {
        var myAjax = $.ajax({
            type: 'post',
            url: '/commande/recapitulatif/update/',
            data: '&nomCodePromo=' + nomCodePromo,
            async: true,
            dataType: 'json',
            success: function(response) {
                renderResults(response);
            }
        });
    } else {
        debloquer();
    }
}

function supprimerCodePromo(idReduction) {
    var myAjax = $.ajax({
        type: 'post',
        url: '/commande/recapitulatif/update/',
        data: '&idReduction=' + idReduction + '&codePromo=' + 1,
        async: true,
        dataType: 'json',
        success: function(response) {
            renderResults(response);
        }
    });
}

function setCodePostal () {
    var codePostal = $("[name=cp_text]").val();

    $.ajax ({
        type: "POST",
        url: "/commande/setcodepostal",
        data: "codePostal=" + codePostal,
        dataType: 'json',
        success: function (response) {
            if (response != true) {
                options = new Array();
                options["picto"] = "error";
                messageBox (response.title, response.message, response.boutton, options);
            } else {
                refreshPanier();
            }
        } 
    });
}

function initPostalCode () {
    $.ajax ({
        type: "POST",
        url: "/commande/initcodepostal",
        data: null,
        success: function (response) {
            refreshPanier();
        }
    });
}

function refreshPanier() {
    var myAjax = $.ajax({
             type: 'post',
             url: '/commande/recapitulatif/update/',
             data: null,
             async: true,
             dataType: 'json',
             success: function(response) {
                 renderResults(response);
             }
     });
 }

function clearText(thefield){
    if (thefield.defaultValue==thefield.value) {
        thefield.value = "";
    }
} 