/// <reference path="../../../Script/jquery.js" />

var HCAffiliateBoxes = {};

HCAffiliateBoxes.Query = {

    getQStringParams: function (name)
    {

        var qString = document.location.search.substr(1);
        var result = '';
        if (qString != "")
        {
            var curName;
            var arrNameVal = qString.split('&');
            for (i = 0; i < arrNameVal.length; i++)
            {
                curName = arrNameVal[i].split('=')[0];
                if (curName.toLowerCase() == name.toLowerCase())
                {
                    result = arrNameVal[i].split('=')[1];
                }
            } 
        }
        return result;
    }
};

HCAffiliateBoxes.Search = {

    _searchoptions: {},

    SearchButtonOptions: function (options) {
        options = options || {};
        HCAffiliateBoxes.Search._searchoptions = $.extend(options, HCAffiliateBoxes.Search._searchoptions);
    },

    OpenInNewWindow: function () {
        var openInNewWindow = HCAffiliateBoxes.Query.getQStringParams('OpenInNewWindow');
        return (openInNewWindow || openInNewWindow == 1) ? "_blank" : "_parent";
    },


    GetCityFileName: function () {
        var city = HCAffiliateBoxes.Query.getQStringParams('fileName');
        if (city == undefined) {

            var destinationString = $('#cityTranslation').val();
            if ($('#citySearch').length > 0 && destinationString != $('#citySearch').val()) {
                city = $('#citySearch').val();
            } else {
                city = '';
            }
        }

        return city;
    },

    GetLanguageCode: function () {
        var language = HCAffiliateBoxes.Query.getQStringParams('languageCode');
        //Make sure a default language is specified
        if (language == '') {
            language = 'EN';
        }

        return language;
    },

    GetCurrencyCode: function () {
        var currencyCode = HCAffiliateBoxes.Query.getQStringParams('currencyCode');
        //Make sure a currency value is specified
        if (currencyCode == '') {
            currencyCode = 'HOTELS';
        }

        return currencyCode;
    },

    BuildStandardSearchOptions: function () {

        var options = { languageCode: HCAffiliateBoxes.Search.GetLanguageCode(),
            cityFileName: HCAffiliateBoxes.Search.GetCityFileName(),
            affiliateId: HC.Cookies.get('a_aid').value,
            brandId: HC.Cookies.get('brandId').value,
            searchBoxContainer: 'searchBoxContainer',
            currencyCode: HCAffiliateBoxes.Search.GetCurrencyCode(),
            target: HCAffiliateBoxes.Search.OpenInNewWindow(),
            domain:HCAffiliateBoxes.Query.getQStringParams('domain')
        };
        options = $.extend(options, HCAffiliateBoxes.Search._searchoptions);

        return options;
    },

    IsHotelSearch: function (options) {
        return (options.hotelId != undefined && options.hotelId != "");
    },

    DoSearch: function (options) {

        var individualCalSettings = HC.Calendar.settings[options.searchBoxContainer].individualCalSettings;

        var checkinDateSupplied = individualCalSettings['searchBoxContainer_Checkin'].selectedDate;
        var checkoutDateSupplied = individualCalSettings['searchBoxContainer_Checkout'].selectedDate;

        var bypassDateValidation = (checkinDateSupplied == null) && (checkoutDateSupplied == null);
        options = $.extend({ bypassDateValidation: bypassDateValidation }, options);

        //log click
        if (HC.Common.Cookies.getCookie('a_aid', false) != "" && HC.Common.Cookies.getCookie('affiliateClickId', false) == "") {
            url = document.location;
            AffiliateClick(url, '');
        }

       if (!HCAffiliateBoxes.Search.IsHotelSearch(options)) {
            //City search
            return HC.HomePage.SearchBtn(options.languageCode, options.target, options.affiliateId, options.cityFileName, options.domain, options.brandId, options, options.searchBoxContainer);
        } else {
            //hotel search
            return DoSearch(options.searchBoxContainer, options);
       }

    }
};


