/**
 * Search tour main application.
 * @author Sergey Lagutkin
 */
var st;
var object2_data;
var AkcijosSlideInterval;
$(function(){getActiveObjects(); getHotelSegments();});
$(document).bind('PresearcherObjectsLoded', function() {
	$.ajaxSetup({traditional: true});
    jQuery('#st-hotel-segments-area input').live('change', function(){
    	var SegmentId = $(this).attr('idx');
    	var thisState = $(this).attr('checked');
    	//console.log($('.st-clickable-item', selectedHotelsListContent));
    	var Segments = jQuery('#st-hotel-segments-area input:checked');
    	var HotelId;
    	var Check = false;
        $('#st-all-hotels-list .st-checkable-item').each(function() {
        	HotelId = object2_data.hotels[$(this).children('input:visible').val()].hotelId;
        	Check = true;
            if ((Segments.length == 0) && (!(jQuery('#st-option-my-hotels').attr('checked') != undefined && jQuery('#st-option-my-hotels').attr('checked') != false)))
                Check = false;
            else
            {
	        	Segments.each(function(){
	        		if (jQuery.inArray($(this).attr('idx')+'', ActiveObjects.HotelSegments[HotelId]) == -1){
	        			Check = false;
	        		} else {
	        		}
	        	});
	            if (!userRecommendedHotels[HotelId] && (jQuery('#st-option-my-hotels').attr('checked') != undefined && jQuery('#st-option-my-hotels').attr('checked') != false))
	            {
	                Check = false;
	            }
            }
        	if (Check != ($('input', this).attr('checked') == undefined ? false : ($('input', this).attr('checked') == 'checked' ? true : $('input', this).attr('checked'))))
        	{
        		$(this).trigger('click');
        	}
        });
    });
    $('#infoblock-title').html(SvarbiInformacijaTitle);
    $('#infoblock-body').html(SvarbiInformacija);
    if (Authorized)
    {
    	var AkcijosGallery = $('<div><table style="margin-bottom: 5px;"><tr><td id="AkcijosBanners" style="width: 220px; height: 184px; vertical-align: midle; text-align: center; padding-left: 0px; padding-right: 0px;"></td></tr></table><div id="AkcijosBannersPaging"></div></div>');
    	$.each(RezervacineAkcijos, function (key, value){
    		if (key > 0)
    		{
    			AkcijosGallery.find('#AkcijosBanners').append('<a '+(key > 1 ? ' style="display: none;"' : '')+ ' idx="'+key+'" href="'+value['Link']+'" target="_blank"><img src="http://www.teztour.lt/new_page/GetResizedPicture.php?w=220&h=600&Type=3&f='+value['RezervacineAkcijosImages'][1]['Path']+'" /></a>');
    			AkcijosGallery.find('#AkcijosBannersPaging').append('<span idx="'+key+'" style="padding-right: 4px;"><img idx="'+key+'" src="http://teztour.lt/static/images/AkcijosButtons/'+key+'_OFF.jpg" class="off"'+(key == 1 ? ' style="display: none;"' : '')+' /><img idx="'+key+'" src="http://teztour.lt/static/images/AkcijosButtons/'+key+'_ON.jpg"'+(key > 1 ? ' style="display: none;"' : '')+ 'class="on" /></span>');
    		}
    	});
    	
    	var AkcijosGalleryFadeInProcess = false;
    	AkcijosGallery.find('#AkcijosBannersPaging .off').css('cursor', 'pointer').click(function(event){
    		if (!AkcijosGalleryFadeInProcess)
    		{
	    		clearInterval(AkcijosSlideInterval);
	    		AkcijosGallery.find('#AkcijosBannersPaging .on').css('display', 'none');
	    		AkcijosGallery.find('#AkcijosBannersPaging .off').css('display', '');
	    		$(this).next().css('display', '');
	    		$(this).css('display', 'none');
	    		var index = $(this).attr('idx');
	    		AkcijosGalleryFadeInProcess = true;
	    		AkcijosGallery.find('#AkcijosBanners a:visible').fadeOut("slow", function(){AkcijosGallery.find('#AkcijosBanners a[idx='+index+']').fadeIn("slow", function(){AkcijosGalleryFadeInProcess = false;});});
    		}
    	});
        if (AkcijosGallery.find('#AkcijosBanners a').length > 1)
        {
            AkcijosSlideInterval = setInterval(function(){
                var ObjToShow = null;
                var ObjToHide = null;
                var selectedIndex = 1;
                AkcijosGallery.find('#AkcijosBanners a').each(function(i){
                    if (AkcijosGallery.find('#AkcijosBannersPaging span[idx='+$(this).attr('idx')+'] .on').css('display') != 'none')
                    {
                        ObjToHide = this;
                        selectedIndex = i;
                    }
                    if (i == (selectedIndex + 1))
                    {
                        ObjToShow = this;
                    }
                });
                if (ObjToShow == null)
                {
                    ObjToShow = AkcijosGallery.find('#AkcijosBanners a:first');
                }
                if ((selectedIndex + 1) == AkcijosGallery.find('#AkcijosBanners a').length)
                {
                	ObjToShow = AkcijosGallery.find('#AkcijosBanners a:first');
                }
                AkcijosGalleryFadeInProcess = true;
                $(ObjToHide).fadeOut("slow", function(){$(ObjToShow).fadeIn("slow", function(){AkcijosGalleryFadeInProcess = false;});});
                AkcijosGallery.find('#AkcijosBannersPaging span[idx='+$(ObjToHide).attr('idx')+'] .off').css('display', '');
                AkcijosGallery.find('#AkcijosBannersPaging span[idx='+$(ObjToHide).attr('idx')+'] .on').css('display', 'none');
                AkcijosGallery.find('#AkcijosBannersPaging span[idx='+$(ObjToShow).attr('idx')+'] .on').css('display', '');
                AkcijosGallery.find('#AkcijosBannersPaging span[idx='+$(ObjToShow).attr('idx')+'] .off').css('display', 'none');
            }, 5000);
        }

    	//console.log(AkcijosGallery);
    	$('#AkcijuBlokas .block-area').append(AkcijosGallery);
    	$('#AkcijuBlokas .block-area').append(AkcijuBlokas);
        $('#AkcijuBlokas .block-title').html(AkcijuBlokasTitle);
        $('#AkcijuBlokas').css('display', 'inline');
        $(".mopTip_userRecomendedHotels").mopTip({'w':250, 'h':130, 'runThen': 'click', 'style':"overClick", 'get':".mopTipText_userRecomendedHotels", 'useOverlap':true});
        $('#MyHotelsCheck').css('display', '');
        $('#onlineIcons').css('display', '');
    }

    function parseHotelCategory (myString)
    {
    	myregexp = /[\d\D]+(\d+) \*/;
        return myString.replace(myregexp, "$1");
    }
    function parseAccommodation (accommodation)
    {
        myregexp = /(\d+\+\d+\+\d+)/;
        myString=accommodation;
        return myString.replace(myregexp, "<br /><small>$1</small>");
    }
    function parseAccommodationForCart (accommodation)
    {
        myregexp = /(\d+\+\d+\+\d+)/;
        myString=accommodation;
        return myString.replace(myregexp, "");
    }
    function parseAccommodationForCartAges (accommodation)
    {
        myregexp = /([\w\W]+[^\d]+)(\d+\+\d+\+\d+)/;
        myString=accommodation;
        return myString.replace(myregexp, "$2");
    }
    function prepareSpoNumber(SPO, SPOType)
    {
        return SPO.replace('SPO', SPOType);
    }
    function getFlightDate(date)
    {
        myregexp = /(flight )(\d+)\.(\d+)/;
        myString=date;
        return myString.replace(myregexp, "skrydis $3.$2");
    }
    function compareArrays (t, z) {
        if (z.length != t.length) { return false; }
        var a = z.sort(),
            b = t.sort();
        for (var i = 0; t[i]; i++) {
            if (a[i] !== b[i]) {
                    return false;
            }
        }
        return true;
    };
    function hotelInfoBlock()
    {
    	if (st.before.datepicker("getDate"))
    	{
	        var after = st.after.datepicker("getDate");
	        var before = new Date(st.before.datepicker("getDate").getTime() + $('#st-nights-max').val()*86400000);
	        var DinnerDates = [
	                           new Date('2010-12-24'),
	                           new Date('2010-12-31'),
	                           new Date('2011-01-06')
	                        ];
	        var TDinnerDates = [
	                           new Date('2010-12-24'),
	                           new Date('2010-12-31'),
	                           new Date('2011-01-06'),
	                           new Date('2011-02-03'),
	                           new Date('2011-02-04'),
	                           new Date('2011-02-05'),
	                           new Date('2011-02-06'),
	                           new Date('2011-02-07'),
	                           new Date('2011-02-08'),
	                           new Date('2011-02-09'),
	                           new Date('2011-04-13'),
	                           new Date('2011-04-14'),
	                           new Date('2011-04-15'),
	                           new Date('2011-04-16')
	                        ];
	        var showBlock = false;
	        var LookUpDates = DinnerDates;
	        if ($('#st-to-country select').val() == '12695')LookUpDates = TDinnerDates; 
	        $.each(LookUpDates, function(Key, Value){
	        	if ((after <= Value) && (Value <= before))
	        		showBlock = true;
	        });
	        if (showBlock)
	        {
	        	var Country = $('#st-to-country select').val();
	        	var regions = [];
	        	$('#st-tour-list input:checked').each(function(){
	        		regions[regions.length] = object2_data.tours[$(this).val()].tourId;
	        	});
	        	var region = ','+regions.join(',')+',';
	        	var hotels = [];
	        	$('#st-all-hotels-list input:checked').each(function(){
	        		
	        		hotels[hotels.length] = object2_data.hotels[$(this).val()].hotelId;
	        	});
	        	var hotel = ','+hotels.join(',')+',';
	        	var dateFrom = st.after.val();
	        	var dateTo = dateToString(before);
	        	$('#hotelInfoBlock').html($('#NewSearch_Locales .DoNotForgetDinner').html()+' <a href="http://book.teztour.com/book/vc/site_lt/hotelNotes-lt?country='+Country+'&dateFrom='+dateFrom+'&dateTo='+dateTo+'&region='+region+'&hotel='+hotel+'" target="blank">'+$('#NewSearch_Locales .CheckHere').html()+'</a>').css('display', '');
	        }
	        else $('#hotelInfoBlock').css('display', 'none');
    	}
    	
    }
    $('#st-option-my-hotels').click(function(){
            userRecomendedHotelIdsGetNew(null);
    });
    var JSON=window.JSON||{};JSON.stringify=JSON.stringify||function(obj){var t=typeof(obj);if(t!="object"||obj===null){if(t=="string")obj='"'+obj+'"';return String(obj);}else{var n,v,json=[],arr=(obj&&obj.constructor==Array);for(n in obj){v=obj[n];t=typeof(v);if(t=="string")v='"'+v+'"';else if(t=="object"&&v!==null)v=JSON.stringify(v);json.push((arr?"":'"'+n+'":')+String(v));}return(arr?"[":"{")+String(json)+(arr?"]":"}");}};
    //jQuery.ajaxSettings.traditional = true;
    var defaultMaxCurrencies = {
        5561: 10000, //Доллар
        8390: 430000, // Рубль
        18864: 10000, // Евро
        46688: 120000, //Гривна
        132329: 44000000, //Белорусский рубль
        53570: 30000, //LTL
        50159: 15000, //LVL
        174757: 30000 //EEK
    }
    
    var urls = {
/*
        object1:'http://json.teztour.com/agencytoursearch/references',
        object2:'http://json.teztour.com/agencytoursearch/byCountry',
        calendar:'http://json.teztour.com/agencytoursearch/calendar',
        callback:'http://json.teztour.com/agencytoursearch/callback',
        result:'http://json.teztour.com/agencytoursearch/getResult'
*/
        object1:'/app.action?obj1=',
        object2:'/app.action?obj2=',
        calendar:'/app.action?calendar=',
        result:'/app.action?result='
    };

    if( $urls ) urls = $urls; // remove after release

    var defaults = {
        fromCityId:345,
        toCountryId:1104,
        after:new Date(),
        before:(function() { var d = new Date(); d.setDate(d.getDate()+7); return d; })(),
        nightsMin:7,
        nightsMax:10,
        nightsLimits:[2,30],
        accommodationId:1234,
        childAge1: 4,
        childAge2: 9,
        childAge3: 9,
        childAgeLimits:[0,16],
        priceMin:0,
        priceMax:9999,
        currency:53570,
        specialId:1234,
        tourId:['all'],
        hotelClassId:9006279,
        hotelClassBetter:true,
        rAndBId:9006288,
        rAndBBetter:true,
        resultsNum:100,
        hotelId:[],
        hotelInStop:false,
        specialInStop:false,
        noTicketsTo:false,
        noTicketsFrom:false
    };

    if( $defaults ) defaults = $defaults; // remove after release

    var l10n = { };

    (function() {
        var loc = $('#st-l10n-datepicker span');
        l10n.dp = new Array(loc.length);
        $.each(loc, function(idx, value) { l10n.dp[idx] = ($(this).text()); });
        
        loc = $('#st-l10n-datepickerForRequest span');
        l10n.dpFR = new Array(loc.length);
        $.each(loc, function(idx, value) { l10n.dpFR[idx] = ($(this).text()); });
        
        loc = $('#st-l10n-alerts span');
        l10n.alerts = new Array(loc.length);
        $.each(loc, function(idx, value) { l10n.alerts[idx] = ($(this).text()); });
        
        loc = $('#st-l10n span');
        l10n.other = new Array(loc.length);
        $.each(loc, function(idx, value) { l10n.other[idx] = ($(this).text()); });
        //console.log(l10n);
    })();

    var ValidateDate = function validateDate(dateText,inst) {
        var MinDays = 0;
        var MaxDays = 89;

        if (this.id == st.after.attr('id')) { // Если изменена after
        var after = st.after.datepicker("getDate");
            var before = st.before.datepicker("getDate");


            // Проверка на диапазон дат выезда короче двух дней
            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);
            }
            hotelInfoBlock();
        }

        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);
            }
            hotelInfoBlock();
        }
        if (this.id == st.birthday1.attr('id')) { // Если изменена дата рождения первого ребёнка
            var today = new Date();
            var birth1Date = st.birthday1.datepicker("getDate");
            var years = Math.floor((today.getTime() - birth1Date.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
            if (years < 0) { years = 0; }
            st.childAge1.val(years);
        }
        if (this.id == st.birthday2.attr('id')) { // Если изменена дата рождения второго ребёнка
            var today = new Date();
            var birth2Date = st.birthday2.datepicker("getDate");
            var years = Math.floor((today.getTime() - birth2Date.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
            st.childAge2.val(years);
        }
        if (this.id == st.birthday3.attr('id')) { // Если изменена дата рождения второго ребёнка
            var today = new Date();
            var birth3Date = st.birthday3.datepicker("getDate");
            var years = Math.floor((today.getTime() - birth3Date.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
            st.childAge3.val(years);
        }
    }
    var TempDate = new Date();
    var NowDate = new Date (TempDate.getFullYear(), TempDate.getMonth(), TempDate.getDate(), 0, 0, 0, 0);
    var datepickerConfig = { changeMonth:true, changeYear:true, firstDay:l10n.dp[0], dateFormat:l10n.dp[1],
        dayNames:[l10n.dp[2], l10n.dp[3], l10n.dp[4], l10n.dp[5], l10n.dp[6], l10n.dp[7], l10n.dp[8]],
        dayNamesMin:[l10n.dp[9], l10n.dp[10], l10n.dp[11], l10n.dp[12], l10n.dp[13], l10n.dp[14], l10n.dp[15]],
        dayNamesShort:[l10n.dp[16], l10n.dp[17], l10n.dp[18], l10n.dp[19], l10n.dp[20], l10n.dp[21], l10n.dp[22]],
        monthNames:[l10n.dp[23], l10n.dp[24], l10n.dp[25], l10n.dp[26], l10n.dp[27], l10n.dp[28], l10n.dp[29], l10n.dp[30], l10n.dp[31], l10n.dp[32], l10n.dp[33], l10n.dp[34]],
        monthNamesShort:[l10n.dp[23], l10n.dp[24], l10n.dp[25], l10n.dp[26], l10n.dp[27], l10n.dp[28], l10n.dp[29], l10n.dp[30], l10n.dp[31], l10n.dp[32], l10n.dp[33], l10n.dp[34]],
        prevText:l10n.dp[47], nextText:l10n.dp[48],
        showAnim: '',
        duration: '',
        onSelect: ValidateDate,
        beforeShowDay: function(date) {
    		
            var css = "", text = "";
            switch (this.id) {
                case st.after.attr('id'): //если After
                    var neighbourDate = st.before.datepicker("getDate");
                    if ( neighbourDate && ( neighbourDate.getTime() - date.getTime() > 89*24*60*60*1000 ) ) { css = "dateoverlimit"; text = l10n.alerts[3]; }
                    break
                case st.before.attr('id'): //если Before
                    var neighbourDate = st.after.datepicker("getDate");
                    if ( neighbourDate && ( date.getTime() - neighbourDate.getTime() > 89*24*60*60*1000) ) { css = "dateoverlimit"; text = l10n.alerts[3]; }
                    break
            }
            for( var i = 0, length = calendar_data.length, y = date.getFullYear(); i < length; i++ ) {
                if( calendar_data[i][0] == y ) {
                	if ($('#tourType').val() == 1)
                	{
	                    if( $.inArray(date.getDate(), calendar_data[i][date.getMonth()+1]) != -1 ) return [true, css, text];
	                    else return [false, ''];
                	}
                	else
                	{
	                    if( $.inArray(date.getDate(), calendar_data[i][date.getMonth()+1]) != -1 ) return [true, (css == '' ? 'selectable_date_with_flights' : css), text];
	                    else if (date < NowDate) return [false, ''];
	                    else return [true, (css == '' ? 'selectable_date_without_flights' : css), (css == '' ? $('#NewSearch_Locales .CalendarDayWithoutFlight').text() : text)];
                	}
                }
            }
        	if ($('#tourType').val() != 1)
        	{
                if (date < NowDate) return [false, ''];
                else return [true, (css == '' ? 'selectable_date_without_flights' : css), (css == '' ? $('#NewSearch_Locales .CalendarDayWithoutFlight').text() : text)];
        	}
            return [false, ''];
        }
    };

    st = {
        main:$('#st-main'),
        error:$('#st-error'),
        allCheckAllCheckboxes:$('input.st-check-all'),
        tourCheckbox:$('#st-tour-checkbox'),
        allHotelsCheckbox:$('#st-all-hotels-checkbox'),
        fromCitySelect:$('#st-from select'),
        toCountrySelect:$('#st-to-country select'),
        after:$('#st-after'),
        before:$('#st-before'),
        allDates:$('#st-after,#st-before'),
        nightsMin:$('#st-nights-min'),
        nightsMax:$('#st-nights-max'),
        allNights:$('#st-nights-min,#st-nights-max'),
        accommodationSelect:$('#accommodation'),
        childAge1: $("#st-child-age-1"),
        childAge2: $("#st-child-age-2"),
        childAge3: $("#st-child-age-3"),
        allChildAges: $("#st-child-age-1,#st-child-age-2,#st-child-age-3"),
        birthday1:$('#st-birthday-1'),
        birthday2:$('#st-birthday-2'),
        birthday3:$('#st-birthday-3'),
        allBirthdays:$('#st-birthday-1,#st-birthday-2,#st-birthday-3'),
        regionSelect:$('#st-region select'),
        tourList:$('#st-tour-list'),
        tourListContent:$('#st-tour-list .st-listbox-content'),
        hcSelect:$('#st-hotel-class select'),
        hcBetterCheckbox:$('#st-hc-better-checkbox'),
        rbSelect:$('#st-r-and-b select'),
        rbBetterCheckbox:$('#st-rb-better-checkbox'),
        hotelNameFilter:$('#st-hotel-name'),
        allHotelsList:$('#st-all-hotels-list'),
        allHotelsListContent:$('#st-all-hotels-list .st-listbox-content'),
        selectedHotelsList:$('#st-selected-hotels-list'),
        selectedHotelsListContent:$('#st-selected-hotels-list .st-listbox-content'),
        bothHotelListsContent:$('#st-all-hotels .st-listbox-content,#st-selected-hotels .st-listbox-content'),
        hotelInStopCheckbox:$('#st-option-hotel-in-stop'),
        specialInStopCheckbox:$('#st-option-special-in-stop'),
        noTicketsToCheckbox:$('#st-option-no-tickets-to'),
        noTicketsFromCheckbox:$('#st-option-no-tickets-from'),
        OptionChipest:$('#st-option-chipest'),
        allOptionCheckboxes:$('#st-misc input:checkbox'),
        priceMin:$('#st-price-min'),
        priceMax:$('#st-price-max'),
        allPrices:$('#st-price-min,#st-price-max'),
        currencySelect:$('#st-currency select'),
        findButton:$('#st-find button'),
        findButtonText:$('#st-find strong'),
        result:$('#st-result'),
        resultInfo:$('#st-result-info'),
        resultTable:$('#st-result-table'),
        infoblockTitle: $('#infoblock-title'),
        infoblockBody: $('#infoblock-body'),
        moreresults: $('#moreresults'),
        moreresultsA: $('#moreresultsA'),
        paging: $('#paging'),
        excelblockA: $('#excelblockA'),
        excelblock: $('#excelblock'),
        excelblocktextarea: $('#excelblock textarea'),
        errors:[],
        resultCount: 0
    };
    	function orderByColumn(Order, column)
    	{
    	}
        $('th', st.resultTable).each(function(column) {
          if ($(this).is('.sort-alpha')) {
            $(this).addClass('clickable').hover(function() {
              $(this).addClass('hover');
            }, function() {
              $(this).removeClass('hover');
            }).click(function() {
              if ($(this).hasClass('OrderDESC'))
              {
            	  Order = 'ASC';
            	  $(this).removeClass('OrderDESC').addClass('OrderASC');
              }
              else if ($(this).hasClass('OrderASC'))
              {
            	  Order = 'DESC';
            	  $(this).removeClass('OrderASC').addClass('OrderDESC');
              }
              else
              {
            	  Order = 'ASC';
            	  $(this).addClass('OrderASC');
              }
              var rows = st.resultTable.find('tbody > tr.st-result-row').get();
              rows.sort(function(a, b) {
            	//console.log($(b));
                var keyA = $(a).children('td').eq(column).children('.sortValue').val().toUpperCase();
                var keyB = $(b).children('td').eq(column).children('.sortValue').val().toUpperCase();
                if(Order == 'ASC')
                {
	                if (keyA < keyB) return -1;
	                if (keyA > keyB) return 1;
                }
                else
                {
	                if (keyA < keyB) return 1;
	                if (keyA > keyB) return -1;
                }
                return 0;
              });
              $.each(rows, function(index, row) {
            	  st.resultTable.children('tbody').append(row);
              });
            });
          }
        });

    /* global objects */
    var object1_data, result_info, result_secret, result_data, calendar_data, grequest = [];
    var tempResult = [];
    var uriData = {};
    var pagerCounter = 1;
    var rowCounter = 0;
    var paging = st.paging.html();
    (function getUriData() {

        var rgxp = /result(.+)/;
        var ql =  window.location.hash.match(rgxp);
        if ( ql && ql[1] != '' ) {
            uriData = eval('('+decodeURIComponent(ql[1])+')');
            for (var key in uriData) {
                defaults[key] = uriData[key];
            }
            defaults.fromCityId = defaults.cityId;
            defaults.toCountryId = defaults.countryId;
            if ( defaults.after ) defaults.after = stringToDate(defaults.after);
            if ( defaults.before ) defaults.before = stringToDate(defaults.before);
            if ( defaults.birthday1 ) defaults.birthday1 = stringToDate(defaults.birthday1);
            if ( defaults.birthday2 ) defaults.birthday2 = stringToDate(defaults.birthday2);
            if ( defaults.birthday3 ) defaults.birthday3 = stringToDate(defaults.birthday3);
            if (uriData['tourType']) $('#tourType').val(uriData['tourType']);

            startFindAnimation();
            if (uriData.Chipest)
            {
            	tempResult = [];
            	fGetResChipest(uriData, false, true);
            }
            else
            	fGetRes(uriData);
        }
    })()
    
    function extend(from, to)
    {
        if (from == null || typeof from != "object") return from;
        if (from.constructor != Object && from.constructor != Array) return from;
        if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function ||
            from.constructor == String || from.constructor == Number || from.constructor == Boolean)
            return new from.constructor(from);

        to = to || new from.constructor();

        for (var name in from)
        {
            to[name] = typeof to[name] == "undefined" ? extend(from[name], null) : to[name];
        }

        return to;
    }
    function checkIfChipestRow(tempResult, ResultRow)
    {
    	var Chipest = true;
    	$.each(tempResult, function(idx, d) {
    		if (
    			(d[1] == ResultRow[1]) &&
    			(d[4] == ResultRow[4]) &&
    			(d[7] == ResultRow[7]) &&
    			//(d[13] == ResultRow[13]) &&
    			(d[15] == ResultRow[15])
    		)
    			Chipest = false;
    	});
    	return Chipest;
    }
    var  ResChipestTempCounter = 0;
    var newTempResult = [];
    function fGetResChipest (request, scrlTo, newRequest) {
    	if (newRequest)
    	{
    		ResChipestTempCounter = 0;
    		newTempResult = [];
    	}
        grequest = extend(request);
        $('#formcontainerOverlay').css('display', '');
        $('#formcontainerPreloader').css('display', '');
        $.ajax({ type:'POST', url:urls.result, data:request, dataType:'json',
            error:function() {
                st.error.css('visibility', 'visible');
                stopFindAnimation();
                $('#formcontainerOverlay').css('display', 'none');
                $('#formcontainerPreloader').css('display', 'none');
            },
            success:function(response) {
                if (response.success) {
                    st.error.css('visibility', 'hidden');
                    result_info = response.info;
                    result_secret = response.secret;
                    result_data = response.data;
                    var NewCounter = 0;
            		$.each(result_data, function(idx, d) {
            			if (ResChipestTempCounter < 100)
	            			if (checkIfChipestRow(tempResult, d))
	            			{
	            				NewCounter++;
	            				ResChipestTempCounter = ResChipestTempCounter + 1;
	            				tempResult[tempResult.length] = d;
	            				newTempResult[newTempResult.length] = d;
	            			}
            		});
            		if (newRequest) location.hash = "result" + encodeURIComponent(JSON.stringify(request));
                    if (result_info[1][1] != 0) {
//                    	console.log(ResChipestTempCounter);
//                    	console.log(response.data);
                        grequest.priceMin = response.data[response.data.length-1][16].replace(/[^\d]/g, '');
                    }
//                    if ((result_info[1][1] == defaults.resultsNum) && grequest.priceMin < request.priceMax && ResChipestTempCounter < defaults.resultsNum)
//                    {
//                    	//fGetResChipest(grequest, scrlTo, false);
//                    }
//                    else
//                    {
	            		result_data = newTempResult;
	            		renderResults(scrlTo);
	                    st.result.show();
	                    if (ResChipestTempCounter != 0) {
	                        if(result_info[1][1] != 0)
	                        {
	                        	grequest.priceMin = response.data[response.data.length-1][16].replace(/[^\d]/g, '');
		                        if ( grequest.priceMin < request.priceMax && response.info[1][1] >= defaults.resultsNum) {
		                            st.moreresults.show();
		                            st.moreresultsA.show();
		
		                        } else { st.moreresultsA.hide(); st.moreresults.hide(); }
	                        } else { st.moreresultsA.hide(); st.moreresults.hide(); }
	
	                        if (st.excelblock.is(":visible")) { // Если открыт блок с экселем, обновляем данные
	                            appendResultToExcelBlock();
	                        } else {
	                            st.excelblockA.show();
	                        }
	                        resizeIframe ();
	                        if (! scrlTo) {  // Прокручиваем страницу к результатам, если что-то нашлось и это не moreresults
	                        	var tempHash = window.location.hash;
	                            window.location.hash = "a";
	                            window.location.hash = "result";
	                            window.location.hash = tempHash;
	                            st.excelblocktextarea.text(''); // И очищаем данные для Экселя, по умолчанию они туда аппендятся
	                        }
	                    } else {
	                        st.moreresults.hide();
	                        st.excelblockA.hide();
	                        st.excelblock.hide();
	                    }
	                    if (newRequest) location.hash = "result" + encodeURIComponent(JSON.stringify(request));
	                    //stopFindAnimation();
//                	}
//                    else
//                    {renderResults(scrlTo);st.result.show();}
                    stopFindAnimation();
                } else {
                    if (response.message) $('span.st-error-message', st.error).text(' (' + response.message + ')');
                    st.error.css('visibility', 'visible');
                    stopFindAnimation();
                }
                $('#formcontainerOverlay').css('display', 'none');
                $('#formcontainerPreloader').css('display', 'none');
            }
        });
    }
    function fGetRes (request, scrlTo) {
        grequest = extend(request);
        $('#formcontainerOverlay').css('display', '');
        $('#formcontainerPreloader').css('display', '');
        $.ajax({ type:'POST', url:urls.result, data:request, dataType:'json',
            error:function() {
                st.error.css('visibility', 'visible');
                stopFindAnimation();
                $('#formcontainerOverlay').css('display', 'none');
                $('#formcontainerPreloader').css('display', 'none');
            },
            success:function(response) {
                if (response.success) {
                    st.error.css('visibility', 'hidden');
                    result_info = response.info;
                    result_secret = response.secret;
                    result_data = response.data;
                    renderResults(scrlTo);
                    st.result.show();
                    if (result_info[1][1] != 0) {
                        grequest.priceMin = response.data[response.data.length-1][16].replace(/[^\d]/g, '');
                        if ( grequest.priceMin < request.priceMax && response.info[1][1] >= defaults.resultsNum ) {
                            st.moreresults.show();
                            st.moreresultsA.show();

                        } else { st.moreresultsA.hide(); st.moreresults.hide(); }

                        if (st.excelblock.is(":visible")) { // Если открыт блок с экселем, обновляем данные
                            appendResultToExcelBlock();
                        } else {
                            st.excelblockA.show();
                        }
                        resizeIframe ();
                        if (! scrlTo) {  // Прокручиваем страницу к результатам, если что-то нашлось и это не moreresults
                            window.location.hash = "a";
                            window.location.hash = "result";
                            st.excelblocktextarea.text(''); // И очищаем данные для Экселя, по умолчанию они туда аппендятся
                        }
                    } else {
                        st.moreresults.hide();
                        st.excelblockA.hide();
                        st.excelblock.hide();
                    }
                    location.hash = "result" + encodeURIComponent(JSON.stringify(request));
                } else {
                    if (response.message) $('span.st-error-message', st.error).text(' (' + response.message + ')');
                    st.error.css('visibility', 'visible');
                }
                stopFindAnimation();
                $('#formcontainerOverlay').css('display', 'none');
                $('#formcontainerPreloader').css('display', 'none');
            }
        });
    }
    st.allCheckAllCheckboxes.click(function() { // 'check all' checkboxes
        var checkboxes = $('div.st-checkable-item:visible input', $(this).parent().next());
        //$('#st-option-my-hotels').removeAttr('checked');
        if( $(this).attr('checked') ) {
            checkboxes.parent().addClass('st-checked');
            checkboxes.filter(':not(:checked)').attr('checked', 'checked').trigger('echecked');
        } else {
            checkboxes.parent().removeClass('st-checked');
            checkboxes.filter(':checked').removeAttr('checked').trigger('unchecked');
        }
        hotelInfoBlock()
    });

    var selectedCity = false, selectedRegion = false;

    st.fromCitySelect.change(function() {
    	initCountries();
    	st.toCountrySelect.trigger('change');
        var city = object1_data.cities[st.fromCitySelect.val()];
//        if( selectedCity ) $.each(selectedCity.tours, function(idx, tour) {
//            if( $.inArray(tour, city.tours) == -1 ) {
//                if( $('input', tour.el).attr('checked') ) tour.el.trigger('click');
//                tour.el.hide();
//            }
//        });
        $.each(city.tours, function(idx, tour) {
            tour.el.show();
        });
        selectedCity = city;
        updateCalendar();
    });

    st.regionSelect.change(function() {
        var regionIdx = st.regionSelect.val();
        if( regionIdx != l10n.other[2] ) {
            if( selectedRegion ) $.each(selectedRegion.hotels, function(idx, hotel) {
                hideHotel(hotel);
            }); else {
                $('.st-checkable-item.st-checked', st.tourListContent).trigger('click');
                st.tourCheckbox.removeAttr('checked');
                st.allHotelsCheckbox.removeAttr('checked'); 
            }
            selectedRegion = object2_data.regions[regionIdx];
            var hc = new HotelFilter();
            $.each(selectedRegion.hotels, function(idx, hotel) {
                if( !hc.isFiltered(hotel) ) hotel.el.show();
            });
        } else {
            if( selectedRegion ) $.each(selectedRegion.hotels, function(idx, hotel) {
                hideHotel(hotel);
            });
            selectedRegion = false;
        }
    });

    st.hcSelect.change(refreshHotels);
    st.hcBetterCheckbox.click(refreshHotels);
    st.rbSelect.change(refreshHotels);
    st.rbBetterCheckbox.click(refreshHotels);
    st.hotelNameFilter.keyup(refreshHotelsSimple);

    st.allDates.datepicker(datepickerConfig);
    delete datepickerConfig.beforeShowDay;
    st.allBirthdays.datepicker(datepickerConfig);

    st.accommodationSelect.change(function() {
        var c = object2_data.accommodations[st.accommodationSelect.val()].children;
        c == 0 && (st.allChildAges.attr('disabled', 'disabled'), st.allBirthdays.datepicker("disable") );
        if (c == 1) { // Включаем выбор даты рождения и возраста для одного ребёнка
            st.childAge1.removeAttr('disabled');
            st.childAge2.attr('disabled', 'disabled');
            st.childAge3.attr('disabled', 'disabled');
            st.birthday1.datepicker("enable");
            st.birthday2.datepicker("disable");
            st.birthday3.datepicker("disable");

            if ( st.birthday1.datepicker('getDate') === null ) { st.childAge1.change(); } else { ValidateDate.call(st.birthday1[0]); } // Если нет даты рождения в URL, берем из селекта "возраст" 
        };
        if (c == 2) {
            st.childAge1.removeAttr('disabled');
            st.childAge2.removeAttr('disabled');
            st.childAge3.attr('disabled', 'disabled');
            st.birthday1.datepicker("enable");
            st.birthday2.datepicker("enable");
            st.birthday3.datepicker("disable");
            
            st.allChildAges.removeAttr('disabled')
            st.allBirthdays.datepicker("enable")
            if  ( st.birthday1.datepicker('getDate') === null ) { st.childAge1.change(); } else { ValidateDate.call(st.birthday1[0]); }
            if  ( st.birthday2.datepicker('getDate') === null ) { st.childAge2.change(); } else { ValidateDate.call(st.birthday2[0]); }
        }
        if (c > 2) {
            st.allChildAges.removeAttr('disabled')
            st.allBirthdays.datepicker("enable")
            if  ( st.birthday1.datepicker('getDate') === null ) { st.childAge1.change(); } else { ValidateDate.call(st.birthday1[0]); }
            if  ( st.birthday2.datepicker('getDate') === null ) { st.childAge2.change(); } else { ValidateDate.call(st.birthday2[0]); }
            if  ( st.birthday3.datepicker('getDate') === null ) { st.childAge3.change(); } else { ValidateDate.call(st.birthday3[0]); }
        }
    });

    function hideHotel(hotel) {
        if( hotel.selected ) hotel.el.trigger('click');
    	try
    	{hotel.el.hide();}
    	catch(err)
    	{}
    }
    function hideHotelSimple(hotel) {
    	try
    	{hotel.el.hide();}
    	catch(err)
    	{}
    }

    function showHotel(hotel) {
    	try
    	{hotel.el.show();}
    	catch(err)
    	{}
    }

    function HotelFilter() {
        this.filter = $.trim(st.hotelNameFilter.val()).toLowerCase();
        if( this.filter.length >= 3 ) this.byName = function(hotel) { return hotel.name.toLowerCase().indexOf(this.filter) == -1; };
        else this.byName = function(hotel) { return false; };
        this.hcWeight = object1_data.hotelClasses[st.hcSelect.val()].weight;
        this.rbWeight = object1_data.rAndBs[st.rbSelect.val()].weight;
        if( st.hcBetterCheckbox.attr('checked') ) this.byHC = function(hotel) { return hotel.hcWeight < this.hcWeight; };
        else this.byHC = function(hotel) { return hotel.hcWeight != this.hcWeight };
        if( st.rbBetterCheckbox.attr('checked') ) this.byRB = function(hotel) {
            var lowerWeight = this.rbWeight, filtered = true;
            $.each(hotel.rbWeight, function(idx, weight) {
                return filtered = (weight < lowerWeight);
            });
            return filtered;
        }; else this.byRB = function(hotel) { return $.inArray(this.rbWeight, hotel.rbWeight) == -1; };
    }

    HotelFilter.prototype.isFiltered = function(hotel) {
        return ( this.byName(hotel) || this.byHC(hotel) || this.byRB(hotel) );
    };

    HotelFilter.prototype.hideOrShow = function(hotel) {
        this.isFiltered(hotel) ? hideHotel(hotel) : showHotel(hotel);
    };
    HotelFilter.prototype.hideOrShowSimple = function(hotel) {
        this.isFiltered(hotel) ? hideHotelSimple(hotel) : showHotel(hotel);
    };

    function refreshHotels() {
        var hf = new HotelFilter();
        st.allHotelsCheckbox.removeAttr('checked');
        if( selectedRegion ) $.each(selectedRegion.hotels, function(idx, hotel) {
            hf.hideOrShow(hotel);
        }); else $('.st-checkable-item.st-checked', st.tourListContent).each(function() {
            $.each(object2_data.tours[$('input', this).val()].hotels, function(idx, hotel) {
                hf.hideOrShow(hotel);
            });
        });
        changeHotelSegments();
    }
    function refreshHotelsSimple() {
        var hf = new HotelFilter();
        if( selectedRegion ) $.each(selectedRegion.hotels, function(idx, hotel) {
            hf.hideOrShowSimple(hotel);
        }); else $('.st-checkable-item.st-checked', st.tourListContent).each(function() {
            $.each(object2_data.tours[$('input', this).val()].hotels, function(idx, hotel) {
                hf.hideOrShowSimple(hotel);
            });
        });
        changeHotelSegments();
    }
    function updateTourCheckboxStatus() {
        var IsChecked = true;
        $('div.st-checkable-item:visible input', st.tourListContent).each(function(){
            if (!this.checked)
                IsChecked = false;
        });
        if (IsChecked)
            st.tourCheckbox.attr('checked', 'checked');
        else
            st.tourCheckbox.removeAttr('checked');
        
    }
    function checkInfotoursCountry (CountryId)
    {
    	//return ((jQuery.inArray(CountryId, ActiveObjects.Countries) != -1) || (object1_data.cities[st.fromCitySelect.val()]['cityId'] != 4800));
    	var countries = [5732,5733,1104,7067498,12695,147573,158976];
    	if (object1_data.cities[st.fromCitySelect.val()]['cityId'] == 4800)
    	{
    		return(jQuery.inArray(CountryId, countries) != -1)
    	}
    	else
    		return ((jQuery.inArray(CountryId, ActiveObjects.Countries) != -1));
    }
    function checkInfotoursRegion (RegionId)
    {
    	//return ((jQuery.inArray(RegionId.tourId[0], ActiveObjects.Regions) != -1) || (object1_data.cities[st.fromCitySelect.val()]['cityId'] != 4800));
    	if (object1_data.cities[st.fromCitySelect.val()]['cityId'] == 4800)
    		return ((jQuery.inArray(RegionId.tourId[0], ActiveObjects.Regions) != -1));
    	else
    		return true;
    }
    function checkInfotoursHotel (HotelId)
    {
    	//return ((jQuery.inArray(HotelId, ActiveObjects.Hotels) != -1) || (object1_data.cities[st.fromCitySelect.val()]['cityId'] != 4800));
    	if (object1_data.cities[st.fromCitySelect.val()]['cityId'] == 4800)
    		return ((jQuery.inArray(HotelId, ActiveObjects.Hotels) != -1));
    	else
    		return true;
    }
    function getInfotoursCountryName (CountryId)
    {
    	var countriesNames = {
        		1104: 'TURKEY',
        		5732: 'EGYPT',
        		158976: 'BULGARIA',
        		5733: 'SPAIN',
        		7067498: 'GREECE',
        		12695: 'THAILAND',
        		111137: 'CUBA',
        		147573: 'AUSTRIA',
        		138865: 'SRI LANKA'
        	};
    	return countriesNames[CountryId];
    }
    function clearUnActiveObjects(objectData)
    {
    	var countriesNames = {
    		1104: 'TURKEY',
    		5732: 'EGYPT',
    		5733: 'SPAIN',
    		158976: 'BULGARIA',
    		7067498: 'GREECE',
    		12695: 'THAILAND',
    		111137: 'CUBA',
    		147573: 'AUSTRIA',
    		138865: 'SRI LANKA'
    	};
        jQuery.each(objectData.countries, function(key, value){
        	if (countriesNames[value.countryId])
        		objectData.countries[key].name = countriesNames[value.countryId];
        });
        return objectData;
    }
    function clearUnActiveObjects2(objectData)
    {
    	if (
        		st.toCountrySelect.val() == '1104'
        	)
        	{
        		var Keys = [];
        		jQuery.each(objectData.accommodations, function(key, value)
        		{
        			if (
        				value.accommodationId == 15369
        			)
        			{
        				Keys[value.accommodationId] = true;
        			}
        		});
            	if (!Keys[15369]) objectData.accommodations.push({accommodationId: 15369, name: 'DBL+3CHD', children: 3});
            	
        	}
    	var regionsNames = {
    		  111143: 'VARADERO',
    	      14351: 'EL GOUNA',
    	      26313: 'DAHAB',
    	      5734: 'HURGHADA',
    	      14355: 'MAKADY BAY',
    	      26576: 'LUXOR',
    	      111466: 'MARSA ALAM',
    	      14353: 'SAFAGA',
    	      5735: 'SHARM EL SHEIKH',
    	      14354: 'SOMA BAY',
    	      9004230: 'CRETE-CHANIA',
    	      7067584: 'CRETE-HERAKLION',
    	      199545: 'CRETE-LASSITHI',
    	      9004227: 'CRETE-RETHYMNO',
    	      9003981: 'RHODES',
    	      64746: 'BARCELONA',
    	      66920: 'COSTA BRAVA',
    	      115783: 'COSTA DE BARCELONA-MARESME',
    	      5743: 'COSTA DEL SOL',
    	      174793: 'COSTA DEL SOL-MARBELLA',
    	      66922: 'COSTA DORADA',
    	      134244: 'MALLORCA',
    	      9004257: 'MALAGA',
    	      52403: 'TENERIFE - COSTA ADEJE',
    	      177634: 'TENERIFE - GUIA DE ISORA',
    	      177631: 'TENERIFE - PUERTO DE LA CRUZ',
    	      14358: 'BANGKOK',
    	      14259: 'PATTAYA',
    	      14369: 'PHUKET',
    	      14372: 'SAMUI',
    	      1285: 'ANTALYA',
    	      12689: 'BELEK',
    	      12706: 'BODRUM',
    	      9004247: 'DIDIM',
    	      12705: 'FETHIYE',
    	      4433: 'INCEKUM - ALANYA',
    	      5736: 'KEMER',
    	      139343: 'KUSADASI',
    	      4434: 'MARMARIS',
    	      12691: 'SIDE',
    	      263634: 'MUNICH',
    	      3024283: 'BAD GASTEIN',
    	      3025256: 'ZELL AM SEE'
    	     };
        jQuery.each(objectData.tours, function(key, value){
        	var Name = [];
        	jQuery.each(value.tourId, function(key2, value2){
        		if (regionsNames[value2])
        			Name[Name.length] = regionsNames[value2]
        	});
        	if (Name.length > 0)
        	{
        		objectData.tours[key].name = Name.join(' + ');
        		if (objectData.tours[key].name == 'BAD GASTEIN + MUNICH')
        			objectData.tours[key].name = 'MUNICH + BAD GASTEIN';
        		if (objectData.tours[key].name == 'ZELL AM SEE + MUNICH')
        			objectData.tours[key].name = 'MUNICH + ZELL AM SEE';
        	}
        });
        return objectData;
    }
    st.toCountrySelect.change(function() { // 'to country' select box loads tours, regions and hotels
    	if (st.toCountrySelect.val() == '1104')
    	{
    		st.hcSelect.find('option').each(function (){
    			if (object1_data.hotelClasses[$(this).val()].classId == 269506)
    				st.hcSelect.val($(this).val());
    		});
    		st.rbSelect.find('option').each(function (){
    			if (object1_data.rAndBs[$(this).val()].rAndBId == 2424)
    				st.rbSelect.val($(this).val());
    		});
    	} else if (st.toCountrySelect.val() == '147573')
    	{
    		st.hcSelect.find('option').each(function (){
    			if (object1_data.hotelClasses[$(this).val()].classId == 269506)
    				st.hcSelect.val($(this).val());
    		});
    		st.rbSelect.val(0);
    	} else if (st.toCountrySelect.val() == '5733')
    	{
    		st.hcSelect.val(0);
    		st.rbSelect.find('option').each(function (){
    			if (object1_data.rAndBs[$(this).val()].rAndBId == 2424)
    				st.rbSelect.val($(this).val());
    		});
    	}
    	else
    	{
    		st.hcSelect.find('option').each(function (){
    			if (object1_data.hotelClasses[$(this).val()].classId == 2567)
    				st.hcSelect.val($(this).val());
    		});
    		st.rbSelect.find('option').each(function (){
    			if (object1_data.rAndBs[$(this).val()].rAndBId == 2424)
    				st.rbSelect.val($(this).val());
    		});
    	}
        //st.tourCheckbox.removeAttr('checked');
        st.tourCheckbox.attr('checked', 'checked');
        st.allHotelsCheckbox.removeAttr('checked');
        //$('#st-option-my-hotels').removeAttr('checked');
        st.bothHotelListsContent.children().remove();
        st.regionSelect.children().remove();
        st.tourListContent.children().remove();
        var sr=object2_data.accommodations[st.accommodationSelect.val()]; //  Сохраняем Id типа проживания
        // load tours, regions and hotels from remote side
        $.getJSON(urls.object2, { countryId:st.toCountrySelect.val(), locale:l10n.other[1] }, function(data) {
            object2_data = data;
            if( object2_data.success ) {
                object2_data = clearUnActiveObjects2(object2_data);
                updateCalendar();

                var cityTmp = {}, tourTmp= {}, regionTmp = {}, hf = new HotelFilter();

                st.regionSelect.append(selectableItem({
                    text:l10n.other[2], selected:true
                }));

                $.each(object2_data.regions, function(idx, region) {
                    regionTmp['$'+region.regionId] = region;
                    region.hotels = [];
                    st.regionSelect.append(region.el = selectableItem({
                        text:region.name, value:idx
                    }));
                });

                $.each(object1_data.cities, function(idx, city) {
                    cityTmp['$'+city.cityId] = city;
                    city.tours = [];
                });

                $.each(object2_data.hotels, function(idx, hotel) {
	                    hotel.visibilityCounter = 0;
	                    var key, hotels;
	                    if( hotel.tourId ) {
	                        key = '$'+hotel.tourId;
	                        hotels = tourTmp[key]
	                        if( hotels ) hotels.push(hotel);
	                        else tourTmp[key] = [ hotel ];
	                    }
	                    if( hotel.regionId ) regionTmp['$'+hotel.regionId].hotels.push(hotel);
                });
                
                
                
                
                $.each(object2_data.tours, function(idx, tour) {
                	
                	if (checkInfotoursRegion(tour))
                	{
	                    var visible = false;
	                    $.each(tour.fromCityId, function(idx, fromCityId) {
	                        var city = cityTmp['$'+fromCityId];
	                        if( city ) {
	                            city.tours.push(tour);
	                            if( city.cityId == selectedCity.cityId ) visible = true;
	                        }
	                    });
	                    tour.hotels = [];
	                    $.each(tour.tourId, function(idx, tourId) {
	                        var hotels = tourTmp['$'+tourId];
	                        if(hotels) $.each(hotels, function(idx, hotel) {
	                            tour.hotels.push(hotel);
	                        });
	                    });
	                    var checked = false;
	                    if( visible )  {
	                        if(  defaults.tourId[0] == 'all' || (function () { for(var i=0; i<defaults.tourId.length; i++) { if ( compareArrays(tour.tourId, defaults.tourId[i]) ) return true; } return false; })() ) {
	                            //alert('true')
	                            checked = true;
	                            $.each(tour.hotels, function(idx, hotel) { hotel.visibilityCounter++; });
	                        }
	                    }
	                    st.tourListContent.append(tour.el = checkableItem({
	                        text:tour.name, value:idx,
	                        checked:checked,
	                        hidden:!visible,
	                        bind:{
	                            checked:function() {
	                    			//$('#st-option-my-hotels').removeAttr('checked');
	                                if( selectedRegion ) {
	                                    st.regionSelect.val(l10n.other[2]);
	                                    st.regionSelect.trigger('change');
	                                }
	                                var hf = new HotelFilter();
	                                $.each(object2_data.tours[$(this).val()].hotels, function(i, hotel) {
                                    	try
                                    	{
                                    		if( hotel.visibilityCounter++ == 0 && !hf.isFiltered(hotel) ) hotel.el.show();
                                    	}
                                        catch(err)
                                        {}
	                                });
	                                changeHotelSegments();
	                            },
	                            unchecked:function() {
	                            	//$('#st-option-my-hotels').removeAttr('checked');
	                                $.each(object2_data.tours[$(this).val()].hotels, function(i, hotel) {
	                                    if( --hotel.visibilityCounter == 0 ) {
	                                    	try
	                                    	{
		                                        if( $('input', hotel.el).attr('checked') ) hotel.el.trigger('click');
		                                        hotel.el.hide();
	                                    	}
	                                        catch(err)
	                                        {}
	                                    }
	                                });
	                                changeHotelSegments();
	                            }
	                        }
	                    }));
	
	                    
	                    
	                    
	                    // Воркэраунд для IE6 - проставляем галочки после отображения чекбоксов
	                    if( visible && checked ) {
	                        tour.el.children('input').attr('checked','checked');
	                    }
                	}
                });
                
                
                $.each(object2_data.hotels, function(idx, hotel) {
                	if (checkInfotoursHotel(hotel.hotelId))
                	{
	                    st.allHotelsListContent.append(hotel.el = checkableItem({
	                        text:this.name, value:idx,
	                        trigger:($.inArray(hotel.hotelId, defaults.hotelId) != -1),
	                        hidden:(hotel.visibilityCounter == 0 || hf.isFiltered(hotel)),
	                        bind:{
	                            checked:function() {
	                                var idx = $(this).val();
	                                var hotel = object2_data.hotels[idx];
	                                st.selectedHotelsListContent.append(
	                                    hotel.selected = clickableItem({ text:hotel.name, idx:idx }).click(function() {
	                                        $('.st-checkable-item input[value='+$(this).attr('idx')+']', st.allHotelsListContent).trigger('click');
	                                    })
	                                );
	                            },
	                            unchecked:function() {
	                                var hotel = object2_data.hotels[$(this).val()];
	                                hotel.selected.remove();
	                                hotel.selected = undefined;
	                            }
	                        }
	                    }));
	                    if ($.inArray(hotel.hotelId, defaults.hotelId) != -1) hotel.el.children('input').attr('checked','checked'); // Воркэраунд для IE6 - проставляем галочки после отображения чекбоксов
                	}
                });
                changeHotelSegments();

                // accommodation
                
                st.accommodationSelect.children().remove();
                
                if (sr && $.inArray(sr.accommodationId, object2_data.accommodations) != -1)  {sr = sr.accommodationId} else { sr = defaults.accommodationId};
                $.each(object2_data.accommodations, function(idx, accommodation) {
                    st.accommodationSelect.append(selectableItem({
                        text:accommodation.name, value:idx,
                        selected:(accommodation.accommodationId == sr)
                    }));
                });
                st.accommodationSelect.trigger('change');
            } else {
                if( object2_data.message ) $('span.st-error-message', st.error).text(' ('+object2_data.message+')');
                st.error.css('visibility', 'visible');
            }
            updateTourCheckboxStatus();
        });
        hotelInfoBlock();
    });

    $('#st-selected-hotels a').click(function() { // clear selected hotels list
        $('.st-checkable-item.st-checked', st.allHotelsListContent).trigger('click');
        st.allHotelsCheckbox.removeAttr('checked');
        return false;
    });

    st.findButton.click(search);


    $.getJSON(urls.object1, { locale:l10n.other[1] }, function(data) {
        object1_data = data;
        if( object1_data.success ) {
            object1_data = clearUnActiveObjects(object1_data);
            init();
            
        } else {
            if( object1_data.message ) $('span.st-error-message', st.error).text(' ('+object1_data.message+')');
            st.error.css('visibility', 'visible');
        }
    });
    st.childAge1.change(function () {
           st.birthday1.datepicker("setDate", -$(this).val()+"y");
    });
    st.childAge2.change(function () {
           st.birthday2.datepicker("setDate", -$(this).val()+"y");
    });
    st.childAge3.change(function () {
        st.birthday3.datepicker("setDate", -$(this).val()+"y");
 });
    st.currencySelect.change(function () {
    		//console.log(defaultMaxCurrencies);
           st.priceMax.val(defaultMaxCurrencies[st.currencySelect.val()]);
    });
    st.infoblockTitle.click(function () {
        st.infoblockBody.toggle();
        resizeIframe();
        this.className === 'infoblock-title' ? this.className = 'infoblock-title-close' : this.className = 'infoblock-title';
    });
    $('#hotel-segments-title').click(function () {
    	$('#st-hotel-segments-area').toggle();
        //resizeIframe();
        this.className === 'hotel-segments-title' ? this.className = 'hotel-segments-title-close' : this.className = 'hotel-segments-title';
    });
    st.excelblockA.toggle(function () {
        appendResultToExcelBlock();
        st.excelblock.show();
        resizeIframe();
        },
        function () {
            st.excelblock.hide();
        }
    );
    st.moreresultsA.click(function () {
    	if (grequest.Chipest)
    		fGetResChipest(grequest, true, true);
    	else
    		fGetRes(grequest, true);
    })
//    st.moreresults.click(function () {
//        grequest.priceMin = result_data[result_data.length-1][16].replace(/[^\d]/, '');
//        fGetRes(grequest, true);
//    })
    
    /* no sequential code below, functions only */

    function checkableItem(config) {
        var el = $('<div class="st-checkable-item" unselectable="on"><input type="checkbox" /><label unselectable="on">'+config.text+'</label></div>')
            .mouseenter(function() { $(this).addClass('st-highlight'); })
            .mouseleave(function() { $(this).removeClass('st-highlight'); })
            .click(function() {
                var i = $('input', this);
                if( !i.attr('disabled') ) {
                    if( $(this).toggleClass('st-checked').hasClass('st-checked') ) {
                        i.attr('checked', true);
                        i.trigger('echecked');
                    } else {
                        i.removeAttr('checked').trigger('unchecked');
                    }
                }
                hotelInfoBlock()
            });
        var i = el.children('input');
        if( config.value !== undefined ) i.val(config.value); 
        if( config.bind ) {
            if( config.bind.checked ) i.bind('echecked', config.bind.checked);
            if( config.bind.unchecked ) i.bind('unchecked', config.bind.unchecked);
        }
        if( config.hidden ) el.hide();
        else if( config.checked || config.trigger ) {
            el.addClass('st-checked');
            i.attr('checked', 'checked');
            if( config.trigger ) i.trigger('echecked');
        } 
        return el;
    }

    function clickableItem(config) {
        var el = $('<div class="st-clickable-item" unselectable="on"><img src="/static/ts-lt/images/back.png"/><label unselectable="on">'+config.text+'</label></div>')
            .mouseenter(function() { $(this).addClass('st-highlight'); })
            .mouseleave(function() { $(this).removeClass('st-highlight'); });
        $.each(config, function(name, value) { if( name != 'text' ) el.attr(name, value); });
        return el;
    }

    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 updateCalendar() {
        calendar_data = [];
        var request = {
            cityId:selectedCity.cityId,
            countryId:st.toCountrySelect.val()
        };
        if( request.cityId && request.countryId ) {
            //loadAttention(request);
        	st.infoblockTitle.show();
            $('#formcontainerOverlay').css('display', '');
            $('#formcontainerPreloader').css('display', '');
            $.ajax({ type:'POST', url:urls.calendar, data:request, dataType:'json',
            error:function() {
                st.error.css('visibility', 'visible');
                $('#formcontainerOverlay').css('display', 'none');
                $('#formcontainerPreloader').css('display', 'none');
            },
            success:function(response) {

                if( response.success ) {
                    calendar_data = response.data;
                    if ($('#st-to-country select').val() == '12695')
                    {
	                	var Year;
	                	var Month;
	                	var Day;
	                	var NewDate;
	                	var Dates = [];
	                	var Years = [];
	                    $.each(calendar_data, function(Key, Value){
	                    	if (Key >= 0)
	                    	{
	                    		Year = Value[0];
	                    		$.each(Value, function(MKey, MValue){
	                    			if (MKey > 0)
	                    			{
	                    				Month = MKey - 1;
	                    				$.each(MValue, function(DKey, DValue){
	                    					Day = DValue + 1;
	                    					NewDate = new Date();
	                    					NewDate.setFullYear(Year,Month,Day);
	                    					Dates[Dates.length] = NewDate;
	                    				});
	                    			}
	                    		});
	                    	}
	                    });
	                    calendar_data = [];
	                    $.each(Dates, function(Key, Value){
	                    	if( $.inArray(Value.getFullYear(), Years) == -1 )
	                    		Years[Years.length] = Value.getFullYear();
	                    });
	                    $.each(Years, function(Key, Value){
	                    	calendar_data[Key] = [Value,[],[],[],[],[],[],[],[],[],[],[],[]];
	                        $.each(Dates, function(DatesKey, DatesValue){
	                        	if (DatesValue.getFullYear() == Value)
	                        	{
	                        		var temp = calendar_data[Key][DatesValue.getMonth()+1];
	                        		temp[temp.length] = DatesValue.getDate();
	                        		calendar_data[Key][DatesValue.getMonth()+1] = temp;
	                        	}
	                        });
	                    });
                    }
                    //setCurrency(response.defaultCurrency);
                }  else {
                    if( response.message ) $('span.st-error-message', st.error).text(' ('+response.message+')');
                    st.error.css('visibility', 'visible');
                }
                $('#formcontainerOverlay').css('display', 'none');
                $('#formcontainerPreloader').css('display', 'none');
            }
            });
        }
    }

    function dateToString(date) {
        return $.datepicker.formatDate(l10n.dp[1], date);
    }
    function dateToStringForRequest(date) {
        return $.datepicker.formatDate(l10n.dpFR[0], date);
    }
    function stringToDate(date) {
        return $.datepicker.parseDate(l10n.dpFR[0], date);
    }

    var findDotCount, findText = st.findButtonText.text(), findAnimation;

    function startFindAnimation() {
        st.findButton.attr('disabled', 'disabled');
        findDotCount = 1;
        findAnimation = setInterval(function() {
            switch( findDotCount ) {
                case 3: st.findButtonText.text('   ' + findText + '...'); findDotCount = 1; break;
                case 2: st.findButtonText.text('  ' + findText + '..'); findDotCount++; break;
                case 1: st.findButtonText.text(' ' + findText + '.'); findDotCount++; break;
            }
        }, 400);
    }

    function stopFindAnimation() {
        clearInterval(findAnimation);
        st.findButtonText.text(findText);
        st.findButton.removeAttr('disabled');
    }

    function search() {
    	if (($('#st-hotel-segments-area input:checked').length > 0) && ($('#st-all-hotels-list input:checked').length == 0))
    	{
    		alert($('.SegmentsSelectionWithoutResult').html());
    	}
    	else
    	{
	        st.result.hide();
	        $('tr.st-result-row', st.resultTable).remove();
	        st.resultCount = 0;
	        rowCounter = 0;
	        pagerCounter = 1;
	        var request = {
	            lite:true,
	            locale:l10n.other[1],
	            cityId:selectedCity.cityId,
	            countryId:st.toCountrySelect.val(),
	            after:st.after.datepicker('getDate'),
	            before:st.before.datepicker('getDate'),
	            nightsMin:parseInt(st.nightsMin.val()),
	            nightsMax:parseInt(st.nightsMax.val()),
	            priceMin:parseFloat(st.priceMin.val()),
	            priceMax:parseFloat(st.priceMax.val()),
	            currency:st.currencySelect.val(),
	            tourId:[],
	            hotelClassId:object1_data.hotelClasses[st.hcSelect.val()].classId,
	            hotelClassBetter:(st.hcBetterCheckbox.attr('checked') != false && st.hcBetterCheckbox.attr('checked') != undefined),
	            rAndBId:object1_data.rAndBs[st.rbSelect.val()].rAndBId,
	            rAndBBetter:(st.rbBetterCheckbox.attr('checked') != false && st.rbBetterCheckbox.attr('checked') != undefined),
	            hotelId:[],
	            hotelInStop:(st.hotelInStopCheckbox.attr('checked') != false && st.hotelInStopCheckbox.attr('checked') != undefined),
	            Chipest:(st.OptionChipest.attr('checked') != false && st.OptionChipest.attr('checked') != undefined),
	            specialInStop:(st.specialInStopCheckbox.attr('checked') != false && st.specialInStopCheckbox.attr('checked') != undefined),
	            noTicketsTo:(st.noTicketsToCheckbox.attr('checked') != false && st.noTicketsToCheckbox.attr('checked') != undefined),
	            noTicketsFrom:(st.noTicketsFromCheckbox.attr('checked') != false && st.noTicketsFromCheckbox.attr('checked') != undefined),
	            tourType:jQuery('#tourType').val()
	        };
	        if( selectedRegion ) request.regionId = selectedRegion.regionId;
	        else {
	            //checkedToursValues = [];
	            $('.st-checkable-item input:checked', st.tourListContent).each(function() {
	                //request.tourId.push(object2_data.tours[$(this).val()].tourId.join());
	                request.tourId.push(object2_data.tours[$(this).val()].tourId);
	                //checkedToursValues.push($(this).val());
	            });
	        }
	        $('.st-clickable-item', st.selectedHotelsListContent).each(function() {
	            request.hotelId.push(object2_data.hotels[$(this).attr('idx')].hotelId);
	        });
	
	        $.each(st.errors, function(idx, el) { el.removeClass('error'); });
	        st.errors = [];
	
	        if( request.regionId == undefined && request.tourId.length == 0 ) {
	            st.errors.push(st.regionSelect);
	            st.errors.push(st.tourList);
	        }
	
	        if( request.after.getTime() > request.before.getTime() ) {
	            st.errors.push(st.after);
	            st.errors.push(st.before);
	        }
	        if( request.nightsMin > request.nightsMax ) {
	            st.errors.push(st.nightsMin);
	            st.errors.push(st.nightsMax);
	        }
	
	        var accommodation = object2_data.accommodations[st.accommodationSelect.val()];
	        switch( accommodation.children ) {
	            case 3:
	                request.birthday3 = st.birthday3.datepicker('getDate');
	                if( request.birthday3 == null ) st.errors.push(st.birthday3);
	            case 2:
	                request.birthday2 = st.birthday2.datepicker('getDate');
	                if( request.birthday2 == null ) st.errors.push(st.birthday2);
	            case 1:
	                request.birthday1 = st.birthday1.datepicker('getDate');
	                if( request.birthday1 == null ) st.errors.push(st.birthday1);
	        }
	        request.accommodationId = accommodation.accommodationId;
	
	        var valid = true;
	        if( isNaN(request.priceMin) ) { st.errors.push(st.priceMin); valid = false; }
	        if( isNaN(request.priceMax) ) { st.errors.push(st.priceMax); valid = false; }
	        if( valid && request.priceMin > request.priceMax ) {
	            st.errors.push(st.priceMin);
	            st.errors.push(st.priceMax);
	        }
	        if( st.errors.length > 0 ) $.each(st.errors, function(idx, el) { el.addClass('error'); });
	        else {
	            startFindAnimation();
	
	            request.after = dateToStringForRequest(request.after);
	            request.before = dateToStringForRequest(request.before);
	            if( request.birthday1 ) request.birthday1 = dateToStringForRequest(request.birthday1);
	            if( request.birthday2 ) request.birthday2 = dateToStringForRequest(request.birthday2);
	            if( request.birthday3 ) request.birthday3 = dateToStringForRequest(request.birthday3);
	            //alert(JSON.stringify(request))
	            if (request.Chipest)
	            {
	            	tempResult = [];
	            	fGetResChipest(request, false, true);
	            }
	            else
	            	fGetRes(request);
	        }
    	}
        return false;
    }

    function initCountries()
    {
    	st.toCountrySelect.children().remove();
        $.each(object1_data.countries, function(idx, country) {
        	if (checkInfotoursCountry(country.countryId))
            st.toCountrySelect.append(selectableItem({
                text:country.name, value:country.countryId,
                selected:(country.countryId == defaults.toCountryId)
            }));
        });
    }
    function init() { // reinitialize form
        //object1_data['currencies'] = {};
        var NewCurrencies = {};
        var curIndex = 0;
        NewCurrencies[0] = {currencyId: '53570', name: 'LTL'};
        NewCurrencies[1] = {currencyId: '50159', name: 'LVL'};
        //NewCurrencies[2] = {currencyId: '174757', name: 'EEK'};
        //NewCurrencies[3] = {currencyId: '132329', name: 'BYR'};
        NewCurrencies[2] = {currencyId: '18864', name: 'EUR'};
        NewCurrencies[3] = {currencyId: '5561', name: 'USD'};
        object1_data['currencies'] = NewCurrencies;
        
        object2_data = { tours:[], regions:[], hotels:[], accommodations:[] };

        st.hotelNameFilter.val('');

        st.allCheckAllCheckboxes.removeAttr('checked');

        // hotel classes
        st.hcSelect.children().remove();
        $.each(object1_data.hotelClasses, function(idx, hotelClass) {
            st.hcSelect.append(selectableItem({
                text:hotelClass.name, value:idx,
                selected:(hotelClass.classId == defaults.hotelClassId)
            }));
        });
        if( defaults.hotelClassBetter ) st.hcBetterCheckbox.attr('checked', 'checked');
        else st.hcBetterCheckbox.removeAttr('checked');

        // r and b
        st.rbSelect.children().remove();
        $.each(object1_data.rAndBs, function(idx, rAndB) {
            st.rbSelect.append(selectableItem({
                text:rAndB.name, value:idx,
                selected:(rAndB.rAndBId == defaults.rAndBId)
            }));
        });
        if( defaults.rAndBBetter ) st.rbBetterCheckbox.attr('checked', 'checked');
        else st.rbBetterCheckbox.removeAttr('checked');

        // from cities
        object1_data.cities = {
            	0: {cityId: 4800, name: 'VILNIUS'},
            	1: {cityId: 523, name: 'RIGA'},
            	2: {cityId: 3746, name: 'TALLIN'},
            	3: {cityId: 786, name: 'MINSK'},
            	4: {cityId: 345, name: 'MOSCOW'}
//            	5: {cityId: 521, name: 'SAINT PETERSBURG'},
//            	6: {cityId: 3667, name: 'KIEV'}
            };
        st.fromCitySelect.children().remove();
        $.each(object1_data.cities, function(idx, city) {
            city.tours = city.regions = [];
            st.fromCitySelect.append(selectableItem({
                text:city.name, value:idx,
                selected:(city.cityId == defaults.fromCityId)
            }));
        });
        st.fromCitySelect.trigger('change');

        // to countries
//        initCountries();
//        st.toCountrySelect.trigger('change');

        // dates
        st.after.datepicker('setDate', defaults.after);
        st.before.datepicker('setDate', defaults.before);

        // nights
        st.allNights.children().remove();
        for( var i = defaults.nightsLimits[0]; i <= defaults.nightsLimits[1]; i++ ) st.nightsMin.append(selectableItem({ text:i, selected:(i == defaults.nightsMin) }));
        for( i = defaults.nightsLimits[0]; i <= defaults.nightsLimits[1]; i++ ) st.nightsMax.append(selectableItem({ text:i, selected:(i == defaults.nightsMax) }));

        // Child ages
        for (i = defaults.childAgeLimits[0]; i <= defaults.childAgeLimits[1]; i++) st.childAge1.append(selectableItem({
            text: i,
            selected: i == defaults.childAge1
        }));
        for (i = defaults.childAgeLimits[0]; i <= defaults.childAgeLimits[1]; i++) st.childAge2.append(selectableItem({
            text: i,
            selected: i == defaults.childAge2
        }));
        for (i = defaults.childAgeLimits[0]; i <= defaults.childAgeLimits[1]; i++) st.childAge3.append(selectableItem({
            text: i,
            selected: i == defaults.childAge3
        }));
        
        // Child birthdays
        if (defaults.birthday1) { st.birthday1.datepicker('setDate', defaults.birthday1); }
        if (defaults.birthday2) { st.birthday2.datepicker('setDate', defaults.birthday2); }
        if (defaults.birthday3) { st.birthday3.datepicker('setDate', defaults.birthday3); }
        
        // price
        st.priceMin.val(defaults.priceMin != null ? defaults.priceMin : '');
        st.priceMax.val(defaults.priceMax != null ? defaults.priceMax : '');

        // currencies
        st.currencySelect.children().remove();
        $.each(object1_data.currencies, function(idx, currency) {
            st.currencySelect.append(selectableItem({
                text:currency.name, value:currency.currencyId,
                selected:(currency.currencyId == defaults.currency)
            }));
        });

        // misc options
        st.allOptionCheckboxes.removeAttr('checked');
        if( defaults.hotelInStop ) st.hotelInStopCheckbox.attr('checked', 'checked');
        if( defaults.specialInStop ) st.specialInStopCheckbox.attr('checked', 'checked');
        if( defaults.noTicketsTo ) st.noTicketsToCheckbox.attr('checked', 'checked');
        if( defaults.noTicketsFrom ) st.noTicketsFromCheckbox.attr('checked', 'checked');
        if( defaults.Chipest ) st.OptionChipest.attr('checked', 'checked');

    }

    /* RESULT TABLE LAYOUT
        <tr>
            <td rowspan="2">0</td>
            <td rowspan="2">1,2,3</td>
            <td rowspan="2">4,5</td>
            <td rowspan="2">6,7,8,9</td>
            <td rowspan="2">10,11</td>
            <td rowspan="2">12</td>
            <td rowspan="2">13,14</td>
            <td rowspan="2">15</td>
            <td rowspan="2">16,17</td>
            <td rowspan="2">18</td>
            <td>19</td><td>20</td><td>21</td><td>22</td>
            <td>27</td><td>28</td><td>29</td><td>30</td>
        </tr>
        <tr>
            <td>23</td><td>24</td><td>25</td><td>26</td>
            <td>31</td><td>32</td><td>33</td><td>34</td>
        </tr>
     */
    function getWeekDay(dateStr)
    {
        var date = new Date(stringToDate(dateStr));
        var myDays = [$('#NewSearch_Locales .Sunday').html(),$('#NewSearch_Locales .Monday').html(),$('#NewSearch_Locales .Tuesday').html(),$('#NewSearch_Locales .Wednesday').html(),$('#NewSearch_Locales .Thursday').html(),$('#NewSearch_Locales .Friday').html(),$('#NewSearch_Locales .Saturday').html(),$('#NewSearch_Locales .Sunday').html()];
        return myDays[date.getDay()];
    }
    function getDateTo(dateStr, days)
    {
        var date = new Date(stringToDate(dateStr));
        return dateToString(new Date(date.setDate(date.getDate() + days)));
    }
    function renderResults(scrlTo) {

        var info = '';
        var t;
        var translatebull = {
            "Many":"<span class='bullet-many'>&bull;</span>",
            "Few":"<span class='bullet-many'>&bull;</span>",
            "No":"<span class='bullet-no'>&bull;</span>"
        };

        $('#specInfo').html(result_secret[0][0]+': '+result_secret[0][1]+', '+result_secret[1][0]+': '+result_secret[1][1]);
        var tototo;
        if (result_data.length == 0)
        {
            $('#NoResultMessage').css('display', '');
            $('#st-result-table').css('display', 'none');
            $('#st-result-legend').css('display', 'none');
        }
        else
        {
            $('#NoResultMessage').css('display', 'none');
            $('#st-result-table').css('display', '');
            $('#st-result-legend').css('display', '');
        }
        var ResultsHtml = '';
        var tempRowCounter = 0;
        var myRowCounter = 0;
        var rowClass = 'st-odd';
        $.each(result_data, function(idx, d) {
        	tempRowCounter++;
        	rowCounter++;
            if (object1_data.cities[st.fromCitySelect.val()]['cityId'] == 4800)
            {}
            else if (checkInfotoursHotel(d[7]))
            	myRowCounter++;
        	var backgroundClass = "";
        	if ((d[12] == 1) || (d[12] == 5) || (d[12] == 3) || (d[12] == 7))
        	{
        		backgroundClass = ' green';
        	}
            var row = $('<tr class="st-result-row'+backgroundClass+'"></tr>');
            row.append('<td nowrap="nowrap" class="c '+rowClass+'">'+(object1_data.cities[st.fromCitySelect.val()]['cityId'] == 4800 ? rowCounter : myRowCounter)+'</td>');
            row.append('<td nowrap="nowrap" class="c '+rowClass+'"><input type="hidden" class="sortValue" value="'+dateToString(stringToDate(d[1]))+'" />'+dateToString(stringToDate(d[1]))+'<br/><small>'+getWeekDay(d[1])+'<br/>'+getFlightDate(d[3])+'</small></td>');
            row.append('<td nowrap="nowrap" class="c '+rowClass+'"><input type="hidden" class="sortValue" value="'+d[4]+'" />'+d[4]+'<br/><small>'+$('#NewSearch_Locales .DurationTo').html()+' '+getDateTo(d[1], d[4])+'<small></td>');
            var hotelLinkStyle = '';
            if ($('#tourType').val() != 1)
            {
            	hotelLinkStyle = ' style="color: #00A651;"';
            }
            if(selectedCity.cityId == 4800)
            	var n = '<a target=_blank href="http://www.teztour.lt/?lang=LTH&new_desc=T&page=Pages/HotelDescriptions/'+d[10][2]+'&hotel='+d[7]+'&region='+d[10][2]+'"'+hotelLinkStyle+'>'+d[6]+'</a>';
            else if (selectedCity.cityId == 523)
            	var n = '<a target=_blank href="http://www.teztour.lv/?controller=hotel_out&tezid='+d[7]+'&l=1"'+hotelLinkStyle+'>'+d[6]+'</a>';
            else if (selectedCity.cityId == 3746)
            	var n = '<a target=_blank href="http://www.teztour.lv/?controller=hotel_out&tezid='+d[7]+'&l=3"'+hotelLinkStyle+'>'+d[6]+'</a>';
            else
            	var n = '<a target=_blank href="http://www.teztour.com/book/vc/site_c/s/catalog?hotel='+d[7]+'"'+hotelLinkStyle+'>'+d[6]+'</a>';
            var Icon = '<td class="none Rezults_HotelRow'+d[7]+'" style="text-align: right; width: 0px;"></td>';
            var InfoIcon = '';
            var InfoIconWidth = 0;
            try
            {
	            if (ActiveObjects.HotelSegments[d[7]].length > 0)
	            {
	            	InfoIconWidth = 16;
	            	var segments = '';
	            	$.each(ActiveObjects.HotelSegments[d[7]], function(key, value){
	            		segments = segments + '<tr class="none"><td class="none" style="padding: 2px;"><img style="width: 25px; height: 25px;" src="http://teztour.lt/static/images/segments/'+value+'.jpg" border="0" alt="" /></td><td style="padding: 2px;" class="none"> - '+$('#NewSearch_Locales .Segment'+value).html()+'&nbsp;&nbsp;&nbsp;</td></tr>';
	            	});
	            	segments = '<table style="margin-bottom: 0px; margin-top: 7px;">'+segments +'</table>'; 
	            	InfoIcon = '<img class="SegmentsInfoButton" src="http://teztour.lt/static/images/INFO.jpg" id="SegmentsInfoButton'+d[9][0][1]+'" border="0" alt="" />' + '<div style="display: none;" id="SegmentsInfo'+d[9][0][1]+'"><div style="white-space:nowrap; padding-right: 3px;">'+segments+'</div></div>';
	            }
            }
            catch(e)
            {}
            if (d[12] == 5) Icon = '<td class="none Rezults_HotelRow'+d[7]+'" style="text-align: right; width: '+(32+InfoIconWidth)+'px;"><img src="/static/ts-lt/ICON_4.PNG" class="RecomendedHotel'+d[7]+'" title="'+$('#NewSearch_Locales .TezRecommends').html()+'"/><img src="/static/ts-lt/ICON_1.PNG" title="'+$('#NewSearch_Locales .InstantConfirmation').html()+'"/>'+InfoIcon+'</td>';
            else if (d[12] == 3) Icon = '<td class="none Rezults_HotelRow'+d[7]+'" style="text-align: right; width: '+(32+InfoIconWidth)+'px;"><img src="/static/ts-lt/ICON_2.PNG" title="I&scaron;ankstiniai pirkimai"/><img src="/static/ts-lt/ICON_1.PNG" title="'+$('#NewSearch_Locales .InstantConfirmation').html()+'"/>'+InfoIcon+'</td>';
            else if (d[12] == 6) Icon = '<td class="none Rezults_HotelRow'+d[7]+'" style="text-align: right; width: '+(32+InfoIconWidth)+'px;"><img src="/static/ts-lt/ICON_4.PNG" class="RecomendedHotel'+d[7]+'" title="'+$('#NewSearch_Locales .TezRecommends').html()+'"/><img src="/static/ts-lt/ICON_2.PNG" title="'+$('#NewSearch_Locales .EarlyBooking').html()+'"/>'+InfoIcon+'</td>';
            else if (d[12] == 7) Icon = '<td class="none Rezults_HotelRow'+d[7]+'" style="text-align: right; width: '+(50+InfoIconWidth)+'px;"><img src="/static/ts-lt/ICON_4.PNG" class="RecomendedHotel'+d[7]+'" title="'+$('#NewSearch_Locales .TezRecommends').html()+'"/><img src="/static/ts-lt/ICON_2.PNG" title="'+$('#NewSearch_Locales .EarlyBooking').html()+'"/><img src="/static/ts-lt/ICON_1.PNG" title="'+$('#NewSearch_Locales .InstantConfirmation').html()+'"/>'+InfoIcon+'</td>';
            else if (d[12] == 1) Icon = '<td class="none Rezults_HotelRow'+d[7]+'" style="text-align: right; width: '+(16+InfoIconWidth)+'px;"><img src="/static/ts-lt/ICON_1.PNG" title="'+$('#NewSearch_Locales .InstantConfirmation').html()+'"/>'+InfoIcon+'</td>';
            else if (d[12] == 2) Icon = '<td class="none Rezults_HotelRow'+d[7]+'" style="text-align: right; width: '+(16+InfoIconWidth)+'px;"><img src="/static/ts-lt/ICON_2.PNG" title="'+$('#NewSearch_Locales .EarlyBooking').html()+'"/>'+InfoIcon+'</td>';
            else if (d[12] == 4) Icon = '<td class="none Rezults_HotelRow'+d[7]+'" style="text-align: right; width: '+(16+InfoIconWidth)+'px;"><img src="/static/ts-lt/ICON_4.PNG" class="RecomendedHotel'+d[7]+'" title="'+$('#NewSearch_Locales .TezRecommends').html()+'"/>'+InfoIcon+'</td>';
            else Icon = '<td class="none Rezults_HotelRow'+d[7]+'" style="text-align: right; width: '+(InfoIconWidth)+'px;">'+InfoIcon+'</td>';
            var h = $('<td class="'+rowClass+'"><input type="hidden" class="sortValue" value="'+parseHotelCategory(d[6])+'" /><table style="width: 100%; margin-bottom: 2px;"><tr class="none"><td class="none"><input type="hidden" class="Rezults_HotelId" value="'+d[7]+'" />'+n+'<br/><small class="RoomType">'+d[8]+'</small></td>'+Icon+'</table></td>');
            if( d[9].length > 1 || d[9][0][0] != '' ) {
                var cb = $('<select index="'+idx+'" style="width: 176px;"></select>');
                var tempArr2 = d[9];
                $.each(tempArr2, function(idxx, op) {
                	tempArr2[idxx][0][0] = op;
                	tempArr2[idxx][0][1] = idxx;
                });
                var tempArr = tempArr2.sort(function (keyA, keyB){
                	
                	if (keyA[0][0] < keyB[0][0]) return -1
                	
                	if (keyA[0][0] > keyB[0][0]) return 1
                	
                	return 0 
                });
                $.each(tempArr, function(idxx, op) {
                	//console.log(op);
                    cb.append('<option value="'+op[4]+'">'+op[0]+'</option>');
                });
                h.find('.RoomType').after(cb);
                h.find('.RoomType').after('<br />'+$('#NewSearch_Locales .ForChoose').html()+':<br />');
            }
            row.append(h);
            try
            {
	            if (ActiveObjects.HotelSegments[d[7]].length > 0)
	            {
	            	row.find('#SegmentsInfoButton'+d[9][0][1]).mopTip({'w':'calculate', 'h':'calculate', 'runThen': 'over', 'style':"overOut", 'get':"#SegmentsInfo"+d[9][0][1]});
	            }
            }
            catch(e)
            {}
            
/*
            row.append('<td rowspan="2">'+d[10]+'<br/>'+d[11]+'</td>');
            row.append('<td rowspan="2">'+(d[12] != '0' ? '<img src="ICON_'+d[12]+'.PNG"/>' : '')+'</td>');
            row.append('<td rowspan="2" title="'+d[14]+'">'+d[13]+'</td>');
            row.append('<td rowspan="2">'+d[15]+'</td>');
            row.append('<td rowspan="2"><a price="price" index="'+idx+'" href="'+d[9][0][1]+'">'+d[16]+'</a><br/><a specialPrice="specialPrice" index="'+idx+'" href="'+d[9][0][2]+'">'+d[17]+'</a></td>');
            row.append('<td rowspan="2">'+d[18]+'</td>');    
*/
            row.append('<td class="c '+rowClass+'">' + d[10][3] + "</td>");
            row.append('<td class="c '+rowClass+'">' + d[13] + "</td>");
            
            var PriceSplited = d[16].split(' ');
            var roomType = d[8];
            var CartData = [
                            dateToString(stringToDate(d[1])),
                            d[4],
                            d[10][0],
                            d[10][2],
                            d[7],
                            d[6],
                            d[10][3],
                            roomType.replace(/\"/gi, ''),
                            d[13],
                            parseAccommodationForCart(d[15]),
                            parseAccommodationForCartAges(d[15]),
                            d[9][0][1],
                            PriceSplited[1],
                            PriceSplited[0],
                            d[9][0][2],
                            d[9][0][3],
                            d[17],
                            st.fromCitySelect.find('option:selected').text()
                            ];
            row.append('<td class="c '+rowClass+'">' + parseAccommodation(d[15]) + '<input id="TourSearchCart'+d[9][0][1]+'" type="hidden" value="'+CartData.join(';')+'" /></td>');
            var spoType = 'SPO';
            if (d[36] == 112201)
            	spoType = 'Standard';
            if (d[36] == 112203)
            	spoType = 'Last minute';
            if (parent.Authorized && (d[19] != 'No') && (d[27] != 'No') && (d[18] == 'exist'))
            {
            	choosedHotelResource = '';
            	if (d[9][0].length > 4)
            	{
            		choosedHotelResource = d[9][0][4];
            	}
            	if($('#tourType').val() == 2)
                	row.append('<td nowrap="nowrap" class="c '+rowClass+'"><h5><a price="price" index="' + idx + '" href="http://'+parent.location.host+'/book/actions/rFiller.sdo?template='+site_lv+'&action=createFromSD&page=newRes-lt&view=avia&TempNext=T&urId=0&spoContainerDateId=' + d[9][0][1] + '&choosedHotelResource='+ choosedHotelResource +'" target=_blank'+hotelLinkStyle+'>' + d[16] + '</a> <img title="'+$('#NewSearch_Locales .AddToMyOffers').html()+'" src="/static/ts-lt/cart_put.png" onclick="parent.submitTourSearchCartNew(' + d[9][0][1] + ', \''+choosedHotelResource+'\')" style="cursor: pointer;" /></h5><small><a specialPrice="specialPrice" index="' + idx + '" href="http://'+parent.location.host+'/book/vc/site_lt/spo_lt?spoId=' + d[9][0][2] + '&hotelRoomId=' + d[9][0][3] + '#hotelContent' + d[9][0][3] + '" target=_blank>' + prepareSpoNumber(d[17], spoType) + '</a></small></td>');
            	else
            		row.append('<td nowrap="nowrap" class="c '+rowClass+'"><h5><a price="price" index="' + idx + '" href="http://'+parent.location.host+'/book/actions/rFiller.sdo?template='+site_lv+'&action=createFromSD&page=newRes-lt&view=preview&TempNext=T&urId=0&spoContainerDateId=' + d[9][0][1] + '&choosedHotelResource='+ choosedHotelResource +'" target=_blank'+hotelLinkStyle+'>' + d[16] + '</a> <img title="'+$('#NewSearch_Locales .AddToMyOffers').html()+'" src="/static/ts-lt/cart_put.png" onclick="parent.submitTourSearchCartNew(' + d[9][0][1] + ', \''+choosedHotelResource+'\')" style="cursor: pointer;" /></h5><small><a specialPrice="specialPrice" index="' + idx + '" href="http://'+parent.location.host+'/book/vc/site_lt/spo_lt?spoId=' + d[9][0][2] + '&hotelRoomId=' + d[9][0][3] + '#hotelContent' + d[9][0][3] + '" target=_blank>' + prepareSpoNumber(d[17], spoType) + '</a></small></td>');
            }
            else if (parent.Authorized && $('#tourType').val() != 1)
            {
            	choosedHotelResource = '';
            	if (d[9][0].length > 4)
            	{
            		choosedHotelResource = d[9][0][4];
            	}
            	if($('#tourType').val() == 2)
            		row.append('<td nowrap="nowrap" class="c '+rowClass+'"><h5><a price="price" index="' + idx + '" href="http://'+parent.location.host+'/book/actions/rFiller.sdo?template='+site_lv+'&action=createFromSD&page=newRes-lt&view=avia&TempNext=T&urId=0&spoContainerDateId=' + d[9][0][1] + '&choosedHotelResource='+ choosedHotelResource +'" target=_blank style="color: #00A651;">' + d[16] + '</a> <img title="'+$('#NewSearch_Locales .AddToMyOffers').html()+'" src="/static/ts-lt/cart_put.png" onclick="parent.submitTourSearchCartNew(' + d[9][0][1] + ', \''+choosedHotelResource+'\')" style="cursor: pointer;" /></h5><small><a specialPrice="specialPrice" index="' + idx + '" href="http://'+parent.location.host+'/book/vc/site_lt/spo_lt?spoId=' + d[9][0][2] + '&hotelRoomId=' + d[9][0][3] + '#hotelContent' + d[9][0][3] + '" target=_blank>' + prepareSpoNumber(d[17], spoType) + '</a></small></td>');
            	else
            		row.append('<td nowrap="nowrap" class="c '+rowClass+'"><h5><a price="price" index="' + idx + '" href="http://'+parent.location.host+'/book/actions/rFiller.sdo?template='+site_lv+'&action=createFromSD&page=newRes-lt&view=preview&TempNext=T&urId=0&spoContainerDateId=' + d[9][0][1] + '&choosedHotelResource='+ choosedHotelResource +'" target=_blank style="color: #00A651;">' + d[16] + '</a> <img title="'+$('#NewSearch_Locales .AddToMyOffers').html()+'" src="/static/ts-lt/cart_put.png" onclick="parent.submitTourSearchCartNew(' + d[9][0][1] + ', \''+choosedHotelResource+'\')" style="cursor: pointer;" /></h5><small><a specialPrice="specialPrice" index="' + idx + '" href="http://'+parent.location.host+'/book/vc/site_lt/spo_lt?spoId=' + d[9][0][2] + '&hotelRoomId=' + d[9][0][3] + '#hotelContent' + d[9][0][3] + '" target=_blank>' + prepareSpoNumber(d[17], spoType) + '</a></small></td>');
            	//row.append('<td nowrap="nowrap" class="c"><h5>' + d[16] + '</h5><small><a specialPrice="specialPrice" index="' + idx + '" href="http://'+parent.location.host+'/book/vc/site_lt/spo_lt?spoId=' + d[9][0][2] + '&hotelRoomId=' + d[9][0][3] + '#hotelContent' + d[9][0][3] + '" target=_blank>' + prepareSpoNumber(d[17], spoType) + '</a></small></td>');
            }
            else
            {
                row.append('<td nowrap="nowrap" class="c '+rowClass+'"><h5>' + d[16] + '</h5><small>' + prepareSpoNumber(d[17], spoType) + '</small></td>');
            }
            row.append('<td class="c '+rowClass+'">' + (d[18] == 'exist' ? '<span class="bullet-many">'+jQuery('#bullet-many').text()+'</span>' : '<span class="bullet-no">'+jQuery('#bullet-no').text()+'</span>') + "</td>");
            
            
            translatebull.hasOwnProperty(d[19]) ? t = translatebull[d[19]] : t = '<strong>'+d[19]+'</strong>';
            row.append('<td class="c '+rowClass+'">'+t+'<br/><small title="' + result_info[2][1] + '">' + d[23] + '</small></td>');
            
            translatebull.hasOwnProperty(d[27]) ? t = translatebull[d[27]] : t = '<strong>'+d[27]+'</strong>';
            row.append('<td class="c '+rowClass+'">'+t+'<br/><small title="' + result_info[2][1] + '">' + d[31] + '</small></td>');

            if (scrlTo && tempRowCounter == 1) {
            	if (pagerCounter == 1)
            	{
                    var fdiv=$('<div class="pager-el-normal">'+pagerCounter+'</div>');
                    st.paging.append(fdiv);
                    fdiv.bind('click', function () {$.scrollTo($('#ResultsHeader'), {offset: {left: 0, top:-40 }});});
            	}
            	pagerCounter++;
                tototo = $('<tr class="st-result-row"><td colspan="15"><div class="td-dotted-separator" style="font-weight: bold;">'+$('#NewSearch_Locales .PageNumber').html()+' '+ pagerCounter +'</div></td></tr>');
                st.resultTable.append(tototo);
                var pdiv=$('<div class="pager-el-normal">'+pagerCounter+'</div>');
                st.paging.append(pdiv);
                pdiv.bind('click', function () {$.scrollTo(tototo, {offset: {left: 0, top:-40 }});});
                tototo = row; 
            };
            if (object1_data.cities[st.fromCitySelect.val()]['cityId'] == 4800)
            	st.resultTable.append(row);
            else if (checkInfotoursHotel(d[7]))
            	st.resultTable.append(row);
        });
        info += '<span>'+$('#NewSearch_Locales .GeneratedTime').html()+'</span>: '+result_info[0][1]+' '+$('#NewSearch_Locales .GeneratedTimeSec').html();
        info += '<br><span>'+$('#NewSearch_Locales .ResultCount').html()+'</span>: '+rowCounter;
//        $.each(result_info, function(idx, i) {
//            if( idx > 0 ) info += '; ';
//            info += '<span>'+idx+i[0]+"</span>: "+i[1];
//        });
        st.resultInfo.html(info);
        if ( tototo )
        {
        	$.scrollTo(tototo, {offset: {left: 0, top:-40 }});
        }
        $('select', st.resultTable).change(function() {
            var t = $(this), idx = t.attr('index'), hotelIdx = t.val();
            
            myregexp = /choosedHotelResource=\d+/;
            myString=$('a[price=price][index='+idx+']', st.resultTable).attr('href');
            myString = myString.replace(myregexp, "choosedHotelResource=");
            $('a[price=price][index='+idx+']', st.resultTable).attr('href', myString+hotelIdx);
            $('a[specialPrice=specialPrice][index='+idx+']', st.resultTable).attr('href', result_data[idx][9][hotelIdx][2]);
        });
//        $('tr:not(.none):even:even td:not(.none)[rowspan=2], tr:not(.none):even:odd td:not(.none)[rowspan!=2], tr:not(.none):even:even td:not(.none)[rowspan!=2]', st.resultTable).addClass('st-even');
//        $('tr:not(.none):even:odd td:not(.none)[rowspan=2], tr:not(.none):odd:even td:not(.none)[rowspan!=2], tr:not(.none):odd:odd td:not(.none)[rowspan!=2]', st.resultTable).addClass('st-odd');
        if (rowClass == 'st-odd') rowClass = 'st-even';
        else rowClass = 'st-odd';
        $('.st-even .SegmentsInfoButton').attr('src', 'http://teztour.lt/static/images/INFO2.jpg');
        $('.green .SegmentsInfoButton').attr('src', 'http://teztour.lt/static/images/INFO1.jpg');
        parent.userRecomendedHotelsGetByIdsNew();
        parent.recomendedHotelsGetByIdsNew();
        if (result_info[1][1] != 0) resizeIframe();
        else
        {
            if (window.top !== window.self) {
                parent.document.getElementById('tsSimpleFrame').height = $("div#formcontainer").attr("clientHeight")+150+'px';
            }
        }
        
    }
    

    function setCurrency(getFromServerCurrency) {
        if ( st.currencySelect.val() != getFromServerCurrency && ! uriData.currency ) {
            st.currencySelect.val(getFromServerCurrency); st.currencySelect.change();
        }
        delete uriData.currency;
    }
    function resizeIframe () {
        if (window.top !== window.self) {
            parent.document.getElementById('tsSimpleFrame').height = $("div#formcontainer").attr("clientHeight")+70+'px';
            //alert(parent.document.getElementById('tsSimpleFrame').height+' - '+$("div#formcontainer").attr("clientHeight"));
        }
    }
    function loadAttention(np) { // Загружаем содержимое блока Внимание
    var attUrl = "/ssi/include/country_imp_info/" + np.countryId + "_" + np.cityId + ".js";
    $('#formcontainerOverlay').css('display', '');
    $('#formcontainerPreloader').css('display', '');
        $.ajax({ url: attUrl, dataType:"text", type: "GET",
            error: function () { 
            	//console.log(attUrl);
//                st.infoblockBody.hide();
//                st.infoblockTitle.hide();
            	st.infoblockTitle.show();
                $('#formcontainerOverlay').css('display', 'none');
                $('#formcontainerPreloader').css('display', 'none');
            },
            success: function(attText) { 
            if (attText != '') {
                st.infoblockTitle.show();
                // вырезаем оттуда яваскрипт
                attText = attText.replace('function dw(a) {document.write(a); }', '');
                attText = attText.replace(new RegExp('dw[\(]" ','g'), '');
                attText = attText.replace(new RegExp('"[\)];','g'), '');
                attText = attText.replace(new RegExp('."','g'), '"');
                attText = attText.replace(new RegExp("style='.+'",'g'), 'class="infoblock-content"');
                attText = attText.match(new RegExp('<div[\\s\\S]+div>','m'));
                //st.infoblockBody.html(attText[0]);
            } else {
        st.infoblockBody.hide();
            st.infoblockTitle.hide();
            }
            $('#formcontainerOverlay').css('display', 'none');
            $('#formcontainerPreloader').css('display', 'none');
        }}) 
    }
    function hypxl (link, str) {
        //return '=HYPERLINK("'+link+'";"'+str+'")';
        return '=hyperlink("'+link+'";"'+str+'")';
    }
    function objToExcel (o) {
    	var a, t="\t", res = $('#NewSearch_Locales .Excel_ArrivalToHotel').html()+t+$('#NewSearch_Locales .Excel_NaightCount').html()+t+$('#NewSearch_Locales .Excel_Region').html()+t+$('#NewSearch_Locales .Excel_Hotel').html()+t+$('#NewSearch_Locales .Excel_RoomType').html()+t+$('#NewSearch_Locales .Excel_Pansion').html()+t+$('#NewSearch_Locales .Excel_AccommodationType').html()+t+$('#NewSearch_Locales .Excel_Price').html()+t+$('#NewSearch_Locales .Excel_SPO').html()+"\n";
        for (var i = 0; i < o.length; i++) {
        a = o[i];
        res += a[1]+t+a[4]+t+a[10][3]+t+hypxl('http://www.teztour.lt/?lang=LTH&amp;new_desc=T&amp;page=Pages/HotelDescriptions/'+a[10][2]+'&amp;hotel='+a[7]+'&amp;region='+a[10][2],a[6])+t+a[8]+t+a[13]+t+a[15].match("^\\w+")[0]+t+hypxl('http://'+parent.location.host+'/book/actions/rFiller.sdo?template='+site_lv+'&action=createFromSD&page=newRes-lt&view=preview&TempNext=T&urId=0&spoContainerDateId=' + a[9][0][1],a[16])+t+hypxl('http://'+parent.location.host+'/book/vc/site_lt/spo_lt?spoId=' + a[9][0][2] + '&hotelRoomId=' + a[9][0][3] + '#hotelContent' + a[9][0][3],a[17])+"\n";
    }
    return res;
    }
    function appendResultToExcelBlock(){
        st.excelblocktextarea.append(objToExcel(result_data));
    }
    

});

function showWin() {
    $(".opinionWindowBgr").show();
    $(".opinionWindow").show();
    window.location.hash = "";
}

function hideWin() {
    $(".opinionWindow").hide();
    $(".opinionWindowBgr").hide();
}

function appendComment() {
    //alert($('form').serialize());
    var commentForm = $("#st-comment form");
    var commentTextArea = $("#st-comment textarea");
    if (commentTextArea.val() != '') {
        $.ajax({
            type: "POST",
            url: "/cgi-bin/addcomment.cgi",
            data: commentForm.serialize(),
            dataType: "text",
            error: function () {
                $("#st-comment").html("error");
            },
            success: function (d) {
                commentTextArea.val('');
                hideWin();
            }
        });
    } else {
        hideWin();
    }
}

