/*--------------------------------------------------------------------------------*/
/*                                      AGENCY                                    */
/*--------------------------------------------------------------------------------*/


/**
 * <code>chooseAgence</code>
 * Chooses a specific agency.
 * @param agenceid : the agence id.
 * @param uri : the uri to go back to.
 */
function chooseAgence(agenceid, uri) {
  window.location.href = "/chooseAgence?id=" + agenceid + "&location=" + (uri !== undefined ? uri : escape(window.location.href));
}


/**
 * <code>reloadMap</code>
 * Reloads the google map when a user clicks an agency.
 * @param id : the agence id.
 * @param url : the google map url.
 */
function reloadMap(id, url) {
  $("ul.results li").attr("class", "");
  $("#" + id).attr("class", "active");
  $("#googleMap").html('<iframe width="344" height="472" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="' + url + '"></iframe><br /><small><a href="' + url + '" style="color:#0000FF;text-align:left" target="_blank">Agrandir le plan</a></small>');
}


/**
 * <code>check_codePostal</code>
 * Checks a postal code for validity.
 * @param e : the postal code.
 */
function check_codePostal(e) {
  ok = "1234567890";
  if (e.length != 5 && e.length != 2) {
    return false;
  }
  for (i = 0; i < e.length; i++) {
    if (ok.indexOf(e.charAt(i)) < 0) {
      if (i == 1) {
        if (!(e.charAt(0) == "9" && (e.charAt(1) == "A" || e.charAt(1) == "B" || e.charAt(1) == "a" || e.charAt(1) == "b"))) {
          return false;
        }
      } else {
        return false;
      }
    }
  }
  return true;
}


/**
 * <code>fillAgencyWithCookies</code>
 * Replaces various html fragments with the content of the agency cookie.
 * @return true if an agency was found, false otherwise.
 */
function fillAgencyWithCookies() {

  var agence = "";

  if ($.cookies && $.cookies.get("agency") === null && $.cookies.get("defaultAgency") !== null) {
    $.cookies.set("agency", $.cookies.get("defaultAgency"));
  }

  if ($.cookies && $.cookies.get("agency") !== null) {
    agence = $.map($.cookies.get("agency").split("&&&"), function(val) { return val.replace(/\+/g, " ").replace("null", ""); });
  }

  if (agence !== "") {

     $("div.chosen").show().find("h1.rm").text(agence[5]);
     if ($(".agence").hasClass("chosen")) {
       $(".address").html(agence[0]);
     } else {
       $(".address").html(agence[0].replace(/<br\/>/g," "));
     }
     $(".telephone").empty().prepend(agence[1]);
     $(".telephone, #tel-message-error, #tel-contact, #tarif-tel").empty();
     $(".telephone, #tel-contact").prepend(agence[1]);
     $("#tel-message-error").prepend(agence[1]);
     $("#openingHours-error").html(agence[8]);
     $("#tel-right").find("h3").html(agence[1]).end().find("p").remove();
     $(".mail a").attr("href", "mailto:" + agence[2]);
     /*if ($(".mail a").length > 0 && $(".mail a").html().length == 0) {
       $(".mail a").html(agence[2]);
     }*/
     $(".map a").attr("href", "/fiche-agence.jsp?code=" + agence[4] + "&uri=" + location.pathname + "&width=830&height=700");
     $(".change a, #head-ag-search").attr("href", "/no-cache/agence.jsp?uri=" + location.pathname + "&width=830&height=700");
     $("#head-ag-search").addClass("thickbox");
     setResaWithAgency(agence);

     return true;

  } else {

    $("div.unknown").show();
    $("div.no-agency").show();
    setResaWithDefault();

    return false;

  }

}

function setResaWithDefault(){
    $("#channelCode").val("60");
    $("#organizationCode").val("62");
    $("#agentEmail").val("serviceclient@selectour.com");
    $("#organizationName").val("Centrale de réservation Selectour");
    $("#agencyName").val("Centrale de réservation Selectour");
    $("#agencyCode").val("62");
    $("#agencyEmail").val("serviceclient@selectour.com");
    $("#agencyPhone").val("05 61 12 67 55");
    $("#agencyAddress").val("17 AVENUE HONORE SERRES 31000 TOULOUSE");
    $("#agencyFax").val("05 61 12 61 60");
}

