$(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 showInfoInput(idInput, msg) {
    var currentInput = $('#' + idInput);
    currentInput.easyTooltip({
        tooltipId: 'tooltip-Info',
        yOffset: 50,
        content: msg
    });
    currentInput.one('blur', function(e) {
        $(this).unbind('.tooltip-Info');
        $('#tooltip-Info').remove();
    });
}

function showErrorInput(idInput, msg) {
    var currentInput = $('#' + idInput);
    currentInput.addClass('error');
    currentInput.easyTooltip({
        tooltipId: 'tooltip-error',
        yOffset: 50,
		content: msg
    });
    currentInput.one('focus', function(e) {
        $(this).removeClass('error');
        $(this).unbind('.tooltip-error');
        $('#tooltip-error').remove();
    });
}

function clearErrorInput(idInput) {
    var currentInput = $('#' + idInput)
    currentInput.removeClass('error');
    if (currentInput.attr('type') == 'text') {
        currentInput.val("");
    }
    currentInput.unbind('.tooltip-error');
    $('#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",
        closeHTML: "",
        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 showPopupDiv(nom) {
    function ajaxPost(method, data, success, error) {
        $.ajax({
            type: "POST",
            url: "/AjaxServices/Popup.svc/" + method,
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                success(data);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if ($.isFunction(error)) {
                    error(XMLHttpRequest, textStatus, errorThrown);
                }
            }
        });
    }

    // récup param ajaxpost
    ajaxPost('GetPopup', '{"titre": "' + nom + '"}',
        function(data) {
            // onsuccess :
            var dlg = $("<div>" + data.d.contenu + "</div>");
            if (data.d.duree) {
                var timeoutId = setTimeout($.modal.close, data.d.duree * 1000);
            }
            var options = {
                overlayCss: { backgroundColor: "rgb(38, 38, 38)" },
                opacity: 90,
                zIndex: 100000,
                closeClass: "btnClose",
                closeHTML: data.d.boutonFermeture ? '<a class="btnClose modalCloseImg" href="#"></a>' : "",
                minWidth: data.d.largeur,
                minHeight: data.d.hauteur,
                onClose: function() {
                    $.modal.close();
                    dlg.remove();
                    clearTimeout(timeoutId);
                }
            };
            $.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(strAccents) {
    var strAccentsOut = strAccents.split('');
    strAccents = strAccents.split('');
    var strAccentsLen = strAccents.length;
    var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
    var accentsOut = ['A', 'A', 'A', 'A', 'A', 'A', 'a', 'a', 'a', 'a', 'a', 'a', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'o', 'o', 'o', 'o', 'o', 'o', 'E', 'E', 'E', 'E', 'e', 'e', 'e', 'e', 'e', 'C', 'c', 'D', 'I', 'I', 'I', 'I', 'i', 'i', 'i', 'i', 'U', 'U', 'U', 'U', 'u', 'u', 'u', 'u', 'N', 'n', 'S', 's', 'Y', 'y', 'y', 'Z', 'z'];

    for (var y = 0; y < strAccentsLen; y++) {
        var idx = accents.indexOf(strAccents[y]);
        if (idx != -1) {
            strAccentsOut[y] = accentsOut[idx];
        }
    }
    strAccentsOut = strAccentsOut.join('');
    return strAccentsOut;
}

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);
}

