$(document).ready(function() {

    /*DOCUMENTATION INTERNET PRATIQUE POUR JQUERY :
    http://jquery.com
    http://jquery.developpeur-web2.com/documentation.php
    */
    if (BrowserDetect.OS == "Mac") {
        $("#zoneFixeNofolo").css({ 'top': 472 });
    }
    if (window.devicePixelRatio)  //If WebKit browser
    {
        //IF CHROME
        if (escape(navigator.javaEnabled.toString()) == 'function%20javaEnabled%28%29%20%7B%20%5Bnative%20code%5D%20%7D') {
            $("#followOnTwitter").css({ top: -20 });
            $("#bookmark").css({ left: 325, top: -16 });
            $(".block").css({ top: -25 });
            $("#chipRss").css({ top: 8 });
        }
    }
    if ($.browser.opera) {
        $("#chipRss").css({ top: 31 });
    }
    if ($.browser.msie) {
        if (BrowserDetect.version == 7 || BrowserDetect.version == 6) {
            //$(".dernierNo").wrap('<div class="absolute"><div>');
            $(".dernierNo").css({ width: 420, margin: 0, padding: 4 });
        }
    }
    //Cache la colonne client par défaut//
    $("#colonneClientFixe").addClass("hidden");
    //Cache la zone d'identification du NO par défaut//
    $("#identificationNo").hide();
    //Cache le tag d'identification du NO par défaut//
    $("#tagIdentificationNo").hide();
    //Cache le tag qui apparait apres l'ajout du NO par défaut//
    $("#absoluteWrap").hide();
    //Vide le champ input (certains navigateurs conservent les valeur des champs input lors d'un rafraîchissement//
    $("#iNewNo").removeAttr("value");
    //Met automatiquement le Focus dans le champ Input//
    $("#iNewNo").focus();

    //Lie (bind) l'évènement click au (?) au bas de de la page (ouvre ou ferme le panneau Client)//
    $("#idWho").click(function() {
        $("#colonneClientFixe").toggleClass("hidden");
    });
    //Lie (bind) l'évènement click au (NOFOLO) au bas de de la page (ouvre ou ferme le panneau Client)//
    $("#idMore").click(function() {
        $("#colonneClientFixe").toggleClass("hidden");
    });
    //Lie (bind) l'évènement click au (X) dans la zone Client (ferme le panneau Client)//
    $("#clientXfermer").click(function() {
        $("#colonneClientFixe").toggleClass("hidden");
    });


    //Désactive visuellement le (+) nouveau NO tant que le champ est vide//
    $("#lienPlus").attr("disabled", "disabled");
    $("#lienPlus").removeClass("lienPlusActif");
    $("#lienPlus").addClass("lienPlusInactif");
    $("#lienPlus").css({ cursor: "default" });
    //Désactive visuellement le (+) identification NO tant que le champ est vide//
    $("#idIdentificationLienPlus").attr("disabled", "disabled");
    $("#idIdentificationLienPlus").removeClass("lienPlusActif");
    $("#idIdentificationLienPlus").addClass("lienPlusInactif");
    $("#idIdentificationLienPlus").css({ cursor: "default" });

    //Vérifie au keyUp si le champ d'ajout d'un NO a quelquechose d'écrit, si oui, modifie le (+) pour le rendre "actif"//	
    $("#iNewNo").keyup(verifierContenuChampNouveauNo);

    //Lie les LI dans la liste au bas de la page pour avoir un effet survol//
    $(".dernierNo").bind("mouseover", hoverInDeLaListe);
    $(".dernierNo").bind("mouseout", hoverOutDeLaListe);
    $("#listeDesNo > li").bind("mouseover", hoverInDeLaListe);
    $("#listeDesNo > li").bind("mouseout", hoverOutDeLaListe);

    $("#tagIdentificationNo").hover(function() {
        $("#tagIdentificationNo").show();
        //event.stopPropagation();
    },
        function() {
            $("#tagIdentificationNo").hide();
            $("#quiDitNo").empty();
            $("#dateOuSite").empty();
            //event.stopPropagation();
        });


    //Agit à la soumission du formulaire étape 1 (no)//
    $('#fNewNo').submit(function() {
        $("#errorCode").hide();

        var theNewNo = $("#iNewNo").val();
        theNewNo = trim(theNewNo, " ");

        if (theNewNo != "") {
            $("#iNewNo").attr("disabled", "disabled");
            $("#lienPlus").attr("disabled", "disabled");
            $("#lienPlus").removeClass("lienPlusActif");
            $("#lienPlus").addClass("lienPlusInactif");
            $("#lienPlus").css({ cursor: "default" });
            var idDuDernierNo = $(".dernierNo").attr("id");
            $(".dernierNo").removeAttr("id");
            $("#listeDesNo").prepend('<li id="' + idDuDernierNo + '">' + $(".dernierNo").text() + "</li>");
            $(".dernierNo").unbind("mouseover", hoverInDeLaListe);
            $(".dernierNo").unbind("mouseout", hoverOutDeLaListe);
            $(".dernierNo").text(theNewNo)

            $("#listeDesNo > li").unbind("mouseover", hoverInDeLaListe);
            $("#listeDesNo > li").unbind("mouseout", hoverOutDeLaListe);
            $("#listeDesNo > li").bind("mouseover", hoverInDeLaListe);
            $("#listeDesNo > li").bind("mouseout", hoverOutDeLaListe);

            $("#iNewNo").removeAttr("value");

            if ($("#iIdNomNo").val() != "" && $("#iIdNomNo").val() != "Votre nom" || $("#iIdCourrielNo").val() != "" && $("#iIdCourrielNo").val() != "Lien facultatif (Facebook, LinkedIn, etc.)") {
                $("#idIdentificationLienPlus").removeAttr("disabled", "disabled");
                $("#idIdentificationLienPlus").addClass("lienPlusActif");
                $("#idIdentificationLienPlus").removeClass("lienPlusInactif");
                $("#idIdentificationLienPlus").css({ cursor: "pointer" });
            };


            //$("#grosNoDernier").after('<div id="absoluteWrap"></div>');

            $("#tagIdentificationNo").hide()
            $("#laisseTonNo").fadeTo(1000, 0.1)
            if ($.browser.mozilla || $.browser.safari || $.browser.opera) {
                $("#section2").fadeOut(1000, function() {
                    $("#section2").remove();
                    $("#laisseTonNo").empty();
                    $("#laisseTonNo").append("<br />Assume ton <strong>NO</strong>");
                    $("#laisseTonNo").fadeTo(1000, 1);

                    var posYid = $(".dernierNo").findPos();

                    $("#absoluteWrap").css({ top: posYid.y + 6, zIndex: 11 });
                    $("#absoluteWrap").fadeIn(500, function() {
                        $("#bloc2").animate({ height: 160 }, 1000);
                        if ($.browser.opera) {
                            $("#chipRss").animate({ top: 31 }, 1000);
                        }
                        else {
                            if ($.browser.mozilla || $.browser.safari)
                            { $("#chipRss").animate({ top: 4 }, 1000); } //top: 12
                        }
                        $("#absoluteWrap").animate({ top: posYid.y + 126 }, 1000, function() {
                            $("#identificationNo").fadeIn(1000);
                            $("#absoluteWrap").fadeTo(10000, 1, function() {
                                $("#absoluteWrap").fadeOut(500);
                            });
                        });
                        $("#iIdCourrielNo").keyup(verifierContenuChampIdentificationNo);
                        $("#iIdCourrielNo").mouseup(verifierContenuChampIdentificationNo);
                        $("#iIdCourrielNo").blur(blurChampCourriel);
                        $("#iIdCourrielNo").focus(focusChampCourriel);
                        $("#iIdNomNo").keyup(verifierContenuChampIdentificationNo);
                        $("#iIdNomNo").mouseup(verifierContenuChampIdentificationNo);
                        $("#iIdNomNo").focus(focusChampNom);
                        $("#iIdNomNo").blur(blurChampNom);
                    });
                });
            }
            else {
                $("#section2").hide(1, function() {
                    $("#section2").remove();
                    $("#laisseTonNo").empty();
                    $("#laisseTonNo").append("<br />Assume ton <strong>NO</strong>");
                    $("#laisseTonNo").fadeTo(1000, 1);

                    var posYid = $(".dernierNo").findPos();

                    if (BrowserDetect.version == 7 || BrowserDetect.version == 6) {
                        $("#absoluteWrap").insertBefore(".dernierNo");
                        $("#absoluteWrap").wrap('<div class="absolute"></div>');
                        if (BrowserDetect.version == 7) {
                            $("#absoluteWrap").css({ top: 6, left: -90 });
                        }
                        else {
                            $("#absoluteWrap").css({ top: 6, left: -82 });
                        }

                        $("#absoluteWrap").fadeIn(500, function() {
                            $("#bloc2").animate({ height: 200 }, 1000);
                            $("#absoluteWrap").animate({ top: 6 }, 1000);
                            $("#chipRss").animate({ top: 5 /*top: 13*/ }, 1000, function() {
                                $("#identificationNo").show();
                                $("#absoluteWrap").fadeTo(10000, 1, function() {
                                    $("#absoluteWrap").fadeOut(500);
                                });
                            });
                            $("#iIdCourrielNo").keyup(verifierContenuChampIdentificationNo);
                            $("#iIdCourrielNo").blur(blurChampCourriel);
                            $("#iIdCourrielNo").focus(focusChampCourriel);
                            $("#iIdNomNo").keyup(verifierContenuChampIdentificationNo);
                            $("#iIdNomNo").focus(focusChampNom);
                            $("#iIdNomNo").blur(blurChampNom);
                        });
                    }
                    else {

                        $("#absoluteWrap").css({ top: posYid.y + 6, left: 252 });
                        $("#absoluteWrap").fadeIn(500, function() {
                            $("#bloc2").animate({ height: 200 }, 1000);
                            $("#absoluteWrap").animate({ top: posYid.y + 162 }, 1000);
                            $("#chipRss").animate({ top: 4 /*top: 12*/ }, 1000, function() {
                                $("#identificationNo").show();
                                $("#absoluteWrap").fadeTo(10000, 1, function() {
                                    $("#absoluteWrap").fadeOut(500);
                                });
                            });
                            $("#iIdCourrielNo").keyup(verifierContenuChampIdentificationNo);
                            $("#iIdCourrielNo").blur(blurChampCourriel);
                            $("#iIdCourrielNo").focus(focusChampCourriel);
                            $("#iIdNomNo").keyup(verifierContenuChampIdentificationNo);
                            $("#iIdNomNo").focus(focusChampNom);
                            $("#iIdNomNo").blur(blurChampNom);
                        });
                    }

                });
            }
        }
        else { //si champ est VIDE
            $("#errorCode").html("Le champ doit contenir quelquechose.");
            $("#errorCode").show();

        };


        return false;
    });

    //Agit à la soumission du formulaire étape 2 (nom + courriel/site/date)//
    $('#fIdentificationNo').submit(function() {
        $("#errorCode").hide();
        $("#idIdentificationLienPlus").attr("disabled", "disabled");
        $("#iIdNomNo").attr("disabled", "disabled");
        $("#iIdCourrielNo").attr("disabled", "disabled");
        $("#idIdentificationLienPlus").removeClass("lienPlusActif");
        $("#idIdentificationLienPlus").addClass("lienPlusInactif");
        $("#idIdentificationLienPlus").css({ cursor: "default" });
        var valeurCourriel = "";
        var valeurNom = "Quelqu'un";
        if ($("#iIdNomNo").val() != "" && $("#iIdNomNo").val() != "Votre nom") {
            valeurNom = $("#iIdNomNo").val();
        };

//        if ($("#iIdCourrielNo").val() != "" && $("#iIdCourrielNo").val() != "Lien facultatif (Facebook, LinkedIn, etc.)") {
//            valeurCourriel = $("#iIdCourrielNo").val();
//        };


        if ($("#iIdCourrielNo").val() != "Lien facultatif (Facebook, LinkedIn, etc.)") {
            valeurCourriel = $("#iIdCourrielNo").val();
        }
        else {
            valeurCourriel = "";
        };
        
        
        //alert("Qui : " + valeurNom + "Quand ou site? : " + valeurCourriel + "");

        $("#vousDitesNo").empty();
        $("#votreSiteOuCourriel").empty();

        $("#vousDitesNo").append(valeurNom);
        $("#votreSiteOuCourriel").append(valeurCourriel);
        pos = $("#grosNoDernier").findPos();
        $("#tagVotreNo").css({ top: pos.y - 1 });
        $("#tagVotreNo").fadeIn(500, function() {
            $("#absoluteWrap").hide();
            $("#tagVotreNo").fadeTo(10000, 1, function() {
                $("#tagVotreNo").fadeOut(500);
            });
        });



        //ICI NOUS AVONS LA REQUETE A LA PAGE saveInfosNewNo.aspx ET ON LUI ENVOIE
        //LE CONTENU DES INPUTS.  IL Y LE MESSAGE/CODE D'ERREUR OU DE CONFIRMATION À RECEVOIR

        // !!!! IMPORTANT : il faut faire en sorte que la date soit enregistrée dans la BD 
        // pour le courriel ou le site en format (01-01-01) car elle est utilisée lorsque le 
        // champ est laissé vide.

        var theMessage = $(".dernierNo").text();

        //alert("Le message : " + theMessage + "; le nom : " + valeurNom + "; le courriel " + valeurCourriel);

        $.get("SaveNewMessage.aspx",
		    { message: theMessage, name: valeurNom, email: valeurCourriel },
			function(data) {
			    //alert(data);
			    //0 == tout est OK; 1 == courriel invalide; 2 == nom invalide; 3 == message invalide.
			    if (data != 0) { //Si il y a une erreur
			        $("#idIdentificationLienPlus").removeAttr("disabled", "disabled");
			        $("#iIdNomNo").removeAttr("disabled", "disabled");
			        $("#iIdCourrielNo").removeAttr("disabled", "disabled");
			        $("#idIdentificationLienPlus").addClass("lienPlusActif");
			        $("#idIdentificationLienPlus").removeClass("lienPlusInactif");
			        $("#idIdentificationLienPlus").css({ cursor: "pointer" });
			        if (data == 1) { //si le courriel est invalide
			            $("#errorCode").html("Votre courriel est invalide (ex: 'nom@domaine.ca'");
			            $("#errorCode").show();
			        }
			        else {
			            if (data == 2) { //si le nom est invalide
			                $("#errorCode").html("Votre nom est invalide (ex: 'David'");
			                $("#errorCode").show();
			            }
			            else { //le message est invalide
			                $("#errorCode").html("Votre message ne convient pas.");
			                $("#errorCode").show();
			            };
			        };

			    }
			    else {
			        //inclure le reste de l'animation ici, pour n'animer que si tout est OK.
			        //todo: ne pas faire un refresh total de la page, mais juste le controle.
			        //setTimeout("location.reload(true);", 5000);
			    };
			});

        return false;
    });

});

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function hoverInDeLaListe(){
    //au Hover IN
    var stringID = this.id;
    var myStringIDList = stringID.split('_-_-_');

    pos = $(this).findPos();
    $("#tagIdentificationNo").css({ 'top': pos.y + 4 });
    $("#quiDitNo").empty();
    $("#dateOuSite").empty();
    $("#quiDitNo").append(myStringIDList[0]);

    var theLink = myStringIDList[1];
    if (!theLink.match("http://")) {
        if (theLink.match("@")) {
            theLink = "mailto:" + theLink;
            $("#dateOuSite").append("<a href='" + theLink + "' target='_blank'>" + myStringIDList[1] + "</a>");
        }
        else {

            var x = new Date();

            if (theLink.match(x.getFullYear())) {
                //It's a date, so we don't link it whith URL
                $("#dateOuSite").append(theLink.substr(0, (theLink.toString().length - 3)));
            }
            else {
                theLink = "http://" + theLink;
                $("#dateOuSite").append("<a href='" + theLink + "' target='_blank'>" + myStringIDList[1] + "</a>");
            }
        }
    }
    else {
        $("#dateOuSite").append("<a href='" + theLink + "' target='_blank'>" + myStringIDList[1] + "</a>");
    }


    $("#tagIdentificationNo").show();

};
function hoverOutDeLaListe(){
//au Hover OUT
  $("#tagIdentificationNo").hide();     
};


