﻿var reservShowed = false;
var IsPromotion = false;
var DistributionInformation;
var checkoutUrl = "";
var ABTest = true;
var tempUrlHotelResults = "";

function Init() {
    checkoutUrl = SSLUrl + "/Booking/HotelCheckout/PurchaseForm/";
    if($("#Errors").text().length == 0){
        $('.lnkHomeLink').attr('href', BaseUrl + '/Hotels/Home/' + cityCode + '/');
        vPais = $('#ltIdiomaCalendariosp').text();

        var configuration;
        $.ajax({
        url: "/Contents/Servicies/CalendarService.ashx",
            async: false,
            success: function(data) {
                configuration = data;
            },
            dataType: "json"
        });

        var product;
        for (i = 0; i < configuration.products.length; i++) {
            if (configuration.products[i].cod == "hot") {
                product = configuration.products[i];
            }
        }
        product.data.anticipationDays = product.data.defaultAnticipationDays;
        
        $("#buscadorHotelesFechaSalida").calendar({
            tripType: "go",
            inputRelatedID: 'buscadorHotelesFechaRegreso',
            shownMonths: 2,
            language: options.lan,
            product: "hot",
            configuration: configuration
        });

        $("#buscadorHotelesFechaRegreso").calendar({
            tripType: "return",
            inputRelatedID: 'buscadorHotelesFechaSalida',
            shownMonths: 2,
            language: options.lan,
            product: "hot",
            configuration: configuration
        });        

        $("#FRMmapa").attr('src', BaseUrl + '/Hotels/IframeMap.aspx');
        $("#FRMmapa").load(LoadMapAction);
        if (glJson.VirtualTours != undefined) {
            if (glJson.VirtualTours.length != 0) {
	            $("#tabContentVirtualTour").show();
	            $("#virtualTourContainer").html('<iframe id="virtualTour" name="virtualTour" class="virtualTourIframe" src="' + glJson.VirtualTours[0].Url + '"></iframe>');
            }
        }
		
		$("#btnChangeDates").bind("click",function(){
			$("#bNoResults").hide();
			$("#divSearch").show();
		});
		
    }
}

function loadScript(name, path, callBack, charset) {
    var head = document.getElementsByTagName('head')[0];
    var scriptTag;
    scriptTag = document.createElement("script");
    scriptTag.id = name;
    scriptTag.src = path;
    scriptTag.type = "text/javascript";
    if (charset != undefined) {
        scriptTag.charset = charset;
    }
    if (callBack != undefined) {
        scriptTag.onload = scriptTag.onreadystatechange = callBack;
    }
    head.appendChild(scriptTag);
}

function loadCss(path, callBack) {
    var scriptTag;
    var head = document.getElementsByTagName('head')[0];
    scriptTag = document.createElement("link");
    scriptTag.rel = "stylesheet";
    scriptTag.href = path;
    scriptTag.type = "text/css";
    if (callBack != undefined) {
        scriptTag.onload = scriptTag.onreadystatechange = callBack;
    }
    head.appendChild(scriptTag);
}

function loadHtml(destDiv, sourceDiv, sourceFile, callBack) {
    if (callBack != undefined) {
        $("#" + destDiv).load(sourceFile + " #" + sourceDiv, null, callBack);
    } else {
        $("#" + destDiv).load(sourceFile + " #" + sourceDiv);
    }

}

function enableErrorMsg() {

    loadPopups = true;
}

function LoadMapAction() {

    map = document.getElementById('FRMmapa').contentWindow.map;
    map.ImagePath = staticHost + "/images/" + brandName + "/hoteles/maps/";
    map.MessageErrorInit = "Ocurrio un error al cargar la pagina\nPor favor, vuelva a intentarlo.\nGracias.";

    document.getElementById('FRMmapa').contentWindow.document.getElementById('DIVmapa').style.width = "660px";
    document.getElementById('FRMmapa').contentWindow.document.getElementById('DIVmapa').style.height = "400px";
    map.Bound = document.getElementById('FRMmapa').contentWindow.getNewGLatLngBounds();
    map.Init("DIVnoMapa", "DIVmapa");
    map.CreateHMarker(glJson);
}

String.prototype.capitalize = function() {
    
        return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();

    };

function formatCurrency(num, showCents) {

    if (typeof (num) != undefined) {
        num = num.toString().replace(/\$|\,/g, '');
        if (isNaN(num)) {
            num = "0";
        }
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num * 100 + 0.50000000001);
        cents = num % 100;
        num = Math.floor(num / 100).toString();
        if (cents < 10) {
            cents = "0" + cents;
        }
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
            num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));
        }
        var out = (sign ? '' : '-') + num;
        if (showCents) {
            out += '.' + cents;
        }
        return out;
    }
    return num;
}