function setResaWithAgency(agence){
    $("#agentEmail").val(agence[2]);
     $("#channelCode").val(agence[3]);
     $("#organizationCode").val(agence[4]);
     $("#organizationName").val(agence[5]);
     $("#agencyName").val(agence[5]);
    $("#agencyCode").val(agence[4]);
    $("#agencyEmail").val(agence[2]);
    $("#agencyPhone").val(agence[1]);
    $("#agencyAddress").val(agence[0].replace("<br/>", " "));
    $("#agencyFax").val(agence[9]);
}


/*--------------------------------------------------------------------------------*/
/*                TOOLS : Search history, favorites, comparator                   */
/*--------------------------------------------------------------------------------*/


/**
 * <code>loadTools</code>
 * Loads and initialize the left tool box.
 */
function loadTools() {

  if ($("div.tools").length > 0) {

    $("div.tools")
      .html("<img src=\"/csvweb/images/ajax-loader-big.gif\" style=\"padding: 50px 0 50px 90px\" alt=\"Chargement...\" title=\"Chargement...\" />")
      .load("/no-cache/elements/tools.jsp", function() {

      var initialHeight = $("#historyScroll").find("div.scrolledTo").height() + "px";

      $("#accordion").accordion({
        header: "h3",
        active: false,
        autoHeight: false,
        collapsible: true
      });

      $("#historyScroll").css("height", initialHeight);

      $("#accordion a.arrow_down").click(function() {
        var next = $("#historyScroll div.scrolledTo").next();
        if (next.length > 0) {
          $("#historyScroll").animate({height: next.css("height")}, {duration: 800, queue: false});
          $("#historyScroll").scrollTo(next, 800, {onAfter:function() {next.addClass("scrolledTo").siblings().removeClass("scrolledTo");} });
        }
        return false;
      });

      $("#accordion a.arrow_up").click(function() {
        var prev = $("#historyScroll div.scrolledTo").prev();
        if (prev.length > 0) {
          $("#historyScroll").animate({height: prev.css("height")}, {duration: 800, queue: false});
          $("#historyScroll").scrollTo(prev, 800, {onAfter:function() {prev.addClass("scrolledTo").siblings().removeClass("scrolledTo");} });
        }
        return false;
      });

      $("#clearHistory").click(function() {clearHistory(); return false;});

      $("#accordion .cpElements").each(function(){
        var cookieValue = $.cookies.get($(this).attr('id'));
        if (cookieValue && cookieValue != "undefined" && cookieValue !== "") {
            var elements = cookieValue.split("&&&");
            var length = elements.length;
            if (length > 0) {
                var title = $(this).find("h4");
                var button = $(this).find(".button");
                var listItems = "";
                title.prepend(length + "&nbsp;");
                $(this).show();
                $("#emptyCp").hide();
                listItems = "<ul>";
                for (i = 0; i < length; i++) {
                    var elementInfo = elements[i].split("#=#");
                    if (elementInfo.length > 3) {
                         listItems += "<li><a href=\"" + elementInfo[2] +"\">" + elementInfo[3] + "</a></li>";
                    }
                }
                listItems += "</ul>";
                button.before($(listItems));
            }

        }
      });

    });

  }

}


/*--------------------------------------------------------------------------------*/
/*                                      FAVORITES                                 */
/*--------------------------------------------------------------------------------*/


/**
 * <code>addFavorite</code>
 * Adds a new favorite.
 * @param id : the product id.
 * @param elt : the dom element clicked.
 */
function addFavorite(id, elt) {
  $.post("/favorite", {action: "addFavorite", id: id, url: elt.href, label: elt.rel}, function(ajaxData) {
    var fav = [],
        addFav = 0;

    if (ajaxData === "true") {
      $(elt)
        .text("Retirer des favoris").attr("title", "Retirer des favoris").unbind().click(function(){removeFavorite(id, this); return false;})
        .parent().removeClass("fav").addClass("favon");
      fav = /Afficher les favoris \(([\d]+)\)/.exec($(".rm-favoris, #fc .favoris").text());
      if (fav !== null && fav[1] !== null) {
        addFav = parseInt(fav[1], 10) + 1;
        $(".rm-favoris, #fc .favoris").text("Afficher les favoris (" + addFav + ")");
      }
      $(elt).wTooltip({fadeIn: 350, offsetY: 15,offsetX: -15});
      $(elt).trackClick("Ajouter_aux_favoris");
    } else {
      jAlert("Vous avez atteint le nombre maximum autorisé de favoris.", "Avertissement");
    }
  });
}


