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, messagePatienter, arrayConfirmation) {
	var options = new Array();
	var count = 0;
	//faire une copie du tableau et compter le nombre d'éléments
	//NB : array.length ne fonctionne pas avec un tableau indexé!
	if ( typeof arrayConfirmation == 'array' ||  typeof arrayConfirmation == 'object'){
		for(i in arrayConfirmation){
			options[i] = arrayConfirmation[i];
			count++;
		}
	}
	
	if (
			arrayConfirmation != undefined 
			&& count >0 
			&& arrayConfirmation['confirm'] != true
	){
		var message = '';
		if (arrayConfirmation['picto'] == undefined){
			options['picto'] = 'avertissement';
		}
		
		
//		options['boutonDroitLibelle']="oui";
		//NB : attention aux quote (') qui posent problème si on a un délimiter ' => .replace(/'/g,'\\\'')
		// et double quote (") parce qu'on est dans un onclick!  => .replace(/"/g,'&quot;')
		options['boutonDroitLien'] = 'javascript:supprProduit('+reference+', \''+messagePatienter.replace(/'/g,'\\\'')+'\', {\'confirm\':true} );';
		options['boutonDroitLien'] = options['boutonDroitLien'].replace(/"/g,'&quot;');
		
		message = arrayConfirmation['message'];
		messageBox(arrayConfirmation['titre'], message, arrayConfirmation['boutonGaucheLibelle'], options);
		return false;
	}else {
		bloquer(messagePatienter);
	}
    $.ajax({
        type: 'post', 
        url: '/commande/recapitulatif/update/',
        data: '&idProduitVente=' + reference + '&quantite=0',
        async: true,
        dataType: 'json',
        success: renderResults
    });
}

function changerQuantite(difference, id, message) {
	if (parseInt(document.getElementById(id).value) + parseInt(difference) >0){
		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 checkPostalCode(link) {
    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);
                initPostalCode();
            } else {
            	window.location = link;
                return true;
            }
        } 
    });
}

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 = "";
    }
} 
