﻿$(document).ready(function() {

    var START_DATE = CURRDATE.clone().addDays(7);
    var END_DATE = START_DATE.clone().addDays(DEFAULT_NUMBER_OF_NIGHTS);

    // Cache the selector.
    var agentIdOrIata = $("#agentId input:hidden:eq(0)");
    var isVisible = $("#agentId input:hidden:eq(1)");
    var numOfRooms = $("#hiddenNumOfRoom");
    var numOfAdults = $("#hiddenNumOfAdult");
    var numOfChilds = $("#hiddenNumOfChild");
    var enableHotelPackage = $("#hdnEnableHotelPackage").val();

    // Cache the selector.

    var agentBox = $("#agentId");
    var agentIdTextBox = $("#agentId input:text");
    var departureCityBox = $("#departureCity");
    var departureCityTextBox = $("#DepartureCity");
    var hotelOnlyRadio = $("#hotelOnly");
    var hotelPackageRadio = $("#hotelPackage");
    var promotionCodeBox = $("#promotionCode");
    var promotionCodeTextBox = $("#PromotionCode");
    var lnkSearchButton = $("#lnkSearch");
    var checkInDateTextBox = $("#CheckInDate");
    var checkOutDateTextBox = $("#CheckOutDate");
    var nightsSpan = $("span.nights cite");
    var roomSelect = $("#Rooms");
    var adultsSelect = $("#Adults");
    var childrenSelect = $("#Children");
    var searchRoomForm = $("#searchRoomForm");
    var promotionBox = $("#promotion");
    var promotionCite = $("#promotion cite");

    var allowSubmit = true;

    // Strip the unknown characters.
    function stripCharacter(input) {
        // The characters can be changed to any character, but "\";
        var characterToStrip = "!@#$%^&*()+=|[]{};':”,.<>/?`~";
        // Add "\" to strip characters.
        var convertedCharacterToStrip = characterToStrip.replace(/[\$\^\*\(\)\+\|\[\]\{\}\.\/\?\-]/g, "\\$&");
        // Generate exp for strip characters.
        var stripRegEx = eval("/[" + convertedCharacterToStrip + "\\\\]/g");
        return input.replace(stripRegEx, "");
    }


    // Show the tool tip.
    function showTooltip(control, message, hideDelay) {
        if (control.data("qtip")) {
            control.qtip("hide");
        }

        if (control.data("tooltipTimer")) {
            clearTimeout(control.data("tooltipTimer"));
        }

        control.qtip({
            content: message,
            position: {
                corner: {
                    target: 'topRight',
                    tooltip: 'bottomLeft'
                }
            },
            style: {
                border: {
                    width: 1,
                    radius: 3
                },
                padding: 10,
                textAlign: 'left',
                tip: true // Give it a speech bubble tip with automatic corner detection
                //name: 'cream' // Style it according to the preset 'cream' style
            },
            show: {
                when: false, // Don't specify a show event
                ready: true // Show the tooltip when ready
            },
            hide: false
        });

        if (null != hideDelay) {
            var timerId = setTimeout(function() {
                control.qtip("hide");
            }, hideDelay * 1000);

            control.data("tooltipTimer", timerId);
        }
    }

    // Check the query string and display agentid or promotion.
    function checkAgentId() {
        if (agentIdOrIata.val() == "" || enableHotelPackage == "False") {
            hotelOnlyRadio.attr('checked', true);
        } else {
            agentIdTextBox.val(agentIdOrIata.val());

            if (isVisible.val() == "True") {
                agentBox.removeClass("hidden").show();
                promotionCodeBox.hide();
            }
            else {
                promotionCodeBox.hide();
            }
            departureCityBox.removeClass("hidden").show();
            hotelPackageRadio.attr('checked', true);
            lnkSearchButton.text(RoomResources.SearchAirHotelPackage);
            SetSubmitButtonStatus();
        }
    }
    
    departureCityTextBox.keyup(function() {
        SetSubmitButtonStatus();
    });

    function SetSubmitButtonStatus() {
        if (hotelOnlyRadio.attr('checked') == true) {
            if (allowSubmit) {
                lnkSearchButton.removeClass("disabled");
            } else {
                lnkSearchButton.addClass("disabled");
            }
        } else {
            if (departureCityTextBox.val() != "" && allowSubmit == true) {
                lnkSearchButton.removeClass("disabled");
            } else {
                lnkSearchButton.addClass("disabled");
            }
        }
    }

    function handleCheckInDateChange() {
        var checkInDate = WBE.parseDate(checkInDateTextBox.val());
        if (null == checkInDate) {
            // When the inputted check in date is invalid
            // uses check out date substract nights to calculate the check out date.
            checkInDate = WBE.parseDate(checkOutDateTextBox.val()).addDays("-" + nightsSpan.text());
            checkInDateTextBox.val(checkInDate.toLocalString());
        } else if (checkInDate < CURRDATE) {
            // When check in date less than today, revert check date.
            checkInDate = WBE.parseDate(checkOutDateTextBox.val()).addDays("-" + nightsSpan.text());
            checkInDateTextBox.val(checkInDate.toLocalString());
            showTooltip(checkInDateTextBox, RoomResources.CheckInBeforeToday, 3);
        } else if (checkInDate > CURRDATE.clone().addYears(2)) {
            // When check in date later than 2 years, revert check date.
            checkInDate = WBE.parseDate(checkOutDateTextBox.val()).addDays("-" + nightsSpan.text());
            checkInDateTextBox.val(checkInDate.toLocalString());
        }
        // Format the check date.
        checkInDateTextBox.val(WBE.parseDate(checkInDateTextBox.val()).toLocalString());

        var checkOutDate = checkInDate.clone().addDays(nightsSpan.text());
        checkOutDateTextBox.val(checkOutDate.toLocalString());

        // Set the date less than check in date is not be selectable.
        checkOutDateTextBox.datepicker("option", "minDate", checkInDate.clone().addDays(1));

        // Auto calculate the nights number.
        var nights = timeDiff(checkInDate, checkOutDate);
        if (nights <= NUMBER_OF_MAX_STAY_DAYS) {
            allowSubmit = true;
            SetSubmitButtonStatus();
            // Hide all tips.
            if (checkOutDateTextBox.data("qtip")) {
                checkOutDateTextBox.qtip("hide"); // Destroys the tooltip
            }
        }
    }

    function handleCheckOutDateChange() {
        var checkInDate = WBE.parseDate(checkInDateTextBox.val());
        var checkOutDate = WBE.parseDate(checkOutDateTextBox.val());

        if (null == checkOutDate) {
            // When the inputted check out date is invalid
            // uses check in date added up nights to calculate the check out date.
            checkOutDate = WBE.parseDate(checkInDateTextBox.val()).addDays(nightsSpan.text());
            checkOutDateTextBox.val(checkOutDate.toLocalString());
        } else if (checkOutDate <= checkInDate) {
            // When check out date less than check in date,
            // revert check out date by check in date and number of nights.
            checkOutDate = WBE.parseDate(checkInDateTextBox.val()).addDays(nightsSpan.text());
            checkOutDateTextBox.val(checkOutDate.toLocalString());
            showTooltip(checkOutDateTextBox, RoomResources.CheckInAfterCheckOut, 3);
        } else if (checkOutDate > MAX_SELECTABLE_DATE) {
            // When check out date later than max selectable date,
            // revert check out date by check in date and number of nights.
            checkOutDate = WBE.parseDate(checkInDateTextBox.val()).addDays(nightsSpan.text());
            checkOutDateTextBox.val(checkOutDate.toLocalString());
        }
        // Format the check date.
        checkOutDateTextBox.val(WBE.parseDate(checkOutDateTextBox.val()).toLocalString());
        // Auto calculate the nights number.
        var nights = timeDiff(checkInDate, checkOutDate);
        if (nights > NUMBER_OF_MAX_STAY_DAYS) {
            allowSubmit = false;
            SetSubmitButtonStatus();
            // Show the tips.
            showTooltip(checkOutDateTextBox, RoomResources.ExceedDays);
            nights = NUMBER_OF_MAX_STAY_DAYS;
        } else {
            allowSubmit = true;
            SetSubmitButtonStatus();
            // Hide all tips.
            if (checkOutDateTextBox.data("qtip")) {
                checkOutDateTextBox.qtip("hide"); // Destroys the tooltip
            }
        }
        nightsSpan.text(nights);
    }

    function selectDate() {

        // Init the default date for check in and check out.
        function initDate() {
            // Start date is today and endDate is 3 days from today (3 nights)
            if (checkInDateTextBox.val() == "") {
                checkInDateTextBox.val(START_DATE.toLocalString());
            }
            if (checkOutDateTextBox.val() == "") {
                checkOutDateTextBox.val(END_DATE.toLocalString());
            }
            nightsSpan.text(timeDiff(WBE.parseDate(checkInDateTextBox.val()), WBE.parseDate(checkOutDateTextBox.val())));

            // Set the default number of rooms
            if (numOfRooms.val() == "0") {
                roomSelect.val(1);
            }
            else {
                roomSelect.val(numOfRooms.val());
            }

            // Set the default number of adults
            if (numOfAdults.val() == "0") {
                adultsSelect.val(2);
            }
            else {
                adultsSelect.val(numOfAdults.val());
            }

            childrenSelect.val(numOfChilds.val());

            return false;
        }
        checkAgentId();
        initDate();

        checkInDateTextBox.change(function(event) {
            handleCheckInDateChange();
            return false;
        });

        checkInDateTextBox.keydown(function(event) {
            // When press down tab key, focus the check out date text box.
            if (event.keyCode == 9) {
                checkInDateTextBox.datepicker("hide");
                checkOutDateTextBox.focus();
                return false;
            }
            // When press down enter key, hide the calendar.
            if (event.keyCode == 13) {
                handleCheckInDateChange();
                checkInDateTextBox.datepicker("hide");
                return false;
            }
        });

        // Add the datepicker functional for check in textbox.
        var checkInDatepickerOption = {
            numberOfMonths: 2,
            minDate: CURRDATE.clone(),
            maxDate: CURRDATE.clone().addYears(2),
            showAnim: 'fadeIn',
            duration: 100,
            showOn: 'both',
            buttonImage: calendarIcon,
            buttonImageOnly: true,
            buttonText: '',
            hideIfNoPrevNext: true,
            onSelect: function(dateText, inst) {
                handleCheckInDateChange();
                return false;
            }
        };

        $.extend(checkInDatepickerOption, datepickerI18nOption);
        checkInDateTextBox.datepicker(checkInDatepickerOption);

        checkOutDateTextBox.change(function(event) {
            handleCheckOutDateChange();
            return false;
        });

        checkOutDateTextBox.keydown(function(event) {
            // When press down enter key, hide the calendar.
            if (event.keyCode == 13) {
                handleCheckOutDateChange();
                checkOutDateTextBox.datepicker("hide");
                return false;
            }
        });

        // Add the datepicker functional for check out textbox.
        var checkOutDatepickerOption = {
            numberOfMonths: 2,
            showAnim: 'fadeIn',
            duration: 100,
            minDate: WBE.parseDate(checkInDateTextBox.val()).addDays(1),
            maxDate: MAX_SELECTABLE_DATE,
            hideIfNoPrevNext: true,
            showOn: 'both',
            buttonImage: calendarIcon,
            buttonImageOnly: true,
            buttonText: '',
            onSelect: function(dateText, inst) {
                handleCheckOutDateChange();
                return false;
            }
        };
        $.extend(checkOutDatepickerOption, datepickerI18nOption);
        checkOutDateTextBox.datepicker(checkOutDatepickerOption);

        // put this webURL in config file
        var webPackageURL = $("#hdnHotelPackageBaseURL").val();
        // hard code from airport until text box is available
        var fromAirport = "SFO";
        // Add the loading effect and display search condition.

        lnkSearchButton.click(function() {
            // Set default value.
            var departureAirport = "SFO";
            if (hotelPackageRadio.attr('checked')) {

                if (departureCityTextBox.val() == "" || !allowSubmit) {
                    return false;
                } else {
                    var checkInDate = checkInDateTextBox.val();
                    var checkOutDate = checkOutDateTextBox.val();
                    var adults = adultsSelect.val();
                    var children = childrenSelect.val();
                    var numRoom = roomSelect.val();
                    var txtDepartureCity = encodeURI(stripCharacter(departureCityTextBox.val()));
                    if (txtDepartureCity != "") {
                        departureAirport = txtDepartureCity;
                    }
                    var redirectURL = webPackageURL + "&FrAirport=" + departureAirport + "&fromDate=" + checkInDate + "&ToDate=" + checkOutDate + "&NumAdult=" + adults + "&NumChild=" + children + "&CityId=178276:LAS&NumRoom=" + numRoom;
                    window.open(redirectURL);
                    // sample url window.open("http://travel.wwte10.com/pubspec/scripts/eap.asp?goto=PACKAGEWIZ&eapid=19379-30010&jurl=&PackageType=2&mdpcid=19379-30010.10.1&FrAirport=LAX&FromDate=10/16/2009&ToDate=10/19/2009&NumAdult=2&NumChild=0&CityId=178276:LAS&NumRoom=1");
                }
                return false;
            }

            if (!allowSubmit) {
                return false;
            }
            $("strong.checkIn").text(WBE.parseDate(checkInDateTextBox.val()).toString(DateTimeResources.checkInOutDateDisplayFormat));
            $("strong.checkOut").text(WBE.parseDate(checkOutDateTextBox.val()).toString(DateTimeResources.checkInOutDateDisplayFormat));

            $("strong.nights").text(nightsSpan.text());
            $("strong.rooms").text(roomSelect.val());
            $("strong.adults").text(adultsSelect.val());
            $("strong.children").text(childrenSelect.val());

            promotionCite.text(promotionCodeTextBox.val());

            if (promotionCite.text() != "") {
                promotionBox.show();
            }

            $("#searchInfo").slideDown(600);
            $("#searchBox").hide();

            $("#loadingBox").html(RoomResources.Searching + " <img src='" + BASEURL + "/Content/images/ajax-loader.gif' class='statusimage'/>").show();
            searchRoomForm.submit();
            return false;
        });
    }

    selectDate();

    var manuallyRooms = 1;

    function updateRooms() {
        var rooms = parseInt(roomSelect.val());
        var total = parseInt(adultsSelect.val()) + parseInt(childrenSelect.val());
        var minRooms = Math.ceil(total / 4.0);

        if (rooms > minRooms && rooms > manuallyRooms) {
            rooms = manuallyRooms;
        }

        if (rooms < minRooms) {
            rooms = minRooms;
            if (rooms > parseInt(roomSelect.val())) {
                showTooltip(roomSelect, RoomResources.MaxGuestNumber, 3);
            }
        }

        roomSelect.val(rooms);
    }

    adultsSelect.change(function() {
        updateRooms();
    });

    childrenSelect.change(function() {
        updateRooms();
    });

    roomSelect.change(function() {
        manuallyRooms = parseInt(roomSelect.val());
        updateRooms();
    });
    // Add current page style.
    $("div.wynnNavigation > ul li:eq(0)").addClass("current");
    // Disable links.
    $("div.wynnNavigation > ul li a").click(function() {
        return false;
    });
    // Display promotion code.
    hotelOnlyRadio.click(function() {
        promotionCodeBox.show();
        agentBox.hide();
        departureCityBox.hide();
        lnkSearchButton.text(RoomResources.SearchAvailability);

        SetSubmitButtonStatus();
    });

    // Display air hotel package.
    hotelPackageRadio.click(function() {
        if (isVisible.val() == "True") {
            agentBox.show();
            departureCityBox.show();
        }
        else {
            agentBox.hide();
            departureCityBox.show();
        }
        promotionCodeBox.hide();
        lnkSearchButton.text(RoomResources.SearchAirHotelPackage);
        SetSubmitButtonStatus();
    });

    $("div.promotionBanner").bindLoggedIn(promotionBannerURL).bindLoggedOut(promotionBannerURL);

    if (isLoggedIn) {
        $.trigger(CUSTOM_EVENTS.LOGGEDIN);
    } else {
        $.trigger(CUSTOM_EVENTS.LOGGEDOUT);
    }
});