function parseDateHour(jsonDate) {
    var d;
    if (jsonDate == null)
        return null;
    var m = jsonDate.match(/^\/Date\((\d+)([-+]\d\d)(\d\d)\)\/$/);
    if (m == null) {

        m = jsonDate.replace(')/', '').split("/Date(");

        if (m == null) {
            return null;
        }
        d = new Date(parseInt(m[1]));
        if (d == null) {
            return null;
        }
        return new Date(parseInt(m[1]) + d.getTimezoneOffset() * 60 * 1000);
    }

    return new Date(parseInt(m[1]));
}

function parseDate(stringDate) {
    var dateparts = stringDate.split("-");

    return new Date(dateparts[0], dateparts[1] - 1, dateparts[2], 0, 0, 0);
}

function getFormatedDate(input) {
    var d = input.split(new RegExp('/', 'gi'));
    return d[2] + "-" + d[1] + "-" + d[0];
}

function hideReserveOptions() {
    window.currentRoomId = null;
    $(".trSelected").removeClass("trSelected");
    $('#popUpReserva').hide();
}

function showBestWar() {
    $('#BestPriceWarPop').show();
}

function noAvailability() {
    $("#btnOtherHotels").bind("click", function() {
        window.location = tempUrlHotelResults;
    });
    
    $('#tabContentFares > .loadingModal').hide();
    $('#tabContentFares > .loadingBox').hide();
    $('#divSearch').hide();
    $("#bNoResults").show();

    $("#lblFaresOtherDate").css("text-align", "center");
    $("#lblFaresOtherDate").show();
}

function ajaxErrorNoDisp(XMLHttpRequest, textStatus) {
    noAvailability();             
}

function AddStaticContentHost(url) {
    if (url.indexOf('/') == 0) {
        return staticHost + url;
    } else {
        return url;
    }
}

function setMainPhoto(PhotoUrl) {
    $("#imgMain").attr("src", AddStaticContentHost(PhotoUrl));
}

function validateParams() {
    var result = true;
    var texto = "";
    spFrom = $("#buscadorHotelesFechaSalida").val().split(new RegExp('/', 'gi'));
    spTo = $("#buscadorHotelesFechaRegreso").val().split(new RegExp('/', 'gi'));
    var Dfrom = Date.parse(spFrom[1] + "/" + spFrom[0] + "/" + spFrom[2]);
    var Dto = Date.parse(spTo[1] + "/" + spTo[0] + "/" + spTo[2]);
    var titulo = $("#lterrordatossp").text().split('-');
    var errordestino = $("#ltErrordestinosp").text().split('-');
    var errorfregreso = $("#ltErrofFregresosp").text().split('-');
    var errorfsalida = $("#ltErrorFsalidasp").text().split('-');
    var errorfimposible = $("#ltErrorFimposiblesp").text().split('-');
    var errorredades = $("#ltErroredadessp").text().split('-');
    texto = titulo[1] + ":\n";


    if (isNaN(Dfrom) == true || $("#buscadorHotelesFechaSalida").data("isValid")!=true) {
        texto += "-" + errorfregreso[1] + "\n";
        result = false;
    }

    if (isNaN(Dto) == true || $("#buscadorHotelesFechaRegreso").data("isValid") != true) {
        texto += "-" + errorfsalida[1] + "\n";
        result = false;
    }

    if (isNaN(Dfrom) == false && isNaN(Dto) == false) {
        Dfrom = new Date(Dfrom);
        Dto = new Date(Dto);

        if (Dfrom > Dto) {
            texto += "-" + errorfimposible[1] + "\n";
            result = false;
        }
    }
    var cnnAgeOk = true;
    $(".passangersCnnAgeSelection:visible").each(function(e) {
        if ($(this).attr("value") == '-1') {
            cnnAgeOk = false;
        }
    });
    if (!cnnAgeOk) {
        texto += "-" + errorredades[1] + "\n";
        result = false;
    }

    if (result == false) {
        alert(texto);
    }
    return result;
}

function setCheckRoomValues(qtyRoom, total, checkIn, checkOut) {

    var checkInString = getDateParse(checkIn).toString();
    var checkOutString = getDateParse(checkOut).toString();
    $("#bCheckInDateStr").text(checkInString.capitalize());
    $("#bCheckOutDateStr").text(checkOutString.capitalize());
    $("#bNRooms").text(qtyRoom);
    if (qtyRoom > 1) {

        $("#CantHab").text(" " + qtyRoom);
        $("#conjuncion").text($("#ltlassp").text());
        $("#habitaciones").text($("#ltVarhabitacionessp").text());
    }
    else {
        $("#CantHab").text("");
        $("#conjuncion").text($("#ltlasp").text());
        $("#habitaciones").text($("#ltUnahabitacionessp").text());
    }
    if (qtyRoom > 1)
        $("#ltRooms").text($("#lblHabPl").text());
    else
        $("#ltRooms").text($("#lblHabSin").text());


    $("#bPeople").text(total);
    $("#NPersonas").text(total);
    
    if (total > 1)
        $("#ltPass").text($("#lblPasPl").text());
    else
        $("#ltPass").text($("#lblPasSin").text());

}

