var SF_object;
var SF_objectByCountry;
var l10n = {};
var calendar_data = [];
    var TempDate = new Date();
    var NowDate = new Date (TempDate.getFullYear(), TempDate.getMonth(), TempDate.getDate(), 0, 0, 0, 0);

$().ready(function(){
        loc = $('#st-l10n-alerts span');
        l10n.alerts = new Array(loc.length);
        $.each(loc, function(idx, value) { l10n.alerts[idx] = ($(this).text()); });
        // Child ages
        for (i = 0; i <= 16; i++) $('#st-child-age-1').append(selectableItem({
            text: i,
            selected: i == 4
        }));
        for (i = 0; i <= 16; i++) $('#st-child-age-2').append(selectableItem({
            text: i,
            selected: i == 9
        }));
var datePickerConfig = {
        clearText: 'Dz&#275;st', // Display text for clear link
        clearStatus: 'Dz&#275;st konkr&#275;to datumu', // Status text for clear link
        closeText: 'Beigt', // Display text for close link
        closeStatus: 'Beigt, nesaglab&#257;jot izmai&#326;as ', // Status text for close link
        prevText: '&#x3c; '+$('#SF_filter_locales .sf_month_prev').html(), // Display text for previous month link
        prevStatus: 'R&#257;d&#299;t iepriek&scaron;&#275;jo m&#275;nesi ', // Status text for previous month link
        prevBigText: '&#x3c;&#x3c;', // Display text for previous year link
        prevBigStatus: 'R&#257;d&#299;t iepriek&scaron;&#275;jo gadu ', // Status text for previous year link
        nextText: $('#SF_filter_locales .sf_month_next').html()+' &#x3e;', // Display text for next month link
        nextStatus: 'R&#257;d&#299;t n&#257;kamo m&#275;nesi ', // Status text for next month link
        nextBigText: '&#x3e;&#x3e;', // Display text for next year link
        nextBigStatus: 'R&#257;d&#299;t n&#257;kamo gadu ', // Status text for next year link
        currentText: '&Scaron;odien', // Display text for current month link
        currentStatus: 'R&#257;d&#299;t &scaron;o m&#275;nesi ', // Status text for current month link
        monthNames: [$('#SF_filter_locales .sf_month_name_1').html(), $('#SF_filter_locales .sf_month_name_2').html(),
        $('#SF_filter_locales .sf_month_name_3').html(),
        $('#SF_filter_locales .sf_month_name_4').html(), $('#SF_filter_locales .sf_month_name_5').html(),
        $('#SF_filter_locales .sf_month_name_6').html(), $('#SF_filter_locales .sf_month_name_7').html(),
        $('#SF_filter_locales .sf_month_name_8').html(), $('#SF_filter_locales .sf_month_name_9').html(),
        $('#SF_filter_locales .sf_month_name_10').html(), $('#SF_filter_locales .sf_month_name_11').html()
        , $('#SF_filter_locales .sf_month_name_12').html()], // Names of months for drop-down and formatting
        monthNamesShort: ['Jan', 'Feb', 'Mar',
                          'Apr', 'Maijs','Jun',
                          'J&#363;l', 'Aug', 'Sep',
                          'Okt', 'Nov', 'Dec'], // For formatting
        monthStatus: 'R&#257;d&#299;t da&#382;&#257;dus m&#275;ne&scaron;us', // Status text for selecting a month
        yearStatus: 'R&#257;d&#299;t da&#382;&#257;dus gadus ', // Status text for selecting a year
        weekHeader: 'Wk', // Header for the week of the year column
        weekStatus: 'Gada ned&#275;&#316;a ', // Status text for the week of the year column
        dayNames: ['Sv&#275;tdiena', 'Pirmdiena', 'Otrdiena', 'Tre&scaron;diena',
                   'Ceturtdiena', 'Piektdiena','Sestdiena'], // For formatting
        dayNamesShort: [$('#SF_filter_locales .sf_weekday_7').html(), $('#SF_filter_locales .sf_weekday_1').html(),$('#SF_filter_locales .sf_weekday_2').html(),$('#SF_filter_locales .sf_weekday_3').html(),$('#SF_filter_locales .sf_weekday_4').html(),$('#SF_filter_locales .sf_weekday_5').html(),$('#SF_filter_locales .sf_weekday_6').html()], // For formatting
        dayNamesMin: [$('#SF_filter_locales .sf_weekday_7').html(), $('#SF_filter_locales .sf_weekday_1').html(),$('#SF_filter_locales .sf_weekday_2').html(),$('#SF_filter_locales .sf_weekday_3').html(),$('#SF_filter_locales .sf_weekday_4').html(),$('#SF_filter_locales .sf_weekday_5').html(),$('#SF_filter_locales .sf_weekday_6').html()], // Column headings for days starting at Sunday
        dayStatus: 'nor&#257;d&#299;t DD k&#257; ned&#275;&#316;as pirmo dienu', // Status text for the day of the week selection
        dateStatus: 'Izv&#275;l&#275;ties GG, M, d', // Status text for the date selection
        dateFormat: 'Izv&#275;l&#275;ties datumu', // See format options on parseDate
        firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
        initStatus: 'Izv&#275;l&#275;ties datumu', // Initial Status text on opening
        isRTL: false, // True if right-to-left language, false if left-to-right
        onSelect: ValidateDate,
        beforeShowDay: function(date) {
            var css = "", text = "";
            switch (this.id) {
                case 'SF_date_from': //если After
                    var neighbourDate = $('#SF_date_to').datepicker("getDate");
                    if ( neighbourDate && ( neighbourDate.getTime() - date.getTime() > 89*24*60*60*1000 ) ) { css = "dateoverlimit"; text = '' }
                    break
                case 'SF_date_to': //если Before
                    var neighbourDate = $('#SF_date_from').datepicker("getDate");
                    if ( neighbourDate && ( date.getTime() - neighbourDate.getTime() > 89*24*60*60*1000) ) { css = "dateoverlimit"; text = '' }
                    break
            }
            for( var i = 0, length = calendar_data.length, y = date.getFullYear(); i < length; i++ ) {
                if( calendar_data[i][0] == y ) {
                        if( $.inArray(date.getDate(), calendar_data[i][date.getMonth()+1]) != -1 ) return [true, css, text];
                        else return [false, ''];
                }
            }

            return [false, ''];
        },
        useSpecialLinks: false,
        dateFormat: "dd.mm.yy",
        firstDay: 1,
        showOn: "both",
        mandatory: true,
        buttonImageOnly: true,
        buttonImage: "http://www.teztour.lv/i/old/cal.gif" 
    };
    $('#st-child-age-1').change(function () {
           $('#st-birthday-1').datepicker("setDate", -$(this).val()+"y");
    });
    $('#st-child-age-2').change(function () {
           $('#st-birthday-2').datepicker("setDate", -$(this).val()+"y");
    });
    $('#SF_accommodation_type').change(function() {
        accObj = getAccommodationObject($(this).val());
        var c = accObj.children;
        var birthday1 = $('#st-birthday-1');
        var birthday2 = $('#st-birthday-2');
        var childAge1 = $('#st-child-age-1');
        var childAge2 = $('#st-child-age-2');
        var allChildAges = $('#st-child-age-1, #st-child-age-2');
        var allBirthdays = $('#st-birthday-1, #st-birthday-2');
        allChildAges.attr('disabled', 'disabled');
        allBirthdays.attr('disabled', 'disabled');
        allBirthdays.datepicker("disable");
        if (c == 1) { // Включаем выбор даты рождения и возраста для одного ребёнка
            childAge1.removeAttr('disabled');
            birthday1.removeAttr('disabled');
            birthday1.datepicker("enable");
            if ( birthday1.datepicker('getDate') === null ) { childAge1.change(); } else { ValidateDate.call(birthday1[0]); } // Если нет даты рождения в URL, берем из селекта "возраст" 
        };
        if (c >= 2) {
            allChildAges.removeAttr('disabled')
            allBirthdays.datepicker("enable")
            if  ( birthday1.datepicker('getDate') === null ) { childAge1.change(); } else { ValidateDate.call(birthday1[0]); }
            if  ( birthday2.datepicker('getDate') === null ) { childAge2.change(); } else { ValidateDate.call(birthday2[0]); }
        }
    });
    loadSF_object();
    $('#SF_form').submit(function(){
        //location.hash = SF_buildHashData;
        var doRevoke = (location.href.indexOf('controller=tez_search') != -1)
        location.href = 'http://www.teztour.lv/?l='+$('#SF_language').val()+'&controller=tez_search#'+SF_buildHashData();
        if (doRevoke) revokeSearch();
        return false;
    });
    loadSF_tours();
    loadSF_FlightDepartures();
    $('#SF_city_from').live('change', function(){
        loadSF_FlightDepartures();
    });
    $('#SF_country').live('change', function(){
        loadSF_tours();
        loadSF_FlightDepartures();
    });
    $('#SF_date_from').datepicker(datePickerConfig);
    $('#SF_date_to').datepicker(datePickerConfig);
    delete datePickerConfig.beforeShowDay;
    $('#st-birthday-1').datepicker(datePickerConfig);
    $('#st-birthday-2').datepicker(datePickerConfig);
});
function selectableItem(config) {
    var el = $('<option>'+config.text+'</option>');
    if( config.value != undefined ) el.val(config.value);
    if( config.hidden ) el.hide();
    else if( config.selected ) el.attr("selected", "selected");
    return el;
}
function dateToString(date) {
    return $.datepicker.formatDate('dd.mm.yy', date);
}
var ValidateDate = function validateDate(dateText,inst) {
    var MinDays = 0;
    var MaxDays = 89;
    var st_after = $('#SF_date_from');
    var st_before = $('#SF_date_to');
    var birthday1 = $('#st-birthday-1');
    var birthday2 = $('#st-birthday-2');
    var childAge1 = $('#st-child-age-1');
    var childAge2 = $('#st-child-age-2');
    var allChildAges = $('#st-child-age-1, #st-child-age-2');
    var allBirthdays = $('#st-birthday-1, #st-birthday-2');
    
    
    if (this.id == st_after.attr('id')) { // Если изменена after
        var after = st_after.datepicker("getDate");
        var before = st_before.datepicker("getDate");
        //console.log('aa');

        // Проверка на диапазон дат выезда короче двух дней
        if ( after.getTime() + MinDays*86400000 > before.getTime() ) {
            st_before.datepicker("setDate", after);
        }
        // Проверка на диапазон дат выезда больше трех месяцев
        if ( before.getTime() - after.getTime() > MaxDays*86400000 ) {
            before.setTime(after.getTime() + (MaxDays)*86400000);
            alert (l10n.alerts[0] + MaxDays + l10n.alerts[1] +dateToString(before));
            st.before.datepicker("setDate", before);
        }
    }

    if (this.id == st_before.attr('id')) { // Если изменена before
        var after = st_after.datepicker("getDate");
        var before = st_before.datepicker("getDate");

        // Проверка на диапазон дат выезда короче двух дней
        if ( after.getTime() + MinDays*86400000 > before.getTime() ) {
            st_after.datepicker("setDate", before);
        }
        // Проверка на диапазон дат выезда больше трех месяцев
        if ( before.getTime() - after.getTime() > MaxDays*86400000 ) {
            after.setTime(before.getTime() - (MaxDays)*86400000);
            alert (l10n.alerts[0] + MaxDays + l10n.alerts[2] + dateToString(after));
            st_after.datepicker("setDate", after);
        }
    }
    
    
    
    if (this.id == birthday1.attr('id')) { // Если изменена дата рождения первого ребёнка
        var today = new Date();
        var birth1Date = birthday1.datepicker("getDate");
        var years = Math.floor((today.getTime() - birth1Date.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
        if (years < 0) { years = 0; }
        childAge1.val(years);
    }
    if (this.id == birthday2.attr('id')) { // Если изменена дата рождения второго ребёнка
        var today = new Date();
        var birth2Date = birthday2.datepicker("getDate");
        var years = Math.floor((today.getTime() - birth2Date.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
        childAge2.val(years);
    }
}
function getAccommodationObject(Id)
{
    var ret = null;
    $.each(SF_objectByCountry.accommodations, function(Key, Value){
        if (Value.accommodationId == Id)
        {
            ret = Value;
        }
    });
    return ret;
}
function loadSF_object()
{
    $.ajax({
        url: 'http://book.teztour.com/toursearch/references',
        data: {locale:'lv'},
        dataType: 'jsonp',
        success: function(data){
            SF_object = data;
        }
    });
}
function loadSF_FlightDepartures()
{
    $.ajax({
        url: 'http://book.teztour.com/toursearch/getFlightDeparture',
        data: {cityId:$('#SF_city_from').val(), countryId:$('#SF_country').val()},
        dataType: 'jsonp',
        success: function(data){
            calendar_data = data.data;
            var Year = calendar_data[0][0];
            var Month = 0;
            var Day = 0;
            $.each(calendar_data[0], function (key, value){
                if (value.length > 0 && Month == 0){
                    Month = key;
                    Day = value[0];
                }
            });
            if (Month < 10) Month = '0' + '' + Month;
            if (Day < 10) Day = '0' + '' + Day;
            var dateStart = Day+'.'+Month+'.'+Year;
            $('#SF_date_from').val(dateStart);
            $('#SF_date_to').val(dateStart);
        }
    });
}
function loadSF_tours(selected)
{
    $('#SF_region').html('');
    $.ajax({
        url: 'http://book.teztour.com/toursearch/byCountry',
        data: {locale:'en', countryId:$('#SF_country').val()},
        dataType: 'jsonp',
        success: function(data){
            SF_objectByCountry = data;
            $('#SF_region').html('');
            var cityId = $('#SF_city_from').val()*1;
            var allIds = [];
            $.each(data.tours, function(key, value){
                if (jQuery.inArray(cityId, value.fromCityId) >= 0)
                {
                    $('#SF_region').append('<option value="'+value.tourId.join(';')+'"'+(value.tourId.join(';') == selected ? ' selected="selected"' : '')+'>'+value.name+'</option>');
                    allIds[allIds.length] = value.tourId.join(';');
                }
            });
            $('#SF_region').prepend('<option value=""'+(!selected ? ' selected="selected"' : '')+'>'+$('#SF_filter_locales .sf_all_regions').html()+'</option>');
            if (!selected) {
                $('#SF_region option:eq(0)').attr('selected', true);
            }
            $('#SF_accommodation_type').trigger('change');
        }
    });
}
function SF_buildHashData()
{
    var hotelClassAllId = $('#SF_hotel_category option:eq(1)').val();
    var rAndBAllId = $('#SF_pansion_type option:eq(1)').val();
    var data = {
        lite: 'true',
        locale: 'lv',
        cityId: $('#SF_city_from').val(),
        countryId: $('#SF_country').val(),
        after: $('#SF_date_from').val(),
        before: $('#SF_date_to').val(),
        nightsMin: $('#SF_duration_from').val(),
        nightsMax: $('#SF_duration_to').val(),
        priceMin: $('#SF_priceFrom').val(),
        priceMax: $('#SF_priceTo').val(),
        currency: 50159,
        tourId: $('#SF_region').val().split(';'),
        hotelClassId: ($('#SF_hotel_category').val() != '' ? $('#SF_hotel_category').val() : hotelClassAllId),
        hotelClassBetter: (($('#SF_hotel_category_beter').attr('checked') || $('#SF_hotel_category').val() == '') ? 'true' : 'false'),
        hotelClassIdAll: ($('#SF_hotel_category').val() != '' ? 'false' : 'true'),
        rAndBId: ($('#SF_pansion_type').val() != '' ? $('#SF_pansion_type').val() : rAndBAllId),
        rAndBBetter: (($('#SF_pansion_type_beter').attr('checked') || $('#SF_pansion_type').val() == '') ? 'true' : 'false'),
        rAndBIdAll: ($('#SF_pansion_type').val() != '' ? 'false' : 'true'),
        hotelId: [],
        hotelInStop: 'false',
        noTicketsTo: 'false',
        noTicketsFrom: 'false',
        tourType: 1,
        accommodationId: $('#SF_accommodation_type').val()
    };
    var accommodation = getAccommodationObject($('#SF_accommodation_type').val());
    switch( accommodation.children ) {
        case 2:
            data.birthday2 = $('#st-birthday-2').val();
        case 1:
            data.birthday1 = $('#st-birthday-1').val();

    }
    var hashString = '';
    var hashData = [];
    $.each(data, function(key, value){
        if ($.isArray(value)){
            tempValArr = []
            $.each(value, function(key2, value2){
                tempValArr[tempValArr.length] = '['+value2+']';
            });
            temptVal = '['+tempValArr.join(',')+']';
            if (temptVal == '') temptVal = '[]';
        } else {
            temptVal = '"'+value+'"';
        }
        hashData[hashData.length] = '"'+key+'":'+temptVal;
    });
    return 'result{'+hashData.join(',')+'}';
}
function SF_loadCountries (city_from)
{
    
}