/**
 * <code>removeFavorite</code>
 * Adds a new favorite.
 * @param id : the product id.
 * @param elt : the dom element clicked.
 */
function removeFavorite(id, elt) {
  $.post("/favorite", {action: "removeFavorite", id: id, url: elt.href, label: elt.rel}, function(ajaxData) {
    var fav = [],
        removeFav = 0;

    if (ajaxData === "true") {
      if ($(elt).is(".suppr")) {
        location.href = location.href;
      } else {
        $(elt)
          .text("Ajouter aux favoris").attr("title", "Ajouter aux favoris").unbind().click(function(){addFavorite(id, this); return false;})
          .parent().removeClass("favon").addClass("fav");
        fav = /Afficher les favoris \(([\d]+)\)/.exec($(".rm-favoris, #fc .favoris").text());
        if (fav !== null && fav[1] !== null) {
          removeFav = parseInt(fav[1], 10) - 1;
          $(".rm-favoris, #fc .favoris").text("Afficher les favoris (" + removeFav + ")");
        }
        $(elt).wTooltip({fadeIn: 350, offsetY: 15,offsetX: -15});
        $(elt).trackClick("Retirer_des_favoris");
      }
    }
  });
}


/**
 * <code>loadFavorites</code>
 * Loads the existing favorites and modify the page to include them.
 */
function loadFavorites() {
  $.post("/favorite", {action: "loadFavorites"}, function(ajaxData) {

    // Init variables
    var favorites = [],
        favoriteIds = [],
        favoriteDates = [];

    // Update them if found
    if (ajaxData) {
      favorites = ajaxData.split("&&&");
      favoriteIds = $.map(favorites, function(val){
        return (/elementId="([\d]+)"/.exec(val)[1]);
      });
      favoriteDates = $.map(favorites, function(val){
        var date = /createTimestamp="([\d]+)-([\d]+)-([\d]+)/.exec(val);
        return date[3] + "/" + date[2] + "/" + date[1];
      });
      $(".rm-favoris,#fc .favoris").text("Afficher les favoris (" + favorites.length + ")");
    }

    $.each($("li.fav a, a.fav"), function() {

      // Get useful element info.
      var id = this.id.substring(this.id.indexOf("_") + 1);
      var foundFavIndex = $.inArray(id, favoriteIds);

      if (foundFavIndex > -1) {

        // Update the parent li background image
        $(this).text("Retirer des favoris").attr("title", "Retirer des favoris").parent().removeClass("fav").addClass("favon");

        // Update the element block depending on the page
        if ($(this).parents("div.rm-result:first").hasClass("favDisplay")) {
          $(this)
            .unbind().click(function(){ return false; })
            .parents("div.rm-result:first")
            .find("div.rm-tools ul")
              .append("<li class=\"added\">Ajouté aux Favoris le <span>" + favoriteDates[foundFavIndex] + "</span></li>").end()
            .find("div.right")
              .prepend("<a href=\"#\" class=\"suppr\" title=\"Supprimer le favori\">Supprimer le favori</a>")
            .find("a:first").unbind().click(function(){
              removeFavorite(id, this);
              return false;
            });
        } else {
          $(this).unbind().click(function(){removeFavorite(id, this); return false;});
        }

      } else {

        $(this).text("Ajouter aux favoris").attr("title", "Ajouter aux favoris").unbind().click(function(){addFavorite(id, this); return false;});

      }

    });

  });
}


/**
 * <code>clearFavorites</code>
 * Clears all the user favorites.
 */
function clearFavorites() {
  $.post("/favorite", {action: "clearFavorites"}, loadTools);
}
/**
 * Loads the product tarifs.
 */
function loadTarifs(){
  var productId=$("#pid").val();
  var date=$("#date").val();
  $("#tarifTable").load("/elements/resultAllPrices.jsp?pid="+productId+"&dp="+$("#depCityCode").val()+"&date="+date);

}

/**
 * Loads the booking channel data.
 */
