﻿/// <reference path="jquery-1.3.1-vsdoc.js" />
/**
* Copyright (c) 2009 Web Revolution s. r. o.
*/

$(document).ready(function() {
    // Datepickers for the search form
    $("#arrivaldate").datepicker({ onSelect: function(formatted, dates) {
        var aDate = Widgets.parseDate(formatted);
        var dDate = Widgets.parseDate($("#departuredate").val());
        if (aDate != null && (dDate == null || dDate < aDate)) {
            dDate = aDate;
            dDate.setDate(aDate.getDate() + 1);
            $("#departuredate").datepicker("setDate", dDate);
        }

    }, dateFormat: 'dd.mm.yy'
    });

    $("#departuredate").datepicker({ onSelect: function() { }, dateFormat: 'dd.mm.yy' });
    $(".dtpick").datepicker({ onSelect: function() { }, dateFormat: 'dd.mm.yy' });
    $(".birthDtPick").datepicker({
        onSelect: function() { },
        dateFormat: 'dd.mm.yy',
        minDate: new Date(1910, 0, 1),
        yearRange: '-99:+0'
    });
});

// Incoming prototype
var Incoming = {
    res: {},

    setResource: function(_res) {
        this.res = _res;
    },

    // Get price of the term for hotel
    getTermPrice: function(_elem, _hotel, _from, _to) {
        var _langId = __langId;
        var roomType = _elem.value;
        var pricelist = hpList[_hotel][roomType].split(":");
        var perWhat = _pType == "p" ? this.res.perPerson : this.res.perNight;
        $("#lhp" + _hotel).html(pricelist == null || pricelist[1] == "0" ? this.res["noroomsavaible"] : "<strong>" + pricelist[0] + "</strong>" + perWhat);

        if (pricelist == null || pricelist[1] == "0") {
            $('#reservationButton').hide();
            $('#checkButton').show();
        }
        else {
            $('#reservationButton').show();
            $('#checkButton').hide();
        }
    },

    // Set URL reservation according to the hotel, room and term
    setReservationUrl: function(elemId, _room, _from, _to) {
        var urls = $("#" + elemId);
        if (urls.size() > 0) {
            var currentUrl = urls[0];
            var end = currentUrl.href.indexOf("?");
            if (end == -1) {
                end = currentUrl.href.length;
            }
            else {
                currentUrl.href = currentUrl.href.substr(0, end);
            }
            currentUrl.href += "?room=" + _room + "&arrivaldate=" + _from + "&departuredate=" + _to;
        }
    },

    // Get the content of the selector for city (according to the country)
    fillCity: function(_elem) {
        var _langId = __langId;
        var _parentId = _elem.value;
        $.ajax({
            type: "POST",
            url: "/Services/Incoming.asmx/GetLocalityList",
            data: "{langId: '" + _langId + "', parentId: '" + _parentId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $("#citySelect").html(msg.d);
            }
        });
    },

    // Confirm term price - confirm date fill
    confirmTermPriceTestWithId: function(formId, arrivalDateId, departureDateId) {
        var aDate = Widgets.parseDate($("#" + arrivalDateId)[0].value);
        var dDate = Widgets.parseDate($("#" + departureDateId)[0].value);
        if (aDate == null || dDate == null) {
            if (formId == "HotelSearchForm") {
                return true;
            }

            alert(this.res.insertTermDate);
            return false;
        }
        if (aDate >= dDate) {
            alert(this.res.higherTermDate);
            return false;
        }

        var form = $("#" + formId);
        if (form.length > 0 && formId != "HotelSearchForm" && formId != "checkTermForm") {
            form[0].action = "";
        }

        return true;
    },

    // Confirm term price - confirm date fill
    confirmTermPriceTest: function(formId) {
        return this.confirmTermPriceTestWithId(formId, "arrivaldate", "departuredate");
    },

    // Add hotel to the depository
    addHotelDepository: function(hotel) {
        var _langId = __langId;
        $.ajax({
            type: "POST",
            url: "/Services/Incoming.asmx/AddHotelDepository",
            data: "{langId: '" + _langId + "', hotelId: '" + hotel + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $("#odklDep").html(msg.d);
            }
        });
    },

    // Remove hotel from the depository
    removeHotelDepository: function(hotel) {
        var _langId = __langId;
        $.ajax({
            type: "POST",
            url: "/Services/Incoming.asmx/RemoveHotelDepository",
            data: "{langId: '" + _langId + "', hotelId: '" + hotel + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $("#odklDep").html(msg.d);
            }
        });
    },

    // Set room total price to the price span
    setRoomTotalPrice: function(rooms, price, id) {
        $("#rt" + id).html(Widgets.formatPrice(rooms * price));
    },

    // Set service total price to the price span
    setServiceTotalPrice: function(price, id, priceType) {
        var count = $("#service_" + id).val();

        if (priceType == 0) {
            $("#st" + id).html(Widgets.formatPrice(count * price));
            return;
        }

        // 1. Find date elems
        var arrDate = Widgets.parseDate($("#arrDate" + id).val());
        var depDate = Widgets.parseDate($("#depDate" + id).val());
        var dayCount = 0;

        if (arrDate != null && depDate != null && arrDate <= depDate) {
            var dateSpan = new Date(depDate - arrDate);

            if (priceType == 1) {
                // Per day
                dayCount = dateSpan.getDate();
            } else if (priceType == 2) {
                // Per night
                dayCount = dateSpan.getDate() - 1;
            }
        }

        $("#st" + id).html(Widgets.formatPrice(dayCount * count * price));
    },

    // Fill room capacity info 
    fillCapacity: function(roomType, rewrite) {
        var r = $("#r" + roomType)[0].value;
        var p = $("#p" + roomType)[0].value;
        var c = $("#c" + roomType)[0].value;
        var s = $("#s" + roomType)[0].value;
        var m = $("#m" + roomType)[0].value;

        var rItems = $("[id^=r" + roomType + "_]");
        var pItems = $("[id^=p" + roomType + "_]");
        var cItems = $("[id^=c" + roomType + "_]");
        var sItems = $("[id^=s" + roomType + "_]");
        var mItems = $("[id^=m" + roomType + "_]");

        for (var i = 0; i < rItems.length; i++) {
            rItems[i].value = ((rewrite || rItems[i].value == "") && r != "") ? r : rItems[i].value;
            pItems[i].value = ((rewrite || pItems[i].value == "") && p != "") ? p : pItems[i].value;
            cItems[i].value = ((rewrite || cItems[i].value == "") && c != "") ? c : cItems[i].value;
            sItems[i].value = ((rewrite || sItems[i].value == "") && s != "") ? s : sItems[i].value;
            mItems[i].value = ((rewrite || mItems[i].value == "") && m != "") ? m : mItems[i].value;
        }
    },
    googleMap: null,
    googleMapOverlays: [],

    // Get the instance of the google map
    getGoogleMap: function() {
        var mapElem = document.getElementById("map");

        try {
            if (mapElem) {
                if (this.googleMap == null) {
                    this.googleMap = new GMap2(mapElem);
                    this.googleMap.addControl(new GMapTypeControl());
                    this.googleMap.addControl(new GLargeMapControl());
                }

                return this.googleMap;
            }
        } catch (e)
        { }

        return null;
    },

    // Initialize google map
    googleMapsInitialize: function() {
        for (var i = 0; i < this.googleMapOverlays.length; i++) {
            this.putGoogleMapOverlay(this.googleMapOverlays[i].icon,
                    this.googleMapOverlays[i].lat,
                    this.googleMapOverlays[i].lng,
                    null);
        }
        this.googleMapOverlays = new Array();
    },

    // Put overlay image to google map
    putGoogleMapOverlay: function(icon, lat, lng, message) {
        if (this.googleMap == null) {
            this.googleMapOverlays.push({ icon: icon, lat: lat, lng: lng });
            return;
        }
        var map = this.getGoogleMap();
        var gIcon = new GIcon(G_DEFAULT_ICON);
        gIcon.image = icon;
        gIcon.iconSize = new GSize(16, 16);
        gIcon.shadowSize = new GSize(0, 0);
        markerOptions = { icon: gIcon };
        var gMarker = new GMarker(new GLatLng(lat, lng), markerOptions);
        if (message != null) {
            gMarker.bindInfoWindowHtml(message);
        }
        map.addOverlay(gMarker);
    },

    rActiveHotelId: null,

    // Open form for insert rating for the hotel
    openRatingForm: function(hotelId) {
        if ($("#popupForm").length > 0) {
            // Form has been alerady open
            return;
        }

        var _langId = __langId;
        this.rActiveHotelId = hotelId;

        $.ajax({
            type: "POST",
            url: "/Services/Incoming.asmx/GetRatingForm",
            data: "{langId: '" + _langId + "', hotelId: '" + hotelId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $("#contIn").prepend(msg.d);
            }
        });
    },

    // Open form for unavailable term ask
    openTermAskForm: function(hotelId, formId) {
        if ($("#popupForm").length > 0) {
            // Form has been alerady open
            return;
        }

        var theForm = $("#" + formId)[0];
        var _langId = __langId;
        this.rActiveHotelId = hotelId;
        var _arrivalDate = theForm.arrivaldate.value;
        var _departureDate = theForm.departuredate.value;

        $.ajax({
            type: "POST",
            url: "/Services/Incoming.asmx/GetTermAskForm",
            data: "{langId: '" + _langId + "', hotelId: '" + hotelId + "', arrivalDate: '" + _arrivalDate + "', departureDate: '" + _departureDate + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $("#contIn").prepend(msg.d);
            }
        });
    },

    // Close the popup form
    closePopupForm: function() {
        $("#popupForm").remove();
    },

    // Send rating
    sendRating: function() {
        if (this.rActiveHotelId == null || $("#popupForm").length == 0) {
            // Form has been alerady open
            return;
        }

        var _langId = __langId;
        var rName = $("#rName")[0].value;
        var rCountry = $("#rCountry")[0].value;
        var rResId = $("#rResId").size() == 1 ? $("#rResId")[0].value : "";
        var rGroupId = $("#rGroup")[0].value;
        var types = $("[name^=rType]");
        var rPosNote = $("#rPosNote")[0].value;
        var rNegNote = $("#rNegNote")[0].value;

        if (rGroupId == "") {
            alert(this.res.selectGroup);
            return;
        }

        var typesColl = "";
        for (var i = 0; i < types.length; i++) {
            typesColl += types[i].name.substr(5) + ":" + types[i].value + "|";
        }
        if (typesColl.length > 0) {
            typesColl = typesColl.substr(0, typesColl.length - 1);
        }

        $.ajax({
            type: "POST",
            url: "/Services/Incoming.asmx/SendRatingForm",
            data: "{langId: '" + _langId + "', hotelId: '" + (this.rActiveHotelId) + "', name: '" + rName + "', "
                + "country: '" + rCountry + "', groupId: '" + rGroupId + "', refId: '" + rResId + "', types: '" + typesColl + "', "
                + "positiveNote: '" + rPosNote + "', negativeNote: '" + rNegNote + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                var dList = msg.d.split("|");
                alert(dList[1]);
                if (dList[0] == "ok") {
                    Incoming.closePopupForm();
                }
            }
        });
    },

    // Send content of the term ask form to the server and process response
    sendTermAsk: function() {
        if (this.rActiveHotelId == null || $("#popupForm").length == 0) {
            // Form has been alerady open
            return;
        }

        var _langId = __langId;
        var departureDate = $("#departuredate").val();
        var arrivalDate = $("#arrivaldate").val();
        var rName = $("#rName").val();
        var rEmail = $("#rEmail").val();
        var rPhone = $("#rPhone").val();
        var roomTypeId = $("#rRoomTypeId").val();
        var roomCount = $("#rRoomCount").val();

        if (!rEmail) {
            // Email is mandatory
            alert(this.res.emailIsRequired);
            return;
        }

        $.ajax({
            type: "POST",
            url: "/Services/Incoming.asmx/SendTermAskForm",
            data: "{langId: '" + _langId + "', hotelId: '" + (this.rActiveHotelId) + "', arrivalDate: '" + arrivalDate
                + "', departureDate: '" + departureDate + "', email: '" + rEmail + "', name: '" + rName + "', phone: '" + rPhone + "', roomTypeId: '" + roomTypeId + "', roomCount: '" + roomCount + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                var dList = msg.d.split("|");

                if (dList[0] == "ok") {
                    Incoming.closePopupForm();
                    alert(Incoming.res.querySent + " " + Incoming.res.reponseSoon);
                } else {
                    alert(dList[1]);
                }
            }
        });
    },

    removeFromBonusCart: function(giftId) {
        var _langId = __langId;
        $.ajax({
            type: "POST",
            url: "/Services/Incoming.asmx/RemoveFromBonusCart",
            data: "{langId: '" + _langId + "', giftId: '" + giftId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $("#bpCart").html(msg.d);
            }
        });
    },

    // Check room price from the server
    checkRoomPrice: function(roomTypeId) {
        var _langId = __langId;
        var arrivalDate = $("#rArrivaldate").val();
        var departureDate = $("#rDeparturedate").val();
        var hotelId = $("#rHotelId").val();
        var mealTypeId = $("#mealTypeId").val();
        var roomsCount = $("select[name='room[" + roomTypeId + "]']").val();
        var ages = $("select[name^='age[" + roomTypeId + "]']");
        var ageas = $("select[name^='agea[" + roomTypeId + "]']");
        var idx = 0;
        var guests = "";
        $(ages).each(function(idx, elem) {
            var vals = elem.id.split("[");
            var ageRangeId = vals[2].substring(0, vals[2].length - 1);
            guests += ageRangeId + ":" + $(elem).val() + ":" + (ageas.size() > 0 ? $(ageas[idx]).val() : "0") + "|";
        });

        $("#rt" + roomTypeId).html(Incoming.res.priceIsChecking);
        $.ajax({
            type: "POST",
            url: "/Services/Incoming.asmx/GetRoomPrice",
            data: "{langId: '" + _langId + "', hotelId: '" + hotelId + "', roomTypeId: '" + roomTypeId + "', mealTypeId: '" + mealTypeId + "', dateFrom: '" + arrivalDate + "', dateTo: '" + departureDate + "', roomsCount: '" + roomsCount + "', guests: '" + guests + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(price) {
                $("#rt" + roomTypeId).html(price.formattedPrice);
            }
        });
    },

    // Meal type has been changed on the reservation form
    mealTypeChanged: function() {
        var mealTypeId = $("#mealTypeId").val();

        $("#mForm").submit();
    },

    // Copy client name to room term list
    copyClientNameToRoom: function() {
        if ($("#gname_0_0").size() > 0 && $("#gname_0_0").val().trim() == "") {
            $("#gname_0_0").val($("#name").val() + " " + $("#surname").val());
        }
    },

    // Enable/disable payment card confirmation
    enablePaymentCardConfirm: function(enable) {
        if (enable) {
            $("#pacConfirm").show();
        }
        else {
            $("#pacConfirm").hide();
        }
    },

    // Switch to another month
    goHotelCapacities: function(start) {
        $("#start").val(start);
        $("#capacityForm").submit();
    }
};

