$(document).ready(function() {

    /*********** GESTION ALERTE FORMULAIRE ************/

    // Gestion des "placeholder"
    var nativePlaceholder = "placeholder" in document.createElement("input");

    $(".text").each(function() {
        this.placeholder = $(this).attr("title");
    });

    if (!nativePlaceholder) {
        $("input[title].text").filter(function(i) {
            return $.trim(this.value) == "";
        }).val(function() {
            return $(this).attr("title");
        });

        $('.text').focus(
		    function(e) {
		        e.preventDefault();
		        if (this.placeholder == this.value) {
		            this.value = "";
		        }
		    }
	    );
        $('.text').blur(
		    function(e) {
		        if ($.trim(this.value) == "") {
		            this.value = this.placeholder;
		        }
		    }
	    );
    }

    //changement d'image du totem
    $(".leftCol img").hover(
	    function() {
	        var src = $(this).attr("src").match(/[^\.]+/) + "_on.gif";
	        $(this).attr("src", src);
	    },
        function() {
            var src = $(this).attr("src").replace("_on", "");
            $(this).attr("src", src);
        }
    );

    function findNearestSubmit(elt) {
        var search;
        // Cherche le premier submit suivant le noeud considéré dans l'ordre du document,
        // en descendant dans les cousins au besoin
        search = elt.nextAll('input:image,input:submit');
        if (search.length == 0) {
            // Cherche les neveux des frères cadets
            search = elt.nextAll().find('input:image,input:submit');
            if (search.length == 0) {
                elt.parents().each(
                    function(i) {
                        search = $(this).nextAll('input:image,input:submit');
                        if (search.length == 0) {
                            search = $(this).nextAll().find('input:image,input:submit');
                        }
                        return search.length == 0;
                    }
                );
            }
        }

        return search.eq(0);
    }

    $('input.text').keypress(
        function(e) {
            if (e.which == 13) {
                e.preventDefault();
                findNearestSubmit($(this)).click();
            }
        }
    );
});


function showErrorInput(idInput, msg) {    
    var currentInput = $('#' + idInput)
    currentInput.addClass('error');
//    if (currentInput.attr('type') == 'text') {
//        currentInput.val(msg);
//    }
    currentInput.easyTooltip({
        tooltipId: 'tooltip-error',
        yOffset: 50,
		content: msg
    });
    currentInput.one('focus', function(e) {
        $(this).removeClass('error');
        $(this).unbind('mouseenter mouseleave');
        $('#tooltip-error').remove();
//        this.value = "";
    });
}

function clearErrorInput(idInput) {
    var currentInput = $('#' + idInput)
    currentInput.removeClass('error');
    if (currentInput.attr('type') == 'text') {
        currentInput.val("");
    }
    currentInput.unbind('mouseenter mouseleave');
    $('#tooltip-error').remove();
}

function showErrorModal(msg) {

    var dlg = $('<div class="popup">' +
						'<div id="errorMsg">' +
							'<div class="content">' +
								'<p>' + msg + '</p>' +
								'<input type="submit" class="btnOk close" value="OK" />' +
							'</div>' +
						'</div>'+
					'</div>');
    var options = {
        closeClass: "btnOk",
        overlayCss: { backgroundColor: "rgb(38, 38, 38)" },
        opacity: 90,
        zIndex: 100000,
        onClose: function() {
            $.modal.close();
            dlg.remove();
        }
    };
    $.modal(dlg, options);
}

function showSpinnerModal() {

    var dlg = $('<div class="popup" id="loading">' +
					'<div id="loader">' +
						'<img src="/Style%20Library/img/loader.gif" alt="loading stand by..." width="49" height="49" />' +
						'<p>Vos données sont en cours de traitement.<br />' +
						'Merci de bien vouloir patienter</p>' +
					'</div>' +
				'</div>');
    var options = {
        close: false,
        overlayCss: { backgroundColor: "rgb(38, 38, 38)" },
        opacity: 90,
        zIndex: 100000,
        onClose: function() {
            $.modal.close();
            dlg.remove();
        }
    };
    $.modal(dlg, options);
					
}

function ouvre_popup(page, width, height) {
    window.open(page, "nom_popup", "menubar=no, status=no, scrollbars=yes,resizable=yes, menubar=no, width=" + width + ", height=" + height);
}

function removeAccents(msg) {
    /* acentos existentes
    é ý ú í ó á ç
    è   ù ì ò à
    ê   û î ô â
    õ ã   ñ
    ë ÿ ü ï ö ä
    */
    msg = msg.replace(/[áàâãä]/g, "a");
    msg = msg.replace(/[éèêë]/g, "e");
    msg = msg.replace(/[íìîï]/g, "i");
    msg = msg.replace(/[óòôõö]/g, "o");
    msg = msg.replace(/[úùûü]/g, "u");
    msg = msg.replace(/[ýÿ]/g, "y");
    msg = msg.replace(/[ç]/g, "c");
    msg = msg.replace(/[ñ]/g, "n");

    msg = msg.replace(/[ÁÀÂÃÄ]/g, "A");
    msg = msg.replace(/[ÉÈÊË]/g, "E");
    msg = msg.replace(/[ÍÌÎÏ]/g, "I");
    msg = msg.replace(/[ÓÒÔÕÖ]/g, "O");
    msg = msg.replace(/[ÚÙÛÜ]/g, "U");
    msg = msg.replace(/[Ý]/g, "Y");
    msg = msg.replace(/[Ç]/g, "C");
    msg = msg.replace(/[Ñ]/g, "N");
    return msg;
}


function formateNombre(pStr, pDecimalSep, pGroupeSep) {
    pStr += '';
    x = pStr.split('.');
    x0 = x[0];
    x1 = x.length > 1 ? pDecimalSep + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x0)) {
        x0 = x0.replace(rgx, '$1' + pGroupeSep + '$2');
    }
    return x0 + x1;
}

function isDate(d) {
    // Cette fonction permet de vérifier la validité d’une date au format jj/mm/aa ou jj/mm/aaaa

    var e = /^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/;

    if (!e.test(d)) // On teste l’expression régulière pour valider la forme de la date
        return false; // Si pas bon, retourne faux

    // On sépare la date en 3 variables pour vérification, parseInt() converti du texte en entier
    var split = d.split("/");
    var j = parseInt(split[0], 10); // jour
    var m = parseInt(split[1], 10); // mois
    var a = parseInt(split[2], 10); // année

    // Définition du dernier jour de février
    // Année bissextile si annnée divisible par 4 et que ce n’est pas un siècle, ou bien si divisible par 400
    var fev = (a % 4 == 0 && a % 100 != 0 || a % 400 == 0) ? fev = 29 : 28;

    // Nombre de jours pour chaque mois
    var nbJours = [31, fev, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    // Enfin, retourne vrai si le jour est bien entre 1 et le bon nombre de jours, idem pour les mois, sinon retourn faux
    return (m >= 1 && m <= 12 && j >= 1 && j <= nbJours[m - 1]);
}

function isEmail(s) {
    return /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@[A-Za-z0-9]+(([\.\-]?[a-zA-Z0-9]+)*)\.[A-Za-z]{2,}$/.test(s);
}