function loadBookingChannelData() {
    var agence = "";
    if ($.cookies && $.cookies.get("agency") === null && $.cookies.get("defaultAgency") !== null) {
      $.cookies.set("agency", $.cookies.get("defaultAgency"));
    }
    if ($.cookies && $.cookies.get("agency") !== null) {
      agence = $.map($.cookies.get("agency").split("&&&"), function(val) { return val.replace(/\+/g, " ").replace("null", ""); });
    }
    if (agence !== "") {
      $("#agentEmail").val(agence[2]);
      $("#channelCode").val(agence[3]);
      $("#organizationCode").val(agence[4]);
      $("#organizationName").val(agence[5]);
    } else {
        $("#channelCode").val("60");
        $("#organizationCode").val("62");
        $("#organizationName").val("Centrale de réservation Selectour");
    $("#agencyName").val("Centrale de réservation Selectour");
    $("#agencyCode").val("62");
    $("#agencyEmail").val("serviceclient@selectour.com");
    $("#agencyPhone").val("05 61 12 67 55");
    $("#agencyAddress").val("17 AVENUE HONORE SERRES 31000 TOULOUSE");
    $("#agencyFax").val("05 61 12 61 60");
    }
    $("[name=nbChildren]").change(function() {
        if (this.value === 0) {
          $("#childAge").hide();
        } else {
          var val = this.value - 1;
          $("#childAge").show()
            .find("div.childAge:lt(" + this.value + ")").show().end()
            .find("div.childAge:gt(" + val + ")").hide();
        }
    });
}

/*--------------------------------------------------------------------------------*/
/*                                      HISTORY                                   */
/*--------------------------------------------------------------------------------*/


/**
 * <code>updateHistory</code>
 * Adds a new entry to the user search history.
 * @param url : the search url.
 */
function updateHistory(p, u) {
  $.post("/history", {action: "updateHistory", parameters: p, url: u});
}


/**
 * <code>clearHistory</code>
 * Clears the whole user search history.
 */
function clearHistory() {
  $.post("/history", {action: "clearHistory"}, loadTools);
}


/*--------------------------------------------------------------------------------*/
/*                                       LOGIN                                    */
/*--------------------------------------------------------------------------------*/


/**
 * <code>loadLogin</code>
 * Loads and initialize the right login box.
 */
function loadLogin() {

  if ($("#login").length > 0) {

    $("#login")
      .html("<img src=\"/csvweb/images/ajax-loader-big.gif\" style=\"padding: 10px 80px 10px 80px\" alt=\"Chargement...\" title=\"Chargement...\" />")
      .load("/no-cache/elements/login.jsp", function() {

        $("#login")
          .addClass("outliner")
          .addClass("blogin")
          .find("input[type!=submit]").labelValue("#333").end()
          .find("a.ok-log").click(function() {$("#loginForm").get(0).submit(); return false;}).end()
          .find("a.connect").click(function() {$(this).parents("div:first").hide().next().show(); return false;}).end()
          .find("a.deconnexion").click(function() {
            $.post("/login", {disconnect: "true"}, function(ajaxData) {
              location.href = location.href;
            });
            return false;
          });

    });

  }

}









/*--------------------------------------------------------------------------------*/
/*                                      FUNCTIONS                                 */
/*--------------------------------------------------------------------------------*/


/**
 * <code>colorValue</code>
 * Clears and recalls the default value of an input respectively on focus / blur.
 * An optional color may be passed to change the font color when writing in the field.
 * @param color : the color to use when writing in the field.
 */
$.fn.labelValue = function(color) {
  return this.focus(function() {
    if (this.value == this.defaultValue) {
      this.value = "";
    }
    if (color) {
      $(this).css("color", color);
    }
  }).blur(function() {
    if (!this.value.length) {
      this.value = this.defaultValue;
      if (color) {
        $(this).css("color", "");
      }
    }
  });
};

/**
 * <code>trackClick</code>
 * Tracks a click using XITI xt_click.
 */
$.fn.trackClick = function(labelComplement) {
    var trackingInfo = $(this).data("trackingInfo");
    if (trackingInfo) {
      var label = trackingInfo.label;
      if (labelComplement !== null) {
          if (label !== null && label.length > 0) {
            label += !(/.*::/.test(label)) ? "::" + labelComplement: labelComplement;
          } else {
            label = labelComplement;
          }
      }
      xt_click(this, "C", trackingInfo.xtn2, label, trackingInfo.type);
    }
};

/**
 * Function removeInvalidUrlChars.
 * remove the accents and invalid chars.
 *
 * @param {String} url
 * @return {String}
 */