// Manager for transfers
var Transfer = {
    // Pricelist for inbound direction
    inPriceList: new Array(),

    // Pricelist for outbound direction
    outPriceList: new Array(),

    // Max persons for inbound transfer
    inMaxPersons: 20,

    // Max persons for outbound transfer
    outMaxPersons: 20,

    // Transfer page init
    init: function() {
        if ($("#isIndividual").size() == 1) {
            Transfer.individualSwitch(true);
        }
    },

    // Individual / Group switch
    individualSwitch: function(isIndividual) {
        var elemIds = ["inCarId", "outCarId", "inCarLabel", "outCarLabel"];

        $.each(elemIds, isIndividual ? function(i, elem) {
            $("#" + elem).show();
        } : function(i, elem) {
            $("#" + elem).hide();
        });

        this.recomputePrice();
    },

    // Transfer place has been changed
    onPlaceChanged: function(placeId, dir, type) {
        var placeTextBoxId = dir + type + "Place";
        placeId = placeId == "" ? 0 : parseInt(placeId);
        $("#" + placeTextBoxId).css("display", placeId == -1 ? "block" : "none");
    },

    // Route has been changed - recompute price
    onRouteChanged: function(routeId, dir) {
        var _langId = __langId;

        routeId = routeId.split(":")[0];

        // Write "Price is checking..."
        $("#priceIn").html(Incoming.res.priceIsChecking);
        $("#priceOut").html(Incoming.res.priceIsChecking);

        if (routeId != "") {
            $.ajax({
                type: "POST",
                url: "/Services/Incoming.asmx/GetTransferRouteData",
                data: "{langId: '" + _langId + "', transferRouteId: '" + routeId + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(routeData) {
                    Transfer.routeChanged(routeData, dir);
                }
            });
        }
        else {
            Transfer.routeChanged("", dir);
        }
    },

    // Route changed
    routeChanged: function(routeData, dir) {
        var carElem = $("#" + dir + "CarId");
        // 1. Fill cars drop down list
        var oldCarId = carElem[0].value == "" ? "" : carElem[0].value;
        carElem.html("");

        if (routeData != "") {
            $.each(routeData.cars, function(i, car) {
                carElem[0].options[i] = new Option(car.title, car.id);
            });
        }

        carElem[0].value = oldCarId;
        if (carElem[0].selectedIndex == -1) {
            carElem[0].selectedIndex = 0;
        }

        // 2. Recompute price
        this.recomputePrice();
    },

    // Transfer person count has been changed
    personsChanged: function(dir, source) {
        var outpersons = parseInt($("#outPersons").val());
        var outchildren = parseInt($("#outChildren").val());
        var inpersons = parseInt($("#inPersons").val());
        var inchildren = parseInt($("#inChildren").val());
        var enableNamesEdit = $("#enableNE").val() == "1";

        if (enableNamesEdit) {
            var table = $("#" + dir + "Names");
            if (table.size() > 0) {
                var totalPersons = dir == "in" ? (inpersons + inchildren) : (outpersons + outchildren);
                var rows = $("input[name^='" + dir + "Client']");
                var oldPersons = rows.size();

                // 1. Remove additional all rows
                while (table[0].rows.length > totalPersons + 1) {
                    $(table[0].rows[table[0].rows.length - 1]).remove();
                }

                // 2. Add missing rows
                for (var i = oldPersons; i < totalPersons; i++) {
                    var cs = i % 2 == 1 ? " class=\"bg\"" : "";
                    $(table[0]).append("<tr" + cs + "><td>" + (i + 1) + ".</td><td><input class=\"sizeXl\" type=\"text\" id=\"" + dir + "Client_" + i + "\" name=\"" + dir + "Client\" value=\"\" /></td></tr>");
                }
            }
        } else {
            // Update mutual persons count
            var total = parseInt($("#totalRoomPersons").val());
            if (total > 0) {
                var selected = 0;
                var elemId = dir + (source == "c" ? "Persons" : "Children");

                if (source == "c") {
                    selected = dir == "in" ? inchildren : outchildren;
                }
                else {
                    selected = dir == "in" ? inpersons : outpersons;
                }

                $("#" + elemId)[0].value = total - selected;
            }
        }

        // 3. Recompute price
        this.recomputePrice();
    },

    // Recompute transfer price
    recomputePrice: function() {
        var isIndividual = $("#isIndividual").size() == 1 || $("#isIndividualTrue").is(":checked");

        var inRouteId = parseInt($("#inRouteId").val().split(":")[0]);
        var inPersons = parseInt($("#inPersons").val()) + parseInt($("#inChildren").val());
        var inCarId = parseInt($("#inCarId").val());

        var outRouteId = parseInt($("#outRouteId").val().split(":")[0]);
        var outPersons = parseInt($("#outPersons").val()) + parseInt($("#outChildren").val());
        var outCarId = parseInt($("#outCarId").val());

        inRouteId = isNaN(inRouteId) ? 0 : inRouteId;
        outRouteId = isNaN(outRouteId) ? 0 : outRouteId;
        inCarId = isNaN(inCarId) ? 0 : inCarId;
        outCarId = isNaN(outCarId) ? 0 : outCarId;

        // Write "Price is checking..."
        $("#priceIn").html(Incoming.res.priceIsChecking);
        $("#priceOut").html(Incoming.res.priceIsChecking);

        $.ajax({
            type: "POST",
            url: "/Services/Incoming.asmx/GetTransferPrice",
            data: "{inRouteId: '" + inRouteId + "', inPersons: '" + inPersons + "', inCarId: '" + inCarId + "', outRouteId: '" + outRouteId + "', outPersons: '" + outPersons + "', outCarId: '" + outCarId + "', isIndividual: '" + isIndividual + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(priceData) {
                Transfer.priceChanged(priceData);
            }
        });
    },

    // Price has been changed and loaded from the server - show it
    priceChanged: function(priceData) {
        if (priceData != null) {
            $("#priceIn").html("<strong>" + priceData.inPrice + "</strong>");
            $("#priceOut").html("<strong>" + priceData.outPrice + "</strong>");
        } else {
            $("#priceIn").html("<strong>N/A</strong>");
            $("#priceOut").html("<strong>N/A</strong>");
        }
    },

    // Copy inbound data to outbound (with rewrite old data)
    copyDataToReturn: function() {
        var ids = ["PassengerName", "Persons", "Children", "ChildrenAge", "CarId", "StationType"];

        // route-switch direction
        var dirstr = $("#inRouteId").val().split(":");
        if (dirstr.length == 2) {
            var xdir = dirstr[1] == "0" ? "1" : "0";
            $("#outRouteId").val(dirstr[0] + ":" + xdir);
        }

        $(ids).each(function(i, val) {
            $("#out" + val).val($("#in" + val).val());
        });

        var inArrivalPlaceId = $("#inArrivalPlaceId").val();
        var inDeparturePlaceId = $("#inDeparturePlaceId").val();
        $("#outDeparturePlace").val($("#inArrivalPlace").val());
        $("#outArrivalPlace").val($("#inDeparturePlace").val());
        $("#outDeparturePlaceId").val(inArrivalPlaceId);
        $("#outArrivalPlaceId").val(inDeparturePlaceId);

        if (inDeparturePlaceId == -1) {
            $("#outArrivalPlace").show();
        }
        else {
            $("#outArrivalPlace").hide();
        }

        if (inArrivalPlaceId == -1) {
            $("#outDeparturePlace").show();
        }
        else {
            $("#outDeparturePlace").hide();
        }

        // Passenger name copy
        var inClients = $("input[name^='inClient']");
        var outClients = $("input[name^='outClient']");
        if (inClients.size() != outClients.size()) {
            this.personsChanged("out", "c");
            outClients = $("input[name^='outClient']");
        }
        $(inClients).each(function(i, elem) {
            $(outClients[i]).val($(elem).val());
        });

        this.onRouteChanged($("#outRouteId").val(), "out");
    }
};