HCAffiliateBoxes.DropDownCalendar =
{

    DaysInMonth: function (month, year)
    {
        var m = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

        if (month != 2)
        {
            return m[month];
        }

        if (year % 4 != 0)
        {
            return m[1];
        }

        return m[1] + 1;
    },

    GetMonthOptions: function ()
    {

        var monthNames = AbbrMonthNamesVariable.split(',');
        var currentDate = new Date();
        var result = '';

        var startIndex = currentDate.getMonth();
        var addYearValue = 0;
        for (var i = 1; i <= 12; i++)
        {
            var year = (currentDate.getFullYear() + addYearValue) + '';
            result += '<option value=' + startIndex + '>' + monthNames[startIndex] + ', ' + year.substr(2, 2) + '</option>';
            if (startIndex != 11)
            {
                startIndex++;
            } else
            {
                addYearValue = 1;
                startIndex = 0;
            }
        }

        return result;
    },

    GetDayOptions: function (month)
    {
        //pass in month to force that month to be used to determine the number of days
        //or the current month will be used
        var currentDate = new Date();
        if (month == null || month == undefined)
        {
            month = currentDate.getMonth();
        }

        var numberOfDays = HCAffiliateBoxes.DropDownCalendar.DaysInMonth(month, currentDate.getFullYear());
        var result = '';
        for (var i = 1; i <= numberOfDays; i++)
        {
            result += '<option>' + i + '</option>';
        }

        return result;
    },

    GetCheckInOutValue: function (daySelectId, monthYearSelectId)
    {

        var currentDate = new Date();

        var monthYearResult = $('#' + monthYearSelectId).val();
        var year = currentDate.getFullYear();
        var month = parseInt(monthYearResult);
        var day = parseInt($('#' + daySelectId).val());

        if (month < currentDate.getMonth())
        {
            year += 1;
        }

        if (month < 10)
        {
            month = '0' + month;
        }

        if (day < 10)
        {
            day = '0' + day;
        }

        //formatdate (hc.calendar.js) is used here as the dates are validated against the ShortDatePatternVariable
        //which is tied to the language of the site
        return HC.Calendar.formatDate(new Date(year, month, day), ShortDatePatternVariable, 0);
    },

    BuildCalendar: function ()
    {

        $('#searchBoxContainer_Checkin').hide();
        $('#searchBoxContainer_Checkout').hide();
        $('#checkinDay').html(HCAffiliateBoxes.DropDownCalendar.GetDayOptions());
        $('#checkinMonthYear').html(HCAffiliateBoxes.DropDownCalendar.GetMonthOptions());
        $('#checkoutDay').html(HCAffiliateBoxes.DropDownCalendar.GetDayOptions());
        $('#checkoutMonthYear').html(HCAffiliateBoxes.DropDownCalendar.GetMonthOptions());
        $('#searchButton').click(function ()
        {
            //By assigning these values below, HC.HomePage.SearchBtn will work 
            var individualCalSettings = HC.Calendar.settings['searchBoxContainer'].individualCalSettings;
            $('#searchBoxContainer_Checkin').val(HCAffiliateBoxes.DropDownCalendar.GetCheckInOutValue('checkinDay', 'checkinMonthYear'));
            $('#searchBoxContainer_CheckinValue').val($('#searchBoxContainer_Checkin').val());
            individualCalSettings['searchBoxContainer_Checkin'].selectedDate = $('#searchBoxContainer_Checkin').val();

            $('#searchBoxContainer_Checkout').val(HCAffiliateBoxes.DropDownCalendar.GetCheckInOutValue('checkoutDay', 'checkoutMonthYear'));
            $('#searchBoxContainer_CheckoutValue').val($('#searchBoxContainer_Checkout').val());
            individualCalSettings['searchBoxContainer_Checkout'].selectedDate = $('#searchBoxContainer_Checkout').val();
        });

    }


};



 
$(document).ready(function () {


    var options = HCAffiliateBoxes.Search.BuildStandardSearchOptions();

    $('#searchButton').click(function () {
        return HCAffiliateBoxes.Search.DoSearch(options);
    });

    var city = $('#citySearch');
    city.focus(function () {
        if (this.value == $("#cityTranslation").val()) {
            this.value = '';
        }
    });


    city.blur(function () {
        if (this.value == '') {
            this.value = $("#cityTranslation").val();
        }
    });

    if (typeof (maxItems) == 'undefined' || maxItems == null) {
        maxItems = 5;
    } else {
        maxItems == maxItems;
    }

    if (city != null && typeof (city) != "undefined") {
        city.val($("#cityTranslation").val());
        bind(city, {
            useiframe: true,
            affiliate: true,
            width: city.width() < 180 ? 180 : city.width(),
            brandId: "",
            affiliateId: options.affiliateId,
            brandDomain: "",
            maxItemsToShow: maxItems,
            languageCode: options.languageCode,
            showBrowseByCountry: true
        });
    }

    //Really for hotel search only
    $('#searchBoxContainer_Guests').change(function () {
         $('#searchBoxContainer_GuestsValue').val($('#searchBoxContainer_Guests option:selected').val());
    });
    //Really for hotel search only
     $('#searchBoxContainer_Rooms').change(function () {
         $('#searchBoxContainer_RoomsValue').val($('#searchBoxContainer_Rooms option:selected').val());
    });

    HC.Calendar.init(options.searchBoxContainer, 'absolute', { numberOfMonthsToShow: 1, useInbuiltCalendarStyles: false });

});

