var OperatorsListBox;
var DepartureCityComboBox;
var DestinationCountryComboBox;
var CurrencyComboBox;
var MealsListBox;
var StarsListBox;
var HotelsListBox;
var DestinationCitiesListBox;
var TourTypesComboBox;
var PriceTypesComboBox;
var checkinCal, checkoutCal;

function ChangeFirstDate()
{
    var fe = document.getElementById("DateFromTextBox");
    var se = document.getElementById("DateToTextBox");
    var fdate = fe.value;
    var sdate = se.value;
    var fd = Date.fromFormatString(fdate);
    var sd = Date.fromFormatString(sdate);
    if (fd > sd)
    {
        se.value = fe.value;
    }
}

function LoadCurrencies_callback()
{
    RenderItemsComboBox(currenciesDS, CurrencyComboBox, []);
    /* Выбираем валюту по умолчанию */
    CurrencyComboBox.setValue(selectedCurrencyId, false);
    // Заполнение блока "Вы искали..."
    if (document.getElementById('youSearch') != null)
        getYouSearchEtc();
}

function LoadMeals_callback()
{
    RenderItemsListBox(mealsDS, MealsListBox);
    // Заполнение блока "Вы искали..."
    if (Meals != null)
    {
        MealsListBox.setValues(Meals, true);
        if (document.getElementById('youSearch') != null)
        {
            var _meals = MealsListBox.getText(Meals)
            if (_meals != '')
            {
                document.getElementById('youSearch_meals').innerHTML = _meals;
            }
            else
            {
                document.getElementById('youSearch_meals').innerHTML = 'не важно, ';
            }
        }
        Meals = null;
    }
}

function LoadStars_callback()
{
    RenderItemsListBox(starsDS, StarsListBox);
    StarsListBox.onChangeSelected = OnSelectStar;
    // Заполнение блока "Вы искали..."
    if (Stars != null)
    {
        StarsListBox.setValues(Stars, true);
        if (document.getElementById('youSearch') != null)
        {
            var _stars = StarsListBox.getText(Stars)
            if (_stars != '')
            {
                document.getElementById('youSearch_stars').innerHTML = _stars;
            }
            else
            {
                document.getElementById('youSearch_stars').innerHTML = 'не важно, ';
            }
        }
        Stars = null;
    }
}

function loadTourTypes_callback()
{
    RenderItemsComboBox(tourTypesDS, TourTypeComboBox, []);
    TourTypeComboBox.setValue(selectedTourTypeId, false);
}

function loadOperators_callback()
{
    RenderItemsListBox(operatorsDS, OperatorsListBox);
//    StarsListBox.onChangeSelected = OnSelectStar;
}

function LoadHotelsEx_callback()
{
}