// Service reservation manager
var ServiceReservation = {
    init: function() {
        $("#servicesTable").show();
        $(".serviceDesc").hide();
        $("input[name^='arrDate']").each(function(i, elem) {
            $(elem).datepicker({ onSelect: function(formatted, dates) {
                var serviceId = elem.id.substr(7);
                var arrDate = Widgets.parseDate(formatted);
                var depDate = Widgets.parseDate($("#depDate" + serviceId).val());
                if (arrDate != null && (depDate == null || depDate < arrDate)) {
                    depDate = arrDate;
                    $("#depDate" + serviceId).datepicker("setDate", depDate);
                }

                $("#service_" + serviceId).attr("onchange").call();
            }, dateFormat: 'dd.mm.yy'
            });
        });

        $("input[name^='depDate']").each(function(i, elem) {
            $(elem).datepicker({ onSelect: function(formatted, dates) {
                var serviceId = elem.id.substr(7);

                $("#service_" + serviceId).attr("onchange").call();
            }, dateFormat: 'dd.mm.yy'
            });
        });

        var scElem = $("#serviceCategoryId");
        if (scElem.size() == 1) {
            ServiceReservation.selectCategory(scElem.val());
        }
    },
    show: function(serviceId) {
        if ($("#sdRow" + serviceId).is(":hidden")) {
            $("#sdRow" + serviceId).show();
        } else {
            $("#sdRow" + serviceId).hide();
        }

        return false;
    },
    hide: function(serviceId) {
        $("#sdRow" + serviceId).hide();

        return false;
    },
    selectCategory: function(categoryId) {
        $("input[id^='scat_']").each(function(i, elem) {
            if (categoryId == parseInt($(elem).val())) {
                $(elem).parent().parent().show();
            } else {
                var parent = $(elem).parent().parent();
                parent.hide();
                parent.next().hide();
            }
        });
    }
};