$.removeInvalidUrlChars = function(url) {
  url = url.replace(/\u00e9/g, 'e' ); // eacute
  url = url.replace(/\u00e8/g, 'e' ); // egrave
  url = url.replace(/\u00f9/g, 'u' ); // ugrave
  url = url.replace(/\u00e0/g, 'a' ); // agrave
  url = url.replace(/\u00ea/g, 'e' ); // ecirc
  url = url.replace(/\u00f4/g, 'o' ); // ocirc
  url = url.replace(/\u00ee/g, 'i' ); // icirc
  url = url.replace(/\u00fb/g, 'u' ); // ucirc
  url = url.replace(/\u00e2/g, 'a' ); // acirc
  url = url.replace(/\u00eb/g, 'e' ); // euml
  url = url.replace(/\u00f6/g, 'o' ); // ouml
  url = url.replace(/\u00ef/g, 'i' ); // iuml
  url = url.replace(/\u00fc/g, 'u' ); // uuml
  url = url.replace(/\u00e4/g, 'a' ); // auml
  url = url.replace(/\u00e7/g, 'c');  // ccedil
  url = url.replace(/\u00c1/g, 'A');
  url = url.replace(/\u00c2/g, 'A');
  url = url.replace(/\u00c3/g, 'A');
  url = url.replace(/\u00c4/g, 'A');
  url = url.replace(/\u00c5/g, 'A');
  url = url.replace(/\u00c8/g, 'E');
  url = url.replace(/\u00c9/g, 'E');
  url = url.replace(/\u00ca/g, 'E');
  url = url.replace(/\u00cb/g, 'E');
  url = url.replace(/\u00cc/g, 'I');
  url = url.replace(/\u00cd/g, 'I');
  url = url.replace(/\u00ce/g, 'I');
  url = url.replace(/\u00cf/g, 'I');
  url = url.replace(/\u00d2/g, 'O');
  url = url.replace(/\u00d3/g, 'O');
  url = url.replace(/\u00d4/g, 'O');
  url = url.replace(/\u00d5/g, 'O');
  url = url.replace(/\u00d6/g, 'O');
  url = url.replace(/\u00d9/g, 'U');
  url = url.replace(/\u00da/g, 'U');
  url = url.replace(/\u00db/g, 'U');
  url = url.replace(/\u00dc/g, 'U');
  url = url.replace(/\\W/g, "-");
  url = url.replace(/\u002f/g, "-");
  url = url.replace(/\u0020/g, "-");
  url = url.replace(/--+/g, "-");
  if (url.length >= 2 && url.lastIndexOf("-") == url.length - 1){
    return url.substring(0, url.length - 1);
  }
  return url;
};

/**
 * <code>trackClick</code>
 * Set the back URL to the link href attribute.
 */
$.fn.setBackUrl = function() {
  // Set back url
  if ($.cookies && $.cookies.get("backurl") !== null) {
    $(this).attr("href", $.cookies.get("backurl"));
  } else {
    $(this).hide();
  }
};



