/*--------------------------------------------------------------------------------*/
/*                                      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");
     $("#agentEmail").val(agence[2]);
     $("#channelCode").val(agence[3]);
     $("#organizationCode").val(agence[4]);
     $("#organizationName").val(agence[5]);

     return true;

  } else {

    $("div.unknown").show();
    $("#channelCode").val("VOYAGES31");
    $("#organizationCode").val("LI031950031_00");
    $("#agentEmail").val("voyages31.tourisme@selectour.com");
    $("#organizationName").val("VOYAGES 31 TOULOUSE");

    return false;

  }

}


/*--------------------------------------------------------------------------------*/
/*                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) {
    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");
        var fav = /Afficher les favoris \(([\d]+)\)/.exec($(".rm-favoris, #fc .favoris").text());
        if (fav != null && fav[1] != null) {
          $(".rm-favoris, #fc .favoris").text("Afficher les favoris (" + eval(parseInt(fav[1]) + 1) + ")");
        }
     $(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) {
    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");
          var fav = /Afficher les favoris \(([\d]+)\)/.exec($(".rm-favoris, #fc .favoris").text());
          if (fav != null && fav[1] != null) {
            $(".rm-favoris, #fc .favoris").text("Afficher les favoris (" + eval(parseInt(fav[1]) - 1) + ")");
          }
        $(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 = new Array();
    var favoriteIds = new Array();
    var favoriteDates = new Array();

    // 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);
}


/*--------------------------------------------------------------------------------*/
/*                                      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() {

  //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 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").labelValue().end();
  $("div.agence .ok, div.bloc-agency .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});
  }

  //Mail form
  $("#sendMail").live('click', function(){
    var valid = $("#ipt_nom").val() != "" && /.+@.+\.+./.test($("#ipt_email").val()) && $("#contact-form ul li textarea").val() != "";
    if (valid) {
      var submitUrl = $("#contact-form").attr("action") + "?" + $("#contact-form").serialize();
      $(".sendToForm").html("<img src=\"/csvweb/images/ajax-loader-big.gif\" style=\"padding: 50px 0 50px 90px\" alt=\"Chargement...\" title=\"Chargement...\" />");
      $.ajax({
          type: "POST",
          url : submitUrl,
          success: function(data, status){
          $(".sendToForm").html("<span>" + data + "</span>");
          },
          error: function(data, status){
            $(".sendToForm").html("Impossible d'evoyer votre message");
          }
      });
    } else {
      var message = "";
      if ($("#ipt_nom").val() == "") {
        message += " votre nom"
      }
      if (!/.+@.+\.+./.test($("#ipt_email").val())) {
        if (message.length > 0) {
          message += ","
        }
        message += " votre email sous la forme (nom@domaine.fr)";
      }
      if ($("#contact-form ul li textarea").val() == "") {
          if (message.length > 0) {
            message += ","
          }
          message += " votre message";
      }
      jAlert("Veuillez renseigner " + message, "Information");
    }
    return false;
   });
});