// Tour reservation manager
var TourReservation = {
    // Switched group/individual
    individualSwitch: function() {
        this.recomputePrice();
    },

    // Recompute tour price
    recomputePrice: function() {
        var tourId = parseInt($("#tourId").val());
        var tourGuideLangId = parseInt($("#tourGuideLangId").val());
        var persons = parseInt($("#persons").val());
        var students = parseInt($("#students").val());
        var children = parseInt($("#children").val());

        if (isNaN(tourId) || isNaN(persons)) {
            $("#tourPrice").html(Incoming.res.selectTourData);
            TourReservation.refillDateSelect(new Array());
            return;
        }

        if (isNaN(tourGuideLangId)) {
            tourGuideLangId = 1;
        }

        $("#tourPrice").html(Incoming.res.priceIsChecking);
        $.ajax({
            type: "POST",
            url: "/Services/Incoming.asmx/GetTourData",
            data: "{langId: '" + __langId + "', tourId: '" + tourId + "', tourGuideLangId: '" + tourGuideLangId + "', persons: '" + persons + "', children: '" + children + "', students: '" + (isNaN(students) ? 0 : students) + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(tour) {
                $("#patod").html(tour.departureInfo);
                $("#tlen").html(tour.tourLength);
                $("#tourPrice").html("<strong>" + tour.price + "</strong>");
                if (tour.hasLanguageSelection) {
                    $("#tourGuideLangId").show();
                } else {
                    $("#tourGuideLangId").hide();
                }
                TourReservation.refillDateSelect(tour.dates);
            }
        });
    },

    // Persons count changed
    personsChanged: function() {
        var persons = parseInt($("#persons").val());
        var students = parseInt($("#students").val());
        var children = parseInt($("#children").val());
        var table = $("#clientTable");
        var totalPersons = persons + children + (isNaN(students) ? 0 : students);
        var rows = $("input[name^='client']");
        var oldPersons = rows.size();

        // Remove additional all rows
        while (table[0].rows.length > totalPersons + 1) {
            $(table[0].rows[table[0].rows.length - 1]).remove();
        }

        // Add missing rows
        for (var i = oldPersons; i < totalPersons; i++) {
            var cs = "";
            $(table[0]).append("<tr" + cs + "><td>" + (i + 1) + ".</td><td><input class=\"sizeXl\" type=\"text\" id=\"client" + i + "\" name=\"client\" value=\"\" /></td></tr>");
        }

        this.recomputePrice();
    },

    // refill date selector
    refillDateSelect: function(dates) {
        var dateSelect = $("#tourDate");
        var oldSelectTitle = dateSelect[0].options[0].text;
        var oldDateSelect = dateSelect[0].value;
        dateSelect.html("");
        dateSelect[0].options[0] = new Option(oldSelectTitle, "");

        $(dates).each(function(i, val) {
            dateSelect[0].options[i + 1] = new Option(val, val);
        });

        dateSelect[0].value = oldDateSelect;
        if (dateSelect[0].selectedIndex == -1) {
            dateSelect[0].selectedIndex = 0;
        }
    }
};