function getDateParse(inputDate) {
    inputDate = getDate(inputDate);
    return aDayWeekNames[inputDate.getDay()] + ", " + inputDate.getDate() + " " + aMonthNames[inputDate.getMonth()] + " " + inputDate.getFullYear();
}

function getDate(input) {
    var d = input.split(new RegExp('/', 'gi'));
    return new Date(d[2], d[1]-1, d[0], 0, 0, 0, 0);
}

function GetHotelRooms() {
    
    DistributionInformation = getRoomsDetails();

    if (validateParams() == true) {
        $('#tabContentFares > .loadingModal').show();
        $('#tabContentFares > .loadingBox').show();
        $("#lblCheckInOutDetails").show();
        tempFromUrl = urlHotelRoomsDetalle;
        checkInDate = document.getElementById("buscadorHotelesFechaSalida").value;
        checkOutDate = document.getElementById("buscadorHotelesFechaRegreso").value;
        CheckInInvariantDateString = getFormatedDate(checkInDate);
        CheckOutInvariantDateString = getFormatedDate(checkOutDate);
        tempFromUrl = tempFromUrl.replace("#checkInDate#", CheckInInvariantDateString);
        tempFromUrl = tempFromUrl.replace("#checkOutDate#", CheckOutInvariantDateString);
        tempFromUrl = tempFromUrl.replace("#stringDistributions#", DistributionInformation.roomsSerialize);
        
        /*URL de resultados*/
        tempUrlHotelResults = urlHotelResults;
        tempUrlHotelResults = tempUrlHotelResults.replace("#checkInDate#", CheckInInvariantDateString);
        tempUrlHotelResults = tempUrlHotelResults.replace("#checkOutDate#", CheckOutInvariantDateString);
        tempUrlHotelResults = tempUrlHotelResults.replace("#stringDistributions#", DistributionInformation.roomsSerialize);

        RoomDistribution = DistributionInformation.roomsSerialize;
        
        setCheckRoomValues(DistributionInformation.rooms, DistributionInformation.qtyPax, checkInDate, checkOutDate);

        $.ajax({
        url: tempFromUrl,
            type: "POST",
            dataType: "json",
            success: processAvailability,
            error: ajaxErrorNoDisp,
            async: true
        });        
        movement();


    }
}

function setFlow(flow) {
    checkoutUrl += "&flw=" + flow;
}

/**
* Se ejecuta cuando hay disponibilidad, se redirige al checkout
*/
function availability() {

    //crear el objeto ABTest
    //traer el archivo de configuracion
    //
    if (ABTest) {
        var dataABTest = {//por default en caso que falle al traer el archivo.
            "ABTestId": "Checkout",
            "sessionKeepAliveDays": "1",
            "alternatives": [{ "percentage": "100", "params": "a" },
								{ "percentage": "0", "params": "b" },
								{ "percentage": "0", "params": "c" }
							],
            "resetSession": true
        };
        $.ajax({
            url: "/js/FrameworkJS/Site/Hotels/ABTestCheckoutInfo.txt",
            dataType: 'json',
            success: function(data) {
                dataABTest = data;
            },
            async: false,
            error: function(error, textStatus, errorThrown) {
            }
        });

        $.each(dataABTest.alternatives, function(i, e) {
            dataABTest.alternatives[i].callBack = setFlow;
        })

        abTestObj = new Common.ABTest(dataABTest);
    }
    location.href = checkoutUrl;
}

function processAvailability(json) {
    var checkoutUrlQString = "";
    if (json == null || !json.Availability || (json.DiscountPriceWithOutTax == 0 && json.PriceWithOutTax == 0)) {
        noAvailability();
        return;
    } else {
    var checkoutUrlQString = '?nl=' + noLocalCurrency + '&adp=' + json.DiscountPriceWithOutTax + '&pt=' + json.PaymentType;
        checkoutUrl += json.SessionTicket + checkoutUrlQString;
        availability();
    }
}