function verifierContenuChampIdentificationNo(){
	if ($("#iIdCourrielNo").val() != "" && $("#iIdCourrielNo").val() != "Lien facultatif (Facebook, LinkedIn, etc.)" || $("#iIdNomNo").val() != "" && $("#iIdNomNo").val() != "Votre nom"){ 
		$("#idIdentificationLienPlus").removeClass("lienPlusInactif");		
		$("#idIdentificationLienPlus").addClass("lienPlusActif");
		$("#idIdentificationLienPlus").css({cursor:"pointer"});
		$("#idIdentificationLienPlus").removeAttr("disabled", "disabled");		
		}
	else{
		$("#idIdentificationLienPlus").removeClass("lienPlusActif");		
		$("#idIdentificationLienPlus").addClass("lienPlusInactif");	
		$("#idIdentificationLienPlus").css({cursor:"default"});
		$("#idIdentificationLienPlus").attr("disabled", "disabled");		
		}
};
function verifierContenuChampNouveauNo(){
	if (trim(this.value, " ") != ""){ 
		$("#lienPlus").removeClass("lienPlusInactif");		
		$("#lienPlus").addClass("lienPlusActif");
		$("#lienPlus").css({ cursor:"pointer"});
		$("#lienPlus").removeAttr("disabled", "disabled");		
		}
	else{
		$("#lienPlus").removeClass("lienPlusActif");		
		$("#lienPlus").addClass("lienPlusInactif");	
		$("#lienPlus").css({ cursor:"default"});
		$("#lienPlus").attr("disabled", "disabled");		
		}
};	

//Le blur se produit lorsque le focus du champ est perdu	
function blurChampNom(){
	if($("#iIdNomNo").val()==""){
		$("#iIdNomNo").val("Votre nom");
		};
};
//Le focus se propduit lorsque l'utilisateur met le focus (ex. clique) sur le champ
function focusChampNom(){
	if($("#iIdNomNo").val()=="Votre nom"){
		$("#iIdNomNo").val("");
		};
};
//Le blur se produit lorsque le focus du champ est perdu	
function blurChampCourriel(){
	if($("#iIdCourrielNo").val()==""){
		$("#iIdCourrielNo").val("Lien facultatif (Facebook, LinkedIn, etc.)");
		};
};
//Le focus se propduit lorsque l'utilisateur met le focus (ex. clique) sur le champ
function focusChampCourriel(){
	if($("#iIdCourrielNo").val()=="Lien facultatif (Facebook, LinkedIn, etc.)"){
		$("#iIdCourrielNo").val("");
		};
};

jQuery.fn.extend({
   findPos : function() {
       obj = $(this).get(0);
       var curleft = obj.offsetLeft || 0;
       var curtop = obj.offsetTop || 0;
       while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
       }
       return {x:curleft,y:curtop};
   }
});

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