function onloadSearchForm()
{
    ToggleWaitBox("show");

    dictionary = CreateDictionaryFromQueryString();
    if (dictionary.DepCityId != null)
    {
        selectedDepartureCityId = dictionary.DepCityId;
    }
    if (dictionary.DestCountryId != null)
    {
        selectedDestinationCountryId = dictionary.DestCountryId;
    }

    if (document.getElementById("PriceTypesComboBoxLabel") != null)
    {
        PriceTypesComboBox = new ComboBox("PriceTypesComboBox", document.getElementById("PriceTypesComboBoxLabel"));
        PriceTypesComboBox.add(new ComboBoxItem('Цена за человека', 1));
        PriceTypesComboBox.add(new ComboBoxItem('Цена за весь тур', 0));
        PriceTypesComboBox.setValue(1, false);
    }

    TourTypeComboBox = new ComboBox("TourTypeComboBox", document.getElementById("TourTypeComboBoxLabel"));
    TourTypeComboBox.onChangeSelected = OnSelectTourType;
    DepartureCityComboBox = new ComboBox("DepartureCityComboBox", document.getElementById("DepartureCityComboBoxLabel"));
    DepartureCityComboBox.onChangeSelected = OnSelectDepartureCity;
    DestinationCountryComboBox = new ComboBox("DestinationCountryComboBox", document.getElementById("DestinationCountryComboBoxLabel"));
    DestinationCountryComboBox.onChangeSelected = OnSelectDestinationCountry;
    CurrencyComboBox = new ComboBox("CurrencyComboBox", document.getElementById("CurrencyComboBoxLabel"));
    if ((HideCurrenciesFilter == "false") || (HideCurrenciesFilter == false))
    {
        var documentElementRef = document.getElementById("currency");
        if (documentElementRef != null)
        {
            documentElementRef.style.display = "inline";
        }
    }
    if (document.getElementById('OperatorsListBoxLabel') != null)
    {
        OperatorsListBox = new ListBox("OperatorsListBox", document.getElementById("OperatorsListBoxLabel"));
        LoadOperators(loadOperators_callback);
    }
    MealsListBox = new ListBox("MealsListBox", document.getElementById("MealsListBoxLabel"));
    StarsListBox = new ListBox("StarsListBox", document.getElementById("StarsListBoxLabel"));
    HotelsListBox = new ListBox("HotelsListBox", document.getElementById("HotelsListBoxLabel"));
    DestinationCitiesListBox = new ListBox("DestinationCitiesListBox", document.getElementById("DestinationCitiesListBoxLabel"));
    DestinationCitiesListBox.onChangeSelected = OnSelectDestinationCity;

//    SetupCalendar("DateFromTextBox", "DateFromImage");
    //    SetupCalendar("DateToTextBox", "DateToImage");

    var today = new Date().addDays(2);
    if (document.getElementById('DateFromImage') != null)
    {
        checkinCal = Calendar.setup({
            trigger: "DateFromImage",
            inputField: "DateFromTextBox",
            dateFormat: "%d.%m.%Y",
            titleFormat: "%B %Y",
            min: Calendar.dateToInt(today),
            selection: Calendar.dateToInt(BeginDate),
            onSelect: function ()
            {
                var date = Calendar.intToDate(this.selection.get());
                if (this.selection.get() > checkoutCal.selection.get())
                {
                    document.getElementById('DateToTextBox').value = date.toFormatString();
                    checkoutCal.selection.set(date);
                }
                checkoutCal.args.min = date;
                checkoutCal.redraw();
                this.hide();
            }
        });
        checkoutCal = Calendar.setup({
            trigger: "DateToImage",
            inputField: "DateToTextBox",
            dateFormat: "%d.%m.%Y",
            titleFormat: "%B %Y",
            min: Calendar.dateToInt(today),
            selection: Calendar.dateToInt(EndDate),
            onSelect: function () { this.hide(); }
        });
    }
    else
    {
        checkinCal = Calendar.setup({
            trigger: "DateFromTextBox",
            inputField: "DateFromTextBox",
            dateFormat: "%d.%m.%Y",
            titleFormat: "%B %Y",
            min: Calendar.dateToInt(today),
            selection: Calendar.dateToInt(BeginDate),
            onSelect: function ()
            {
                var date = Calendar.intToDate(this.selection.get());
                if (this.selection.get() > checkoutCal.selection.get())
                {
                    document.getElementById('DateToTextBox').value = date.toFormatString();
                    checkoutCal.selection.set(date);
                }
                checkoutCal.args.min = date;
                checkoutCal.redraw();
                this.hide();
            }
        });
        checkoutCal = Calendar.setup({
            trigger: "DateToTextBox",
            inputField: "DateToTextBox",
            dateFormat: "%d.%m.%Y",
            titleFormat: "%B %Y",
            min: Calendar.dateToInt(today),
            selection: Calendar.dateToInt(EndDate),
            onSelect: function () { this.hide(); }
        });
    }

    document.getElementById("DateFromTextBox").value = BeginDate.toFormatString();
    document.getElementById("DateToTextBox").value = EndDate.toFormatString();
    setValuetoField("AdultTextBox", AdultCount);
    setValuetoField("ChildTextBox", ChildCount);
    setValuetoField("PriceFromTextBox", BeginCost);
    setValuetoField("PriceToTextBox", EndCost);
    setValuetoField("NightsFromTextBox", BeginNights);
    setValuetoField("NightsToTextBox", EndNights);

    //LoadOperatorsByDepartureCityAndDestination(DefaultDepartureCity, true, 9, LoadOperators_callback);
    //LoadHotelsEx(3, [], [], LoadHotelsEx_callback);

    LoadTourTypes(loadTourTypes_callback);

    switch (interrelationshipsOfDepartureCitiesAndDestinationCountries)
    {
        case "NoInterrelationships":
            LoadDepartureCities(selectedTourTypeId, LoadDepartureCities_callback);
            LoadDestinationCountries(selectedTourTypeId, LoadDestinationCountries_callback);
            break;
        case "DestinationCountriesDependsOnDepartureCities":
            LoadDepartureCities(selectedTourTypeId, LoadDepartureCities_callback);
            break;
        default:
            LoadDestinationCountries(selectedTourTypeId, LoadDestinationCountries_callback);
    }

    LoadMeals(LoadMeals_callback);
    LoadStars(LoadStars_callback);
    LoadCurrencies(Currencies, LoadCurrencies_callback);
    ToggleWaitBox("hide");
}