$(function() {
  //choose agence help
  $("#agc div.agc-header .j-tooltip").hover(
    function (){
      $("#agc div.agc-header div.help").show();
    },
      function () {
      $("#agc div.agc-header div.help").hide();
      }
    );

    $("#agc div.agc-footer .j-tooltip").hover(
    function (){
      $("div.bottom").show();
    },
      function () {
      $("div.bottom").hide();
      }
    );


  //newsletter form
  $("#newsletter").labelValue();
  $("#news-form-submit").click(function(){
    if (!(/.+@.+\.+./.test( $("#newsletter").val()))) {
      jAlert("Veuillez entrer une adresse email au format nom@domaine.fr");
    } else {
      $.post("/accounts", {action: "checkExistence", mail: $("#newsletter").val()}, function(ajaxData) {
        if (ajaxData == 'false') {
          jAlert("Cette adresse est déjà utilisée<br />Vous pourrez gérer vos newsletters après identification dans votre espace compte");
        } else {
          window.top.location.href = "/creation-compte/mail=" + $("#newsletter").val();
        }
      });
    }
  });

  // Set back url
  $("#return").setBackUrl();

  if (!(/.*agences-de-voyages.*/.test(location.href))) {
    // Set agency
     fillAgencyWithCookies();
  }

  // Click and random Citation
  $('#citations-container').click(function(){
    $('#citations-container .citations').hide();
    var nbrCitation = $('#citations-container .citations').length;
    var rdmCitation = Math.ceil(Math.random() * nbrCitation-1);
    $('#citations-container .citations:eq(' + rdmCitation + ')').show();
  }).click();


  // Agency
  $("div.agence input, div.bloc-agency input, div.no-agency-search input").labelValue().end();
  $("div.agence .ok, div.bloc-agency .ok, div.no-agency-search .ok").live("click", function() {
    var codePostal = $(this).prev().val();
    if (!check_codePostal($.trim(codePostal))) {
      jAlert("\n - Le code postal doit \xEAtre renseign\xE9 et valide.", "Erreur de saisie");
    } else {
      tb_show("", "/no-cache/agence.jsp?postalCode=" + codePostal + "&uri=" + location.pathname + "&width=830&height=700&KeepThis=true", null);
    }
    var trackingInfo = $(this).data("trackingInfo");
    if (trackingInfo) {
      xt_med(trackingInfo.type, trackingInfo.xtn2, trackingInfo.label);
    }
  });


  // Thickbox
  $(".thickbox").live("click", function() {
    if (this.href != "#") {
      tb_show("", $(this).attr("href"), null);
    } else if ($(this).is(".map") || $(this).parent().is(".map")) {
      jAlert("Aucune information n'est disponible pour la localisation de cette agence.", "Aucune information disponible");
    }
    $(this).trackClick();
    return false;
  });


  // Set return url
  if (!(/.*opeid.*/.test(location.href))) {
    $.cookies.set("backurl", location.href);
  }

  //Tool tip
  if ($.fn.wTooltip) {
    $(".tooltip").wTooltip({fadeIn: 350, offsetY: 15,offsetX: -15});
  }
      $("#bottomAgFinder fieldset .ok, #topAgFinder fieldset .ok").live("click", function() {
        var codePostal = $(this).siblings("input.cpVal").val(),
            dpt,
            url;

        if (!check_codePostal($.trim(codePostal))) {
          jAlert("\n - Le code postal doit \xEAtre renseign\xE9 et valide.", "Erreur de saisie");
          return false;
        }
        dpt = codePostal.substring(0, 2);
        if (dpt == 20) {
          url = "/agences-de-voyages/Corse-20";
        } else {
          url = $("#dptList").find("a[href$=" + dpt + "]").attr("href");
        }
        location.href = url.substring(0, url.length - 2) + codePostal;
        return false;
      }).end();

  /** Add live "click" event for open email popin */
  $(".openSendMail").live("click", function(evt){

    // Set variables
    var that = this;
    var href=that.href;
    var mail="";
    if(href&&href.indexOf(":">-1)){
      mail=href.split(":")[1];
    }
      //var reg =  /(?:\b|\+)(?:mailto:)?([\w\.+#-]+)@([\w\.-]+\.\w{2,4})\b/g;
      var  regle=/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;


    // Dont follow event
    evt.preventDefault();
    // Open thickbox when format is good
    if (regle.test(mail)) {
      tb_show("", "/no-cache/mailto.jsp?width=250&amp;height=260", false, function(evt){
        $("#hdn_mailto").val(mail);
      });
    }

  });

  /** Add live "click" event for send email popin */
  $("#sendMail").live("click", function(evt){
    // Set variables
    var send = $(".sendToForm"),
        form = $("#contact-form"),
        getName = $("#ipt_nom").val(),
        getEmail = /.+@.+\.+./.test($("#ipt_email").val()),
        getMessage = $("#tta_message").val(),
        message = "";

    // Dont follow event
    evt.preventDefault();

    // Send email form when values is valid
    if (getName !== "" && getEmail && getMessage !== "") {
      $.ajax({
        type: "POST",
        url : form.attr("action") + "?" + form.serialize(),
        beforeSend: function(xht){
          send.empty();
          $("<img />", {
            src: "/csvweb/images/ajax-loader-big.gif",
            alt: "Envoi du message en cours...",
            title: "Envoi du message en cours...",
            css: {padding: "50px 0 50px 90px"}
          }).appendTo(send);
        },
        success: function(data, status){
          send.empty();
          $("<span />", {html: data}).appendTo(send);
        },
        error: function(data, status){
          send.empty();
          $("<span />", {text: "Impossible d'envoyer votre message"}).appendTo(send);
        }
      });

    // Builds the error message
    } else {
      if (getName === "") {
        message += " votre nom";
      }
      if (!getEmail) {
        if (message.length) {
          message += ",";
        }
        message += " votre email sous la forme (nom@domaine.fr)";
      }
      if (getMessage === "") {
          if (message.length) {
            message += ",";
          }
          message += " votre message";
      }
      jAlert("Veuillez renseigner " + message, "Information");
    }
   });
});