function movement() {
    $("#popUpReglasDeCancelacionTitle").mousedown(function(e) {
        $("#DetalleHotelesBody").mousemove(function(e) {


            $('#popUpReglasDeCancelacionTitle').css("cursor", "move");
            $('#popUpReglasDeCancelacion').css({ left: (e.pageX - ($('#popUpReglasDeCancelacion').width() / 2)), top: e.pageY - (30) });

        });

    });
    $("#popUpReglasDeCancelacionTitle").mouseup(function(e) {

        $('#popUpReglasDeCancelacionTitle').css("cursor", "auto");
        $('#DetalleHotelesBody').unbind('mousemove');
    });

    $("#popUpPrecioDeCadaNocheTitle").mousedown(function(e) {
        $("#DetalleHotelesBody").mousemove(function(e) {

            $('#popUpPrecioDeCadaNocheTitle').css("cursor", "move");

            $('#popUpPrecioDeCadaNoche').css({ left: (e.pageX - ($('#popUpPrecioDeCadaNoche').width() / 2)), top: e.pageY - (30) });

        });

    });
    $("#popUpPrecioDeCadaNocheTitle").mouseup(function(e) {

        $('#popUpPrecioDeCadaNocheTitle').css("cursor", "auto");
        $('#DetalleHotelesBody').unbind('mousemove');
    });

    $("#popUpComodidadesTitle").mousedown(function(e) {

        $('#popUpComodidadesTitle').css("cursor", "move");

        $("#DetalleHotelesBody").mousemove(function(e) {


            $('#popUpComodidades').css({ left: (e.pageX - ($('#popUpComodidades').width() / 2)), top: e.pageY - (30) });

        });

    });
    $("#popUpComodidadesTitle").mouseup(function(e) {

        $('#popUpComodidadesTitle').css("cursor", "auto");
        $('#DetalleHotelesBody').unbind('mousemove');
    });

}

function getMonDay(date) {

    if (date.getDay() == 0)
        return 7;
    else
        return date.getDay();
}

function compareUtc(date1, date2) {
    var result1;
    var result2;
    result1 = ((((Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate()) / 1000) / 60) / 60) / 24);
    result2 = ((((Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate()) / 1000) / 60) / 60) / 24);
    return (result1 == result2)

}

function getFromWeek(date) {
    var result = new Date(date);
    var monthBeg = new Date(result.getFullYear(), result.getMonth(), 1);

    if (compareUtc(result, monthBeg))
        return result;

    if (date.getDay() == 0)
        result.setDate(date.getDate() - 6);
    else
        result.setDate(date.getDate() - (date.getDay() - 1));
    return result;
}

function getToWeek(date) {
    var result = new Date(date);
    var monthBeg = new Date(result.getFullYear(), result.getMonth() + 1, 1);
    monthBeg.setDate(monthBeg.getDate() - 1);

    if (date.getDay() == 0)
        result.setDate(date.getDate());
    else
        result.setDate(date.getDate() + (7 - date.getDay()));

    if (result > monthBeg)
        return monthBeg;
    else
        return result;

}

function buildDistributionList(RoomDist) {
    var result = "";
    var i;
    var j;
    for (i = 0; i < RoomDist.length; i++) {
        if (i >= 1)
            result += "!";
        result += RoomDist[i].Adults;
        for (j = 0; j < RoomDist[i].Children.length; j++)
            result += "-" + RoomDist[i].Children[j];
    }
    return result;
}

////////////////Logging functions ///////////
function doLogging() {
    if ((typeof Despegar).toString() == "object") {
        var reportData = new Despegar.HotelsReportLogData();
        var stage = new Despegar.FlowStage();
        var logger = new Despegar.Logger();
        reportData.ClientTime = CreateJSonDate(new Date());
        reportData.Stage = stage.HotelLanding;
        reportData.CheckIn = CreateJSonDate(getDateFromField(CheckInInvariantDateString));
        reportData.CheckOut = CreateJSonDate(getDateFromField(CheckOutInvariantDateString));
        reportData.Distribution = DistributionInformation.roomsSerialize;
        reportData.Destination = cityCode;
        
        if (JSONRooms == null) {

            reportData.DetailDisponibility = -1;
        } else {
            if (JSONRooms.length > 0)
            { reportData.DetailDisponibility = 1 } else
            { reportData.DetailDisponibility = 0 }
        }
        
        reportData.IsPromotion = IsPromotion;
        
        if (reportData.DetailDisponibility == 1)
            reportData.Provider = JSONRooms[0].Provider;

        reportData.DespegarHotelId = JSONRooms.HotelID;
        reportData.OriginalPrice = resultHotelPrice; 
                       
        logger.LogReport(reportData);

    }

}
function getDateFromField(dateString) {
    var sp = dateString.split("-");
    if (sp.length != 3)
        return new Date();
    else
        return new Date(sp[0], sp[1] - 1, sp[2]);
}