function OpenResults()
{
    var object = AJS.formContents(document.getElementById("search"));
    var queryString = CreateQueryString(object);

    // Опрделение находится ли форма поиска во фрейме
    if (parent.window != null)
    {
        parent.window.location.href = resultPage + queryString;
    }
    else
    {
        windowOpen(resultPage + queryString, resultsPageWidth, resultsPageHeight, openResultsPageInNewWindow);
    }
}

// Заполнение блока "Вы искали..."
function getYouSearchEtc()
{
    var dictionary = CreateDictionaryFromQueryString();

    var youSearch = 'дата заезда: с ' + dictionary.checkinDateFrom_sm + " по " + dictionary.checkinDateTo_sm + ", ";
    youSearch += 'ночей: от ' + dictionary.nightsFrom_sm + " до " + dictionary.nightsTo_sm + ", ";

    youSearch += 'взрослых: ' + dictionary.adultsCount_sm + ", детей: ";
    if (typeof (dictionary.childrenCount_sm) != "undefined" && dictionary.childrenCount_sm != "")
    {
        youSearch += dictionary.childrenCount_sm;
    }
    else
    {
        youSearch += "нет";
    }

    youSearch += ', стоимость: ';
    if (typeof (dictionary.costFrom_sm) != "undefined" && dictionary.costFrom_sm != '')
    {
        youSearch += 'от ' + dictionary.costFrom_sm + ' ' + CurrencyComboBox.getItem(selectedCurrencyId).text.trim();
    }
    if (typeof (dictionary.costTo_sm) != "undefined" && dictionary.costTo_sm != '')
    {
        youSearch += " до " + dictionary.costTo_sm + ' ' + CurrencyComboBox.getItem(selectedCurrencyId).text.trim();
    }
    if ((typeof (dictionary.costFrom_sm) == "undefined" || dictionary.costFrom_sm == '') && (typeof (dictionary.costTo_sm) == "undefined" || dictionary.costTo_sm == ''))
        youSearch += 'не важно';

    document.getElementById('youSearch_etc').innerHTML = youSearch;
}

function checkNights()
{
    var from = document.getElementById('NightsFromTextBox');
    var to = document.getElementById('NightsToTextBox');

    var fromValue = parseInt(from.value);
    var toValue = parseInt(to.value);
    if (fromValue > toValue)
    {
        to.value = fromValue;
    }

    for (i = 0; i < to.length; i++)
    {
        if (i < from.value - 2)
        {
            to.options(i).disabled = true;
        }
        else
        {
            to.options(i).disabled = false;
        }
    }
}
