Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function updateAll(nombre, text) {
- var siblingSelect = $("[name=" + nombre + "]").next();
- $(siblingSelect).children().find(".filter-option").html(text);
- }
- function validateAmount(obj) {
- var isAdultSelect;
- var selectAObj;
- var selectNObj;
- if (obj.name.indexOf("nadults") > -1) {
- isAdultSelect = true;
- selectAObj = $('*[name="' + obj.name + '"]');
- selectNObj = $('*[name="nchilds' + obj.name.split("nadults")[1] + '"]');
- } else {
- isAdultSelect = false;
- selectNObj = $('*[name="' + obj.name + '"]');
- selectAObj = $('*[name="nadults' + obj.name.split("nchilds")[1] + '"]');
- }
- if (isAdultSelect) {
- if (parseInt(selectAObj.val()) + parseInt(selectNObj.val()) > 4) {
- var maxAdultos = 4 - parseInt(selectNObj.val());
- selectAObj.val(maxAdultos).change();
- }
- } else {
- if (parseInt(selectAObj.val()) + parseInt(selectNObj.val()) > 4) {
- var maxNinos = 4 - parseInt(selectAObj.val());
- selectNObj.val(maxNinos).change();
- }
- }
- deleteOptions(obj);
- }
- function deleteOptions(obj) {
- var isAdultSelect;
- var selectAObj;
- var selectNObj;
- if (obj.name.indexOf("nadults") > -1) {
- isAdultSelect = true;
- selectAObj = $('*[name="' + obj.name + '"]');
- selectNObj = $('*[name="nchilds' + obj.name.split("nadults")[1] + '"]');
- } else {
- isAdultSelect = false;
- selectNObj = $('*[name="' + obj.name + '"]');
- selectAObj = $('*[name="nadults' + obj.name.split("nchilds")[1] + '"]');
- }
- if (isAdultSelect) {
- var maxNinos = 4 - parseInt(selectAObj.val());
- if (preAdultos < selectAObj.val()) {
- selectNObj.next().find("li").each(function() {
- if (parseInt($(this).attr("rel")) > maxNinos) $(this).attr("style", "display:none !important");
- });
- selectNObj.children().each(function() {
- if (parseInt($(this).attr("value")) > maxNinos) $(this).attr("style", "display:none !important");
- });
- } else {
- for (var i = 0; i < preAdultos - selectAObj.val(); i++) {
- selectNObj.children("[style = 'display:none !important']:first").attr("style", "");
- selectNObj.next().find("[style = 'display:none !important']:first").attr("style", "");
- }
- }
- preAdultos = selectAObj.val();
- } else {
- var maxAdultos = 4 - parseInt(selectNObj.val());
- if (preNinos < selectNObj.val()) {
- selectAObj.next().find("li").each(function() {
- if (parseInt($(this).attr("rel")) >= maxAdultos) $(this).attr("style", "display:none !important");
- });
- selectAObj.children().each(function() {
- if (parseInt($(this).attr("value")) > maxAdultos) $(this).attr("style", "display:none !important");
- });
- } else {
- for (var i = 0; i < preNinos - selectNObj.val(); i++) {
- selectAObj.children("[style = 'display:none !important']:first").attr("style", "");
- selectAObj.next().find("[style = 'display:none !important']:first").attr("style", "");
- }
- }
- preNinos = selectNObj.val();
- }
- }
- function generateOcupations(valor, room, rooms, adult, adults, child, children, subdomain) {
- valor = parseInt(valor);
- if (valor > 5) {
- multiHab(subdomain);
- $("#habs").val("1");
- $("#habs").change();
- return false;
- }
- var html = "";
- if (valor == 1) {
- $(".ocupaciones").children().first().remove();
- $(".ocupaciones").css("margin-top", "0px");
- }
- if (valor > 1) {
- $(".ocupaciones").css("margin-top", "-9px");
- }
- var sHabitacion = room;
- if (valor > 1) sHabitacion = rooms;
- if (valor > 0) {
- var roomCap = room.charAt(0).toUpperCase() + room.slice(1);
- for (var i = 0; i < valor; i++) {
- var idx = i + 1;
- if (valor >= 1) html += "<label>" + roomCap + " " + idx + "</label>";
- html += '<select name="nadults' + idx + '" class="selectpicker" data-style="btn-info" onchange="updateAll(this.name,this.options[this.selectedIndex].innerHTML); validateAmount(this)">';
- html += '<option class="adulto" value="1">1 ' + adult + "</option>";
- html += '<option class="adulto" value="2" selected>2 ' + adults + "</option>";
- html += '<option class="adulto" value="3">3 ' + adults + "</option>";
- html += '<option class="adulto" value="4">4 ' + adults + "</option>";
- html += "</select> ";
- html += '<select name="nchilds' + idx + '" class="selectpicker" data-style="btn-info" onchange="updateAll(this.name,this.options[this.selectedIndex].innerHTML); validateAmount(this)">';
- html += '<option class="nino" value="0">0 ' + children + "</option>";
- html += '<option class="nino" value="1">1 ' + child + " </option>";
- html += '<option class="nino" value="2">2 ' + children + "</option>";
- html += '<option class="nino" value="3">3 ' + children + "</option>";
- html += "</select>";
- html += '<div class="clearfix"></div>';
- }
- $(".ocupaciones").html(html);
- $(".selectpicker").selectpicker();
- $(".mainSelectRom button .pull-left").html(valor + " " + sHabitacion);
- }
- }
- function generateOcupationsAdvancedSearch(valor, room, rooms, adult, adults, child, children, subdomain) {
- valor = parseInt(valor);
- if (valor > 5) {
- multiHab(subdomain);
- $("#habs").val("1");
- $("#habs").change();
- return false;
- }
- var html = "";
- var cantAgregar;
- if (preValor == 1) {
- sHabitacion = rooms;
- $(".ocupaciones").prepend("<label>" + room + " " + preValor + "</label>");
- }
- if (valor == 1) {
- $(".ocupaciones").children().first().remove();
- }
- if (preValor < valor) {
- cantAgregar = valor - preValor;
- for (var i = 0; i < cantAgregar; i++) {
- var idx = i + 1 + preValor;
- html += '<div id="hab' + idx + '">';
- if (valor > 1) html += "<label>" + room + " " + idx + "</label>";
- html += '<select name="nadults' + idx + '" class="selectpicker" data-style="btn-info" onchange="updateAll(this.name,this.options[this.selectedIndex].innerHTML); validateAmount(this)">';
- html += '<option class="adulto" value="1">1 ' + adult + "</option>";
- html += '<option class="adulto" value="2" selected>2 ' + adults + "</option>";
- html += '<option class="adulto" value="3">3 ' + adults + "</option>";
- html += '<option class="adulto" value="4">4 ' + adults + "</option>";
- html += "</select> ";
- html += '<select name="nchilds' + idx + '" class="selectpicker" data-style="btn-info" onchange="updateAll(this.name,this.options[this.selectedIndex].innerHTML); validateAmount(this)">';
- html += '<option class="nino" value="0">0 ' + children + "</option>";
- html += '<option class="nino" value="1">1 ' + child + " </option>";
- html += '<option class="nino" value="2">2 ' + children + "</option>";
- html += '<option class="nino" value="3">3 ' + children + "</option>";
- html += "</select>";
- html += '<div class="clearfix"></div>';
- html += "</div>";
- }
- var sHabitacion = room;
- if (valor > 1) sHabitacion = rooms;
- $(".ocupaciones").append(html);
- $(".selectpicker").selectpicker();
- $(".mainSelectRom button .pull-left").html(valor + " " + sHabitacion);
- } else {
- for (var i = preValor; i > valor; i--) {
- $("#hab" + i).remove();
- }
- }
- preValor = valor;
- }
- function setMaxRangeDate(iniID, finID, add) {
- var iniElement = $(iniID).length >= 1 ? iniID : "#" + iniID;
- var finElement = $(finID).length >= 1 ? finID : "#" + finID;
- var dateFin = $.datepicker.parseDate(Dates.currentPattern, $(finElement).val());
- var dateIni = $.datepicker.parseDate(Dates.currentPattern, $(iniElement).val());
- if (add) {
- dateFin = dateIni;
- dateFin.setDate(dateFin.getDate() + 15);
- $(finElement).val($.datepicker.formatDate(Dates.currentPattern, dateFin));
- } else {
- dateIni = dateFin;
- dateIni.setDate(dateIni.getDate() - 15);
- $(iniElement).val($.datepicker.formatDate(Dates.currentPattern, dateFin));
- }
- }
- function multiHab(subdomain) {
- showMultiHabAlert(subdomain);
- }
- function showMultiHabAlert(subdomain) {
- var multiHabSubdomain = "";
- if (subdomain != undefined) {
- multiHabSubdomain = subdomain;
- }
- $.fancybox({
- href: multiHabSubdomain + "/booking/lightbox/toContact",
- type: "iframe",
- closeBtn: 1,
- closeClick: !1,
- helpers: {
- overlay: {
- closeClick: !1
- }
- }
- });
- }
- $(document).ready(function() {
- preValor = 1;
- preAdultos = 2;
- preNinos = 0;
- $(".roomsContainer").hide();
- if ($("#calendarIda") == null || $("#calendarIda").size() == 0) {
- $(function() {
- $("#ida").datepicker({
- minDate: 0,
- dateFormat: Dates.currentPattern,
- altField: "#idaAlt",
- altFormat: Dates.pattern,
- onSelect: function(dateText, inst) {
- $("#idaAlt").change();
- var dDay = get2DigitsDateNumber(inst.selectedDay);
- var dMonth = get2DigitsDateNumber(inst.selectedMonth + 1);
- var dYear = get2DigitsDateNumber(inst.selectedYear);
- var dateIniString = dYear + "/" + dMonth + "/" + dDay;
- var dateIni = new Date(dateIniString);
- var dateOut = new Date(dateIni);
- dateOut.setDate(dateIni.getDate() + 1);
- var dateIniFormated = $.datepicker.formatDate(Dates.currentPattern, dateIni);
- var dateOutFormated = $.datepicker.formatDate(Dates.currentPattern, dateOut);
- $("#ida").parent().attr("data-date", dateIniFormated);
- $("#fin").val(dateOutFormated);
- $("#fin").parent().attr("data-date", dateOutFormated);
- $("#fin").datepicker("option", "minDate", dateOutFormated);
- }
- });
- });
- $(function() {
- var minDateFin = 0;
- if ($("#ida").length > 0 && $("#ida").val() != "") {
- minDateFin = $.datepicker.parseDate(Dates.currentPattern, $("#ida").val());
- minDateFin.setDate(minDateFin.getDate() + 1);
- minDateFin = $.datepicker.formatDate(Dates.currentPattern, minDateFin);
- }
- $("#fin").datepicker({
- minDate: 0,
- dateFormat: Dates.currentPattern,
- altField: "#finAlt",
- altFormat: Dates.pattern,
- onSelect: function(dateText, inst) {
- $("#finAlt").change();
- var dDay = get2DigitsDateNumber(inst.selectedDay);
- var dMonth = get2DigitsDateNumber(inst.selectedMonth + 1);
- var dYear = get2DigitsDateNumber(inst.selectedYear);
- var dateIniString = dYear + "/" + dMonth + "/" + dDay;
- var dateIni = new Date(dateIniString);
- var dateFormated = $.datepicker.formatDate(Dates.currentPattern, dateIni);
- var dateFin = $.datepicker.parseDate(Dates.currentPattern, $("#fin").val());
- var dateIni = $.datepicker.parseDate(Dates.currentPattern, $("#ida").val());
- var diffDays = Math.floor((dateFin - dateIni) / 1e3 / 60 / 60 / 24);
- if (diffDays > 15) {
- setMaxRangeDate("ida", "fin", true);
- showCalendarAlert();
- }
- $("#fin").parent().attr("data-date", dateFormated);
- }
- });
- });
- }
- $("#ida").datepicker("option", $.datepicker.regional[Dates.datepickerLang]);
- $("#fin").datepicker("option", $.datepicker.regional[Dates.datepickerLang]);
- $(window).on("orientationchange", function(event) {
- $("#ida").datepicker("hide");
- $("#fin").datepicker("hide");
- $("#ida").blur();
- $("#fin").blur();
- });
- $(window).resize(function() {
- $("#ida").datepicker("hide");
- $("#fin").datepicker("hide");
- $("#ida").blur();
- $("#fin").blur();
- });
- });
- $(document).ready(function() {
- type1 = $("#type").val();
- locality1 = $("#locality").val();
- name1 = $("#name").val();
- $("#location").keyup(function() {
- var params = $("#location").val();
- var lang = $("#lang").val();
- var autocompleteNumber = typeof autocompleteParam != "undefined" ? autocompleteParam : 3;
- if (params.length >= autocompleteNumber) {
- filter(HtmlSpecialChars(params), function(data) {
- var datos = $.parseJSON(data);
- var hoteles = datos[0].results[0];
- var termBuscado = datos[0].results[1];
- var currentParams = $("#location").val();
- if (currentParams.toUpperCase() === termBuscado.term.toUpperCase()) {
- var htmlDestino = "";
- var htmlHotel = "";
- var htmlPoi = "";
- var html = "";
- if (hoteles.length > 0) {
- html += "<ul>";
- for (var i = 0; i < hoteles.length; i++) {
- if (hoteles[i].icon == "hotelHome") htmlHotel += llenarListaLanding(hoteles, i); else if (hoteles[i].icon == "destinationHome") htmlDestino += llenarListaLanding(hoteles, i); else htmlPoi += llenarListaLanding(hoteles, i);
- }
- html += htmlDestino + htmlHotel + htmlPoi;
- html += "</ul>";
- } else {
- html += "<li>";
- html += "<div>";
- html += labelCoincidencias;
- html += "</div>";
- html += "</li>";
- }
- $("#results").html(html);
- $("#results").show();
- }
- });
- } else $("#location").attr("name", "");
- });
- $("#fieldSearch").keyup(function() {
- var params = $("#fieldSearch").val();
- var lang = $("#lang").val();
- var autocompleteNumber = typeof autocompleteParam != "undefined" ? autocompleteParam : 3;
- if (params.length >= autocompleteNumber) {
- filter(HtmlSpecialChars(params), function(data) {
- var datos = $.parseJSON(data);
- var hoteles = datos[0].results[0];
- var termBuscado = datos[0].results[1];
- var currentParams = $("#fieldSearch").val();
- if (currentParams.toUpperCase() === termBuscado.term.toUpperCase()) {
- var htmlDestino = "";
- var htmlHotel = "";
- var htmlPoi = "";
- var html = "";
- if (hoteles.length > 0) {
- html += "<ul>";
- for (var i = 0; i < hoteles.length; i++) {
- if (hoteles[i].icon == "hotelHome") htmlHotel += llenarListaFieldSearch(hoteles, i); else if (hoteles[i].icon == "destinationHome") htmlDestino += llenarListaFieldSearch(hoteles, i); else htmlPoi += llenarListaFieldSearch(hoteles, i);
- }
- html += htmlDestino + htmlHotel + htmlPoi;
- html += "</ul>";
- } else {
- html += "<li>";
- html += "<div>";
- html += labelCoincidencias;
- html += "</div>";
- html += "</li>";
- }
- $("#results").html(html);
- $(".autoComplete").show();
- }
- });
- } else $("#locationCode").attr("name", "");
- });
- });
- function setParametersLocation(name, locality, type, code, tcm) {
- name1 = decodeHtmlSpecialChars(name);
- locality1 = decodeHtmlSpecialChars(locality);
- type1 = type;
- if (type != "destination") $("#location").val(name1 + ", " + locality1); else $("#location").val(name1 + locality1.replace(name1, ""));
- if (type == "hotel") $("#locationCode").attr("name", "hotelId"); else if (type == "destination") {
- $("#locationCode").attr("name", "destinationId");
- $("#destinationTcm").val(tcm);
- } else if (type == "poi") {
- $("#locationCode").attr("name", "poiId");
- $("#destinationTcm").val(tcm);
- }
- $("#locationCode").val(code);
- $("#locationTCM").val(tcm);
- }
- function setParametersLocation(name, locality, type, code, tcm, url, vh) {
- name1 = decodeHtmlSpecialChars(name);
- locality1 = decodeHtmlSpecialChars(locality);
- type1 = type;
- if (type != "destination") $("#location").val(name1 + ", " + locality1); else $("#location").val(name1 + locality1.replace(name1, ""));
- if (type == "hotel") {
- $("#locationCode").attr("name", "hotelId");
- } else if (type == "destination") {
- $("#locationCode").attr("name", "destinationId");
- $("#destinationTcm").val(tcm);
- } else if (type == "poi") {
- $("#locationCode").attr("name", "poiId");
- $("#destinationTcm").val(tcm);
- }
- $("#locationCode").val(code);
- $("#locationTCM").val(tcm);
- $("#url").val(url);
- $("#virtualHotel").val(vh);
- }
- function setParametersFieldSearch(name, locality, type, code, tcm) {
- name1 = decodeHtmlSpecialChars(name);
- locality1 = decodeHtmlSpecialChars(locality);
- type1 = type;
- if (type != "destination") $("#fieldSearch").val(name1 + ", " + locality1); else $("#fieldSearch").val(name1 + locality1.replace(name1, ""));
- if (type == "hotel") $("#locationCode").attr("name", "hotelId"); else if (type == "destination") {
- $("#locationCode").attr("name", "destinationId");
- $("#destinationTcm").val(tcm);
- } else if (type == "poi") {
- $("#locationCode").attr("name", "poiId");
- $("#destinationTcm").val(tcm);
- }
- $("#locationCode").val(code);
- $("#locationTCM").val(tcm);
- }
- function setParametersFieldSearch(name, locality, type, code, tcm, url, vh) {
- name1 = decodeHtmlSpecialChars(name);
- locality1 = decodeHtmlSpecialChars(locality);
- type1 = type;
- if (type != "destination") $("#fieldSearch").val(name1 + ", " + locality1); else $("#fieldSearch").val(name1 + locality1.replace(name1, ""));
- if (type == "hotel") $("#locationCode").attr("name", "hotelId"); else if (type == "destination") {
- $("#locationCode").attr("name", "destinationId");
- $("#destinationTcm").val(tcm);
- } else if (type == "poi") {
- $("#locationCode").attr("name", "poiId");
- $("#destinationTcm").val(tcm);
- }
- $("#locationCode").val(code);
- $("#locationTCM").val(tcm);
- $("#url").val(url);
- $("#virtualHotel").val(vh);
- }
- $(document).click(function(evt) {
- if (evt.target.id == "location" || evt.target.id == "fieldSearch") return;
- if ($(".autoComplete").is(":visible")) {
- $(".autoComplete").hide();
- $("#results").html("");
- }
- });
- function validarlocationSubmit() {
- if (type1 != "destination") {
- if (name1 + " " + locality1 + " " + type1 != $("#location").val() && $("#location").val().toLowerCase() != $("#locationCode").val().toLowerCase()) {
- $("#locationCode").attr("name", "");
- $("#locationCode").val("");
- }
- } else {
- if (name1 + locality1.replace(name1, "") + " " + type1 != $("#location").val() && $("#location").val().toLowerCase() != $("#locationCode").val().toLowerCase()) {
- $("#locationCode").attr("name", "");
- $("#locationCode").val("");
- }
- }
- if ($("#location").attr("name") !== undefined && $("#location").attr("name") === "searchStringID") {
- $("#locationTCM").attr("name", "locationTCM");
- } else {
- $("#locationTCM").attr("name", "searchStringID");
- }
- $("#locationTCM").val($("#location").val());
- callSeguimientoForms("success", "locationForm", "success");
- if ($("#url").val() != "" && $("input[name*='hotelId']").length > 0 && ($("input[name*='fini']").length == 0 || $("input[name*='fini']").val() == "") && ($("input[name*='fout']").length == 0 || $("input[name*='fout']").val() == "")) window.location.href = $("#url").val(); else $("#locationForm").submit();
- }
- function validarLandingSubmit(landing) {
- if ($("#locationCode").val() == "") {
- $("#locationCode").attr("name", "");
- }
- if ($("#location").attr("name") !== undefined && $("#location").attr("name") === "searchStringID") {
- $("#locationTCM").attr("name", "locationTCM");
- } else {
- $("#locationTCM").attr("name", "searchStringID");
- }
- $("#eida").hide();
- $("#efin").hide();
- noerror = true;
- var errorField = "";
- if (typeof isB2E != "undefined" && isB2E != "") {
- var fechaIda = $("#ida").val();
- var fechaFin = $("#fin").val();
- if (!validateLength(fechaIda)) {
- $("#eida").show();
- $("#fechaIda").addClass("error");
- noerror = false;
- if (errorField == "") errorField = "fechaIda";
- } else {
- $("#fechaIda").removeClass("error");
- }
- if (!validateLength(fechaFin)) {
- $("#efin").show();
- $("#fechaFin").addClass("error");
- noerror = false;
- if (errorField == "") errorField = "fechaFin";
- } else {
- $("#fechaFin").removeClass("error");
- }
- }
- $("#locationTCM").val($("#location").val());
- var habis = $("#habs").val();
- var adult = 0;
- var ninos = 0;
- for (var i = 1; i <= habis; i++) {
- adult += parseInt($("[name=nadults" + i + "]").val());
- ninos += parseInt($("[name=nchilds" + i + "]").val());
- }
- if (noerror) {
- $("#loadingModal").modal({
- show: !0,
- backdrop: "static",
- keyboard: !1
- });
- callSeguimientoForms("success", "resultPageForm", "success");
- if (landing == undefined) trackHotelSearch(page_section, $("#locationCode").val(), $("#ida").val(), $("#fin").val());
- if (landing) trackNewGeneralSearch(page_section, $("#locationCode").val(), $("#ida").val(), $("#fin").val(), habis, adult, ninos); else trackModifySearch(page_section, $("#locationCode").val(), $("#ida").val(), $("#fin").val(), habis, adult, ninos);
- if ($("#virtualHotel").val() != "" && $("#url").val() != "" && $("input[name*='hotelId']").length > 0) {
- $("#urlHotel").val($("#url").val());
- $("#locationForm").submit();
- } else {
- if ($("#url").val() != "" && $("input[name*='hotelId']").length > 0 && ($('[data-input-target="fini"]').length == 0 || $('[data-input-target="fini"]').val() == "") && ($('[data-input-target="fout"]').length == 0 || $('[data-input-target="fout"]').val() == "")) window.location.href = $("#url").val(); else $("#locationForm").submit();
- }
- } else {
- callSeguimientoForms("error", "resultPageForm", errorField);
- }
- }
- $(document).ready(function() {
- $("#location").click(function() {
- if (!$(this).hasClass("selected")) {
- $(this).select();
- $(this).addClass("selected");
- }
- });
- $("#location").blur(function() {
- if ($(this).hasClass("selected")) {
- $(this).removeClass("selected");
- }
- });
- $("#inputSearch").click(function() {
- if (!$(this).hasClass("selected")) {
- $(this).select();
- $(this).addClass("selected");
- }
- });
- $("#inputSearch").blur(function() {
- if ($(this).hasClass("selected")) {
- $(this).removeClass("selected");
- }
- });
- $("#fieldSearch").click(function() {
- if (!$(this).hasClass("selected")) {
- $(this).select();
- $(this).addClass("selected");
- }
- });
- $("#fieldSearch").blur(function() {
- if ($(this).hasClass("selected")) {
- $(this).removeClass("selected");
- }
- });
- });
- function clearCalendar() {
- $("#diaSalida").val("");
- $("#mesSalida").val("");
- $("#mesSalidav").val("");
- $("#anioSalida").val("");
- $("#diaLlegada").val("");
- $("#mesLlegada").val("");
- $("#mesLlegadav").val("");
- $("#anioLlegada").val("");
- $("#calendar").hide();
- }
- function llenarListaLanding(hoteles, i) {
- var html = "";
- if (hoteles[i].url != null && hoteles[i].url != undefined) html += '<li onclick="setParametersLocation(' + "'" + HtmlSpecialChars(hoteles[i].name) + "'" + ", " + "'" + HtmlSpecialChars(hoteles[i].locality) + "'" + ", " + "'" + hoteles[i].type + "'" + ", " + "'" + hoteles[i].code + "'" + ", " + "'" + hoteles[i].tcm + "'" + ", " + "'" + hoteles[i].url + "'" + ", " + "'" + hoteles[i].vh + "'" + ");showOptions('#calendar');$('.autoComplete').hide()\">"; else html += '<li onclick="setParametersLocation(' + "'" + HtmlSpecialChars(hoteles[i].name) + "'" + ", " + "'" + HtmlSpecialChars(hoteles[i].locality) + "'" + ", " + "'" + hoteles[i].type + "'" + ", " + "'" + hoteles[i].code + "'" + ", " + "'" + hoteles[i].tcm + "'" + ");showOptions('#calendar');$('.autoComplete').hide()\">";
- html += '<a href="#">';
- if (hoteles[i].icon == "airtport") html += '<span class="icon airports"></span>'; else if (hoteles[i].icon == "hotelHome") html += '<span class="icon hotels"></span>'; else if (hoteles[i].icon == "destinationHome") html += '<span class="icon cities"></span>'; else html += '<span class="icon noplace"></span>';
- html += hoteles[i].name + (hoteles[i].icon != "destinationHome" ? " " + hoteles[i].locality : hoteles[i].locality.replace(hoteles[i].name, ""));
- html += "<small>";
- if (hoteles[i].icon != "hotelHome") html += hoteles[i].num_hotels + " " + (hoteles[i].num_hotels == 1 ? labelHotel : labelHotels);
- html += "</small>";
- html += "</a>";
- html += "</li>";
- return html;
- }
- function llenarListaFieldSearch(hoteles, i) {
- var html = "";
- if (hoteles[i].url != null && hoteles[i].url != undefined) {
- html += '<li onclick="setParametersFieldSearch(' + "'" + HtmlSpecialChars(hoteles[i].name) + "'" + ", " + "'" + HtmlSpecialChars(hoteles[i].locality) + "'" + ", " + "'" + hoteles[i].type + "'" + ", " + "'" + hoteles[i].code + "'" + ", " + "'" + hoteles[i].tcm + "'" + ", " + "'" + hoteles[i].url + "'" + ", " + "'" + hoteles[i].vh + "'" + ");showOptions('#calendar');$('.autoComplete').hide()\">";
- } else {
- html += '<li onclick="setParametersFieldSearch(' + "'" + HtmlSpecialChars(hoteles[i].name) + "'" + ", " + "'" + HtmlSpecialChars(hoteles[i].locality) + "'" + ", " + "'" + hoteles[i].type + "'" + ", " + "'" + hoteles[i].code + "'" + ", " + "'" + hoteles[i].tcm + "'" + ");showOptions('#calendar');$('.autoComplete').hide()\">";
- }
- html += '<a href="#">';
- if (hoteles[i].icon == "airtport") html += '<span class="icon airports"></span>'; else if (hoteles[i].icon == "hotelHome") html += '<span class="icon hotels"></span>'; else if (hoteles[i].icon == "destinationHome") html += '<span class="icon cities"></span>'; else html += '<span class="icon noplace"></span>';
- html += hoteles[i].name + (hoteles[i].icon != "destinationHome" ? " " + hoteles[i].locality : hoteles[i].locality.replace(hoteles[i].name, ""));
- html += "<small>";
- if (hoteles[i].icon != "hotelHome") html += hoteles[i].num_hotels + " " + (hoteles[i].num_hotels == 1 ? labelHotel : labelHotels);
- html += "</small>";
- html += "</a>";
- html += "</li>";
- return html;
- }
- function filterHome(textToFind, callback) {
- var autocompleteSubdomain = "";
- if (typeof subdomainLang != "undefined") {
- autocompleteSubdomain = subdomainLang;
- }
- $.ajax({
- type: "GET",
- url: autocompleteSubdomain + "/rest/auto/autocompleteHome/" + textToFind,
- dataType: "json",
- cache: true,
- error: function() {},
- success: function(data) {
- var resultsArrayFinal = [];
- resultsArrayFinal.push({
- results: data
- });
- callback(JSON.stringify(resultsArrayFinal));
- },
- error: function(xhr, status, error) {
- var err = eval("(" + xhr.responseText + ")");
- alert(err.Message + " " + status + " " + error);
- }
- });
- }
- function filter(textToFind, callback) {
- var autocompleteSubdomain = "";
- if (typeof subdomainLang != "undefined") {
- autocompleteSubdomain = subdomainLang;
- }
- $.ajax({
- type: "GET",
- url: autocompleteSubdomain + "/rest/auto/autocomplete/" + textToFind,
- dataType: "json",
- cache: true,
- error: function() {},
- success: function(data) {
- var resultsArrayFinal = [];
- resultsArrayFinal.push({
- results: data
- });
- callback(JSON.stringify(resultsArrayFinal));
- },
- error: function(xhr, status, error) {
- var err = eval("(" + xhr.responseText + ")");
- alert(err.Message + " " + status + " " + error);
- }
- });
- }
- var Hashtable = function() {
- var FUNCTION = "function";
- var arrayRemoveAt = typeof Array.prototype.splice == FUNCTION ? function(arr, idx) {
- arr.splice(idx, 1);
- } : function(arr, idx) {
- var itemsAfterDeleted, i, len;
- if (idx === arr.length - 1) {
- arr.length = idx;
- } else {
- itemsAfterDeleted = arr.slice(idx + 1);
- arr.length = idx;
- for (i = 0, len = itemsAfterDeleted.length; i < len; ++i) {
- arr[idx + i] = itemsAfterDeleted[i];
- }
- }
- };
- function hashObject(obj) {
- var hashCode;
- if (typeof obj == "string") {
- return obj;
- } else if (typeof obj.hashCode == FUNCTION) {
- hashCode = obj.hashCode();
- return typeof hashCode == "string" ? hashCode : hashObject(hashCode);
- } else if (typeof obj.toString == FUNCTION) {
- return obj.toString();
- } else {
- try {
- return String(obj);
- } catch (ex) {
- return Object.prototype.toString.call(obj);
- }
- }
- }
- function equals_fixedValueHasEquals(fixedValue, variableValue) {
- return fixedValue.equals(variableValue);
- }
- function equals_fixedValueNoEquals(fixedValue, variableValue) {
- return typeof variableValue.equals == FUNCTION ? variableValue.equals(fixedValue) : fixedValue === variableValue;
- }
- function createKeyValCheck(kvStr) {
- return function(kv) {
- if (kv === null) {
- throw new Error("null is not a valid " + kvStr);
- } else if (typeof kv == "undefined") {
- throw new Error(kvStr + " must not be undefined");
- }
- };
- }
- var checkKey = createKeyValCheck("key"), checkValue = createKeyValCheck("value");
- function Bucket(hash, firstKey, firstValue, equalityFunction) {
- this[0] = hash;
- this.entries = [];
- this.addEntry(firstKey, firstValue);
- if (equalityFunction !== null) {
- this.getEqualityFunction = function() {
- return equalityFunction;
- };
- }
- }
- var EXISTENCE = 0, ENTRY = 1, ENTRY_INDEX_AND_VALUE = 2;
- function createBucketSearcher(mode) {
- return function(key) {
- var i = this.entries.length, entry, equals = this.getEqualityFunction(key);
- while (i--) {
- entry = this.entries[i];
- if (equals(key, entry[0])) {
- switch (mode) {
- case EXISTENCE:
- return true;
- case ENTRY:
- return entry;
- case ENTRY_INDEX_AND_VALUE:
- return [ i, entry[1] ];
- }
- }
- }
- return false;
- };
- }
- function createBucketLister(entryProperty) {
- return function(aggregatedArr) {
- var startIndex = aggregatedArr.length;
- for (var i = 0, len = this.entries.length; i < len; ++i) {
- aggregatedArr[startIndex + i] = this.entries[i][entryProperty];
- }
- };
- }
- Bucket.prototype = {
- getEqualityFunction: function(searchValue) {
- return typeof searchValue.equals == FUNCTION ? equals_fixedValueHasEquals : equals_fixedValueNoEquals;
- },
- getEntryForKey: createBucketSearcher(ENTRY),
- getEntryAndIndexForKey: createBucketSearcher(ENTRY_INDEX_AND_VALUE),
- removeEntryForKey: function(key) {
- var result = this.getEntryAndIndexForKey(key);
- if (result) {
- arrayRemoveAt(this.entries, result[0]);
- return result[1];
- }
- return null;
- },
- addEntry: function(key, value) {
- this.entries[this.entries.length] = [ key, value ];
- },
- keys: createBucketLister(0),
- values: createBucketLister(1),
- getEntries: function(entries) {
- var startIndex = entries.length;
- for (var i = 0, len = this.entries.length; i < len; ++i) {
- entries[startIndex + i] = this.entries[i].slice(0);
- }
- },
- containsKey: createBucketSearcher(EXISTENCE),
- containsValue: function(value) {
- var i = this.entries.length;
- while (i--) {
- if (value === this.entries[i][1]) {
- return true;
- }
- }
- return false;
- }
- };
- function searchBuckets(buckets, hash) {
- var i = buckets.length, bucket;
- while (i--) {
- bucket = buckets[i];
- if (hash === bucket[0]) {
- return i;
- }
- }
- return null;
- }
- function getBucketForHash(bucketsByHash, hash) {
- var bucket = bucketsByHash[hash];
- return bucket && bucket instanceof Bucket ? bucket : null;
- }
- function Hashtable(hashingFunctionParam, equalityFunctionParam) {
- var that = this;
- var buckets = [];
- var bucketsByHash = {};
- var hashingFunction = typeof hashingFunctionParam == FUNCTION ? hashingFunctionParam : hashObject;
- var equalityFunction = typeof equalityFunctionParam == FUNCTION ? equalityFunctionParam : null;
- this.put = function(key, value) {
- checkKey(key);
- checkValue(value);
- var hash = hashingFunction(key), bucket, bucketEntry, oldValue = null;
- bucket = getBucketForHash(bucketsByHash, hash);
- if (bucket) {
- bucketEntry = bucket.getEntryForKey(key);
- if (bucketEntry) {
- oldValue = bucketEntry[1];
- bucketEntry[1] = value;
- } else {
- bucket.addEntry(key, value);
- }
- } else {
- bucket = new Bucket(hash, key, value, equalityFunction);
- buckets[buckets.length] = bucket;
- bucketsByHash[hash] = bucket;
- }
- return oldValue;
- };
- this.get = function(key) {
- checkKey(key);
- var hash = hashingFunction(key);
- var bucket = getBucketForHash(bucketsByHash, hash);
- if (bucket) {
- var bucketEntry = bucket.getEntryForKey(key);
- if (bucketEntry) {
- return bucketEntry[1];
- }
- }
- return null;
- };
- this.containsKey = function(key) {
- checkKey(key);
- var bucketKey = hashingFunction(key);
- var bucket = getBucketForHash(bucketsByHash, bucketKey);
- return bucket ? bucket.containsKey(key) : false;
- };
- this.containsValue = function(value) {
- checkValue(value);
- var i = buckets.length;
- while (i--) {
- if (buckets[i].containsValue(value)) {
- return true;
- }
- }
- return false;
- };
- this.clear = function() {
- buckets.length = 0;
- bucketsByHash = {};
- };
- this.isEmpty = function() {
- return !buckets.length;
- };
- var createBucketAggregator = function(bucketFuncName) {
- return function() {
- var aggregated = [], i = buckets.length;
- while (i--) {
- buckets[i][bucketFuncName](aggregated);
- }
- return aggregated;
- };
- };
- this.keys = createBucketAggregator("keys");
- this.values = createBucketAggregator("values");
- this.entries = createBucketAggregator("getEntries");
- this.remove = function(key) {
- checkKey(key);
- var hash = hashingFunction(key), bucketIndex, oldValue = null;
- var bucket = getBucketForHash(bucketsByHash, hash);
- if (bucket) {
- oldValue = bucket.removeEntryForKey(key);
- if (oldValue !== null) {
- if (!bucket.entries.length) {
- bucketIndex = searchBuckets(buckets, hash);
- arrayRemoveAt(buckets, bucketIndex);
- delete bucketsByHash[hash];
- }
- }
- }
- return oldValue;
- };
- this.size = function() {
- var total = 0, i = buckets.length;
- while (i--) {
- total += buckets[i].entries.length;
- }
- return total;
- };
- this.each = function(callback) {
- var entries = that.entries(), i = entries.length, entry;
- while (i--) {
- entry = entries[i];
- callback(entry[0], entry[1]);
- }
- };
- this.putAll = function(hashtable, conflictCallback) {
- var entries = hashtable.entries();
- var entry, key, value, thisValue, i = entries.length;
- var hasConflictCallback = typeof conflictCallback == FUNCTION;
- while (i--) {
- entry = entries[i];
- key = entry[0];
- value = entry[1];
- if (hasConflictCallback && (thisValue = that.get(key))) {
- value = conflictCallback(key, thisValue, value);
- }
- that.put(key, value);
- }
- };
- this.clone = function() {
- var clone = new Hashtable(hashingFunctionParam, equalityFunctionParam);
- clone.putAll(that);
- return clone;
- };
- }
- return Hashtable;
- }();
- (function(jQuery) {
- var nfLocales = new Hashtable();
- var nfLocalesLikeUS = [ "ae", "au", "ca", "cn", "eg", "gb", "hk", "il", "in", "jp", "sk", "th", "tw", "us" ];
- var nfLocalesLikeDE = [ "at", "br", "de", "dk", "es", "gr", "it", "nl", "pt", "tr", "vn" ];
- var nfLocalesLikeFR = [ "cz", "fi", "fr", "ru", "se", "pl" ];
- var nfLocalesLikeCH = [ "ch" ];
- var nfLocaleFormatting = [ [ ".", "," ], [ ",", "." ], [ ",", " " ], [ ".", "'" ] ];
- var nfAllLocales = [ nfLocalesLikeUS, nfLocalesLikeDE, nfLocalesLikeFR, nfLocalesLikeCH ];
- function FormatData(dec, group, neg) {
- this.dec = dec;
- this.group = group;
- this.neg = neg;
- }
- function init() {
- for (var localeGroupIdx = 0; localeGroupIdx < nfAllLocales.length; localeGroupIdx++) {
- localeGroup = nfAllLocales[localeGroupIdx];
- for (var i = 0; i < localeGroup.length; i++) {
- nfLocales.put(localeGroup[i], localeGroupIdx);
- }
- }
- }
- function formatCodes(locale, isFullLocale) {
- if (nfLocales.size() == 0) init();
- var dec = ".";
- var group = ",";
- var neg = "-";
- if (isFullLocale == false) {
- if (locale.indexOf("_") != -1) locale = locale.split("_")[1].toLowerCase(); else if (locale.indexOf("-") != -1) locale = locale.split("-")[1].toLowerCase();
- }
- var codesIndex = nfLocales.get(locale);
- if (codesIndex) {
- var codes = nfLocaleFormatting[codesIndex];
- if (codes) {
- dec = codes[0];
- group = codes[1];
- }
- }
- return new FormatData(dec, group, neg);
- }
- jQuery.fn.formatNumber = function(options, writeBack, giveReturnValue) {
- return this.each(function() {
- if (writeBack == null) writeBack = true;
- if (giveReturnValue == null) giveReturnValue = true;
- var text;
- if (jQuery(this).is(":input")) text = new String(jQuery(this).val()); else text = new String(jQuery(this).text());
- var returnString = jQuery.formatNumber(text, options);
- if (writeBack) {
- if (jQuery(this).is(":input")) jQuery(this).val(returnString); else jQuery(this).text(returnString);
- }
- if (giveReturnValue) return returnString;
- });
- };
- jQuery.formatNumber = function(numberString, options) {
- var options = jQuery.extend({}, jQuery.fn.formatNumber.defaults, options);
- var formatData = formatCodes(options.locale.toLowerCase(), options.isFullLocale);
- var dec = formatData.dec;
- var group = formatData.group;
- var neg = formatData.neg;
- var validFormat = "0#-,.";
- var prefix = "";
- var negativeInFront = false;
- for (var i = 0; i < options.format.length; i++) {
- if (validFormat.indexOf(options.format.charAt(i)) == -1) prefix = prefix + options.format.charAt(i); else if (i == 0 && options.format.charAt(i) == "-") {
- negativeInFront = true;
- continue;
- } else break;
- }
- var suffix = "";
- for (var i = options.format.length - 1; i >= 0; i--) {
- if (validFormat.indexOf(options.format.charAt(i)) == -1) suffix = options.format.charAt(i) + suffix; else break;
- }
- options.format = options.format.substring(prefix.length);
- options.format = options.format.substring(0, options.format.length - suffix.length);
- var number = new Number(numberString);
- return jQuery._formatNumber(number, options, suffix, prefix, negativeInFront);
- };
- jQuery._formatNumber = function(number, options, suffix, prefix, negativeInFront) {
- var options = jQuery.extend({}, jQuery.fn.formatNumber.defaults, options);
- var formatData = formatCodes(options.locale.toLowerCase(), options.isFullLocale);
- var dec = formatData.dec;
- var group = formatData.group;
- var neg = formatData.neg;
- var forcedToZero = false;
- if (isNaN(number)) {
- if (options.nanForceZero == true) {
- number = 0;
- forcedToZero = true;
- } else return null;
- }
- if (suffix == "%") number = number * 100;
- var returnString = "";
- if (options.format.indexOf(".") > -1) {
- var decimalPortion = dec;
- var decimalFormat = options.format.substring(options.format.lastIndexOf(".") + 1);
- if (options.round == true) number = new Number(number.toFixed(decimalFormat.length)); else {
- var numStr = number.toString();
- numStr = numStr.substring(0, numStr.lastIndexOf(".") + decimalFormat.length + 1);
- number = new Number(numStr);
- }
- var decimalValue = number % 1;
- var decimalString = new String(decimalValue.toFixed(decimalFormat.length));
- decimalString = decimalString.substring(decimalString.lastIndexOf(".") + 1);
- for (var i = 0; i < decimalFormat.length; i++) {
- if (decimalFormat.charAt(i) == "#" && decimalString.charAt(i) != "0") {
- decimalPortion += decimalString.charAt(i);
- continue;
- } else if (decimalFormat.charAt(i) == "#" && decimalString.charAt(i) == "0") {
- var notParsed = decimalString.substring(i);
- if (notParsed.match("[1-9]")) {
- decimalPortion += decimalString.charAt(i);
- continue;
- } else break;
- } else if (decimalFormat.charAt(i) == "0") decimalPortion += decimalString.charAt(i);
- }
- returnString += decimalPortion;
- } else number = Math.round(number);
- var ones = Math.floor(number);
- if (number < 0) ones = Math.ceil(number);
- var onesFormat = "";
- if (options.format.indexOf(".") == -1) onesFormat = options.format; else onesFormat = options.format.substring(0, options.format.indexOf("."));
- var onePortion = "";
- if (!(ones == 0 && onesFormat.substr(onesFormat.length - 1) == "#") || forcedToZero) {
- var oneText = new String(Math.abs(ones));
- var groupLength = 9999;
- if (onesFormat.lastIndexOf(",") != -1) groupLength = onesFormat.length - onesFormat.lastIndexOf(",") - 1;
- var groupCount = 0;
- for (var i = oneText.length - 1; i > -1; i--) {
- onePortion = oneText.charAt(i) + onePortion;
- groupCount++;
- if (groupCount == groupLength && i != 0) {
- onePortion = group + onePortion;
- groupCount = 0;
- }
- }
- if (onesFormat.length > onePortion.length) {
- var padStart = onesFormat.indexOf("0");
- if (padStart != -1) {
- var padLen = onesFormat.length - padStart;
- var pos = onesFormat.length - onePortion.length - 1;
- while (onePortion.length < padLen) {
- var padChar = onesFormat.charAt(pos);
- if (padChar == ",") padChar = group;
- onePortion = padChar + onePortion;
- pos--;
- }
- }
- }
- }
- if (!onePortion && onesFormat.indexOf("0", onesFormat.length - 1) !== -1) onePortion = "0";
- returnString = onePortion + returnString;
- if (number < 0 && negativeInFront && prefix.length > 0) prefix = neg + prefix; else if (number < 0) returnString = neg + returnString;
- if (!options.decimalSeparatorAlwaysShown) {
- if (returnString.lastIndexOf(dec) == returnString.length - 1) {
- returnString = returnString.substring(0, returnString.length - 1);
- }
- }
- returnString = prefix + returnString + suffix;
- return returnString;
- };
- jQuery.fn.parseNumber = function(options, writeBack, giveReturnValue) {
- if (writeBack == null) writeBack = true;
- if (giveReturnValue == null) giveReturnValue = true;
- var text;
- if (jQuery(this).is(":input")) text = new String(jQuery(this).val()); else text = new String(jQuery(this).text());
- var number = jQuery.parseNumber(text, options);
- if (number) {
- if (writeBack) {
- if (jQuery(this).is(":input")) jQuery(this).val(number.toString()); else jQuery(this).text(number.toString());
- }
- if (giveReturnValue) return number;
- }
- };
- jQuery.parseNumber = function(numberString, options) {
- var options = jQuery.extend({}, jQuery.fn.parseNumber.defaults, options);
- var formatData = formatCodes(options.locale.toLowerCase(), options.isFullLocale);
- var dec = formatData.dec;
- var group = formatData.group;
- var neg = formatData.neg;
- var valid = "1234567890.-";
- while (numberString.indexOf(group) > -1) numberString = numberString.replace(group, "");
- numberString = numberString.replace(dec, ".").replace(neg, "-");
- var validText = "";
- var hasPercent = false;
- if (numberString.charAt(numberString.length - 1) == "%" || options.isPercentage == true) hasPercent = true;
- for (var i = 0; i < numberString.length; i++) {
- if (valid.indexOf(numberString.charAt(i)) > -1) validText = validText + numberString.charAt(i);
- }
- var number = new Number(validText);
- if (hasPercent) {
- number = number / 100;
- var decimalPos = validText.indexOf(".");
- if (decimalPos != -1) {
- var decimalPoints = validText.length - decimalPos - 1;
- number = number.toFixed(decimalPoints + 2);
- } else {
- number = number.toFixed(validText.length - 1);
- }
- }
- return number;
- };
- jQuery.fn.parseNumber.defaults = {
- locale: "us",
- decimalSeparatorAlwaysShown: false,
- isPercentage: false,
- isFullLocale: false
- };
- jQuery.fn.formatNumber.defaults = {
- format: "#,###.00",
- locale: "us",
- decimalSeparatorAlwaysShown: false,
- nanForceZero: true,
- round: true,
- isFullLocale: false
- };
- Number.prototype.toFixed = function(precision) {
- return jQuery._roundNumber(this, precision);
- };
- jQuery._roundNumber = function(number, decimalPlaces) {
- var power = Math.pow(10, decimalPlaces || 0);
- var value = String(Math.round(number * power) / power);
- if (decimalPlaces > 0) {
- var dp = value.indexOf(".");
- if (dp == -1) {
- value += ".";
- dp = 0;
- } else {
- dp = value.length - (dp + 1);
- }
- while (dp < decimalPlaces) {
- value += "0";
- dp++;
- }
- }
- return value;
- };
- })(jQuery);
- (function() {
- var cache = {};
- this.tmpl = function tmpl(str, data) {
- var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + "with(obj){p.push('" + str.replace(/[\r\t\n]/g, " ").split("<%").join(" ").replace(/((^|%>)[^\t]*)'/g, "$1\r").replace(/\t=(.*?)%>/g, "',$1,'").split(" ").join("');").split("%>").join("p.push('").split("\r").join("\\'") + "');}return p.join('');");
- return data ? fn(data) : fn;
- };
- })();
- (function($) {
- $.baseClass = function(obj) {
- obj = $(obj);
- return obj.get(0).className.match(/([^ ]+)/)[1];
- };
- $.fn.addDependClass = function(className, delimiter) {
- var options = {
- delimiter: delimiter ? delimiter : "-"
- };
- return this.each(function() {
- var baseClass = $.baseClass(this);
- if (baseClass) $(this).addClass(baseClass + options.delimiter + className);
- });
- };
- $.fn.removeDependClass = function(className, delimiter) {
- var options = {
- delimiter: delimiter ? delimiter : "-"
- };
- return this.each(function() {
- var baseClass = $.baseClass(this);
- if (baseClass) $(this).removeClass(baseClass + options.delimiter + className);
- });
- };
- $.fn.toggleDependClass = function(className, delimiter) {
- var options = {
- delimiter: delimiter ? delimiter : "-"
- };
- return this.each(function() {
- var baseClass = $.baseClass(this);
- if (baseClass) if ($(this).is("." + baseClass + options.delimiter + className)) $(this).removeClass(baseClass + options.delimiter + className); else $(this).addClass(baseClass + options.delimiter + className);
- });
- };
- })(jQuery);
- (function($) {
- function Draggable() {
- this._init.apply(this, arguments);
- }
- Draggable.prototype.oninit = function() {};
- Draggable.prototype.events = function() {};
- Draggable.prototype.onmousedown = function() {
- this.ptr.css({
- position: "absolute"
- });
- };
- Draggable.prototype.onmousemove = function(evt, x, y) {
- this.ptr.css({
- left: x,
- top: y
- });
- };
- Draggable.prototype.onmouseup = function() {};
- Draggable.prototype.isDefault = {
- drag: false,
- clicked: false,
- toclick: true,
- mouseup: false
- };
- Draggable.prototype._init = function() {
- if (arguments.length > 0) {
- this.ptr = $(arguments[0]);
- this.outer = $(".draggable-outer");
- this.is = {};
- $.extend(this.is, this.isDefault);
- var _offset = this.ptr.offset();
- this.d = {
- left: _offset.left,
- top: _offset.top,
- width: this.ptr.width(),
- height: this.ptr.height()
- };
- this.oninit.apply(this, arguments);
- this._events();
- }
- };
- Draggable.prototype._getPageCoords = function(event) {
- if (event.targetTouches && event.targetTouches[0]) {
- return {
- x: event.targetTouches[0].pageX,
- y: event.targetTouches[0].pageY
- };
- } else return {
- x: event.pageX,
- y: event.pageY
- };
- };
- Draggable.prototype._bindEvent = function(ptr, eventType, handler) {
- var self = this;
- if (this.supportTouches_) ptr.get(0).addEventListener(this.events_[eventType], handler, false); else ptr.bind(this.events_[eventType], handler);
- };
- Draggable.prototype._events = function() {
- var self = this;
- this.supportTouches_ = "ontouchend" in document;
- this.events_ = {
- click: this.supportTouches_ ? "touchstart" : "click",
- down: this.supportTouches_ ? "touchstart" : "mousedown",
- move: this.supportTouches_ ? "touchmove" : "mousemove",
- up: this.supportTouches_ ? "touchend" : "mouseup"
- };
- this._bindEvent($(document), "move", function(event) {
- if (self.is.drag) {
- event.stopPropagation();
- event.preventDefault();
- self._mousemove(event);
- }
- });
- this._bindEvent($(document), "down", function(event) {
- if (self.is.drag) {
- event.stopPropagation();
- event.preventDefault();
- }
- });
- this._bindEvent($(document), "up", function(event) {
- self._mouseup(event);
- });
- this._bindEvent(this.ptr, "down", function(event) {
- self._mousedown(event);
- return false;
- });
- this._bindEvent(this.ptr, "up", function(event) {
- self._mouseup(event);
- });
- this.ptr.find("a").click(function() {
- self.is.clicked = true;
- if (!self.is.toclick) {
- self.is.toclick = true;
- return false;
- }
- }).mousedown(function(event) {
- self._mousedown(event);
- return false;
- });
- this.events();
- };
- Draggable.prototype._mousedown = function(evt) {
- this.is.drag = true;
- this.is.clicked = false;
- this.is.mouseup = false;
- var _offset = this.ptr.offset();
- var coords = this._getPageCoords(evt);
- this.cx = coords.x - _offset.left;
- this.cy = coords.y - _offset.top;
- $.extend(this.d, {
- left: _offset.left,
- top: _offset.top,
- width: this.ptr.width(),
- height: this.ptr.height()
- });
- if (this.outer && this.outer.get(0)) {
- this.outer.css({
- height: Math.max(this.outer.height(), $(document.body).height()),
- overflow: "hidden"
- });
- }
- this.onmousedown(evt);
- };
- Draggable.prototype._mousemove = function(evt) {
- this.is.toclick = false;
- var coords = this._getPageCoords(evt);
- this.onmousemove(evt, coords.x - this.cx, coords.y - this.cy);
- };
- Draggable.prototype._mouseup = function(evt) {
- var oThis = this;
- if (this.is.drag) {
- this.is.drag = false;
- if (this.outer && this.outer.get(0)) {
- if ($.browser.mozilla) {
- this.outer.css({
- overflow: "hidden"
- });
- } else {
- this.outer.css({
- overflow: "visible"
- });
- }
- if ($.browser.msie && $.browser.version == "6.0") {
- this.outer.css({
- height: "100%"
- });
- } else {
- this.outer.css({
- height: "auto"
- });
- }
- }
- this.onmouseup(evt);
- }
- };
- window.Draggable = Draggable;
- })(jQuery);
- (function($) {
- function isArray(value) {
- if (typeof value == "undefined") return false;
- if (value instanceof Array || !(value instanceof Object) && Object.prototype.toString.call(value) == "[object Array]" || typeof value.length == "number" && typeof value.splice != "undefined" && typeof value.propertyIsEnumerable != "undefined" && !value.propertyIsEnumerable("splice")) {
- return true;
- }
- return false;
- }
- $.slider = function(node, settings) {
- var jNode = $(node);
- if (!jNode.data("jslider")) jNode.data("jslider", new jSlider(node, settings));
- return jNode.data("jslider");
- };
- $.fn.slider = function(action, opt_value) {
- var returnValue, args = arguments;
- function isDef(val) {
- return val !== undefined;
- }
- function isDefAndNotNull(val) {
- return val != null;
- }
- this.each(function() {
- var self = $.slider(this, action);
- if (typeof action == "string") {
- switch (action) {
- case "value":
- if (isDef(args[1]) && isDef(args[2])) {
- var pointers = self.getPointers();
- if (isDefAndNotNull(pointers[0]) && isDefAndNotNull(args[1])) {
- pointers[0].set(args[1]);
- pointers[0].setIndexOver();
- }
- if (isDefAndNotNull(pointers[1]) && isDefAndNotNull(args[2])) {
- pointers[1].set(args[2]);
- pointers[1].setIndexOver();
- }
- } else if (isDef(args[1])) {
- var pointers = self.getPointers();
- if (isDefAndNotNull(pointers[0]) && isDefAndNotNull(args[1])) {
- pointers[0].set(args[1]);
- pointers[0].setIndexOver();
- }
- } else returnValue = self.getValue();
- break;
- case "prc":
- if (isDef(args[1]) && isDef(args[2])) {
- var pointers = self.getPointers();
- if (isDefAndNotNull(pointers[0]) && isDefAndNotNull(args[1])) {
- pointers[0]._set(args[1]);
- pointers[0].setIndexOver();
- }
- if (isDefAndNotNull(pointers[1]) && isDefAndNotNull(args[2])) {
- pointers[1]._set(args[2]);
- pointers[1].setIndexOver();
- }
- } else if (isDef(args[1])) {
- var pointers = self.getPointers();
- if (isDefAndNotNull(pointers[0]) && isDefAndNotNull(args[1])) {
- pointers[0]._set(args[1]);
- pointers[0].setIndexOver();
- }
- } else returnValue = self.getPrcValue();
- break;
- case "calculatedValue":
- var value = self.getValue().split(";");
- returnValue = "";
- for (var i = 0; i < value.length; i++) {
- returnValue += (i > 0 ? ";" : "") + self.nice(value[i]);
- }
- ;
- break;
- case "skin":
- self.setSkin(args[1]);
- break;
- }
- } else if (!action && !opt_value) {
- if (!isArray(returnValue)) returnValue = [];
- returnValue.push(self);
- }
- });
- if (isArray(returnValue) && returnValue.length == 1) returnValue = returnValue[0];
- return returnValue || this;
- };
- var OPTIONS = {
- settings: {
- from: 1,
- to: 10,
- step: 1,
- smooth: true,
- limits: true,
- round: 0,
- format: {
- format: "#,##0.##"
- },
- value: "5;7",
- dimension: ""
- },
- className: "jslider",
- selector: ".jslider-",
- template: tmpl('<span class="<%=className%>">' + "<table><tr><td>" + '<div class="<%=className%>-bg">' + '<i class="l"></i><i class="f"></i><i class="r"></i>' + '<i class="v"></i>' + "</div>" + '<div class="<%=className%>-pointer"></div>' + '<div class="<%=className%>-pointer <%=className%>-pointer-to"></div>' + '<div class="<%=className%>-label"><span><%=settings.from%></span></div>' + '<div class="<%=className%>-label <%=className%>-label-to"><span><%=settings.to%></span><%=settings.dimension%></div>' + '<div class="<%=className%>-value"><span></span><%=settings.dimension%></div>' + '<div class="<%=className%>-value <%=className%>-value-to"><span></span><%=settings.dimension%></div>' + '<div class="<%=className%>-scale"><%=scale%></div>' + "</td></tr></table>" + "</span>")
- };
- function jSlider() {
- return this.init.apply(this, arguments);
- }
- jSlider.prototype.init = function(node, settings) {
- this.settings = $.extend(true, {}, OPTIONS.settings, settings ? settings : {});
- this.inputNode = $(node).hide();
- this.settings.interval = this.settings.to - this.settings.from;
- this.settings.value = this.inputNode.attr("value");
- if (this.settings.calculate && $.isFunction(this.settings.calculate)) this.nice = this.settings.calculate;
- if (this.settings.onstatechange && $.isFunction(this.settings.onstatechange)) this.onstatechange = this.settings.onstatechange;
- this.is = {
- init: false
- };
- this.o = {};
- this.create();
- };
- jSlider.prototype.onstatechange = function() {};
- jSlider.prototype.create = function() {
- var $this = this;
- this.domNode = $(OPTIONS.template({
- className: OPTIONS.className,
- settings: {
- from: this.nice(this.settings.from),
- to: this.nice(this.settings.to),
- dimension: this.settings.dimension
- },
- scale: this.generateScale()
- }));
- this.inputNode.after(this.domNode);
- this.drawScale();
- if (this.settings.skin && this.settings.skin.length > 0) this.setSkin(this.settings.skin);
- this.sizes = {
- domWidth: this.domNode.width(),
- domOffset: this.domNode.offset()
- };
- $.extend(this.o, {
- pointers: {},
- labels: {
- 0: {
- o: this.domNode.find(OPTIONS.selector + "value").not(OPTIONS.selector + "value-to")
- },
- 1: {
- o: this.domNode.find(OPTIONS.selector + "value").filter(OPTIONS.selector + "value-to")
- }
- },
- limits: {
- 0: this.domNode.find(OPTIONS.selector + "label").not(OPTIONS.selector + "label-to"),
- 1: this.domNode.find(OPTIONS.selector + "label").filter(OPTIONS.selector + "label-to")
- }
- });
- $.extend(this.o.labels[0], {
- value: this.o.labels[0].o.find("span")
- });
- $.extend(this.o.labels[1], {
- value: this.o.labels[1].o.find("span")
- });
- if (!$this.settings.value.split(";")[1]) {
- this.settings.single = true;
- this.domNode.addDependClass("single");
- }
- if (!$this.settings.limits) this.domNode.addDependClass("limitless");
- this.domNode.find(OPTIONS.selector + "pointer").each(function(i) {
- var value = $this.settings.value.split(";")[i];
- if (value) {
- $this.o.pointers[i] = new jSliderPointer(this, i, $this);
- var prev = $this.settings.value.split(";")[i - 1];
- if (prev && new Number(value) < new Number(prev)) value = prev;
- value = value < $this.settings.from ? $this.settings.from : value;
- value = value > $this.settings.to ? $this.settings.to : value;
- $this.o.pointers[i].set(value, true);
- }
- });
- this.o.value = this.domNode.find(".v");
- this.is.init = true;
- $.each(this.o.pointers, function(i) {
- $this.redraw(this);
- });
- (function(self) {
- $(window).resize(function() {
- self.onresize();
- });
- })(this);
- };
- jSlider.prototype.setSkin = function(skin) {
- if (this.skin_) this.domNode.removeDependClass(this.skin_, "_");
- this.domNode.addDependClass(this.skin_ = skin, "_");
- };
- jSlider.prototype.setPointersIndex = function(i) {
- $.each(this.getPointers(), function(i) {
- this.index(i);
- });
- };
- jSlider.prototype.getPointers = function() {
- return this.o.pointers;
- };
- jSlider.prototype.generateScale = function() {
- if (this.settings.scale && this.settings.scale.length > 0) {
- var str = "";
- var s = this.settings.scale;
- var prc = Math.round(100 / (s.length - 1) * 10) / 10;
- for (var i = 0; i < s.length; i++) {
- str += '<span style="left: ' + i * prc + '%">' + (s[i] != "|" ? "<ins>" + s[i] + "</ins>" : "") + "</span>";
- }
- return str;
- } else return "";
- return "";
- };
- jSlider.prototype.drawScale = function() {
- this.domNode.find(OPTIONS.selector + "scale span ins").each(function() {
- $(this).css({
- marginLeft: -$(this).outerWidth() / 2
- });
- });
- };
- jSlider.prototype.onresize = function() {
- var self = this;
- this.sizes = {
- domWidth: this.domNode.width(),
- domOffset: this.domNode.offset()
- };
- $.each(this.o.pointers, function(i) {
- self.redraw(this);
- });
- };
- jSlider.prototype.update = function() {
- this.onresize();
- this.drawScale();
- };
- jSlider.prototype.limits = function(x, pointer) {
- if (!this.settings.smooth) {
- var step = this.settings.step * 100 / this.settings.interval;
- x = Math.round(x / step) * step;
- }
- var another = this.o.pointers[1 - pointer.uid];
- if (another && pointer.uid && x < another.value.prc) x = another.value.prc;
- if (another && !pointer.uid && x > another.value.prc) x = another.value.prc;
- if (x < 0) x = 0;
- if (x > 100) x = 100;
- return Math.round(x * 10) / 10;
- };
- jSlider.prototype.redraw = function(pointer) {
- if (!this.is.init) return false;
- this.setValue();
- if (this.o.pointers[0] && this.o.pointers[1]) this.o.value.css({
- left: this.o.pointers[0].value.prc + "%",
- width: this.o.pointers[1].value.prc - this.o.pointers[0].value.prc + "%"
- });
- this.o.labels[pointer.uid].value.html(this.nice(pointer.value.origin));
- this.redrawLabels(pointer);
- };
- jSlider.prototype.redrawLabels = function(pointer) {
- function setPosition(label, sizes, prc) {
- sizes.margin = -sizes.label / 2;
- label_left = sizes.border + sizes.margin;
- if (label_left < 0) sizes.margin -= label_left;
- if (sizes.border + sizes.label / 2 > self.sizes.domWidth) {
- sizes.margin = 0;
- sizes.right = true;
- } else sizes.right = false;
- label.o.css({
- left: prc + "%",
- marginLeft: sizes.margin,
- right: "auto"
- });
- if (sizes.right) label.o.css({
- left: "auto",
- right: 0
- });
- return sizes;
- }
- var self = this;
- var label = this.o.labels[pointer.uid];
- var prc = pointer.value.prc;
- var sizes = {
- label: label.o.outerWidth(),
- right: false,
- border: prc * this.sizes.domWidth / 100
- };
- if (!this.settings.single) {
- var another = this.o.pointers[1 - pointer.uid];
- var another_label = this.o.labels[another.uid];
- switch (pointer.uid) {
- case 0:
- if (sizes.border + sizes.label / 2 > another_label.o.offset().left - this.sizes.domOffset.left) {
- another_label.o.css({
- visibility: "hidden"
- });
- another_label.value.html(this.nice(another.value.origin));
- label.o.css({
- visibility: "visible"
- });
- prc = (another.value.prc - prc) / 2 + prc;
- if (another.value.prc != pointer.value.prc) {
- label.value.html(this.nice(pointer.value.origin) + " – " + this.nice(another.value.origin));
- sizes.label = label.o.outerWidth();
- sizes.border = prc * this.sizes.domWidth / 100;
- }
- } else {
- another_label.o.css({
- visibility: "visible"
- });
- }
- break;
- case 1:
- if (sizes.border - sizes.label / 2 < another_label.o.offset().left - this.sizes.domOffset.left + another_label.o.outerWidth()) {
- another_label.o.css({
- visibility: "hidden"
- });
- another_label.value.html(this.nice(another.value.origin));
- label.o.css({
- visibility: "visible"
- });
- prc = (prc - another.value.prc) / 2 + another.value.prc;
- if (another.value.prc != pointer.value.prc) {
- label.value.html(this.nice(another.value.origin) + " – " + this.nice(pointer.value.origin));
- sizes.label = label.o.outerWidth();
- sizes.border = prc * this.sizes.domWidth / 100;
- }
- } else {
- another_label.o.css({
- visibility: "visible"
- });
- }
- break;
- }
- }
- sizes = setPosition(label, sizes, prc);
- if (another_label) {
- var sizes = {
- label: another_label.o.outerWidth(),
- right: false,
- border: another.value.prc * this.sizes.domWidth / 100
- };
- sizes = setPosition(another_label, sizes, another.value.prc);
- }
- this.redrawLimits();
- };
- jSlider.prototype.redrawLimits = function() {
- if (this.settings.limits) {
- var limits = [ true, true ];
- for (key in this.o.pointers) {
- if (!this.settings.single || key == 0) {
- var pointer = this.o.pointers[key];
- var label = this.o.labels[pointer.uid];
- var label_left = label.o.offset().left - this.sizes.domOffset.left;
- var limit = this.o.limits[0];
- if (label_left < limit.outerWidth()) limits[0] = false;
- var limit = this.o.limits[1];
- if (label_left + label.o.outerWidth() > this.sizes.domWidth - limit.outerWidth()) limits[1] = false;
- }
- }
- for (var i = 0; i < limits.length; i++) {
- if (limits[i]) this.o.limits[i].fadeIn("fast"); else this.o.limits[i].fadeOut("fast");
- }
- }
- };
- jSlider.prototype.setValue = function() {
- var value = this.getValue();
- this.inputNode.attr("value", value);
- this.onstatechange.call(this, value);
- };
- jSlider.prototype.getValue = function() {
- if (!this.is.init) return false;
- var $this = this;
- var value = "";
- $.each(this.o.pointers, function(i) {
- if (this.value.prc != undefined && !isNaN(this.value.prc)) value += (i > 0 ? ";" : "") + $this.prcToValue(this.value.prc);
- });
- return value;
- };
- jSlider.prototype.getPrcValue = function() {
- if (!this.is.init) return false;
- var $this = this;
- var value = "";
- $.each(this.o.pointers, function(i) {
- if (this.value.prc != undefined && !isNaN(this.value.prc)) value += (i > 0 ? ";" : "") + this.value.prc;
- });
- return value;
- };
- jSlider.prototype.prcToValue = function(prc) {
- if (this.settings.heterogeneity && this.settings.heterogeneity.length > 0) {
- var h = this.settings.heterogeneity;
- var _start = 0;
- var _from = this.settings.from;
- for (var i = 0; i <= h.length; i++) {
- if (h[i]) var v = h[i].split("/"); else var v = [ 100, this.settings.to ];
- v[0] = new Number(v[0]);
- v[1] = new Number(v[1]);
- if (prc >= _start && prc <= v[0]) {
- var value = _from + (prc - _start) * (v[1] - _from) / (v[0] - _start);
- }
- _start = v[0];
- _from = v[1];
- }
- } else {
- var value = this.settings.from + prc * this.settings.interval / 100;
- }
- return this.round(value);
- };
- jSlider.prototype.valueToPrc = function(value, pointer) {
- if (this.settings.heterogeneity && this.settings.heterogeneity.length > 0) {
- var h = this.settings.heterogeneity;
- var _start = 0;
- var _from = this.settings.from;
- for (var i = 0; i <= h.length; i++) {
- if (h[i]) var v = h[i].split("/"); else var v = [ 100, this.settings.to ];
- v[0] = new Number(v[0]);
- v[1] = new Number(v[1]);
- if (value >= _from && value <= v[1]) {
- var prc = pointer.limits(_start + (value - _from) * (v[0] - _start) / (v[1] - _from));
- }
- _start = v[0];
- _from = v[1];
- }
- } else {
- var prc = pointer.limits((value - this.settings.from) * 100 / this.settings.interval);
- }
- return prc;
- };
- jSlider.prototype.round = function(value) {
- value = Math.round(value / this.settings.step) * this.settings.step;
- if (this.settings.round) value = Math.round(value * Math.pow(10, this.settings.round)) / Math.pow(10, this.settings.round); else value = Math.round(value);
- return value;
- };
- jSlider.prototype.nice = function(value) {
- value = value.toString().replace(/,/gi, ".").replace(/ /gi, "");
- if ($.formatNumber) {
- return $.formatNumber(new Number(value), this.settings.format || {}).replace(/-/gi, "−");
- } else {
- return new Number(value);
- }
- };
- function jSliderPointer() {
- Draggable.apply(this, arguments);
- }
- jSliderPointer.prototype = new Draggable();
- jSliderPointer.prototype.oninit = function(ptr, id, _constructor) {
- this.uid = id;
- this.parent = _constructor;
- this.value = {};
- this.settings = this.parent.settings;
- };
- jSliderPointer.prototype.onmousedown = function(evt) {
- this._parent = {
- offset: this.parent.domNode.offset(),
- width: this.parent.domNode.width()
- };
- this.ptr.addDependClass("hover");
- this.setIndexOver();
- };
- jSliderPointer.prototype.onmousemove = function(evt, x) {
- var coords = this._getPageCoords(evt);
- this._set(this.calc(coords.x));
- };
- jSliderPointer.prototype.onmouseup = function(evt) {
- if (this.parent.settings.callback && $.isFunction(this.parent.settings.callback)) this.parent.settings.callback.call(this.parent, this.parent.getValue());
- this.ptr.removeDependClass("hover");
- };
- jSliderPointer.prototype.setIndexOver = function() {
- this.parent.setPointersIndex(1);
- this.index(2);
- };
- jSliderPointer.prototype.index = function(i) {
- this.ptr.css({
- zIndex: i
- });
- };
- jSliderPointer.prototype.limits = function(x) {
- return this.parent.limits(x, this);
- };
- jSliderPointer.prototype.calc = function(coords) {
- var x = this.limits((coords - this._parent.offset.left) * 100 / this._parent.width);
- return x;
- };
- jSliderPointer.prototype.set = function(value, opt_origin) {
- this.value.origin = this.parent.round(value);
- this._set(this.parent.valueToPrc(value, this), opt_origin);
- };
- jSliderPointer.prototype._set = function(prc, opt_origin) {
- if (!opt_origin) this.value.origin = this.parent.prcToValue(prc);
- this.value.prc = prc;
- this.ptr.css({
- left: prc + "%"
- });
- this.parent.redraw(this);
- };
- })(jQuery);
- function validateHomeNHRewards() {
- var noerror = true;
- var errorField = "";
- $("#einputEmail").hide();
- $("#einputPassword").hide();
- var usuario = $("#inputEmail").val();
- if (!validateLength(usuario) || usuario == $("#inputEmail").attr("placeholder")) {
- $("#einputEmail").show();
- $("#inputEmail").addClass("error");
- noerror = false;
- if (errorField == "") errorField = "user";
- } else {
- $("#inputEmail").removeClass("error");
- }
- var password = $("#inputPassword").val();
- if (!validateLength(password) || password == $("#inputPassword").attr("placeholder")) {
- $("#einputPassword").show();
- $("#inputPassword").addClass("error");
- noerror = false;
- if (errorField == "") errorField = "password";
- } else {
- $("#inputPassword").removeClass("error");
- }
- if (!noerror) callSeguimientoForms("error", "loginRewardsForm", errorField);
- return noerror;
- }
- function validateHomeNHRewardsMob() {
- var noerror = true;
- var errorField = "";
- $("#einputEmailMob").hide();
- $("#einputPasswordMob").hide();
- var usuario = $("#inputEmailMob").val();
- if (!validateLength(usuario) || usuario == $("#inputEmailMob").attr("placeholder")) {
- $("#einputEmailMob").show();
- $("#inputEmailMob").addClass("error");
- noerror = false;
- if (errorField == "") errorField = "user";
- } else {
- $("#inputEmailMob").removeClass("error");
- }
- var password = $("#inputPasswordMob").val();
- if (!validateLength(password) || password == $("#inputPasswordMob").attr("placeholder")) {
- $("#einputPasswordMob").show();
- $("#inputPasswordMob").addClass("error");
- noerror = false;
- if (errorField == "") errorField = "password";
- } else {
- $("#inputPasswordMob").removeClass("error");
- }
- if (!noerror) callSeguimientoForms("error", "loginRewardsFormMob", errorField);
- return noerror;
- }
- $(function() {
- $("img.lazy").lazyload({
- effect: "fadeIn",
- failure_limit: 1
- });
- setTimeout(function() {
- $(window).trigger("scroll");
- }, 100);
- setUserDataGEOIP();
- $(".fancybox").fancybox();
- $("#allreviews").fancybox({
- height: 500
- });
- $(".qty-opiniones").fancybox({
- height: 500
- });
- $("a#modificar").fancybox({
- hideOnContentClick: true
- });
- $(".selectpicker").selectpicker();
- $("#lnkForgotPassword").attr("onclick", "forgotPassword();");
- $("#lnkForgotPasswordMob").attr("onclick", "forgotPasswordMob();");
- $("#userLoggedMenu").hide();
- $(".btnLogout").click(function() {
- logout();
- });
- $("#loginForm").submit(function(event) {
- var nomb = $("#inputEmail").val();
- var psw = $("#inputPassword").val();
- doLogin(ssoUrl, nomb, psw, ssoService, ssoAuth);
- event.preventDefault();
- });
- $("#loginFormMob").submit(function(event) {
- var nombMob = $("#inputEmailMob").val();
- var pswMob = $("#inputPasswordMob").val();
- doLogin(ssoUrl, nombMob, pswMob, ssoService, ssoAuth);
- event.preventDefault();
- });
- if (readAcceptCookie() == "true" || decoratorData.pageID.indexOf("83289") > -1) {
- $(".politicaRewards").hide();
- } else {
- $(".politicaRewards").show();
- }
- createAcceptCookie(false);
- });
- function resetPass(email) {
- if (email.attr("placeholder") == email.val()) {
- email.addClass("error");
- } else {
- email.removeClass("error");
- var request = $.ajax({
- type: "GET",
- url: "/auth/ResetPwd.do",
- data: "user=" + email.val() + "&lang=" + globalLang,
- success: function(result) {
- var json = JSON.parse(result);
- if (json["errors"]["ERROR_002"] != null) {
- alert(json["errors"]["ERROR_002"]);
- }
- }
- });
- email.val("");
- }
- }
- function forgotPasswordMob() {
- var email = $("#inputEmailMob");
- resetPass(email);
- }
- function forgotPassword() {
- var email = $("#inputEmail");
- resetPass(email);
- }
- function logout() {
- var accion = "/j_spring_security_logout";
- $.ajaxSetup({
- cache: false
- });
- $.getJSON(accion, null, function(data) {
- var urlLogin = globalHttpProtocol + location.href;
- window.location = urlLogin;
- var cookieName = "userLoggedData";
- sessionStorage.removeItem(cookieName);
- var cookieRememberMe = "rememberme";
- $.cookie(cookieRememberMe, null, {
- path: "/"
- });
- });
- }
- var dynamicTelephones = function() {
- var _campId = typeof campId != "undefined" ? campId : "";
- var _country = typeof country != "undefined" ? country : "";
- var _countryName = typeof countryName != "undefined" ? countryName : "";
- var _continent = typeof continent != "undefined" ? continent : "";
- var _webSection = typeof page_section != "undefined" ? page_section : "";
- var channelIndex = "-1";
- var telephone = "";
- var telephoneWebSection = "";
- var global = "";
- var countryName = "";
- var countryText = "";
- var countryFound = false;
- var telephoneJSON = "/resources/telephoneJSON.txt";
- var telephoneCountry = "";
- var countryUser = "";
- var init = function() {
- if (typeof Agent != "undefined") {
- _country = Agent.country;
- _campId = Agent.campId;
- _countryName = Agent.countryName;
- _continent = Agent.continent;
- if (Agent.country != getCookieValue("USER_CT_COUNTRYCODE")) {
- console.log("Agentcountry, ", Agent.country, "USER_CT_COUNTRYCODE: ", getCookieValue("USER_CT_COUNTRYCODE"));
- }
- }
- _continent = getCookieValue("USER_CT_CONTINENT") != "" && getCookieValue("USER_CT_CONTINENT") != "null" ? getCookieValue("USER_CT_CONTINENT") : _continent;
- _country = getCookieValue("USER_CT_COUNTRYCODE") != "" && getCookieValue("USER_CT_COUNTRYCODE") != "null" ? getCookieValue("USER_CT_COUNTRYCODE") : _country;
- _countryName = getCookieValue("USER_CT_COUNTRYCODE") != "" && getCookieValue("USER_CT_COUNTRYCODE") != "null" ? getCookieValue("USER_CT_COUNTRYCODE") : _countryName;
- countryText = _country;
- countryUser = _country;
- if (_campId == "8431996") {
- $(".labelMeta").removeClass("hidden");
- $(".imageMetaSearch").html('<img src="/system/img/trivago.png" alt="" class="triplogo">');
- }
- if (_campId == "8565112") {
- $(".labelMeta").removeClass("hidden");
- $(".imageMetaSearch").html('<img src="/system/img/logos/logo-google.svg" alt="" class="triplogo">');
- }
- if (_campId == "8435709") {
- $(".labelMeta").removeClass("hidden");
- $(".imageMetaSearch").html('<img src="/system/img/tripadvisor.png" alt="" class="triplogo">');
- }
- $.ajax({
- cache: true,
- url: telephoneJSON,
- dataType: "json",
- success: function(data) {
- if (_campId != null) {
- for (var i = 0; i < data.channels.length; i++) {
- for (var j = 0; j < data.channels[i].agent.length; j++) {
- if (data.channels[i].agent[j].campId == _campId) {
- channelIndex = i;
- }
- }
- }
- if (channelIndex != "-1") {
- for (var k = 0; k < data.channels[channelIndex].telephones.length; k++) {
- if (data.channels[channelIndex].telephones[k].country == countryUser) {
- telephoneCountry = data.channels[channelIndex].telephones[k].telephone;
- telephone = data.channels[channelIndex].telephones[k].telephone;
- countryName = data.channels[channelIndex].telephones[k].countryName;
- countryFound = true;
- } else {
- $(".telephoneList").append('<li><a href="tel:' + data.channels[channelIndex].telephones[k].telephone + '">' + data.channels[channelIndex].telephones[k].telephone + " (" + data.channels[channelIndex].telephones[k].country + ")" + "</a></li>");
- }
- }
- if (data.channels[channelIndex].globalChannel != "") {
- if (countryFound) {
- $(".telephoneList").html($(".telephoneList").html() + '<li><a href="tel:' + data.channels[channelIndex].globalChannel + '">' + data.channels[channelIndex].globalChannel + " (" + labelGlobalAccess + ")" + "</a></li>");
- global = data.channels[channelIndex].globalChannel;
- } else {
- telephone = data.channels[channelIndex].globalChannel;
- global = data.channels[channelIndex].globalChannel;
- countryText = labelGlobalAccess;
- }
- }
- }
- }
- if (channelIndex == "-1") {
- for (var i = 0; i < data.channels.length; i++) {
- if (data.channels[i].defaultChannel == "Yes") {
- for (var k = 0; k < data.channels[i].telephones.length; k++) {
- if (data.channels[i].telephones[k].country == _country) {
- telephone = data.channels[i].telephones[k].telephone;
- countryName = data.channels[i].telephones[k].countryName;
- countryFound = true;
- } else {
- $(".telephoneList").html($(".telephoneList").html() + '<li><a href="tel:' + data.channels[i].telephones[k].telephone + '">' + data.channels[i].telephones[k].telephone + " (" + data.channels[i].telephones[k].country + ")" + "</a></li>");
- }
- }
- if (data.channels[i].globalChannel != "") {
- if (countryFound) {
- $(".telephoneList").html($(".telephoneList").html() + '<li><a href="tel:' + data.channels[i].globalChannel + '">' + data.channels[i].globalChannel + " (" + labelGlobalAccess + ")" + "</a></li>");
- global = data.channels[i].globalChannel;
- } else {
- telephone = data.channels[i].globalChannel;
- global = data.channels[i].globalChannel;
- countryText = labelGlobalAccess;
- }
- }
- }
- if (data.channels[i].webSection != null && data.channels[i].webSection == _webSection) {
- for (var k = 0; k < data.channels[i].telephones.length; k++) {
- if (data.channels[i].telephones[k].country == _country) {
- telephoneWebSection = data.channels[i].telephones[k].telephone;
- break;
- } else {
- telephoneWebSection = data.channels[i].globalChannel;
- }
- }
- }
- }
- }
- $(".phoneHeader").html(telephone + " (" + countryText + ")" + $(".phoneHeader").html());
- $(".phoneHeaderMob").html(telephone + " (" + countryText + ")" + $(".phoneHeaderMob").html());
- $(".dynamicTelephone").each(function(indice, elemento) {
- $(elemento).text($(elemento).text() + telephone);
- });
- $(".phoneGlobal").html(global);
- $(".phoneCountry").html(countryName);
- if (telephone != global) {
- $(".phoneContact").html(telephone);
- } else {
- $("#telephoneContact").hide();
- }
- if (telephoneWebSection) {
- $(".dynamicTelephoneWidget").html(telephoneWebSection);
- } else {
- $(".dynamicTelephoneWidget").html(telephone);
- }
- var dinamicTel = $(".dynamicTelephone").html();
- var globalTel = $(".phoneGlobal").html();
- var sectionTel = $(".dynamicTelephoneWidget").html();
- $(".dynamicTelephone").attr("href", "tel:" + telephone);
- $(".phoneGlobal").attr("href", "tel:" + global);
- $("#contactTel .dynamicTelephone").html("(" + countryText + ")" + "</br> " + dinamicTel);
- $(".dynamicTelephoneWidget").attr("href", "tel:" + $(".dynamicTelephoneWidget").text());
- changeHTMLMobile();
- },
- error: function() {
- console.log("Error al recuperar los telefonos dynamicos");
- var globalTelephone = "+34 91 398 46 61";
- $(".phoneHeader").html(globalTelephone + " (" + labelGlobalAccess + ") <b class='caret'></b>");
- $(".phoneHeaderMob").html(globalTelephone + " (" + labelGlobalAccess + ") <b class='caret'></b>");
- $().html("<li><a href='tel:+43 0820 40 11 56 08'>+43 0820 40 11 56 08 (AT)</a></li><li><a href='tel:+32 070 35 47 72'>+32 070 35 47 72 (BE)</a></li><li><a href='tel:+33 (0)821 77 42 96'>+33 (0)821 77 42 96 (FR)</a></li><li><a href='tel:+49 30 22388599'>+49 30 22388599 (DE)</a></li><li><a href='tel:(+39) 848 390 227'>(+39) 848 390 227 (IT)</a></li><li><a href='tel:+351 707 500 302'>+351 707 500 302 (PT)</a></li><li><a href='tel:902 570 368'>902 570 368 (ES)</a></li><li><a href='tel:+41 (0)848 20 74 16'>+41 (0)848 20 74 16 (CH)</a></li><li><a href='tel:+31 (0)20 79 56 088'>+31 (0)20 79 56 088 (NL)</a></li><li><a href='tel:+44 (0)870 80 71 359'>+44 (0)870 80 71 359 (GB)</a></li><li><a href='tel:+1 646 568 4725'>+1 646 568 4725 (US)</a></li><li><a href='tel:+54 (0)11 5776 6464'>+54 (0)11 5776 6464 (AR)</a></li><li><a href='tel:+56 (0)2 341 7575'>+56 (0)2 341 7575 (CL)</a></li><li><a href='tel:+57 1 589 7744'>+57 1 589 7744 (CO)</a></li><li><a href='tel:+52 (0)55 52291500'>+52 (0)55 52291500 (MX)</a></li><li><a href='tel:+598 (0)2 9160001'>+598 (0)2 9160001 (UY)</a></li><li><a href='tel:+58 295 400 7111'>+58 295 400 7111 (VE)</a></li>");
- $(".dynamicTelephone").each(function(indice, elemento) {
- $(elemento).text(globalTelephone + "");
- });
- $(".phoneGlobal").html(globalTelephone + "");
- $(".phoneCountry").html("Spain");
- $("#telephoneContact").hide();
- telephoneCountry = "+34 91 398 46 61";
- global = "+34 91 398 46 61";
- changeHTMLMobile();
- }
- });
- };
- var changeHTMLMobile = function() {
- countryName = countryName != "" ? countryName : countryText;
- telephoneCountry = telephoneCountry != "" ? telephoneCountry : telephone;
- $("a.mobileDynamicTelephone").attr("href", "tel:" + telephoneCountry.replace(/ /g, "")).html(telephoneCountry);
- $(".mobileDynamicTelephoneTxt").html(telephoneCountry);
- $("a.mobileDynamicTelephoneHref").attr("href", "tel:" + telephoneCountry.replace(/ /g, ""));
- $("a.mobileDynamicPhoneGlobal").attr("href", "tel:" + global.replace(/ /g, "")).html(global);
- $("a.mobileDynamicPhoneGlobalHref").attr("href", "tel:" + global.replace(/ /g, ""));
- $(".mobileDynamicPhoneGlobalTxt").html(global);
- $("#mobileContactTel .mobileDynamicTelephone").html(countryName + "</br> " + telephoneCountry);
- };
- return {
- init: init
- };
- }();
- function getCookieValue(cookieName) {
- cookieMatch = document.cookie.match("(^|;)\\s*" + cookieName + "\\s*=\\s*([^;]+)");
- return cookieMatch ? cookieMatch.pop() : "";
- }
- function getCookieValue(cookieName) {
- cookieMatch = document.cookie.match("(^|;)\\s*" + cookieName + "\\s*=\\s*([^;]+)");
- return cookieMatch ? cookieMatch.pop() : "";
- }
- $(document).ready(function() {
- dynamicTelephones.init();
- });
- function trackClickDetectIPOrigin(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "click availability pop up",
- event: "availability | click"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackShowDetectIPOrigin(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "impression availability pop up",
- event: "availability | impression"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackChangeLanguage(page, language) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "change language",
- eventLabel: language,
- event: "header | language"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackGeneralSearch(page, name, startDate, endDate, nrooms, nadults, nchild) {
- try {
- var nights = calculateNumNights(startDate, endDate);
- utag.link({
- eventCategory: page,
- eventAction: "search",
- eventLabel: createLabelSearchData(name, startDate, endDate, nrooms, nadults, nchild),
- eventValue: nights,
- event: "home | searchbox"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackSignupNewsletter(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "sign up newsletter",
- eventLabel: "",
- event: "home | newsletter"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackSignupRewardsHome(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "sign up nh rewards",
- eventLabel: "",
- event: "home | nh rewards"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackNewGeneralSearch(page, name, startDate, endDate, nrooms, nadults, nchild) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "new search",
- eventLabel: createLabelSearchData(name, startDate, endDate, nrooms, nadults, nchild),
- eventValue: calculateNumNights(startDate, endDate),
- event: "SRP | newSearch"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackSelectHotel(page, hotelsearch, checkin, checkout, price, position, numHabis) {
- try {
- var numNights = calculateNumNights(checkin, checkout);
- var quantity = parseInt(numNights) * parseInt(numHabis);
- utag.link({
- eventCategory: page,
- eventAction: "select hotel",
- eventLabel: createLabelHotelSearchData(hotelsearch, checkin, checkout),
- eventValue: numNights,
- event: "SRP | select hotel",
- ecommerce_action: "add",
- ecommerce_actionField_list: "search results",
- products_id: [ hotelsearch ],
- products_price: [ price ],
- products_position: [ position ],
- products_quantity: [ quantity ]
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackBookHotelPage(page, hotelsearch, checkin, checkout, price, numHabis) {
- try {
- var numNights = calculateNumNights(checkin, checkout);
- var quantity = parseInt(numNights) * parseInt(numHabis);
- utag.link({
- eventCategory: page,
- eventAction: "book now",
- eventLabel: hotelsearch,
- event: "PDP | book",
- ecommerce_action: "add",
- ecommerce_actionField_list: "Hotel Page",
- products_id: [ hotelsearch ],
- products_price: [ price ],
- products_quantity: [ quantity ]
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackViewHotelPage(page, name, price, position) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "view hotel page",
- eventLabel: name,
- event: "SRP | view hotel",
- ecommerce_action: "product_click",
- ecommerce_actionField_list: "Search Results",
- products_id: [ name ],
- products_position: [ position ],
- products_price: [ price ]
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackHotelSearch(page, hotelsearch, checkin, checkout) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "search",
- eventLabel: createLabelHotelSearchData(hotelsearch, checkin, checkout),
- eventValue: calculateNumNights(checkin, checkout),
- event: "PDP | search"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackSignupRewards(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "sign up nh rewards",
- eventLabel: "",
- event: "PDP | nh rewards"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceSearch(page, name, nrooms, nasistentes, nsalones, eventType) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "search a meeting",
- eventLabel: createLabelMiceSearchData(name, nrooms, nasistentes, nsalones, eventType),
- event: "mice | search"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceSearchInResult(page, name, nrooms, nasistentes, nsalones, eventType) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "search a meeting",
- eventLabel: createLabelMiceSearchData(name, nrooms, nasistentes, nsalones, eventType),
- event: "mice | search results"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceSearchInDestiny(page, name, nrooms, nasistentes, nsalones, eventType) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "search a meeting",
- eventLabel: createLabelMiceSearchData(name, nrooms, nasistentes, nsalones, eventType),
- event: "mice | search"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceRequestQuote(page, where, name, nrooms) {
- try {
- var eventTrack = "request a quote | " + where;
- utag.link({
- eventCategory: page,
- eventAction: eventTrack,
- eventLabel: createLabelMiceSearchDataQuote(name, nrooms),
- event: "mice | search results"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceRequestQuotePopup(page, hotel, nrooms) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "request a quote | pop up",
- eventLabel: createLabelMiceSearchDataHeader(hotel, nrooms),
- event: "micesearch | quote"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMicePersonalize(page, hotels) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "personalize event",
- eventLabel: hotels,
- event: "Micefunnel | step1"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceSendEnquiry(page, hotels) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "send enquiry",
- eventLabel: hotels,
- event: "Micefunnel | step1"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackDealsSearch(page, country, city, startDate, endDate) {
- try {
- var eventLabelTrack = country + "|" + city + "|" + startDate + "-" + endDate;
- utag.link({
- eventCategory: page,
- eventAction: "search an offer",
- eventLabel: eventLabelTrack,
- eventValue: calculateNumNights(startDate, endDate),
- event: "offers | search"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackDealsBook(page, tabName, offerName, id, position) {
- try {
- var eventLabelTrack = tabName + "|" + offerName;
- utag.link({
- eventCategory: page,
- eventAction: "book an offer",
- eventLabel: eventLabelTrack,
- event: "offers | book",
- ecommerce_action: "promo_click",
- promotions_id: [ id ],
- promotions_name: [ offerName ],
- promotions_position: [ position ],
- promotions_creative: [ tabName ]
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackShowRewardsRate(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "select nh rewards rates tab",
- eventLabel: "",
- event: "funnel | step1 | nhrewtab"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackShowPackageRate(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "select packages tab",
- event: "funnel1 | step1 | packagestab"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackBookRoom(page, name, roomType, startDate, endDate, nrooms, nadults, nchild) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "book",
- eventLabel: createLabelRoomData(name, roomType, startDate, endDate, nrooms, nadults, nchild),
- eventValue: calculateNumNights(startDate, endDate),
- event: "funnel | step1 | book now"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackSelectRoom(page, name, roomType, startDate, endDate, nrooms, nadults, nchild) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "room display",
- eventLabel: createLabelRoomData(name, roomType, startDate, endDate, nrooms, nadults, nchild),
- eventValue: calculateNumNights(startDate, endDate),
- event: "funnel | step1 | book"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackSelectRoomRewards(page, name, roomType, startDate, endDate, nrooms, nadults, nchild) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "room display | NH Rewards",
- eventLabel: createLabelRoomData(name, roomType, startDate, endDate, nrooms, nadults, nchild),
- eventValue: calculateNumNights(startDate, endDate),
- event: "funnel | step1 | booknhrew"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackModifySearch(page, name, startDate, endDate, nrooms, nadults, nchild) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "modify search",
- eventLabel: createLabelSearchData(name, startDate, endDate, nrooms, nadults, nchild),
- eventValue: calculateNumNights(startDate, endDate),
- event: "funnel | step1 | modify"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackProceedToBook(page, name, startDate, endDate, nrooms, nadults, nchild, rate) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "proceed to book",
- eventLabel: createLabelBook(name, startDate, endDate, nrooms, nadults, nchild, rate),
- eventValue: calculateNumNights(startDate, endDate),
- event: "funnel | step2"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackFilterAvail(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "filters use | select only available hotels",
- event: "SRP | filtersAvailability"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackFilterStars(page, stars) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "filters use | select stars",
- eventLabel: stars,
- event: "SRP | filtersStars"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackFilterPrice(page, minPrice, maxPrice) {
- try {
- var priceRange = minPrice + "-" + maxPrice;
- utag.link({
- eventCategory: page,
- eventAction: "filters use | select price range",
- eventLabel: priceRange,
- event: "SRP | filtersPrice"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackFilterServices(page, service) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "filters use | select services",
- eventLabel: service,
- event: "SRP | filterServices"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackFilterBrand(page, brand) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "filters use | select brand",
- eventLabel: brand,
- event: "SRP | filterBrand"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackFilterNearTo(page, nearTo) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "filters use | select near to",
- eventLabel: nearTo,
- event: "SRP | filterNext"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackChangeOrder(page, orderBy) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "order by",
- eventLabel: orderBy,
- event: "SRP | order"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackHotelPageCheckAvail(page, name, startDate, endDate, nrooms, nadults, nchild) {
- try {
- var nights = calculateNumNights(startDate, endDate);
- utag.link({
- eventCategory: page,
- eventAction: "search",
- eventLabel: createLabelSearchData(name, startDate, endDate, nrooms, nadults, nchild),
- eventValue: nights,
- event: "PDP | search"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackHotelPageWeather(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "see weather prediction",
- event: "PDP | weather"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackHotelPageAll(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "see all hotels in destination",
- event: "PDP | all"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceComercial(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "contact comercial team",
- event: "mice | comercial"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceNewsletter(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "sign up newsletter",
- event: "mice | newsletter"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceRequestQuoteBuscador(page, name, nrooms) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "request a quote | header",
- eventLabel: createLabelMiceSearchDataHeader(name, nrooms),
- event: "mice | search results"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceFilterStars(page, stars) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "filters use | select stars",
- eventLabel: stars,
- event: "mice | search | filtersStars"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceFilterServices(page, service) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "filters use | select services",
- eventLabel: service,
- event: "mice | search | filterServices"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceFilterBrand(page, brand) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "filters use | select brand",
- eventLabel: brand,
- event: "mice | search | filterBrand"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceFilterNearTo(page, nearTo) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "filters use | select near to",
- eventLabel: nearTo,
- event: "mice | search | filterNext"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceSalones(page, minSalones, maxSalones) {
- try {
- var salones = minSalones + "-" + maxSalones;
- utag.link({
- eventCategory: page,
- eventAction: "filters use | select meeting rooms",
- eventLabel: salones,
- event: "mice | search | filterMeetingRooms"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceRooms(page, minRooms, maxRooms) {
- try {
- var rooms = minRooms + "-" + maxRooms;
- utag.link({
- eventCategory: page,
- eventAction: "filters use | select rooms",
- eventLabel: rooms,
- event: "mice | search | filterRooms"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceCapacidad(page, minCap, maxCap) {
- try {
- var cap = minCap + "-" + maxCap;
- utag.link({
- eventCategory: page,
- eventAction: "filters use | select max capacity",
- eventLabel: cap,
- event: "mice | search | filterCapacity"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackMiceChangeOrder(page, orderBy) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "order by",
- eventLabel: orderBy,
- event: "mice | search | order"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackSelectHotelMice(page, name) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "select hotel",
- eventLabel: name,
- event: "mice | search | selecthotel"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackViewHotelMice(page, name) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "view hotel page",
- eventLabel: name,
- event: "mice | search | view hotel"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackAdvanceSearch(page, name, startDate, endDate, nrooms, nadults, nchild) {
- try {
- var nights = "";
- if (startDate != undefined && endDate != undefined) {
- nights = calculateNumNights(startDate, endDate);
- }
- utag.link({
- eventCategory: page,
- eventAction: "advanced search",
- eventLabel: createLabelSearchData(name, startDate, endDate, nrooms, nadults, nchild),
- eventValue: nights,
- event: "advsearch"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackCallBook(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "call to book",
- event: "call | book"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackCancel(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "cancel booking",
- event: "mybookings"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackModify(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "modify booking",
- event: "mybookings"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackConfirm(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "confirm booking",
- event: "mybookings"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackChat(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "chat online",
- event: "chat"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackCalendarSearch(page, name, startDate, endDate) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "book",
- eventLabel: createLabelCalendar(name, startDate, endDate),
- event: "calendar | check availability"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackTripAdvisor(page, hotel) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "read Tripadvisor reviews",
- eventLabel: hotel,
- event: "PDP | ta"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackConfirmationOtraReserva(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "book another stay",
- event: "mybookings"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function formAbandon(form, campo) {
- try {
- utag.link({
- eventCategory: form,
- eventAction: "form analysys abandon",
- eventLabel: campo,
- event: "form"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function formSuccess(form) {
- try {
- utag.link({
- eventCategory: form,
- eventAction: "form analysys success",
- event: "form"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function formError(form, campo) {
- try {
- utag.link({
- eventCategory: form,
- eventAction: "form analysys error",
- eventLabel: campo,
- event: "form"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function createLabelSearchData(name, startDate, endDate, nrooms, nadults, nchild) {
- var eventLabelTrack = name + "|" + startDate + "-" + endDate + "|" + nrooms + "|" + nadults + "|" + nchild;
- return eventLabelTrack;
- }
- function createLabelHotelSearchData(hotelsearch, checkin, checkout) {
- var eventLabelTrack = hotelsearch + "|" + checkin + "|" + checkout;
- return eventLabelTrack;
- }
- function createLabelMiceSearchDataHeader(name, nrooms) {
- var eventLabelTrack = "";
- name.each(function(hotel) {
- eventLabelTrack += $(this).attr("id") + "|" + nrooms + ",";
- });
- eventLabelTrack = eventLabelTrack.substring(0, eventLabelTrack.length - 1);
- return eventLabelTrack;
- }
- function createLabelMiceSearchData(name, nrooms, nasistentes, nsalones, eventType) {
- var eventLabelTrack = name + "|" + nrooms + "|" + nasistentes + "|" + nsalones + "|" + eventType;
- return eventLabelTrack;
- }
- function createLabelMiceSearchDataQuote(name, nrooms) {
- var eventLabelTrack = name + "|" + nrooms;
- return eventLabelTrack;
- }
- function createLabelRoomData(name, roomType, startDate, endDate, nrooms, nadults, nchild) {
- var eventLabelTrack = name + "|" + roomType + "|" + startDate + "-" + endDate + "|" + nrooms + "|" + nadults + "|" + nchild;
- return eventLabelTrack;
- }
- function createLabelBook(name, startDate, endDate, nrooms, nadults, nchild, rate) {
- var eventLabelTrack = name + "|" + startDate + "-" + endDate + "|" + nrooms + "|" + nadults + "|" + nchild + "|" + rate;
- return eventLabelTrack;
- }
- function createLabelCalendar(name, startDate, endDate) {
- var eventLabelTrack = name + "|" + startDate + "-" + endDate;
- return eventLabelTrack;
- }
- function calculateNumNights(start, end) {
- var dateIni = $.datepicker.parseDate("dd/mm/yy", start);
- var dateFin = $.datepicker.parseDate("dd/mm/yy", end);
- var diffDays = Math.floor((dateFin - dateIni) / 1e3 / 60 / 60 / 24);
- return diffDays;
- }
- var formsAnalysys = [ "flexiblePaymentForm", "flexiblePaymentPersonalForm", "flexiblePaymentRoomForm", "flexiblePaymentGarantizaForm", "prepaymentPersonalForm", "prepaymentRoomForm", "prepaymentPagoForm", "prepaymentFacturaForm", "prepaymentForm", "loginRewardsForm", "rewardsForm", "newsletterSubscribeForm", "loginb2tForm", "loginb2bForm", "b2bForm", "b2tForm", "miceOrganizeForm", "micePersonalizeForm", "signupRewardsForm", "homeForm" ];
- function trackPromoClick(page, promoId, promoName, promoCreative, promoPosition) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "promotion click",
- ecommerce_action: "promo_click",
- promotions_id: [ promoId ],
- promotions_name: [ promoName ],
- promotions_creative: [ promoCreative ],
- promotions_position: [ promoPosition ]
- });
- } catch (err) {
- console.log(err);
- utagError = err;
- }
- }
- function trackVirtualTourClick(page, hotel) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "virtual tour",
- eventLabel: hotel
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackTravelGuideAccede(page, guideName) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "accede to guides",
- eventLabel: guideName
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackTravelGuideAccedeFooter(page, guideName) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "accede to guides footer",
- eventLabel: guideName
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackTravelGuideBookNow(hotel) {
- try {
- utag.link({
- eventCategory: "travel guides",
- eventAction: "click in book now",
- eventLabel: hotel
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackTravelGuideSearch(page, name, startDate, endDate, nrooms, nadults, nchild) {
- try {
- var nights = calculateNumNights(startDate, endDate);
- utag.link({
- eventCategory: page,
- eventAction: "Search from guides",
- eventLabel: createLabelSearchData(name, startDate, endDate, nrooms, nadults, nchild),
- eventValue: nights,
- event: "Guides | search"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackTripAdvisorLanding(page, hotel) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "read Tripadvisor reviews",
- eventLabel: hotel,
- event: "SRP | ta"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function viewHotelGallery(page, hotel) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "view hotel gallery",
- eventLabel: hotel,
- event: "SRP | gallery"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function viewHotelsInMap(page, destination) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "view hotels in map",
- eventLabel: destination,
- event: "SRP | map"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function createLabelClickShare(name, socialName) {
- var eventLabelTrack = name + "|" + socialName;
- return eventLabelTrack;
- }
- function trackClickShare(page, name, socialName) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "share social",
- eventLabel: createLabelClickShare(name, socialName),
- event: "clickShare"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackCloseFollowUs(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "close follow us",
- event: "closeFollowUs"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackFollowUs(page, destination) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "follow us",
- eventLabel: destination,
- event: "followUs"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackSuscribirseFooter(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "subs Footer",
- event: "suscribirseFooter"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackSuscribirseModal(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "subs Modal",
- event: "suscribirseModal"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackClickDownload(page, name) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "click download",
- eventLabel: name,
- event: "clickDownload"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickHomePrintCard(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR printcard",
- eventLabel: "n/a",
- event: "home | printcard"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickHomePassBook(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR passbook",
- eventLabel: "n/a",
- event: "home | passbook"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickAppUp(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR app up",
- eventLabel: "n/a",
- event: "app"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickAppLeft(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR app left",
- eventLabel: "n/a",
- event: "app"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickAddCoholder(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR add a co holder",
- eventLabel: "n/a",
- event: "co holder"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickGoTransfer(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR go to transfer points",
- eventLabel: "n/a",
- event: "points | transfer"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickGoDonate(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR go to donate points",
- eventLabel: "n/a",
- event: "points | donate"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickTransferPoints(page, party, mail, points) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR transfer points",
- eventLabel: party + "|" + mail,
- eventValue: points,
- event: "points | transfer"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickDonatePoints(page, organization, points) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR donate points",
- eventLabel: organization,
- eventValue: points,
- event: "points | donate"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickSocial(page, social) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR social media",
- eventLabel: social,
- eventValue: "n/a",
- event: "profile | social media"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickModify(page, hotelId, localizer) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR modify",
- eventLabel: hotelId + "|" + localizer,
- eventValue: "n/a",
- event: "modify"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickReadTripAdvisor(page, hotelId) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR read Tripadvisor reviews",
- eventLabel: hotelId,
- eventValue: "n/a",
- event: "bookigns | TripAdvisor"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickRepeatStay(page, hotelId, localizer) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR repeat stay",
- eventLabel: hotelId + "|" + localizer,
- eventValue: "n/a",
- event: "bookigns | repeat stay"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickFilterFaq(page, filterUsed) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR filter FAQs",
- eventLabel: filterUsed,
- eventValue: "n/a",
- event: "customer care"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickContactUsLeft(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR contact us left",
- eventLabel: "n/a",
- eventValue: "n/a",
- event: "contact"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackRWClickMissinPoints(page) {
- try {
- utag.link({
- eventCategory: page,
- eventAction: "NHR missing points",
- eventLabel: "n/a",
- eventValue: "n/a",
- event: "points | missing"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function trackLandingLazyload(data) {
- try {
- if (data) {
- utag.view({
- busqHSinDispo: data.busqHSinDispo,
- busqListado: data.busqListado,
- busqNumResult: data.busqNumResult,
- busqSinDispo: data.busqSinDispo,
- products_id: data.products_id,
- products_list: data.products_list,
- products_position: data.products_position,
- products_price: data.products_price,
- products_quantity: data.products_quantity,
- search: data.search
- });
- }
- } catch (err) {
- utagError = err;
- }
- }
- function trackLogin(eventCategory, eventLabel, eventAction) {
- try {
- utag.link({
- eventCategory: eventCategory,
- eventAction: eventAction,
- eventLabel: eventLabel,
- event: "event"
- });
- } catch (err) {
- utagError = err;
- }
- }
- function sendUtagData() {
- (function(a, b, c, d) {
- a = "//tags.tiqcdn.com/utag/nh-hoteles/es-main-2014/prod/utag.js";
- b = document;
- c = "script";
- d = b.createElement(c);
- d.src = a;
- d.type = "text/java" + c;
- d.async = true;
- a = b.getElementsByTagName(c)[0];
- a.parentNode.insertBefore(d, a);
- })();
- }
- $(document).ready(function() {
- TrackForms.init();
- $("#languageLinks >.dropdown-menu >li").click(function() {
- trackChangeLanguage(page_section, $(this).text().trim());
- });
- $(".listHotelsDisplay >>.hotelItem >>> .title > a").click(function() {
- var price;
- if ($(this).parents(".hotelItem").find(".price-night").length != 0) price = $(this).parents(".hotelItem").find(".price-night >> .priceChange").text(); else price = $(this).parents(".hotelItem").find(".total-price >> .priceChange").text();
- var hotelName = $(this).parents(".hotelItem").find('[name="hotelId"]').val();
- var hotelPosition = $(this).parents(".hotelItem").find(".labels.nhrec").text();
- trackViewHotelPage(page_section, hotelName, price, hotelPosition);
- });
- $(".suscribe").click(function() {
- trackSignupNewsletter(page_section);
- });
- $(".nh-rewards >.btn-xs").click(function() {
- trackSignupRewards(page_section);
- });
- $("#normalRate").find(".btn-xs").click(function() {
- var info = $(this).parents("tr");
- var adults = parseInt(info.find('[name = "nadults1"]').val());
- var child = parseInt(info.find('[name = "nchilds1"]').val());
- var rooms = 2;
- while (info.find('[name = "nadults' + rooms + '"]').val() != "") {
- adults += parseInt(info.find('[name = "nadults' + rooms + '"]').val());
- child += parseInt(info.find('[name = "nchilds' + rooms + '"]').val());
- if (rooms > 5) break;
- rooms += 1;
- }
- trackSelectRoom(page_section, info.find('[name = "hotelId"]').val(), info.find('[name = "roomCategoryCode"]').val(), info.find('[name = "fini"]').val(), info.find('[name = "fout"]').val(), rooms - 1, adults, child, info.find('[name = "ratePriceCode"]').val());
- });
- $("#rewardsRate").find(".btn-xs").click(function() {
- var info = $(this).parents("tr");
- var adults = parseInt(info.find('[name = "nadults1"]').val());
- var child = parseInt(info.find('[name = "nchilds1"]').val());
- var rooms = 2;
- while (info.find('[name = "nadults' + rooms + '"]').val() != "") {
- adults += parseInt(info.find('[name = "nadults' + rooms + '"]').val());
- child += parseInt(info.find('[name = "nchilds' + rooms + '"]').val());
- if (rooms > 5) break;
- rooms += 1;
- }
- trackSelectRoomRewards(page_section, info.find('[name = "hotelId"]').val(), info.find('[name = "roomCategoryCode"]').val(), info.find('[name = "fini"]').val(), info.find('[name = "fout"]').val(), rooms - 1, adults, child, info.find('[name = "ratePriceCode"]').val());
- });
- $("#liRewardsRate").click(function() {
- trackShowRewardsRate(page_section);
- });
- $("#liPromotionsRate").click(function() {
- trackShowPackageRate(page_section);
- });
- $("#promotionsRate").find(".btn-xs").click(function() {
- var info = $(this).parents("tr");
- var adults = parseInt(info.find('[name = "nadults1"]').val());
- var child = parseInt(info.find('[name = "nchilds1"]').val());
- var rooms = 2;
- while (info.find('[name = "nadults' + rooms + '"]').val() != "") {
- adults += parseInt(info.find('[name = "nadults' + rooms + '"]').val());
- child += parseInt(info.find('[name = "nchilds' + rooms + '"]').val());
- if (rooms > 5) break;
- rooms += 1;
- }
- trackSelectRoomRewards(page_section, info.find('[name = "hotelId"]').val(), info.find('[name = "roomCategoryCode"]').val(), info.find('[name = "fini"]').val(), info.find('[name = "fout"]').val(), rooms - 1, adults, child, info.find('[name = "ratePriceCode"]').val());
- });
- $("form[action='/booking/meetings/hotelpagemice']").children("input[type='submit']").click(function() {
- var nasistentes = $("[name = 'nasistentes']").val();
- var fieldSearch = $('[name = "backCode"]').val();
- var where = "";
- if ($(this).parents(".buttons").length == 0) where = "top"; else where = "down";
- trackMiceRequestQuote(page_section, where, fieldSearch, nasistentes);
- });
- $("div[class='card travel']").children("form").children("div[class='intermedio']").children("div[class='pull-right']").children("a").click(function() {
- var tabName = $("#tablist").children(".activa").attr("data-type");
- var offerName = $(this).parent().parent().siblings("h3").text();
- var id = $(this).parent().children(".idpromo").val();
- var position = $(this).parents(".card").index() / 2;
- trackDealsBook(page_section, tabName, offerName, id, position);
- });
- $("div[class='card advance'] > div[class='buttons bottom'] > div[class='pull-right']").click(function() {
- var tabName = "GLOBAL";
- var offerName = $(this).parent().siblings("h3").text().trim();
- var id = $(this).parent().children(".idpromo");
- var position = $(this).parents(".card").index() + 1;
- trackDealsBook(page_section, tabName, offerName, id, position);
- });
- $("#weather >a").click(function() {
- trackHotelPageWeather(page_section);
- });
- $("#seeAll").click(function() {
- trackHotelPageAll(page_section);
- });
- $(".restaurants >>.buttons").eq(0).click(function() {
- trackMiceComercial(page_section);
- });
- $(".latestSearch > button").click(function() {
- trackMiceNewsletter(page_section);
- });
- $(".featured-result >>.row >> button").click(function() {
- var info = $(".hotelItem >>> tbody").find("tr").eq(1);
- var adults = parseInt(info.find('[name = "nadults1"]').val());
- var child = parseInt(info.find('[name = "nchilds1"]').val());
- var rooms = 2;
- while (info.find('[name = "nadults' + rooms + '"]').val() != "") {
- adults += parseInt(info.find('[name = "nadults' + rooms + '"]').val());
- child += parseInt(info.find('[name = "nchilds' + rooms + '"]').val());
- rooms += 1;
- }
- trackBookRoom(page_section, info.find('[name = "hotelId"]').val(), info.find('[name = "roomCategoryCode"]').val(), info.find('[name = "fini"]').val(), info.find('[name = "fout"]').val(), rooms - 1, adults, child, info.find('[name = "ratePriceCode"]').val());
- });
- $("#anotherBook").click(function() {
- trackConfirmationOtraReserva(page_section);
- });
- $("footer a#guides").click(function() {
- trackTravelGuideAccedeFooter(page_section, "n/a");
- });
- });
- var TrackForms = function() {
- var formulary;
- var lblFilledInput = "No data entered";
- var trackedForms = {};
- var init = function() {
- formulary = $("form:not(.no-track)");
- events();
- };
- var events = function() {
- formulary.find("input,textarea,select").on("keydown change", function() {
- var $f = $(this).parents("form");
- var name = $f.attr("name") || $f.attr("id");
- if (name) {
- trackedForms[name] = true;
- }
- });
- formulary.on("submit", function() {
- var name = $(this).attr("name") || $(this).attr("id");
- if (name) {
- trackedForms[name] = false;
- }
- });
- window.onbeforeunload = function() {
- console.log("eventLeave onbeforeunload:", trackedForms);
- if (!$.isEmptyObject(trackedForms)) {
- callTrackFunctions();
- }
- };
- };
- var callTrackFunctions = function() {
- $.each(trackedForms, function(formName, eventLeave) {
- if (formName && eventLeave) {
- var formElement = $('form[name="' + formName + '"]').length ? $('form[name="' + formName + '"]') : $("form#" + formName);
- var formLastInput = formElement.find('input[type!="hidden"][type!="submit"][type!="checkbox"]').filter(function() {
- return $(this).val() != "";
- });
- var formLastInputId = formLastInput.last().attr("id") || lblFilledInput;
- console.log("formAbandon: ", formName, formLastInputId);
- formAbandon(formName, formLastInputId);
- }
- });
- };
- var setTrackedForms = function(formName, value) {
- if (formName && value) {
- trackedForms[formName] = value;
- }
- };
- return {
- init: init,
- setTrackedForms: setTrackedForms,
- trackedForms: trackedForms
- };
- }();
- function eventoMiceRequestQuotePopUp() {
- var hotel = $(".hotelSeleccionadoSpan");
- var nasistentes = $("[name = 'nasistentes']").val();
- trackMiceRequestQuotePopup(page_section, hotel, nasistentes);
- }
- function buscarHotelPage(hotel) {
- var adults = 0;
- var children = 0;
- var rooms = parseInt($("#selectorControlRooms").val());
- for (var n = 1; n <= rooms; n++) {
- adults += parseInt($('[name = "nadults' + n + '"]').val());
- children += parseInt($('[name = "nchilds' + n + '"]').val());
- }
- trackHotelPageCheckAvail(page_section, hotel, $('[name = "fini"]').val(), $('[name = "fout"]').val(), rooms, adults, children);
- }
- function reservarHotelRP(hotel, price, position) {
- trackSelectHotel(page_section, hotel, $("#ida").val(), $("#fin").val(), price, position, $("#habs").val());
- }
- function filtroNearTo(orig) {
- var nearTo = $("#filtroPOI option:selected").text();
- if (orig == "landing") trackFilterNearTo(page_section, nearTo); else if (orig == "mice") trackMiceFilterNearTo(page_section, nearTo);
- }
- var actualCurrency;
- var Currency = function() {
- var currencyJSON;
- var init = function() {
- var currencySel = $("#divisa");
- var currencySel2 = $("#divisa2");
- var currencyInputHidden = $(".divisaInput");
- selectedDivisa = selectedDivisa.split(",")[0];
- selectedDivisa = selectedDivisa != "," && selectedDivisa != null ? selectedDivisa : "";
- getCurrencyData(function() {
- if (selectedDivisa != "") {
- updateDivisaForForm(selectedDivisa);
- divisaAnterior2 = selectedDivisa;
- } else {
- updateDivisaForForm(actualDivisa);
- divisaAnterior2 = actualDivisa;
- currencyInputHidden.val(selectedDivisa || "");
- }
- });
- };
- var getCurrencyData = function(fn) {
- $.ajax({
- url: "/rest/jsonCurrency",
- dataType: "json",
- async: false,
- cache: true,
- success: function(data) {
- currencyJSON = data;
- },
- error: function(data) {}
- });
- if (typeof fn == "function") {
- fn();
- }
- };
- var changeCurrency = function(precio, currencyIn, currencyOut) {
- var cambio = importeCambioFromJson(currencyIn, currencyOut);
- precio = precio * cambio;
- return precio;
- };
- var importeCambioFromJson = function(currencyIn, currencyOut) {
- var cambio;
- if (currencyJSON) {
- $.each(currencyJSON.currencies, function(key, val) {
- if (currencyJSON.currencies[key].cur_origin == currencyIn) {
- $.each(currencyJSON.currencies[key].conversions, function(key2, val2) {
- if (currencyJSON.currencies[key].conversions[key2].cur_dest == currencyOut) {
- cambio = currencyJSON.currencies[key].conversions[key2].rate;
- }
- });
- }
- });
- }
- return cambio;
- };
- var cambiarDivisa = function(id) {
- var to = $("#" + id).val();
- if (id == "divisa" || id == "divisa2") {
- var tasa = 0;
- $(".divisaInput").val(to);
- if (to != actualCurrency) {
- tasa = parseFloat(importeCambioFromJson(actualCurrency, to));
- $(".currencyChange").text(to);
- $(".priceChange").each(function() {
- var precio = parseFloat($(this).siblings(".originalPrice").text());
- precio = precio * tasa;
- precio = (Math.round(precio * 100) / 100).toFixed(2);
- $(this).text(precio);
- if ($(this).parents(".hotelItem").length > 0) {
- if (precio.length >= 7) {
- $(this).parents(".dataHotel").removeClass("col-md-2").addClass("col-md-3");
- $(this).parents(".hotelItem").find(".carousel.slide.hotel").removeClass("col-md-10").addClass("col-md-9");
- } else if (precio.length < 7) {
- $(this).parents(".dataHotel").removeClass("col-md-3").addClass("col-md-2");
- $(this).parents(".hotelItem").find(".carousel.slide.hotel").removeClass("col-md-9").addClass("col-md-10");
- }
- }
- });
- treatMoreData(tasa, tasa);
- } else {
- URL = buildQuery("1", divisaAnterior, actualCurrency);
- tasa = parseFloat(importeCambioFromJson(divisaAnterior, actualCurrency));
- $(".currencyChange").text(actualCurrency);
- $(".priceChange").each(function() {
- var precio = $(this).siblings(".originalPrice").text();
- $(this).text(precio);
- if ($(this).parents(".hotelItem").length > 0) {
- if (precio.length >= 7) {
- $(this).parents(".dataHotel").removeClass("col-md-2").addClass("col-md-3");
- $(this).parents(".hotelItem").find(".carousel.slide.hotel").removeClass("col-md-10").addClass("col-md-9");
- } else if (precio.length < 7) {
- $(this).parents(".dataHotel").removeClass("col-md-3").addClass("col-md-2");
- $(this).parents(".hotelItem").find(".carousel.slide.hotel").removeClass("col-md-9").addClass("col-md-10");
- }
- }
- });
- treatMoreData(1, tasa);
- }
- divisaAnterior = to;
- } else {
- return;
- }
- if ($("body").hasClass("page-landing") || $("#mapGoogleMob").length != 0 && markersMob.length > 0) {
- setDivisaOnMap();
- }
- };
- var setDivisaOnMap = function() {
- if (mapMob) {
- to = $(".divisaInput:first").val();
- $(".info-result-room").each(function() {
- var $this = $(this);
- var price_change = $this.find(".priceChange");
- var price_total = $this.find(".total-price .priceChange");
- var price_night = $this.find(".price-night .priceChange");
- var num = $this.find(".nhrec").text();
- if (price_total.length != 0) {
- var content_window = markersMob[parseInt(num)].infoWindows.content_;
- re1 = $(content_window).find(".total-price .pull-right").html();
- re2 = price_total.html();
- var output = content_window.replace(re1, re2 + "<sup>" + to + "</sup>");
- if (price_night.length != 0) {
- re1 = $(output).find(".night-price .pull-right").html();
- re2 = price_night.html();
- var output = output.replace(re1, re2 + "<sup>" + to + "</sup>");
- }
- markersMob[parseInt(num)].infoWindows.setContent(output);
- }
- });
- }
- };
- var treatMoreData = function(tasa, tasaControlPoint) {
- var rangoPrecio = new Array(2);
- var controlPoints = new Array(2);
- controlPoints[0] = 0;
- controlPoints[1] = 0;
- rangoPrecio[0] = 99999;
- rangoPrecio[1] = -1;
- if ($("#range2").length > 0 || $("#rangeMob").length > 0) {
- var hoteles = $("div.hotelItem.hotelDispo, div.hotelItem.hotelNearby");
- hoteles.each(function() {
- var precio = parseFloat($(this).find(".hotel-total-price").text());
- if (!isNaN(precio) && rangoPrecio[0] >= precio) rangoPrecio[0] = precio;
- if (!isNaN(precio) && rangoPrecio[1] <= precio) rangoPrecio[1] = precio;
- });
- if (rangoPrecio[0] == 99999 && rangoPrecio[1] == -1) {
- rangoPrecio[0] = 0;
- rangoPrecio[1] = 1;
- }
- }
- if ($("#range2").length > 0) {
- var porcentage = $("#range2").slider("prc").split(";");
- controlPoints = $("#range2").slider("value").split(";");
- controlPoints[0] = tasaControlPoint * controlPoints[0];
- controlPoints[1] = tasaControlPoint * controlPoints[1];
- updateSlider("#range2", rangoPrecio[0], controlPoints[0], controlPoints[1], rangoPrecio[1]);
- $("#range2").slider("prc", porcentage[0], porcentage[1]);
- }
- if ($("#rangeMob").length > 0) {
- var porcentage = $("#rangeMob").slider("prc").split(";");
- controlPoints = $("#rangeMob").slider("value").split(";");
- controlPoints[0] = tasaControlPoint * controlPoints[0];
- controlPoints[0] = (Math.round(controlPoints[0] * 100) / 100).toFixed(2);
- controlPoints[1] = tasaControlPoint * controlPoints[1];
- controlPoints[1] = (Math.round(controlPoints[1] * 100) / 100).toFixed(2);
- updateSlider("#rangeMob", rangoPrecio[0], controlPoints[0], controlPoints[1], rangoPrecio[1]);
- $("#rangeMob").slider("prc", porcentage[0], porcentage[1]);
- }
- if ($("#rangeMob").length > 0 || $("#range2").length > 0) {
- filtroPrecioActi[0] = controlPoints[0];
- filtroPrecioActi[1] = controlPoints[1];
- }
- };
- var updateSlider = function(sliderID, ini, p1, p2, fin) {
- var slideParent = $(sliderID).parent();
- var inputRange2 = slideParent.find("h3").prop("outerHTML") + $(sliderID).prop("outerHTML") + slideParent.find("span.small").prop("outerHTML");
- slideParent.text("");
- slideParent.append(inputRange2);
- if (ini == fin) ini = 1;
- $(sliderID).val("" + Math.floor(ini) + ";" + Math.ceil(fin) + "");
- $(sliderID).attr("value", "" + Math.floor(ini) + ";" + Math.ceil(fin) + "");
- $(sliderID).after("<scr" + "ipt>" + ' $("' + sliderID + '").slider({ from:' + Math.floor(ini) + ", to: " + Math.ceil(fin) + ', step: 1, round: 1, dimension: " ' + $(".currencyChange").first().text() + '", skin: "plastic", callback: function( value ){ var min =this.o.pointers[0].value.origin; var max =this.o.pointers[1].value.origin; filterByPrice(min, max ); } }); </scr' + "ipt>");
- $(sliderID).slider("value", p1, p2);
- };
- var buildQuery = function(amount, from, to) {
- var str = "https://rate-exchange.appspot.com/currency?from=" + from + "&to=" + to + "&q=" + amount;
- return str;
- };
- var cambiarInfoTags = function(selectedCurrency, actualCurrency) {
- cloneOriginalPrices();
- $(".divisaInput").val(selectedCurrency);
- var tasa = 1;
- if (actualCurrency && selectedCurrency) {
- tasa = parseFloat(importeCambioFromJson(actualCurrency, selectedCurrency));
- }
- $(".currencyChange").text(selectedCurrency);
- $(".priceChange").each(function() {
- var precio = parseFloat($(this).siblings(".originalPrice").text());
- precio = precio * tasa;
- precio = (Math.round(precio * 100) / 100).toFixed(2);
- $(this).text(precio);
- });
- };
- var updateDivisaForForm = function(divisa) {
- if (divisa == "") {
- divisa = "EUR";
- divisaAnterior = divisa;
- actualCurrency = divisa;
- } else {
- actualCurrency = "";
- if ($(".currencyChange").length > 1) actualCurrency = $(".currencyChange").first().text(); else actualCurrency = $(".currencyChange").text();
- actualCurrency = $.trim(actualCurrency);
- if (actualCurrency == "") actualCurrency = "EUR";
- divisaAnterior = actualCurrency;
- }
- divisaAnterior2 = actualCurrency;
- cloneOriginalPrices();
- $("#divisa").val(divisa).change();
- $("#divisa2").val(divisa).change();
- $(".divisaInput").val($("#divisa").val());
- cambiarDivisa("divisa");
- };
- var cloneOriginalPrices = function() {
- $(".hidden.originalPrice").remove();
- $(".priceChange").each(function() {
- var precio = $(this).text();
- $(this).after('<span class="hidden originalPrice">' + precio + "</span>");
- });
- };
- var spaSelectDivisa = function() {
- actualCurrency = "";
- if ($(".currencyChange").length > 1) actualCurrency = $(".currencyChange").first().text(); else actualCurrency = $(".currencyChange").text();
- actualCurrency = $.trim(actualCurrency);
- if (actualCurrency == "") actualCurrency = "EUR";
- divisaAnterior = actualCurrency;
- cloneOriginalPrices();
- $("#divisa").val(actualCurrency).change();
- $(".divisaInput").val($("#divisa").val());
- };
- return {
- init: init,
- updateDivisaForForm: updateDivisaForForm,
- cambiarDivisa: cambiarDivisa,
- setDivisaOnMap: setDivisaOnMap
- };
- }();
- $(function() {
- if ($("#divisa").length > 0 || $("#divisa2").length > 0) {}
- });
- function cambiarDivisa(id) {
- Currency.cambiarDivisa(id);
- }
- $(document).on("click", ".fancybox-item.fancybox-close", function(event) {
- if ($("#divisa").length > 0) {
- parent.$("#divisa").addClass("inicioPagina");
- parent.$("#divisa").val(parent.divisaAnterior2).change();
- parent.$("#divisa2").addClass("inicioPagina");
- parent.$("#divisa2").val(parent.divisaAnterior2).change();
- }
- });
- var pois = {};
- var filterPois = {};
- var isCountry = false;
- var mapMob;
- poiMarkersMob = new Array();
- markersMob = new Array();
- var clicado = false;
- var filtroEstrellasActi = {};
- var filtroServiciosActi = {};
- var filtroMarcaActi = {};
- var filtroTypoMarcaActi = {};
- var filtroPrecioActi = new Array(2);
- var filtroDistMonuActi = {
- poi: "",
- distance: 0
- };
- var ratingsDictionary = {
- stars5: 5,
- stars4: 4,
- stars3: 3,
- stars2: 2,
- stars1: 1
- };
- var numHotelByPrice;
- var mostrarNodispo = true;
- var isPageLanding = true;
- var isPageLandingWithoutDates = false;
- var isResultPage = false;
- var tituloHotelesNodispo;
- var tituloHotelesNearby;
- var tituloHotelesNearbyNoDispo;
- var servicesNotToFilter = {
- "icon-rooms": true
- };
- var searchString;
- var value;
- var auxStructure;
- var contadorToShow;
- var BuildFilters = function() {
- var listResults = $("#newResults");
- var init = function() {
- buildStars();
- if (!LandingPage.isNoAvailabilityPage) {
- buildPrice();
- }
- buildServices();
- buildPois();
- buildBrand();
- hideLoadingElements();
- filterEvents();
- initializeHelpersFilters();
- showNumHotelsSidebar();
- updateNumHotelsFiltered();
- handleTitleResults();
- };
- var buildStars = function() {
- var ratingsDictionary = {
- stars5: false,
- stars4: false,
- stars3: false,
- stars2: false,
- stars1: false
- };
- var stars = false;
- ratingsDictionary["stars5"] = $(".hotelItem .stars5").length > 0 ? true : false;
- ratingsDictionary["stars4"] = $(".hotelItem .stars4").length > 0 ? true : false;
- ratingsDictionary["stars3"] = $(".hotelItem .stars3").length > 0 ? true : false;
- ratingsDictionary["stars2"] = $(".hotelItem .stars2").length > 0 ? true : false;
- ratingsDictionary["stars1"] = $(".hotelItem .stars1").length > 0 ? true : false;
- for (var key in ratingsDictionary) {
- if (ratingsDictionary[key]) {
- $("[class='filters']").find("div.starsHotel.firstlevelContent").find("ul").append('<li class="' + key + '"><input name="" type="checkbox" value="" onchange =" activa($(this).parent()), filterHotelsByStars(this)"><span class="totalHotels">2 Hoteles</span></li>');
- $("[class='filters mob']").find("div.starsHotel.firstlevelContent").find("ul").append('<li class="' + key + '"><input name="" type="checkbox" value="" onchange =" activa($(this).parent()), filterHotelsByStars(this)"><span class="totalHotels">2 Hoteles</span></li>');
- }
- }
- };
- var buildServices = function() {
- var servicioIsMain = {};
- var servicioNotMain = {};
- var servicioText = {};
- var aux = $("div.hotelItem");
- aux.each(function(index) {
- var listaServicios = $(this).find(".col-md-3.servicesHotel").children("ul").children("");
- listaServicios.each(function(index) {
- var stringArrayAux = $(this).children().attr("class").split(" ")[0];
- if (!servicesNotToFilter[stringArrayAux]) {
- if ($(this).hasClass("isMainService")) {
- servicioIsMain[stringArrayAux] = true;
- } else {
- servicioNotMain[stringArrayAux] = true;
- }
- servicioText[stringArrayAux] = $(this).text();
- }
- });
- });
- var cont = 0;
- for (var key in servicioIsMain) {
- if (cont < 6) {
- $("[class='filters']").find("div.services.firstlevelContent").find("ul").append('<li class="text-overflow" onClick="activa(this), filterHotelsByServices(this)"><span class="' + key + ' tooltip-icon" title="' + servicioText[key] + '"></span>' + servicioText[key] + "</li>");
- } else {
- $("[class='filters']").find("div.services.firstlevelContent").find("ul").append('<li class="notvisible oculto text-overflow" onClick="activa(this), filterHotelsByServices(this)"><span class="' + key + ' tooltip-icon" title="' + servicioText[key] + '"></span>' + servicioText[key] + "</li>");
- }
- $("[class='filters mob']").find("div.services.firstlevelContent").find("ul").append('<li class="text-overflow" onClick="activa(this), filterHotelsByServices(this)"><span class="' + key + '"></span>' + servicioText[key] + "</li>");
- cont++;
- }
- for (var key in servicioNotMain) {
- if (cont < 6) {
- $("[class='filters']").find("div.services.firstlevelContent").find("ul").append('<li class="text-overflow" onClick="activa(this), filterHotelsByServices(this)"><span class="' + key + ' tooltip-icon" title="' + servicioText[key] + '"></span>' + servicioText[key] + "</li>");
- } else {
- $("[class='filters']").find("div.services.firstlevelContent").find("ul").append('<li class="notvisible oculto text-overflow" onClick="activa(this), filterHotelsByServices(this)"><span class="' + key + ' tooltip-icon" title="' + servicioText[key] + '"></span>' + servicioText[key] + "</li>");
- }
- $("[class='filters mob']").find("div.services.firstlevelContent").find("ul").append('<li class="text-overflow" onClick="activa(this), filterHotelsByServices(this)"><span class="' + key + '"></span>' + servicioText[key] + "</li>");
- cont++;
- }
- if (cont <= 6) {
- $("[class='filters']").find("div.services.firstlevelContent").find("a").remove();
- }
- };
- var buildPois = function() {
- var rangoKm = new Array(2);
- rangoKm[0] = 999999;
- rangoKm[1] = -1;
- filterPois = getPoisToFilter();
- var numPois = 0;
- if (Object.keys) {
- numPois = Object.keys(filterPois).length;
- } else {
- for (var prop in filterPois) {
- if (filterPois.hasOwnProperty(prop)) numPois++;
- }
- }
- if (!lastSearch.isPOI) {
- if (numPois > 0) {
- $("#filtroPOI").append('<option class="empty">' + labelChooseOption + "</option>");
- $("#filtroPOIMob").append('<option class="empty">' + labelChooseOption + "</option>");
- $.map(filterPois, function(element, key) {
- $("#filtroPOI").append('<option class="' + key + '">' + element[0].description + "</option>");
- $("#filtroPOIMob").append('<option class="' + key + '">' + element[0].description + "</option>");
- });
- } else {
- $("#filtroPOI").append('<option class="empty">' + labelEmpty + "</option>");
- $("#filtroPOIMob").append('<option class="empty">' + labelEmpty + "</option>");
- $("#filtroPOI").prop("disabled", true);
- $("#filtroPOIMob").prop("disabled", true);
- }
- } else {
- $("#filtroPOI").append('<option class="' + pageData.keySearch + '">' + pageData.destinationName + "</option>");
- $("#filtroPOIMob").append('<option class="' + pageData.keySearch + '">' + pageData.destinationName + "</option>");
- $("#filtroPOI").prop("disabled", true);
- $("#filtroPOIMob").prop("disabled", true);
- }
- var aux = $("div.hotelItem");
- aux.each(function(index) {
- $(".hotelNearby, .hotelNearbyNoDispo").find("ul.POIS").empty();
- var hotelesNearby = $(".hotelNearby, .hotelNearbyNoDispo").find("ul.POIS");
- hotelesNearby.each(function() {
- var $hotel = $(this);
- var hotelClass = $.trim($(this).parents(".hotelItem").find(".hotelName").text().replace(/\ /g, "").toLowerCase());
- var hotelLat = $hotel.parents(".hotelItem").find(".coordenate .latitude").text();
- var hotelLong = $hotel.parents(".hotelItem").find(".coordenate .longitude").text();
- var distancia = 0;
- $.each(filterPois, function(poi, poi_values) {
- distancia = getDistanceBetweenCoords(hotelLat, hotelLong, poi_values[0].latitude, poi_values[0].longitude);
- var output_pois = "";
- $.each(poi_values[0], function(name, value) {
- output_pois += '<li class="' + name + '">' + value + "</li>";
- });
- var output = '<li class="' + poi + '">' + "<ul>" + '<li data-poiid="' + hotelClass + "-" + poi + '">' + distancia + " Km</li>" + output_pois + "</ul>" + "</li>";
- $hotel.append(output);
- });
- });
- var pois = $(this).find("ul.POIS").children("");
- if (lastSearch.isPOI) {
- pois = $("div.hotelItem").find("ul.POIS").find("li." + pageData.keySearch + "");
- pois.each(function() {
- var km = $(this).find("li").first().text().replace(",", ".");
- km = km.split(" ");
- km = parseFloat(km[0]);
- if (!isNaN(km) && rangoKm[0] >= km) rangoKm[0] = km;
- if (!isNaN(km) && rangoKm[1] <= km) rangoKm[1] = km;
- });
- } else {
- pois.each(function() {
- if ($(this).find("li").siblings(".toFilter").text().toLowerCase() == "yes") {
- var km = $(this).find("li").first().text().replace(",", ".");
- km = km.split(" ");
- km = parseFloat(km[0]);
- if (!isNaN(km) && rangoKm[0] >= km) rangoKm[0] = km;
- if (!isNaN(km) && rangoKm[1] <= km) rangoKm[1] = km;
- }
- });
- }
- });
- if (rangoKm[0] == 999999 && rangoKm[1] == -1) {
- rangoKm[0] = 0;
- rangoKm[1] = 1;
- }
- $("#range1").val("" + Math.ceil(parseFloat(rangoKm[1])) + "");
- $("#range1").attr("value", "" + Math.ceil(parseFloat(rangoKm[1])) + "");
- $("#range1").after("<scr" + 'ipt> jQuery("#range1").slider({ from: 0, to: ' + Math.ceil(parseFloat(rangoKm[1])) + ', step: 0.1, round: 1, dimension: "KM", skin: "plastic", callback: function( value ){ filterByPoi(this.o.pointers[0].value.origin); } }); </scr' + "ipt>");
- $("#rangeMob1").val("" + Math.ceil(parseFloat(rangoKm[1])) + "");
- $("#rangeMob1").attr("value", "" + Math.ceil(parseFloat(rangoKm[1])) + "");
- $("#rangeMob1").after("<scr" + 'ipt> jQuery("#rangeMob1").slider({ from: 0, to: ' + Math.ceil(parseFloat(rangoKm[1])) + ', step: 0.1, round: 1, dimension: "KM", skin: "plastic", callback: function( value ){ filterByPoi(this.o.pointers[0].value.origin); } }); </scr' + "ipt>");
- };
- var buildBrand = function() {
- var marcas = {};
- var aux = $("div.hotelItem");
- var listHotels = $(listResults).find(".hotelItem");
- $.each(listHotels, function(i, ele) {
- marcas[$(ele).attr("data-hotelmarca")] = true;
- });
- cont = 0;
- for (var key in marcas) {
- if (cont < 6) {
- $("[class='filters']").find("div.hotelGroup.firstlevelContent").find("ul").append('<li><input name="" type="checkbox" value="" onchange="activa($(this).parent()), filterBrand(this)">' + key + ' <span class="result">4 hoteles</span></li>');
- } else {
- $("[class='filters']").find("div.hotelGroup.firstlevelContent").find("ul").append('<li class="notvisible oculto"><input name="" type="checkbox" value="" onchange="filterBrand(this)">' + key + '<span class="result">4 hoteles</span></li>');
- }
- $("[class='filters mob']").find("div.hotelGroup.firstlevelContent").find("ul").append('<li class="col-sm-6 col-xs-6"><input name="" type="checkbox" value="" onchange="activa($(this).parent()), filterBrand(this)">' + key + ' <span class="result">4 hoteles</span></li>');
- cont++;
- }
- if (cont < 5) {
- $("[class='filters']").find("div.hotelGroup.firstlevelContent").find("a").remove();
- }
- cont = 0;
- };
- var buildPrice = function() {
- var rangoPrecio = new Array(2);
- rangoPrecio[0] = 99999;
- rangoPrecio[1] = -1;
- var listHotels = $(listResults).find(".hotelItem");
- $.each(listHotels, function(i, ele) {
- var precio = parseFloat($(ele).find(".hotel-total-price").text());
- if (!isNaN(precio) && rangoPrecio[0] >= precio && precio != -1) {
- rangoPrecio[0] = precio;
- }
- if (!isNaN(precio) && rangoPrecio[1] <= precio && precio != -1) {
- rangoPrecio[1] = precio;
- }
- if (rangoPrecio[0] == 99999 && rangoPrecio[1] == -1) {
- rangoPrecio[0] = 0;
- rangoPrecio[1] = 1;
- }
- });
- if (rangoPrecio[0] == rangoPrecio[1]) {
- rangoPrecio[0] = 1;
- }
- $("#range2").val("" + Math.floor(rangoPrecio[0]) + ";" + Math.ceil(rangoPrecio[1]) + "");
- $("#range2").attr("value", "" + Math.floor(rangoPrecio[0]) + ";" + Math.ceil(rangoPrecio[1]) + "");
- $("#range2").after("<scr" + "ipt>" + ' $("#range2").slider({ from:' + Math.floor(rangoPrecio[0]) + ", to: " + Math.ceil(rangoPrecio[1]) + ', step: 1, round: 1, dimension: " ' + $.trim($(".currencyChange").first().text()) + '", skin: "plastic", callback: function( value ){ var min =this.o.pointers[0].value.origin; var max =this.o.pointers[1].value.origin; filterByPrice(min, max ); } }); </scr' + "ipt>");
- $("#rangeMob").val("" + Math.floor(rangoPrecio[0]) + ";" + Math.ceil(rangoPrecio[1]) + "");
- $("#rangeMob").attr("value", "" + Math.floor(rangoPrecio[0]) + ";" + Math.ceil(rangoPrecio[1]) + "");
- $("#rangeMob").after("<scr" + "ipt>" + ' $("#rangeMob").slider({ from:' + Math.floor(rangoPrecio[0]) + ", to: " + Math.ceil(rangoPrecio[1]) + ', step: 1, round: 1, dimension: " ' + $.trim($(".currencyChange").first().text()) + '", skin: "plastic", callback: function( value ){ var min =this.o.pointers[0].value.origin; var max =this.o.pointers[1].value.origin; filterByPrice(min, max ); } }); </scr' + "ipt>");
- $(".prices.firstlevelContent").fadeIn();
- };
- var filterEvents = function() {
- $(".showFilters a.filtersGlobalAux").on("click", function(e) {
- showFiltersAux(".filtersMob");
- });
- $("a.hideFiltersAux").on("click", function(e) {
- $(this).parent().parent().parent().hide();
- hideFiltersAux();
- });
- $("a.hideFilters").on("click", function(e) {
- $("body").css("overflow", "auto");
- });
- $(window).resize(function() {
- if ($("div.shortBy.mob").is(":visible") || $("div.filters.mob").is(":visible")) {
- $("body").css("overflow", "hidden");
- } else {
- $("body").css("overflow", "auto");
- }
- });
- $('.filtersMob [name="disponibilidadMob"], .filters [name="disponibilidad"]').on("click", function() {
- filterHotelsByDisponibilidad($(this).data("filter"));
- });
- $("#filtroPOIMob, #filtroPOI").on("change", function() {
- filterByPoi(-1, this);
- actualizarCampoPOIdeHotelItem();
- cambiarCampo();
- });
- if (lastSearch.isPOI) {
- $("#selectSort").val("distPoiAsc");
- $("#selectSortMob").val("distPoiAsc");
- $("#selectSort").change();
- $("#selectSortMob").change();
- cambiarCampo();
- if ($("div.hotelItem").length > 1) {
- $(".js-total-hotels").text($("div.hotelItem").length);
- $(".destinoBusqueda").html(" " + pageLabels.lblHotelsInPoi + " " + pageData.destino + ", " + pageData.pais);
- } else {
- $(".js-total-hotels").text($("div.hotelItem").length);
- $(".destinoBusqueda").html(" " + pageLabels.lblHotelInPoi + " " + pageData.destino + ", " + pageData.pais);
- }
- } else {
- $("#selectSort").selectpicker("refresh");
- $("#selectSortMob").selectpicker("refresh");
- var toHidePoiasc = $("#selectSort").find('option[value="distPoiAsc"]').text();
- var toHidePoides = $("#selectSort").find('option[value="distPoiDes"]').text();
- $('ul.inner li:contains("' + toHidePoiasc + '")').attr("style", "display:none!important");
- $('ul.inner li:contains("' + toHidePoides + '")').attr("style", "display:none!important");
- if ($("div.hotelItem").length > 1) {
- $(".js-total-hotels").text($("div.hotelItem").length);
- $(".destinoBusqueda").html(" " + pageLabels.lblHotelsInDestination + " " + pageData.destino + ", " + pageData.pais);
- } else {
- $(".js-total-hotels").text($("div.hotelItem").length);
- $(".destinoBusqueda").html(" " + pageLabels.lblHotelInDestination + " " + pageData.destino + ", " + pageData.pais);
- }
- }
- $(window).load(function() {
- if (pageData.filterStars) {
- var stars = pageData.filterStars.split(",");
- buildDynamicStars(stars);
- }
- if (pageData.filterServices) {
- var services = pageData.filterServices.split(",");
- buildDynamicServices(services);
- }
- });
- };
- var getPoisToFilter = function() {
- var pois = {};
- var poisToFilter;
- if (isPageLanding) {
- poisToFilter = $("div.hotelItem").find("ul.POIS>li").filter("li:contains('Yes'),li:contains('yes')");
- } else {
- poisToFilter = $("#hotelesNoDispo .hotelItem").find("ul.POIS>li").filter("li:contains('Yes'),li:contains('yes')");
- }
- poisToFilter.each(function() {
- if ($(this).find("li.toFilter").text() == "Yes" || $(this).find("li.toFilter").text() == "yes") {
- var poi = $(this).attr("class");
- var description = $(this).find("li.description").text();
- var latitude = $(this).find("li.latitude").text();
- var longitude = $(this).find("li.longitude").text();
- var typePOI = $(this).find("li.typePOI").text();
- var isCityCenter = $(this).find("li.isCityCenter").text();
- var toFilter = $(this).find("li.toFilter").text();
- pois[poi] = [ {
- description: description,
- latitude: latitude,
- longitude: longitude,
- toFilter: toFilter,
- isCityCenter: isCityCenter,
- typePOI: typePOI
- } ];
- }
- });
- return pois;
- };
- var initializeHelpersFilters = function() {
- tituloHotelesNodispo = $("#hotelesNoDispo").children("h3, hr");
- tituloHotelesNearby = $("#hotelesNearby").children("h3, hr");
- tituloHotelesNearbyNoDispo = $("#hotelesNearbyNoDispo").children("h3, hr");
- numHotelByPrice = $("div.hotelItem").length;
- var aux = $("[class='filters']").find("div.starsHotel.firstlevelContent").find("ul").children("");
- aux.each(function(index) {
- filtroEstrellasActi[ratingsDictionary[$(this).attr("class")]] = false;
- });
- aux = $("[class='filters']").find("div.services.firstlevelContent").find("ul").children("").children("");
- aux.each(function(index) {
- var elemento = $(this).attr("class");
- elemento = elemento.split(" ");
- filtroServiciosActi[elemento[0]] = false;
- });
- aux = $("[class='filters']").find("div.hotelGroup.firstlevelContent").find("ul").children("");
- aux.each(function(index) {
- filtroMarcaActi[$(this).clone().children().remove().end().text().replace(/ /g, " ").replace(/\s+$/, "")] = false;
- });
- if ($("#range2").length > 0) {
- aux = $("#range2").val().split(";");
- filtroPrecioActi[0] = parseFloat(aux[0]);
- filtroPrecioActi[1] = parseFloat(aux[1]);
- }
- $("#filtroPOI").selectpicker("refresh");
- $("#filtroPOIMob").selectpicker("refresh");
- filtroDistMonuActi.distance = parseFloat($("#range1").slider("value"));
- aux = $("[class='filters']").find("div.nearForm.firstlevelContent").find("div.filter-option.pull-left").text();
- var aux2 = $("[class='filters']").find("div.nearForm.firstlevelContent").find(".selectpicker").find("option:contains(" + aux + ")").attr("class");
- filtroDistMonuActi.poi = "." + aux2;
- if (lastSearch.isPOI) {
- $("#filtroPOI").prop("disabled", false);
- $("#filtroPOI").change();
- $("#filtroPOI").prop("disabled", true);
- }
- if (isCountry != null && isCountry) {
- $(".destino").next().show();
- $(".destino").show();
- var hideDistCentroDes = $("#selectSort").find('option[value="distCentroDes"]').text();
- var hideDistCentroAsc = $("#selectSort").find('option[value="distCentroAsc"]').text();
- $('ul.inner li:contains("' + hideDistCentroDes + '")').attr("style", "display:none!important");
- $('ul.inner li:contains("' + hideDistCentroAsc + '")').attr("style", "display:none!important");
- }
- if ($("#filtroPOI option:selected").attr("class") == "empty") {
- $("span.jslider.jslider_plastic.jslider-single").hide();
- }
- for (var key in filtroTypoMarcaActi) filtroTypoMarcaActi[key] = false;
- if (isPageLandingWithoutDates) {
- $(".hotelSinfecha").removeClass("hidden");
- $("div.hotelItem").each(function() {
- $(this).find(".priceRewards").hide();
- $(this).find(".addToolTip").hide();
- });
- }
- };
- var showNumHotelsSidebar = function() {
- var typeOfRating = {};
- var typeOfMarca = {};
- var domRating = $("[class='filters']").find("div.starsHotel.firstlevelContent").find("ul").children("");
- domRating.each(function() {
- typeOfRating[$(this).attr("class")] = 0;
- });
- var domMarca = $("[class='filters']").find("div.hotelGroup.firstlevelContent").find("ul").children("");
- domMarca.each(function(index) {
- typeOfMarca[$(this).clone().children().remove().end().text().replace(/ /g, " ").replace(/\s+$/, "")] = 0;
- });
- $("div.hotelItem").each(function() {
- if ($(this).find(".stars").length != 0) {
- var rating = $(this).find(".stars").attr("class").replace(/[^0-9\.]+/g, "");
- }
- var marca = $(this).attr("data-hotelMarca");
- typeOfRating["stars" + rating.toString()] += 1;
- typeOfMarca[marca] += 1;
- });
- domRating.each(function() {
- var info = $(this).text();
- var infoArray = info.split(" ");
- infoArray[0] = typeOfRating[$(this).attr("class")];
- if (infoArray[0] > 1) infoArray[1] = labelHotels; else infoArray[1] = labelHotel;
- $(this).children("span").text(infoArray.join(" "));
- });
- domMarca.each(function(index) {
- var info = $(this).children("span").text();
- var infoArray = info.split(" ");
- infoArray[0] = typeOfMarca[$(this).clone().children().remove().end().text().replace(/ /g, " ").replace(/\s+$/, "")];
- if (infoArray[0] > 1) infoArray[1] = labelHotels; else infoArray[1] = labelHotel;
- $(this).children("span").text(infoArray.join(" "));
- });
- domRating = $("[class='filters mob']").find("div.starsHotel.firstlevelContent").find("ul").children("");
- domMarca = $("[class='filters mob']").find("div.hotelGroup.firstlevelContent").find("ul").children("");
- domRating.each(function() {
- var info = $(this).text();
- var infoArray = info.split(" ");
- infoArray[0] = typeOfRating[$(this).attr("class")];
- if (infoArray[0] > 1) infoArray[1] = labelHotels; else infoArray[1] = labelHotel;
- $(this).children("span").text(infoArray.join(" "));
- });
- domMarca.each(function(index) {
- var info = $(this).children("span").text();
- var infoArray = info.split(" ");
- infoArray[0] = typeOfMarca[$(this).clone().children().remove().end().text().replace(/ /g, " ").replace(/\s+$/, "")];
- if (infoArray[0] > 1) infoArray[1] = labelHotels; else infoArray[1] = labelHotel;
- $(this).children("span").text(infoArray.join(" "));
- });
- numHotelByPrice = 0;
- var hoteles = $("div.hotelItem");
- hoteles.each(function() {
- var precio = -1;
- if (!$(this).hasClass("hotelNodispo")) {
- precio = parseFloat($(this).find(".hotel-total-price").text());
- }
- if (!isNaN(precio) && precio != -1) {
- numHotelByPrice++;
- }
- });
- };
- var buildDynamicStars = function(stars) {
- if (stars) {
- for (var i = 0; i < stars.length; i++) {
- if ($(".starsHotel.firstlevelContent > ul").find(".stars" + stars[i] + ">input").get(0) == null) {
- $(".starsHotel.firstlevelContent > ul > li").each(function() {
- if ($(this).attr("class").split("stars")[1] < stars[i]) {
- $('<li class="stars' + stars[i] + '"><input type="checkbox" onchange=" activa($(this).parent()), filterHotelsByStars(this)" value="" name=""><span class="totalHotels">0 Hoteles</span></li>').insertBefore(".starsHotel.firstlevelContent > ul > li." + $(this).attr("class"));
- $(".starsHotel.firstlevelContent").find(".stars" + stars[i] + ">input").prop("checked", true).change();
- $("li.stars" + stars[i]).remove();
- return false;
- }
- });
- } else {
- $(".starsHotel.firstlevelContent").find(".stars" + stars[i] + ">input").prop("checked", true).change();
- }
- }
- }
- };
- var buildDynamicServices = function(services) {
- if (services) {
- $(".more").click();
- for (var j = 0; j < services.length; j++) {
- if ($(".services > ul").find("." + services[j]).get(0) == null) {
- $(".services > ul").prepend('<li class="text-overflow" onclick="activa(this), filterHotelsByServices(this)"><span class="' + services[j] + ' tooltip-icon" data-original-title="' + services[j] + '"></span>' + services[j] + "</li>");
- }
- $(".services > ul").find("." + services[j]).parent().click();
- }
- }
- };
- var hideLoadingElements = function() {
- $(".lazy-hide").fadeIn();
- $(".lazy-disabled").removeClass("lazy-disabled");
- $(".loading-lazy").hide();
- };
- return {
- init: init,
- buildPrice: buildPrice,
- buildDynamicServices: buildDynamicServices,
- buildDynamicStars: buildDynamicStars
- };
- }();
- var LandingFilters = function() {
- var totalNumHotels = 0;
- var init = function() {
- var visibleHotels = $("#view-list .hotelItem").filter(function() {
- return $(this).css("display") == "inline-block";
- });
- totalNumHotels = visibleHotels.length || 0;
- if (totalNumHotels == 0) {
- $(".js-alert-error").show();
- } else {
- pageInitActions();
- }
- };
- var pageInitActions = function() {
- BuildFilters.init();
- isPageLanding = true;
- if (!pageData.withDates) {
- $(".loading-lazy").fadeOut(500);
- $(".lazy-hide").fadeIn(500);
- isPageLandingWithoutDates = true;
- }
- };
- return {
- init: init
- };
- }();
- function updateNumHotelsFiltered(isfirstLoad) {
- var visibleHotels = $("#view-list .hotelItem").filter(function() {
- return $(this).css("display") == "inline-block";
- });
- var totalNumHotels = visibleHotels.length || 0;
- if (!isfirstLoad) {
- $(".js-total-hotels").text(totalNumHotels);
- var lblHotelFound = totalNumHotels == 1 ? labelHotelFound : labelHotelsFound;
- var lblHotelInPOI = totalNumHotels == 1 ? labelHotelInPOI : labelHotelsInPOI;
- var lblHotelInDestination = totalNumHotels == 1 ? labelHotelInDestination : labelHotelsInDestination;
- $(".hotelsFoundText").text(lblHotelFound);
- if (lastSearch.isPOI) {
- $(".destinoBusqueda").text(lblHotelInPOI + " " + pageData.destino + ", " + pageData.pais);
- } else {
- $(".destinoBusqueda").text(lblHotelInDestination + " " + pageData.destino + ", " + pageData.pais);
- }
- if (totalNumHotels == 0) {
- $(".js-alert-filter").show();
- } else {
- $(".js-alert-filter").hide();
- }
- }
- visibleHotels.each(function(index) {
- cambiarNumerodeHotel(index, $(this));
- });
- }
- function applyFilters(filter) {
- if (pageData.isIpad) updatePaginateResults();
- var numEStrellasAct = $("div.starsHotel.firstlevelContent:visible").find("ul").children("").filter(".active").length;
- var numServiciosAct = $("div.services.firstlevelContent:visible").find("ul").children("").filter(".active").length;
- var numMarcasAct = $("div.hotelGroup.firstlevelContent:visible").find("ul").children("").filter(".active").length;
- var numTypesMarcasAct = $("div.hotelType.firstlevelContent:visible").not(".destino").find("ul").children("").filter(".active").length;
- contadorToShow = 0;
- hotel = $("div.hotelItem");
- hotel.each(function(index) {
- if (filter == "filterByPrice") {
- var precio = parseFloat($(this).find(".hotel-total-price").text());
- } else if (filter == "filterSliderGenerico") {
- value = parseFloat($(this).find(searchString).text());
- }
- if (!canShow($(this), numEStrellasAct == 0 ? true : false, numServiciosAct == 0 ? true : false, numMarcasAct == 0 ? true : false, numTypesMarcasAct == 0 ? true : false)) {
- if (markersMob[parseInt($(this).find(".nhrec").text())] != null) {
- markersMob[parseInt($(this).find(".nhrec").text())].setMap(null);
- }
- $(this).hide();
- } else {
- if (markersMob[parseInt($(this).find(".nhrec").text())] != null) {
- markersMob[parseInt($(this).find(".nhrec").text())].setMap(mapMob);
- }
- $(this).show();
- }
- if (filter == "filterByPrice") {
- if (precio >= filtroPrecioActi[0] && precio <= filtroPrecioActi[1]) numHotelByPrice++;
- }
- });
- handleTitleResults();
- if (pageData.isIpad) {
- reorderResults();
- if ($("#selectSort").val() != "distCentroDes" && $("#selectSort").val() != "distCentroAsc" && $("#selectSort").val() != "distPoiDes" && $("#selectSort").val() != "distPoiAsc") $("#selectSort").change();
- }
- }
- function filterHotelsByCity(element) {
- var aux = $(element).parent().attr("class");
- aux = aux.replace(" active", "");
- var activo = element.checked;
- var city = $.trim($(element).parent().clone().children().remove().end().text());
- $(".starsHotel.firstlevelContent:hidden").find("." + aux).children("input");
- var registrarCambioDes = $(".destino.hotelType.firstlevelContent:hidden").filter(":contains('" + city + "')").find("input");
- registrarCambioDes.prop("checked", element.checked);
- activa(registrarCambioDes.parent());
- applyFilters("");
- updateNumHotelsFiltered();
- }
- function filterHotelsByStars(element) {
- var aux = $(element).parent().attr("class");
- aux = aux.replace(" active", "");
- var rating = ratingsDictionary[aux];
- var activo = element.checked;
- var registrarCambioDes = $(".starsHotel.firstlevelContent:hidden").find("." + aux).children("input");
- registrarCambioDes.prop("checked", element.checked);
- activa(registrarCambioDes.parent());
- if (activo) filtroEstrellasActi[rating] = true; else filtroEstrellasActi[rating] = false;
- applyFilters("");
- updateNumHotelsFiltered();
- trackFilterStars(page_section, rating);
- }
- function filterHotelsByDisponibilidad(band) {
- if (pageData.isIpad) updatePaginateResults();
- mostrarNodispo = band;
- if (band) $("div.firstlevelContent.availability:hidden").find("input").first().prop("checked", true); else $("div.firstlevelContent.availability:hidden").find("input").last().prop("checked", true);
- if (band) {
- var numEStrellasAct = $("div.starsHotel.firstlevelContent:visible").find("ul").children("").filter(".active").length;
- var numServiciosAct = $("div.services.firstlevelContent:visible").find("ul").children("").filter(".active").length;
- var numMarcasAct = $("div.hotelGroup.firstlevelContent:visible").find("ul").children("").filter(".active").length;
- var numTypesMarcasAct = $("div.hotelType.firstlevelContent:visible").not(".destino").find("ul").children("").filter(".active").length;
- $("[id = hotelesNoDispo]").show();
- $("#hotelesNoDispo .hotelItem").show();
- $("[id = hotelesNearbyNoDispo]").show();
- $("#hotelesNearbyNoDispo .hotelItem").show();
- applyFilters();
- } else {
- $("[id = hotelesNoDispo]").hide();
- $("#hotelesNoDispo .hotelItem").hide();
- $("[id = hotelesNearbyNoDispo]").hide();
- $("#hotelesNearbyNoDispo .hotelItem").hide();
- $(markersMob).each(function() {
- if (this.metadata && this.metadata.class == "nodisp") {
- this.setMap(null);
- }
- });
- trackFilterAvail(page_section);
- }
- if (pageData.isIpad) reorderResults();
- updateNumHotelsFiltered();
- }
- function filterHotelsByServices(element) {
- var aux = $(element).children().attr("class");
- var activo = $(element).attr("class").search("active") != -1 ? true : false;
- aux = aux.split(" ");
- var servicios = "." + aux[0];
- var hotlesToFilter;
- var filtroOculto = $("div.services.firstlevelContent:hidden").find("ul").find(servicios).parent();
- activa(filtroOculto);
- if (activo) filtroServiciosActi[aux[0]] = true; else filtroServiciosActi[aux[0]] = false;
- applyFilters("");
- updateNumHotelsFiltered();
- trackFilterServices(page_section, aux[0].split("-")[1]);
- }
- function filterBrand(element) {
- var brand = $(element).parent().clone().children().remove().end().text().replace(/ /g, " ").replace(/\s+$/, "");
- var activo = element.checked;
- var registrarCambioDes = $("div.hotelGroup.firstlevelContent:hidden").find("ul").children().filter(":contains(" + brand + ")");
- activa(registrarCambioDes);
- registrarCambioDes = registrarCambioDes.children("input");
- registrarCambioDes.prop("checked", element.checked);
- if (activo) filtroMarcaActi[brand] = true; else filtroMarcaActi[brand] = false;
- applyFilters("");
- updateNumHotelsFiltered();
- trackFilterBrand(page_section, brand);
- }
- function filterTypeBrand(element) {
- var typoHotel = $(element).parent().find("span.hotelTypeName").text();
- var activo = element.checked;
- if (activo) filtroTypoMarcaActi[typoHotel] = true; else filtroTypoMarcaActi[typoHotel] = false;
- applyFilters("");
- updateNumHotelsFiltered();
- }
- function canShow(element, showRating, showServicio, showMarca, showTypeMarca) {
- if (!mostrarNodispo && element.hasClass("hotelNodispo")) {
- return;
- }
- if ($(element).find(".stars").length != 0) {
- var rating = $(element).find(".stars").attr("class").replace(/[^0-9\.]+/g, "");
- }
- var servicio = {};
- var typeHotels = {};
- var listaServicios = $(element).find(".col-md-3.servicesHotel").children("ul").children("");
- listaServicios.each(function(index) {
- var stringArrayAux = $(this).children().attr("class").split(" ")[0];
- servicio[stringArrayAux] = true;
- });
- var listaTypoHotel = $(element).find(".filterHotelType").find("li");
- listaTypoHotel.each(function() {
- var hotelTypeName = $(this).text();
- typeHotels[hotelTypeName] = true;
- });
- var precio = parseFloat($(element).find(".hotel-total-price").text());
- var marca = $(element).attr("data-hotelMarca");
- var haveServicioFiltro = true;
- if (!showServicio) {
- for (key in filtroServiciosActi) {
- if (filtroServiciosActi[key] && !(key in servicio)) {
- haveServicioFiltro = false;
- break;
- }
- }
- } else {
- haveServicioFiltro = true;
- }
- var haveTypeMarcaFilter = true;
- if (!showTypeMarca) {
- for (key in filtroTypoMarcaActi) {
- if (filtroTypoMarcaActi[key] && !(key in typeHotels)) {
- haveTypeMarcaFilter = false;
- break;
- }
- }
- } else {
- haveTypeMarcaFilter = true;
- }
- var haveFiltroRating = showRating ? true : filtroEstrellasActi[rating];
- var haveFilterMarca = showMarca ? true : filtroMarcaActi[marca];
- var filtroPrecio = isNaN(precio) ? true : filtroPrecioActi[0] <= precio && filtroPrecioActi[1] >= precio;
- var haveFiltroDisPoi;
- if ($(element).find("ul.POIS").find(filtroDistMonuActi.poi).length > 0) {
- var aux = $(element).find("ul.POIS").find(filtroDistMonuActi.poi).find("li").first().text().replace(",", ".");
- var disPoi = parseFloat(aux.split(" ")[0]);
- haveFiltroDisPoi = disPoi <= filtroDistMonuActi.distance ? true : false;
- } else if (filtroDistMonuActi.poi == ".empty") {
- haveFiltroDisPoi = true;
- } else {
- if (lastSearch.isPOI) {
- haveFiltroDisPoi = true;
- } else {
- haveFiltroDisPoi = false;
- }
- }
- var haveFilterCity = false;
- haveFilterCity = true;
- if (haveServicioFiltro && haveTypeMarcaFilter && haveFiltroRating && filtroPrecio && haveFilterMarca && haveFiltroDisPoi && haveFilterCity) {
- return true;
- } else {
- return false;
- }
- }
- function filterByPrice(min, max) {
- numHotelByPrice = 0;
- filtroPrecioActi[0] = min;
- filtroPrecioActi[1] = max;
- console.log("filterByPrice: ", filtroPrecioActi);
- $("#range2").slider("value", min, max);
- $("#rangeMob").slider("value", min, max);
- applyFilters("filterByPrice");
- updateNumHotelsFiltered();
- trackFilterPrice(page_section, min, max);
- }
- function genericFilterSlider(min, max, sliderID, auxStructure1, searchString1) {
- searchString = searchString1;
- auxStructure = auxStructure1;
- var numEStrellasAct = $("div.starsHotel.firstlevelContent:visible").find("ul").children("").filter(".active").length;
- var numServiciosAct = $("div.services.firstlevelContent:visible").find("ul").children("").filter(".active").length;
- var numMarcasAct = $("div.hotelGroup.firstlevelContent:visible").find("ul").children("").filter(".active").length;
- var numTypesMarcasAct = $("div.hotelType.firstlevelContent:visible").not(".destino").find("ul").children("").filter(".active").length;
- auxStructure.min = min;
- auxStructure.max = max;
- $(sliderID).slider("value", min, max);
- var parentClass = "." + $("#range-rooms").parent().attr("class").split(" ")[0];
- $(parentClass).filter(":hidden").find("input").slider("value", min, max);
- applyFilters("filterSliderGenerico");
- updateNumHotelsFiltered();
- }
- function filterByPoi(distance, element) {
- if (distance == -1) {
- filtroDistMonuActi.distance = parseFloat($("#range1").slider("value"));
- var value = $(element).val();
- if ($("#filtroPOI").val() != value) $("#filtroPOI").val(value).change();
- if ($("#filtroPOIMob").val() != value) $("#filtroPOIMob").val(value).change();
- } else {
- filtroDistMonuActi.distance = distance;
- $("#range1").slider("value", distance);
- $("#rangeMob1").slider("value", distance);
- }
- if ($("#filtroPOI option:selected").attr("class") == "empty") {
- $("span.jslider.jslider_plastic.jslider-single").hide();
- } else {
- $("span.jslider.jslider_plastic.jslider-single").show();
- }
- var aux;
- var aux2;
- if ($("div.nearForm.firstlevelContent").filter(":visible").length != 0) {
- aux = $("div.nearForm.firstlevelContent").filter(":visible").find("div.filter-option.pull-left").text();
- aux2 = $("div.nearForm.firstlevelContent").filter(":visible").find(".selectpicker").find("option:contains(" + aux + ")").attr("class");
- } else {
- aux = $("div.nearForm.firstlevelContent").first().find("div.filter-option.pull-left").text();
- aux2 = $("div.nearForm.firstlevelContent").first().find(".selectpicker").find("option:contains(" + aux + ")").attr("class");
- }
- filtroDistMonuActi.poi = "." + aux2;
- applyFilters("");
- updateNumHotelsFiltered();
- if (distance != -1) {
- filtroNearTo("landing");
- }
- }
- function handleTitleResults() {
- var wrapHotels = $("#newResults .wrap-hotels");
- $.each(wrapHotels, function(i, ele) {
- var $ele = $(ele);
- if ($ele.find(".hotelItem:visible").length == 0) {
- $ele.find(".wrap-title").hide();
- } else {
- if (!lastSearch.isPromo) {
- $ele.find('.wrap-title:not(".show-promo")').show();
- } else {
- $ele.find('.wrap-title:not(".hide-promo")').show();
- }
- }
- });
- }
- function cambiarCampo() {
- var textInfo = $("div.nearForm.firstlevelContent").filter(":visible").find("div.filter-option.pull-left").text();
- var classInfo = $("div.nearForm.firstlevelContent").filter(":visible").find(".selectpicker").find("option:contains(" + textInfo + ")").attr("class");
- var isCenter = false;
- $(".hotelItem").each(function() {
- if ($(this).find("." + classInfo).find(".isCityCenter").text() == "Yes") {
- isCenter = true;
- return false;
- }
- });
- if (classInfo == "empty" || isCenter) {
- var toHidePoiasc = $("#selectSort").find('option[value="distPoiAsc"]').text();
- var toHidePoides = $("#selectSort").find('option[value="distPoiDes"]').text();
- $('ul.inner li:contains("' + toHidePoiasc + '")').attr("style", "display:none!important");
- $('ul.inner li:contains("' + toHidePoides + '")').attr("style", "display:none!important");
- } else {
- var toHidePoiasc = $("#selectSort").find('option[value="distPoiAsc"]').text();
- var toHidePoides = $("#selectSort").find('option[value="distPoiDes"]').text();
- $('ul.inner li:contains("' + toHidePoiasc + '")').attr("style", "");
- $('ul.inner li:contains("' + toHidePoides + '")').attr("style", "");
- }
- if (!isCenter && ($("#selectSort").val() == "distCentroAsc" || $("#selectSort").val() == "distCentroDes")) {
- if ($("#selectSort").val() == "distCentroAsc") {
- $("#selectSort").val("distPoiAsc");
- } else {
- $("#selectSort").val("distPoiDes");
- }
- $('ul.inner li:contains("distPoiAsc")').attr("style", "");
- $('ul.inner li:contains("distPoiDes")').attr("style", "");
- $("#selectSort").change();
- } else if (isCenter && ($("#selectSort").val() == "distPoiAsc" || $("#selectSort").val() == "distPoiDes")) {
- if ($("#selectSort").val() == "distPoiAsc") {
- $("#selectSort").val("distCentroAsc");
- } else {
- $("#selectSort").val("distCentroDes");
- }
- $("#selectSort").change();
- } else if (!isCenter && ($("#selectSort").val() == "distPoiAsc" || $("#selectSort").val() == "distPoiDes")) {
- $("#selectSort").change();
- }
- textAnterior = textInfo;
- }
- function actualizarCampoPOIdeHotelItem() {
- var textInfo = $("div.nearForm.firstlevelContent").filter(":visible").find("div.filter-option.pull-left").text();
- var classInfo = $("div.nearForm.firstlevelContent").filter(":visible").find(".selectpicker").find("option:contains(" + textInfo + ")").attr("class");
- if (classInfo != "empty") {
- var hoteles = $("div.hotelItem");
- hoteles.each(function() {
- var descriptionInfo = $(this).find("ul.POIS").find("li." + classInfo).find("li.description").text();
- var distanceInfo = $(this).find("ul.POIS").find("li." + classInfo).find("li").first().text();
- $(this).first().find("div.nearFrom").replaceWith('<div class = "nearFrom"><strong>' + distanceInfo + "</strong>" + " " + descriptionInfo + "<div>");
- });
- } else {
- var hoteles = $("div.hotelItem");
- hoteles.each(function() {
- var descriptionInfo = $(this).find("ul.POIS").children().first().find("li.description").text();
- var distanceInfo = $(this).find("ul.POIS").children().first().find("li").first().text();
- $(this).first().find("div.nearFrom").replaceWith('<div class = "nearFrom"><strong>' + distanceInfo + "</strong>" + " " + descriptionInfo + "<div>");
- if ($("#selectSort").val() == "distPoiAsc" || $("#selectSort").val() == "distPoiDes") cambiarOrdenar();
- });
- }
- }
- function cambiarOrdenar() {
- $("#selectSort").val("nhRec");
- $("#selectSortMob").val("nhRec");
- $("#selectSort").change();
- $("#selectSortMob").change();
- }
- function showFiltersAux(filtroMostrar) {
- $(filtroMostrar).addClass("activa");
- $(".showFilters").hide();
- $(".blackBG").show();
- $(filtroMostrar).animate({
- top: 0
- }, 500, function() {
- $("footer").hide();
- });
- $("body").css("overflow", "hidden");
- }
- function hideFiltersAux() {
- $(".filtersMob").removeClass("activa");
- $(".showFilters").show();
- $(".listHotels").show();
- $("footer").show();
- $(".blackBG").hide();
- $("html, body").animate({
- scrollTop: 0
- }, "slow");
- $("body").css("overflow", "auto");
- }
- function cambiarNumerodeHotel(index, element) {
- var indexValues = $(element).find(".hotelIndex");
- indexValues.first().text(index + 1 + ". ");
- indexValues.last().text(index + 1 + ". ");
- }
- $(function() {
- if ($("body").hasClass("page-landing")) {}
- });
- var LandingMap = function() {
- var markers = new Array();
- var init = function() {
- var secondClick2 = 0;
- var googleDomain = isChinese ? "http://maps.google.cn" : "https://maps.googleapis.com";
- var url = googleDomain + "/maps/api/js?client=gme-nhhotels&language=" + pageData.googleLang;
- var urlInfobox = "https://cdn.rawgit.com/googlemaps/v3-utility-library/master/infobox/src/infobox.js";
- $("a.view-map").off("click");
- $("a.view-map").on("click", function(e) {
- e.preventDefault();
- if (typeof google == "undefined" && secondClick2 == 0) {
- $.when($.getScript(url), $.Deferred(function(deferred) {
- $(deferred.resolve);
- })).done(function() {
- $.when($.getScript(urlInfobox), $.Deferred(function(deferred) {
- $(deferred.resolve);
- })).done(function() {
- showHideMap("show");
- secondClick2 = 1;
- });
- });
- } else {
- showHideMap("show");
- }
- });
- $("a.view-list").on("click", function() {
- showHideMap("hide");
- });
- };
- var showHideMap = function(status) {
- switch (status) {
- case "show":
- pois = mapPOIs();
- filterPois = mapPOIsFilter();
- if (!mapMob) {
- mapMob = loadGoogleMap();
- applyFilters();
- Currency.setDivisaOnMap();
- }
- $(".view-map").hide();
- $(".view-list").show();
- $("#view-list").hide();
- $(".wrap-sort-by").hide();
- $("#mapGoogleMob").css({
- visibility: "visible",
- height: "auto"
- });
- $(".google-maps").css("padding-bottom", 15);
- break;
- case "hide":
- $(".view-map").show();
- $(".view-list").hide();
- $("#view-list").show();
- $(".wrap-sort-by").show();
- $("#mapGoogleMob").css({
- visibility: "hidden",
- height: 0
- });
- $(".google-maps").css("padding-bottom", 75 + "%");
- break;
- }
- };
- var loadGoogleMap = function() {
- if (typeof google != "undefined" && typeof MapsData != "undefined") {
- $("body,html").animate({
- scrollTop: $(".listHotels").offset().top
- }, 800);
- var latitude = 40.322038;
- var longitude = -3.865045;
- $.each(MapsData, function(i, ele) {
- if (ele) {
- latitude = MapsData[i].location[0];
- longitude = MapsData[i].location[1];
- return false;
- }
- });
- var latlong = new google.maps.LatLng(latitude, longitude);
- var mapholder = document.getElementById("googleMapMob");
- mapholder.style.height = "650px";
- mapholder.style.width = "100%";
- var myOptions = {
- zoom: 11,
- center: latlong,
- mapTypeId: google.maps.MapTypeId.ROADMAP,
- mapTypeControl: false,
- navigationControlOptions: {
- style: google.maps.NavigationControlStyle.SMALL
- },
- streetViewControl: false,
- scrollwheel: false,
- styles: [ {
- featureType: "poi",
- stylers: [ {
- visibility: "off"
- } ]
- }, {
- featureType: "transit.station.airport",
- elementType: "labels",
- stylers: [ {
- visibility: "off"
- } ]
- } ]
- };
- var map = new google.maps.Map(mapholder, myOptions);
- $.each(MapsData, function(i, dato) {
- if (dato) {
- markers[i] = new google.maps.Marker({
- position: new google.maps.LatLng(dato.location[0], dato.location[1]),
- animation: google.maps.Animation.DROP,
- map: map,
- icon: dato.icon,
- zIndex: google.maps.Marker.MAX_ZINDEX - google.maps.Marker.MAX_ZINDEX / (Math.round(latlong.lat() * -1e5) << 5) * 1e5
- });
- var markerClass = dato.clase != "" ? dato.clase : "dispo";
- markers[i].metadata = {
- "class": markerClass
- };
- if (dato.info) {
- markers[i].infoWindows = new InfoBox({
- disableAutoPan: false,
- maxWidth: 427,
- pixelOffset: new google.maps.Size(-130, -248),
- zIndex: null,
- boxStyle: {},
- closeBoxMargin: "8px 8px 0 0",
- closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
- InfoBoxClearance: new google.maps.Size(1, 1)
- });
- google.maps.event.addListener(markers[i], "click", function() {
- $.each(markers, function(index, ele) {
- if (typeof ele != "undefined" && typeof ele.infoWindows != "undefined") {
- ele.infoWindows.close(map, ele);
- }
- });
- markers[i].infoWindows.setContent(dato.info);
- Currency.setDivisaOnMap();
- markers[i].infoWindows.open(map, markers[i]);
- });
- }
- }
- });
- markersMob = markers;
- centerMap(markers, map, latlong);
- var listener = google.maps.event.addListener(map, "idle", function() {
- google.maps.event.removeListener(listener);
- });
- if (clicado == true) {
- infoWindow.open(map, marker);
- }
- var clicado = false;
- $(window).resize(function() {
- moveGoogleMap();
- });
- if (document.body.orientationchange) {
- function doOnOrientationChange() {
- moveGoogleMap();
- }
- window.addEventListener("orientationchange", doOnOrientationChange);
- }
- return map;
- }
- };
- var mapPOIsFilter = function() {
- var pois = {};
- var i = 0;
- var isFinished = false;
- while (!isFinished) {
- isFinished = true;
- $(".hotelItem").each(function() {
- if ($(this).find("ul.POIS>li").eq(i).length) {
- isFinished = false;
- if ($(this).find("ul.POIS>li").eq(i).find("li.toFilter").text() == "Yes") {
- var poi = $(this).find("ul.POIS>li").eq(i).attr("class");
- pois[poi] = [ $(this).find("ul.POIS>li").eq(i).find("li.description").text(), $(this).find("ul.POIS>li").eq(i).find("li.latitude").text(), $(this).find("ul.POIS>li").eq(i).find("li.longitude").text(), $(this).find("ul.POIS>li").eq(i).find("li.typePOI").text(), $(this).find("ul.POIS>li").eq(i).find("li.isCityCenter").text() ];
- }
- }
- });
- i++;
- }
- return pois;
- };
- var clearPOIsMob = function() {
- for (var i = 1; i < poiMarkersMob.length; i++) {
- poiMarkersMob[i].setMap(null);
- poiMarkersMob[i].infoWindow.open(null);
- }
- poiMarkersMob.length = 0;
- };
- var mapPOIs = function() {
- var pois = {};
- var i = 0;
- var isFinished = false;
- while (!isFinished) {
- isFinished = true;
- $(".hotelItem").each(function() {
- if ($(this).find("ul.POIS>li").eq(i).length) {
- isFinished = false;
- var poi = $(this).find("ul.POIS>li").eq(i).attr("class");
- pois[poi] = [ $(this).find("ul.POIS>li").eq(i).find("li.description").text(), $(this).find("ul.POIS>li").eq(i).find("li.latitude").text(), $(this).find("ul.POIS>li").eq(i).find("li.longitude").text(), $(this).find("ul.POIS>li").eq(i).find("li.typePOI").text(), $(this).find("ul.POIS>li").eq(i).find("li.isCityCenter").text() ];
- }
- });
- i++;
- }
- return pois;
- };
- var moveGoogleMap = function() {
- console.log("moveGoogleMap");
- centerMap(markersMob, mapMob);
- recalcularZoom(mapMob);
- };
- var centerMap = function(markers, map, latlong) {
- var latlongCenter = "";
- if (!lastSearch.isPOI) {
- $(".hotelItem").each(function() {
- $(this).find("ul.POIS>li").each(function() {
- if ($(this).find("li.isCityCenter").text() == "Yes") latlongCenter = new google.maps.LatLng($(this).find("li.latitude").text(), $(this).find("li.longitude").text());
- });
- });
- } else {
- $(".hotelItem").each(function() {
- $(this).find("ul.POIS>li").each(function() {
- if ($(this).attr("class") == "${destinoCode}") latlongCenter = new google.maps.LatLng($(this).find("li.latitude").text(), $(this).find("li.longitude").text());
- });
- });
- }
- if (latlongCenter != "") {
- map.setCenter(latlongCenter);
- } else {
- if (markers.length > 0) {
- if (markers.length == 2) map.setCenter(latlong); else {
- var bounds = new google.maps.LatLngBounds();
- for (var j = 1; j < markers.length; j++) {
- if (markers[j] != null) bounds.extend(markers[j].getPosition());
- }
- map.fitBounds(bounds);
- }
- }
- }
- };
- var recalcularZoom = function(mapa) {
- mapa = mapMob;
- var listener = google.maps.event.addListener(mapa, "idle", function() {
- var markersIn = false;
- while (!markersIn) {
- markersIn = true;
- for (var n = 1; n < markersMob.length; n++) {
- if (markersMob[n] != null) {
- var zoom = mapa.getZoom();
- var latlongAux = markersMob[n].getPosition();
- if (mapa.getBounds() != null && !mapa.getBounds().contains(latlongAux) && !mapa.getBounds().getNorthEast().equals(mapa.getBounds().getSouthWest())) {
- markersIn = false;
- mapa.setZoom(zoom - 1);
- }
- }
- }
- }
- google.maps.event.removeListener(listener);
- });
- };
- return {
- init: init
- };
- }();
- var LandingSort = function() {
- var re_stars = /([1-9])/;
- var parent;
- var init = function() {
- $("#selectSortMob, #selectSort").on("change", function() {
- sortHotels(this, $(this).data("destinoCRS"));
- });
- $("#selectSort").on("change", function() {
- trackChangeOrder(page_section, $(this).val());
- });
- };
- var sortHotels = function(selected) {
- var selected_sortby = selected.value;
- var groups = [ "hotelesDispo", "hotelesNearby", "hotelesNoDispo" ];
- if (selected_sortby == "precioAsc" || selected_sortby == "precioDes") {
- groups = [ "hotelesDispo", "hotelesNearby" ];
- } else if (selected_sortby == "distCentroAsc" || selected_sortby == "distCentroDes") {
- var className = "empty";
- $(".hotelItem").each(function() {
- if ($(this).find("li.isCityCenter").filter(":contains('Yes')").text() == "Yes") {
- className = $(this).find("li.isCityCenter").filter(":contains('Yes')").parent().parent().attr("class");
- return false;
- }
- });
- if ($("#filtroPOI").val() != $("." + className).val()) {
- $("#filtroPOI").val($("." + className).val());
- $("#filtroPOI").change();
- }
- }
- $.each(groups, function(i, group) {
- doSortby(selected_sortby, group);
- });
- if ($("#selectSort").val() != selected.value) {
- $("#selectSort").val(selected.value);
- $("#selectSort").find('option[value="' + selected.value + '"]').change();
- }
- if ($("#selectSortMob").val() != selected.value) {
- $("#selectSortMob").val(selected.value);
- $("#selectSortMob").find('option[value="' + selected.value + '"]').change();
- }
- var visibleHotels = $(" .hotelItem").filter(function() {
- return $(this).css("Display") == "inline-block";
- });
- visibleHotels.each(function(index) {
- cambiarNumerodeHotel(index, $(this));
- });
- $("img.lazy").lazyload();
- };
- var doSortby = function(sortby, group) {
- var group_id = $("#" + group);
- if (pageData.isIpad) {
- updatePaginateResults();
- }
- var hotels_to_sort = $(group_id).find(".hotelItem").detach();
- hotels_to_sort = Array.prototype.slice.call(hotels_to_sort, 0);
- hotels_to_sort.sort(function(a, b) {
- var result = null;
- switch (sortby) {
- case "nhRec":
- var e1 = parseInt($(".nhrec", a).text());
- var e2 = parseInt($(".nhrec", b).text());
- result = e1 > e2 ? 1 : -1;
- break;
- case "precioAsc":
- case "precioDes":
- var e1 = parseFloat($.trim($(".info-result-room", a).find(".priceChange").text()));
- var e2 = parseFloat($.trim($(".info-result-room", b).find(".priceChange").text()));
- if (sortby == "precioAsc") {
- result = e1 > e2 ? 1 : -1;
- } else if (sortby == "precioDes") {
- result = e1 < e2 ? 1 : -1;
- }
- break;
- case "nombreAsc":
- case "nombreDes":
- var e1 = $.trim($(a).find(".starsHotel .title a").text()).replace(/\n/g, "").replace(/ /g, "").replace(/\s/g, "");
- var e2 = $.trim($(b).find(".starsHotel .title a").text()).replace(/\n/g, "").replace(/ /g, "").replace(/\s/g, "");
- if (sortby == "nombreAsc") {
- result = e1 > e2 ? 1 : -1;
- } else if (sortby == "nombreDes") {
- result = e1 < e2 ? 1 : -1;
- }
- break;
- case "distCentroAsc":
- case "distCentroDes":
- case "distPoiAsc":
- case "distPoiDes":
- var e1 = parseFloat($.trim($(".nearFrom", a).text().split("km")[0]));
- var e2 = parseFloat($.trim($(".nearFrom", b).text().split("km")[0]));
- if (sortby == "distCentroAsc" || sortby == "distPoiAsc") {
- result = e1 > e2 || isNaN(e1) ? 1 : -1;
- } else if (sortby == "distCentroDes" || sortby == "distPoiDes") {
- result = e1 < e2 || isNaN(e1) ? 1 : -1;
- }
- break;
- case "catAsc":
- case "catDes":
- var str1 = $(".starsHotel .stars", a).attr("class");
- var str2 = $(".starsHotel .stars", b).attr("class");
- var e1 = parseInt(re_stars.exec(str1)[0]);
- var e2 = parseInt(re_stars.exec(str2)[0]);
- if (sortby == "catAsc") {
- result = e1 > e2 ? 1 : -1;
- } else if (sortby == "catDes") {
- result = e1 < e2 ? 1 : -1;
- }
- break;
- }
- return result;
- });
- for (var i = 0, l = hotels_to_sort.length; i < l; i++) {
- group_id.append(hotels_to_sort[i]);
- }
- if (pageData.isIpad) {
- reorderResults();
- }
- };
- return {
- init: init,
- sortHotels: sortHotels
- };
- }();
- $(function() {
- if ($("body").hasClass("page-landing")) {}
- });
- var LandingPage = function() {
- var lazyHotels;
- var isNoAvailabilityPage = false;
- var isNoDatesPage = false;
- var groupResults = [];
- var analyticsLazyData = {};
- var urlNoPromo;
- var $sv;
- var init = function() {
- $sv = LandingServices;
- if (pageData.javaError == "true") {
- $("#error").fancybox().click();
- } else {
- groupResults["#hotelesDispo"] = 0;
- groupResults["#hotelesNoDispo"] = 0;
- groupResults["#hotelesNearby"] = 0;
- groupResults["#hotelesNearbyNoDispo"] = 0;
- groupResults["#hotelesDispoPromo"] = 0;
- groupResults["#hotelesNearbyPromo"] = 0;
- if (invalidDates()) {
- noAvailabilityPageActions();
- $sv.showErrorLighbox(pageData.tcmDatesError);
- } else {
- $sv.getLastSearch(function(search) {
- console.log("lastSearch:", search);
- fillLastSearch();
- callLazyAjax();
- $sv.callTripAdvisorReviews();
- $sv.callTrustYouReviews();
- $sv.callLoading();
- });
- }
- }
- };
- var fillLastSearch = function() {
- if (!$.isEmptyObject(lastSearch)) {
- if (lastSearch.fini && lastSearch.fout) {
- var finiOutput = lastSearch.fini;
- var foutOutput = lastSearch.fout;
- if (typeof Dates != "undefined" && Dates.isChinese) {
- var finiParsed = $.datepicker.parseDate(Dates.pattern, finiOutput);
- var foutParsed = $.datepicker.parseDate(Dates.pattern, foutOutput);
- finiOutput = $.datepicker.formatDate(Dates.patternCn, finiParsed);
- foutOutput = $.datepicker.formatDate(Dates.patternCn, foutParsed);
- }
- $("#fechaIda").data("date", finiOutput);
- $("#ida").val(finiOutput);
- $("#idaAlt").val(lastSearch.fini);
- $("#fechaFin").data("date", foutOutput);
- $("#fin").val(foutOutput);
- $("#finAlt").val(lastSearch.fout);
- } else {}
- var totalLblAdults = lastSearch.numTotalAdults == 1 ? pageLabels.lblAdult : pageLabels.lblAdults;
- var totalLblChildren = lastSearch.numTotalChildren == 1 ? pageLabels.lblChild : pageLabels.lblChildren;
- var totalLblBabies = lastSearch.numTotalBabies == 1 ? pageLabels.lblBaby : pageLabels.lblBabies;
- var roomsLblData = $(".js-info-nights [data-rooms]").data("rooms");
- if (roomsLblData) {
- var totalLblRooms = roomsLblData.singular;
- if (lastSearch.numRooms > 1) {
- totalLblRooms = roomsLblData.plural.replace("{0}", lastSearch.numRooms);
- }
- $(".js-info-nights [data-rooms]").html(totalLblRooms);
- }
- if (lastSearch.numTotalAdults > 0) {
- $(".js-occupancy-wrap").find("[data-id='optionRooms'] .filter-option").text(lastSearch.numTotalAdults + " " + totalLblAdults + ", " + lastSearch.numTotalChildren + " " + totalLblChildren + ", " + lastSearch.numTotalBabies + " " + totalLblBabies);
- }
- var $modal = $("#occupancy-modal");
- if (lastSearch.numRooms == 1) {
- $modal.find('select.occupancy-select[name="nadults1"]').selectpicker("val", lastSearch.occupancy[0].adults);
- $modal.find('select.occupancy-select[name="nchilds1"]').selectpicker("val", lastSearch.occupancy[0].children);
- $modal.find('select.occupancy-select[name="nbabies1"]').selectpicker("val", lastSearch.occupancy[0].babies);
- } else {
- $modal.find("#habs").selectpicker("val", lastSearch.numRooms);
- $.each(lastSearch.occupancy, function(i, room) {
- var n = i + 1;
- $modal.find('select.occupancy-select[name="nadults' + n + '"]').selectpicker("val", room.adults);
- $modal.find('select.occupancy-select[name="nchilds' + n + '"]').selectpicker("val", room.children);
- $modal.find('select.occupancy-select[name="nbabies' + n + '"]').selectpicker("val", room.babies);
- });
- }
- if (lastSearch.numNights == 1) {
- $(".js-info-nights").hide();
- }
- $(".btn-search").removeClass("btn-primary").addClass("btn-default");
- if (lastSearch.voucherCode) {
- var urlVoucher = $(".js-voucher-param").attr("href");
- var newUrl = urlVoucher.replace(getURLParameter("voucherCode", urlVoucher), lastSearch.voucherCode);
- $(".js-voucher-param").attr("href", newUrl);
- $('input[name="voucherCode"]').val(lastSearch.voucherCode);
- }
- if (lastSearch.groupon) {
- $(".js-groupon-hide").hide();
- $(".js-groupon-show").show();
- } else {
- $(".js-notgroupon-hide").hide();
- $(".js-notgroupon-show").show();
- }
- pageData.filterStars = lastSearch.filterStars;
- pageData.filterServices = lastSearch.filterServices;
- loadResumeData();
- $("#locationCode").val(pageData.keySearch);
- $("#habs").on("change", function() {
- loadResumeData();
- });
- $("#locationForm input").on("click", function() {
- loadResumeData();
- });
- } else {
- console.log("lastSearch is empty!");
- }
- $(".btn-search").attr("disabled", false);
- };
- var loadResumeData = function() {
- var adultos = 0;
- var ninos = 0;
- var bebes = 0;
- var habitaciones = $("#habs").val();
- var pax = false;
- for (var i = 1; i <= habitaciones; i++) {
- var ad = $("[name=nadults" + i + "]").val();
- adultos = adultos + parseInt(ad);
- var ni = $("[name=nchilds" + i + "]").val();
- ninos = ninos + parseInt(ni);
- var be = $("[name=nbabies" + i + "]").val();
- bebes = bebes + parseInt(be);
- }
- $("#loc").html($("#location").val());
- $("#fel").html($("#ida").val());
- $("#fes").html($("#fin").val());
- $("#adu").html(adultos);
- $("#nin").html(ninos);
- $("#beb").html(bebes);
- $("#hab").html(habitaciones);
- };
- var callLazyAjax = function() {
- updateNumHotelsFiltered(true);
- if (LazyDataSend && !$.isEmptyObject(LazyDataSend.hotels) && pageData.destinoCode && JSON.stringify(LazyDataSend)) {
- $.ajax({
- type: "POST",
- url: "/rest/landing/avail/" + pageData.destinoCode,
- headers: {
- Accept: "application/json",
- "Content-Type": "application/json"
- },
- data: JSON.stringify(LazyDataSend),
- dataType: "json",
- cache: false
- }).done(function(data) {
- try {
- if (!$.isEmptyObject(data)) {
- console.log("Result Lazy Dispo:", data);
- lazyHotels = data;
- setLazyAjaxValues();
- } else {
- console.log("resturn Ajax: No Availability page");
- noAvailabilityPageActions();
- }
- } catch (err) {
- console.log("Ajax done but error: ", err);
- $sv.showErrorLighbox(pageData.tcmInternalError);
- }
- }).fail(function(data) {
- try {
- console.log("Fail call: ", data.status, data.responseText, typeof data.responseText);
- var responseParsed = JSON.parse(data.responseText);
- if (typeof responseParsed == "object" && responseParsed.message) {
- $sv.showErrorLighbox(responseParsed.message);
- } else {
- $sv.showErrorLighbox(pageData.tcmInternalError);
- }
- } catch (err) {
- console.log("Ajax fail but error on the code: ", err);
- $sv.showErrorLighbox(pageData.tcmInternalError);
- }
- });
- } else {
- if (!pageData.withDates) {
- console.log("Landing without dates");
- noDatesPageActions();
- } else {
- console.log("Error: There is no hotels to send");
- $sv.showErrorLighbox(pageData.tcmInternalError);
- }
- }
- };
- var setLazyAjaxValues = function() {
- if (lazyHotels) {
- var wrapView = $("#view-list");
- wrapDispo = wrapView.find("#hotelesDispo");
- wrapNearby = wrapView.find("#hotelesNearby");
- var groups = [ wrapDispo, wrapNearby ];
- if (lastSearch.isPromo) {
- urlNoPromo = $sv.getNoPromoUrl();
- }
- $.each(groups, function(i, group) {
- if (group.find(".hotelItem").length > 0) {
- $.each(group.find(".hotelItem"), function(i, ele) {
- setLazyHotelInfo(ele, group);
- });
- }
- });
- if (groupResults["#hotelesDispo"] == 0 && groupResults["#hotelesNearby"] == 0) {
- isNoAvailabilityPage = true;
- }
- pageInitActions();
- }
- };
- var setLazyHotelInfo = function(ele, group) {
- var $ele = $(ele);
- var rec = $ele.find("[data-rec]").data("rec");
- var backcode = $ele.data("backcode");
- var hotelMarca = $ele.data("hotelMarca");
- var idGroup = "#" + group.attr("id");
- if (lazyHotels[backcode]) {
- var lazyHotelEle = lazyHotels[backcode];
- var mealRatePlanTitle = lazyHotelEle.mealRatePlanTitle;
- var roomCapacity = lazyHotelEle.roomCapacity;
- var roomTitle = lazyHotelEle.roomTitle;
- if (lazyHotelEle.price) {
- var currency = lazyHotelEle.price.currency || "EUR";
- actualDivisa = currency;
- var totalPrice = lazyHotelEle.price.priceTotal;
- var dayPrice = lazyHotelEle.price.pricePerDay;
- }
- $ele.find(".js-dayprice").html(dayPrice);
- $ele.find(".js-totalprice").html(totalPrice);
- $ele.find(".js-currency").html(currency);
- $ele.find(".js-meanplan-name").html(mealRatePlanTitle);
- $ele.find(".js-roomname").html(roomTitle);
- if (roomCapacity) {
- var capacityData = $ele.find(".js-roomcapacity").data("capacity");
- if (capacityData && capacityData.singular) {
- var capacityLbl = roomCapacity == 1 ? capacityData.singular : capacityData.plural;
- $ele.find(".js-roomcapacity").html(roomCapacity + " " + capacityLbl);
- }
- } else {
- $ele.find(".wrap-roomcapacity").hide();
- }
- var submitButton = $ele.find('.info-result-room form [type="submit"]');
- if (submitButton.length) {
- submitButton.data("preciodia", dayPrice);
- submitButton.data("preciototal", totalPrice);
- submitButton.on("click", function() {
- var $this = $(this);
- reservarHotelRP($this.data("hotelcode"), $this.data("preciodia"), $this.data("num"));
- });
- submitButton.attr("disabled", false);
- }
- $ele.find(".btn-lazy").hide();
- $ele.find(".js-dispo-show").fadeIn();
- var linkTitle = $ele.find(".js-hotel-title");
- linkTitle.removeAttr("id").removeAttr("class");
- linkTitle.on("click", function(e) {
- e.preventDefault();
- $("#seeRooms" + rec).click();
- });
- if (MapsData[rec]) {
- var mapElement = MapsData[rec];
- var logoImage = mapElement.hotelLogo ? '<img class="logo-hotel" src="' + mapElement.hotelLogo + '" alt="' + mapElement.hotelMarca + '" />' : "";
- var htmlRating = "";
- var htmlStars = "";
- if (mapElement.hotelStars) {
- for (var i = 0; i < parseInt(mapElement.hotelStars); i++) {
- htmlStars += '<span class="star"></span>';
- }
- var htmlRating = '<span class="rating">' + htmlStars + "</span>";
- }
- var htmlPrice = "";
- if (dayPrice && dayPrice != totalPrice) {
- htmlPrice += '<div class="clearfix night-price"><span class="pull-left">' + pageLabels.lblMapFrom + '</span><span class="pull-right"><span class="priceChange">' + dayPrice + '</span><sup class="currencyChange">' + currency + "</sup></span></div>";
- }
- if (totalPrice) {
- htmlPrice += '<div class="total-price"><span class="pull-left">' + pageLabels.lblMapPriceTotal + '</span><span class="pull-right">' + totalPrice + "<sup>" + currency + "</sup></span></div>";
- }
- var htmlWindow = "";
- if (mapElement.hotelLink && mapElement.hotelDescription && mapElement.hotelSubmitForm) {
- htmlWindow = '<div class="infoSite new-pin clearfix"><div class="img-info-hotel pull-left">' + mapElement.hotelImage + '</div><div class="pull-left info-hotel-detail">' + logoImage + '<p class="name-hotel">' + mapElement.hotelLink + "</p>" + htmlRating + "" + htmlPrice + '<div class="">' + mapElement.hotelSubmitForm + "</div></div></div>";
- }
- mapElement.clase = "disp";
- mapElement.info = htmlWindow;
- mapElement.icon = typeof iconHotelPath[mapElement.iconKey] != "undefined" ? iconHotelPath[mapElement.iconKey] : mapElement.icon;
- }
- var isHotelPromo = lazyHotelEle.promo ? true : false;
- if (isHotelPromo) {
- var eleDetached = $ele.detach();
- $(idGroup + "Promo").find(".js-ajax-results").append(eleDetached);
- if (typeof groupResults[idGroup + "Promo"] != "undefined") {
- groupResults[idGroup + "Promo"] = groupResults[idGroup + "Promo"] + 1;
- }
- if ($(idGroup + "Promo").is(":hidden")) {
- $(idGroup + "Promo").show();
- }
- } else {
- if (typeof groupResults[idGroup] != "undefined") {
- groupResults[idGroup] = groupResults[idGroup] + 1;
- if (lastSearch.isPromo && urlNoPromo) {
- $ele.find("[data-preciototal]").parents("form").attr("action", urlNoPromo);
- }
- }
- }
- } else {
- setNoAvailabilityHotel(ele, group);
- }
- };
- var noDatesPageActions = function() {
- isNoDatesPage = true;
- pageInitActions();
- };
- var noAvailabilityPageActions = function() {
- LandingPage.isNoAvailabilityPage = true;
- var wrapView = $("#view-list");
- wrapDispo = wrapView.find("#hotelesDispo");
- wrapNearby = wrapView.find("#hotelesNearby");
- var lazyGroups = [ wrapDispo, wrapNearby ];
- $.each(lazyGroups, function(i, group) {
- if ($(group).find(".hotelItem").length > 0) {
- $.each($(group).find(".hotelItem"), function(i, ele) {
- setNoAvailabilityHotel(ele, group);
- });
- }
- });
- $('#selectSort option[value="precioAsc"]').remove();
- $('#selectSort option[value="precioDes"]').remove();
- $("#selectSort").selectpicker("refresh");
- $(".filters .prices").hide();
- pageInitActions();
- };
- var setNoAvailabilityHotel = function(hotel, group) {
- var $hotel = $(hotel);
- $hotel.find(".btn-lazy").hide();
- $hotel.find(".js-nodispo-show").fadeIn();
- if (!$hotel.data("virtual")) {
- var eleDetached = $hotel.detach();
- var noDispoContent = $(group).data("nodispo");
- $(noDispoContent).find(".js-ajax-results").append(eleDetached);
- if (typeof groupResults[noDispoContent] != "undefined") {
- groupResults[noDispoContent] = groupResults[noDispoContent] + 1;
- }
- }
- };
- var setLazyAnalyticsData = function() {
- if (typeof utag_data != "undefined") {
- $.each($("#view-list .hotelItem"), function(i, hotel) {
- var $hotel = $(hotel);
- var availInfo = $hotel.parents('.wrap-hotels[id$="NoDispo"]').length ? "-no available" : "-available";
- utag_data.products_id.push($hotel.data("backcode"));
- utag_data.products_list.push("search results");
- utag_data.products_position.push(i + 1);
- var firstBusqListado = utag_data.busqListado ? "," : "";
- utag_data.busqListado += firstBusqListado + "" + ($hotel.data("backcode") + "" + availInfo);
- utag_data.busqNumResult = pageData.totalHotels;
- utag_data.busqHSinDispo = parseInt(groupResults["#hotelesNoDispo"]) == 0 ? "" : groupResults["#hotelesNoDispo"].toString();
- utag_data.busqSinDispo = LandingPage.isNoAvailabilityPage ? "No availability" : "";
- var firstHotelsList = utag_data.search.hotelsList ? "," : "";
- utag_data.search.hotelsList += firstHotelsList + "" + ($hotel.data("backcode") + "" + availInfo);
- utag_data.search.results = pageData.totalHotels;
- utag_data.search.hWithoutAvailability = parseInt(groupResults["#hotelesNoDispo"]) == 0 ? "" : groupResults["#hotelesNoDispo"].toString();
- utag_data.search.withoutAvailability = LandingPage.isNoAvailabilityPage ? "No availability" : "";
- if ($hotel.find("[data-preciodia]").length > 0) {
- var precioDia = $hotel.find("[data-preciodia]").data("preciodia");
- if (parseFloat(precioDia)) {
- utag_data.products_price.push(parseFloat(precioDia).toFixed(2));
- } else {
- utag_data.products_price.push("no-avail");
- }
- }
- });
- sendUtagData();
- return true;
- } else {
- return false;
- }
- };
- var pageInitActions = function() {
- $("a#modificar").fancybox({
- hideOnContentClick: true
- });
- if (lastSearch.isPromo) {
- $(".show-promo").show();
- $(".hide-promo").hide();
- $(".wrap-hotels.hide-promo").remove();
- }
- if (pageData.isIpad) {
- reorderResults();
- }
- if (lastSearch.voucherCode && lastSearch.voucherCode != "null") {
- $("#promotional").click();
- }
- if (pageData.withDates) {
- LandingFilters.init();
- LandingSort.init();
- }
- Currency.init();
- LandingMap.init();
- setLazyAnalyticsData();
- };
- var userLoggedActions = function() {
- var userData = getUserLoggedData();
- if (userData) {
- if (userData.userName != "anonymous") {
- $(".NHSign").text("");
- $(".NHSign").attr("class", "");
- if (userData["username"] != "anonymous" && userData["authorities"].length > 0 && userData["authorities"][0]["authority"] != "anonymous" && userData["authorities"][0]["authority"] != "DISAMBIGUATION") {
- showLoggedMenu(userData);
- }
- }
- }
- };
- var invalidDates = function() {
- var invalid = false;
- if ($sv.getURLParameter("fini") && $sv.getURLParameter("fout")) {
- var currentDate = new Date();
- var currentDateFormat = $.datepicker.formatDate("dd/mm/yy", currentDate);
- try {
- var dateFin = $.datepicker.parseDate(Dates.currentPattern, $sv.getURLParameter("fout"));
- var dateIni = $.datepicker.parseDate(Dates.currentPattern, $sv.getURLParameter("fini"));
- var diffDays = Math.floor((dateFin - dateIni) / 1e3 / 60 / 60 / 24);
- invalid = diffDays == 0 || diffDays < 0 || diffDays > 15 || dateFin < dateIni || currentDateFormat != $sv.getURLParameter("fini") && currentDate > dateIni;
- } catch (errorDate) {
- console.log(errorDate);
- invalid = true;
- }
- }
- return invalid;
- };
- return {
- init: init,
- isNoAvailabilityPage: isNoAvailabilityPage
- };
- }();
- var LandingServices = function() {
- var getNoPromoUrl = function() {
- var pcodeParam = window.location.search.match(/pcode\=([0-9]+)/i);
- var current = window.location.href;
- return pcodeParam ? current.replace(pcodeParam[0], "") : null;
- };
- var callLoading = function() {
- $(".js-call-loading").click(function() {
- $("#loadingModal").modal({
- show: true,
- backdrop: "static",
- keyboard: false
- });
- });
- };
- var getLastSearch = function(fn) {
- var extendLastSearch = {
- voucherCode: getURLParameter("voucherCode"),
- selectedDivisa: getURLParameter("divisa"),
- groupon: getURLParameter("gvoucher") == "false" ? false : true,
- isPOI: getURLParameter("poiId"),
- pcode: getURLParameter("pcode"),
- b2b: getURLParameter("b2b"),
- b2bData: null,
- contracts: [ "NHWEB" ],
- rates: null,
- searchLandingExpress: null,
- isB2EEmployee: null,
- isB2EFamily: null,
- filterStars: null,
- filterServices: null,
- isPromo: false
- };
- $.extend(lastSearch, extendLastSearch);
- selectedDivisa = lastSearch.selectedDivisa ? lastSearch.selectedDivisa : "";
- if (lastSearch.b2b) {
- var b2bObj = {
- branch: getURLParameter("b2bData.branch"),
- branchId: getURLParameter("b2bData.branchId"),
- company: getURLParameter("b2bData.company"),
- customer: getURLParameter("b2bData.customer"),
- partyIdCompany: getURLParameter("b2bData.partyIdCompany"),
- partyIdCustomer: getURLParameter("b2bData.partyIdCustomer"),
- bpc: getURLParameter("b2bData.bpc"),
- favouriteHotels: getURLParameter("b2bData.favouriteHotels"),
- frequentHotels: getURLParameter("b2bData.frequentHotels"),
- username: getURLParameter("b2bData.username"),
- ccgType: getURLParameter("b2bData.ccgType"),
- type: getURLParameter("b2bData.type")
- };
- lastSearch.b2BData = b2bObj || null;
- }
- var backingBeanUrl = "/booking/ajax/landing/getFlowInformation.html";
- $.ajax({
- type: "GET",
- url: backingBeanUrl,
- headers: {
- Accept: "application/json",
- "Content-Type": "application/json"
- },
- dataType: "json",
- cache: false,
- async: false
- }).done(function(data) {
- if (typeof data != "undefined" && data) {
- if (data.displayBean) {
- var displayBean = data.displayBean;
- if (!$.isEmptyObject(displayBean.contracts)) {
- lastSearch.contracts = [];
- $.each(displayBean.contracts, function(i, contract) {
- lastSearch.contracts.push(contract);
- });
- }
- if (displayBean.isSearchLandingExpress != "") {
- lastSearch.searchLandingExpress = displayBean.isSearchLandingExpress;
- }
- if (displayBean.isB2EEmployee != "") {
- lastSearch.isB2EEmployee = $.parseJSON(displayBean.isB2EEmployee);
- }
- if (displayBean.isB2EFamily != "") {
- lastSearch.isB2EFamily = $.parseJSON(displayBean.isB2EFamily);
- }
- }
- if (data.backingBean) {
- var backingBean = data.backingBean;
- if (!$.isEmptyObject(backingBean.ratePlansPromo)) {
- lastSearch.rates = [];
- $.each(backingBean.ratePlansPromo, function(i, rate) {
- lastSearch.rates.push(rate);
- });
- }
- }
- }
- }).fail(function(data) {
- console.log("Fail call getFlowInformation: ", data.status, data.responseText);
- });
- LazyDataSend.fini = lastSearch.fini || null;
- LazyDataSend.fout = lastSearch.fout || null;
- LazyDataSend.voucherCode = lastSearch.voucherCode || null;
- LazyDataSend.pCode = lastSearch.pcode || null;
- LazyDataSend.b2b = lastSearch.b2b || null;
- LazyDataSend.roomRequest = [];
- LazyDataSend.b2BData = lastSearch.b2BData || null;
- LazyDataSend.destinationtype = "destination";
- LazyDataSend.contracts = lastSearch.contracts;
- LazyDataSend.rates = lastSearch.rates;
- LazyDataSend.searchLandingExpress = lastSearch.searchLandingExpress;
- LazyDataSend.b2eEmployee = lastSearch.isB2EEmployee || null;
- LazyDataSend.b2eFriends = lastSearch.isB2EFamily || null;
- lastSearch.isPromo = lastSearch.pcode ? true : false;
- if (!$.isEmptyObject(lastSearch.occupancy)) {
- lastSearch.numTotalAdults = 0;
- lastSearch.numTotalChildren = 0;
- lastSearch.numTotalBabies = 0;
- $.each(lastSearch.occupancy, function(i, room) {
- var lazyRoomItem = {
- numberOfAdults: room.adults,
- numberOfChildren: room.children,
- numberOfBabies: room.babies
- };
- LazyDataSend.roomRequest.push(lazyRoomItem);
- lastSearch.numTotalAdults += parseInt(room.adults);
- lastSearch.numTotalChildren += parseInt(room.children);
- lastSearch.numTotalBabies += parseInt(room.babies);
- });
- }
- if (typeof fn != "undefined") {
- fn(lastSearch);
- }
- };
- var showErrorLighbox = function(tcmError) {
- var lightboxError = "#error";
- if (tcmError) {
- utag_data.page.errorType = tcmError;
- var url = $(lightboxError).attr("href");
- if (getURLParameter("tcmError", url)) {
- var newUrl = url.replace(getURLParameter("tcmError", url), tcmError);
- $(lightboxError).attr("href", newUrl);
- } else {
- $(lightboxError).attr("href", url + "&tcmError=" + tcmError);
- }
- }
- $(".wrap-hotels").hide();
- $(lightboxError).fancybox({
- closeClick: false,
- hideOnOverlayClick: false,
- hideOnContentClick: false,
- helpers: {
- overlay: {
- closeClick: false
- }
- }
- }).trigger("click");
- $(document).on("click", ".fancybox-item.fancybox-close", function(event) {
- event.preventDefault();
- parent.window.location.href = "/";
- });
- };
- var getURLParameter = function(name, url) {
- var urlT = url ? url : window.location.href;
- name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
- var regexS = "[\\?&]" + name + "=([^&#]*)";
- var regex = new RegExp(regexS);
- var results = regex.exec(urlT);
- if (results == null) {
- return null;
- } else {
- return decodeURIComponent(results[1].replace(/\+/g, " "));
- }
- };
- var getDiffDays = function(date1, date2) {
- date1 = new Date(date1.split("/")[2], date1.split("/")[1] - 1, date1.split("/")[0]);
- date2 = new Date(date2.split("/")[2], date2.split("/")[1] - 1, date2.split("/")[0]);
- var timeDiff = Math.abs(date1.getTime() - date2.getTime());
- var diffDays = Math.ceil(timeDiff / (1e3 * 3600 * 24));
- return diffDays;
- };
- var callTripAdvisorReviews = function() {
- var widget = $(".js-widget-reviews.js-type-tripadvisor");
- $.each(widget, function(i, widget) {
- var $widget = $(widget);
- var idTrip = $widget.data("id");
- var idHotel = $widget.data("hotel");
- var certificate = $widget.data("certificate");
- var device = $widget.data("device");
- var html;
- var idioma = typeof widgetReviewsData.idioma != "undefined" ? widgetReviewsData.idioma : langTrip;
- var lblOpinions = typeof widgetReviewsData.lblOpinions != "undefined" ? widgetReviewsData.lblOpinions : "";
- var lblCertificateExcellence = typeof widgetReviewsData.lblCertificateExcellence != "undefined" ? widgetReviewsData.lblCertificateExcellence : "";
- if (typeof idTrip != "undefined" && idTrip != "") {
- var url = "/rest/trip/tripadvisorhotelrate/" + idTrip;
- $.ajax({
- cache: true,
- async: true,
- url: url,
- dataType: "json",
- success: function(data) {
- if (data != "null") {
- var htmlCertificate = '<span class="certificate pull-right">' + lblCertificateExcellence + "</span>";
- if (device == "mobile") {
- html = '<div class="hidden-lg hidden-md"><div class="clearfix2"></div><div class="tripadvisor-rating"><div class=""><span class=""></span><span class="qty-rating">' + data.rate + '</span><span><img src="' + data.ratingImageLink + '" /></span></div><a href="https://www.tripadvisor.com/WidgetEmbed-cdspropertydetail?locationId=' + idTrip + "&lang=" + idioma + '&partnerId=674E62BCD5A549E3AA92015CAB228207&isTA=&format=html&display=true" class="qty-opiniones pull-left">' + data.numComents + " " + lblOpinions + "</a>" + (certificate ? htmlCertificate : "") + "</div></div>";
- } else {
- html = '<div class="col-sm-4 visible-lg visible-md addMarginTop15"><div class="tripadvisor-rating pull-right"><div class="text-right"><span class=""></span><span class="qty-rating">' + data.rate + '</span><span><img src="' + data.ratingImageLink + '" /></span></div><a href="https://www.tripadvisor.com/WidgetEmbed-cdspropertydetail?locationId=' + idTrip + "&lang=" + idioma + '&partnerId=674E62BCD5A549E3AA92015CAB228207&isTA=&format=html&display=true" class="fancybox fancybox.iframe qty-opiniones text-right">' + data.numComents + " " + lblOpinions + "</a>" + (certificate ? htmlCertificate : "") + "</div></div>";
- }
- $widget.html(html);
- } else {
- $widget.hide();
- }
- }
- });
- } else {
- $widget.hide();
- }
- });
- };
- var callTrustYouReviews = function(hotelBackCode, device) {
- var widget = $(".js-widget-reviews.js-type-trustyou");
- $.each(widget, function(i, widget) {
- var $widget = $(widget);
- var idTrust = $widget.data("id");
- var device = $widget.data("device");
- var html;
- var idioma = typeof widgetReviewsData.idioma != "undefined" ? widgetReviewsData.idioma : langTrip;
- var lblReviews = typeof widgetReviewsData.lblReviews != "undefined" ? widgetReviewsData.lblReviews : "";
- if (typeof idTrust != "undefined" && idTrust != "") {
- var url = "/trustYou/seal";
- $.ajax({
- cache: true,
- async: true,
- url: url,
- dataType: "json",
- success: function(data) {
- if (data != "null") {
- var score = data.score;
- var scoreDes = data.scoreDes;
- var numReviews = data.numReviews;
- if (device == "mobile") {
- html = '<div class="hidden-lg hidden-md"><div class="summary-header relative"><div class="trustscore2"><div class="value">' + score + '</div><div class="badges-opi"></div><div class="score-opi">' + scoreDes + '</div><div class="trust-opi">' + numReviews + " " + lblReviews + "</div></div></div></div>";
- } else {
- html = '<div class="col-sm-4 visible-lg visible-md addMarginTop15"><div class="summary-header relative"><div class="trustscore2"><div class="value">' + score + '</div><div class="badges-opi"></div><div class="score-opi">' + scoreDes + '</div><div class="trust-opi">' + numReviews + " " + lblReviews + "</div></div></div></div>";
- }
- $widget.html(html);
- } else {
- $widget.hide();
- }
- }
- });
- } else {
- $widget.hide();
- }
- });
- return false;
- };
- return {
- getDiffDays: getDiffDays,
- showErrorLighbox: showErrorLighbox,
- getURLParameter: getURLParameter,
- callTrustYouReviews: callTrustYouReviews,
- callTripAdvisorReviews: callTripAdvisorReviews,
- getLastSearch: getLastSearch,
- callLoading: callLoading,
- getNoPromoUrl: getNoPromoUrl
- };
- }();
- $(function() {
- if ($("body").hasClass("page-landing")) {
- LandingPage.init();
- }
- if (!pageData.withDates) {
- LandingFilters.init();
- LandingSort.init();
- }
- });
Add Comment
Please, Sign In to add comment