﻿//Client tour search
(function ($)
{
    var methods = {
        init: function (options)
        {
            //settings - default options for this plugin
            var settings = {
                //Path to toursearch page
                TourSearchPath: '/TourSearchResults/',
                //Calendar mode enabled
                CalendarMode: false,
                //Calendar mode query name
                QueryCalendarMode: 'tscalmode',
                //Query parameters names
                QueryDepartureCity: 'townid',
                QueryDepartureDateFrom: 'datefrom',
                QueryDepartureDateTo: 'dateto',
                QueryCalendarMonth: 'calendarmonth',
                QueryDestination: 'destinationid',
                QueryHotelCategory: 'rating',
                QueryHotel: 'hotelid',
                QueryMealType: 'mealstype',
                QueryNightCountFrom: 'nightcountfrom',
                QueryNightCountTo: 'nightcountto',
                QueryPriceRangeFrom: 'sumfrom',
                QueryPriceRangeTo: 'sumto',
                QueryTourType: 'tourtypeid',
                QueryAdultCount: 'adultcount',
                QueryKidAges: 'children'
            };

            //options
            if (options)
            {
                jQuery.extend(settings, options);
            }

            // plugin code here

            var $this = jQuery(this);
            var data = $this.data('ClientTourSearch');

            // If the plugin hasn't been initialized yet
            if (!data)
            {

                // If options exist, lets merge them
                // with our default settings
                if (options)
                {
                    jQuery.extend(settings, options);
                }

                //Working class declaration
                function ClientTourSearch(options)
                {
                    //Reference to JS object
                    var that = this;
                    //Reference to DOM container
                    var $this = options.$this;

                    var CollapseExtendedParameters = function ()
                    {
                        var $accordion = $this.find('.PickersAccordion');
                        var $extended = $accordion.find('.Extended:visible');
                        $accordion
                            .css('height', $accordion.height())
                            .css('overflow', 'hidden');
                        var newHeight = 0;
                        $extended.each(function ()
                        {
                            newHeight += jQuery(this).outerHeight();
                        });
                        $accordion.animate(
                            {
                                height: '-=' + newHeight
                            },
                            {
                                complete: function ()
                                {
                                    $extended.hide();
                                    $accordion
                                        .css('height', 'auto')
                                        .css('overflow', 'visible');
                                }
                            }
                        );
                        if ($accordion.find('.Extended.PaneHead.ui-state-active').length > 0)
                        {
                            $this.find('.PickersAccordion').accordion('activate', false);
                        }
                    }

                    var ExpandExtendedParameters = function ()
                    {
                        var $accordion = $this.find('.PickersAccordion');
                        var height = $accordion.height();
                        $accordion
                            .css('height', height)
                            .css('overflow', 'hidden');
                        var $extended = $accordion.find('.PaneHead.Extended');
                        $extended.show();
                        var newHeight = 0;
                        $extended.each(function ()
                        {
                            newHeight += jQuery(this).outerHeight();
                        });
                        $accordion.animate(
                            {
                                height: '+=' + newHeight
                            },
                            {
                                complete: function ()
                                {
                                    $accordion
                                        .css('height', 'auto')
                                        .css('overflow', 'visible');
                                }
                            }
                        );
                    }

                    //Toggles extended tour search parameters on/off depending of visible parameter
                    this.ToggleExtendedParameters = function (expand)
                    {
                        if (expand)
                        {
                            ExpandExtendedParameters();
                        }
                        else
                        {
                            CollapseExtendedParameters();
                        }
                    }

                    //Returns tour search url
                    this.GenerateSearchLink = function (addPath)
                    {
                        var searchLink = '';
                        //supposed, that each control in ".PaneBody" container
                        //has hidden field with class ".UrlValue" that contains url parameter
                        //for adding to tour search url
                        $this.find('.PaneBody .ControlContainer').each(function ()
                        {
                            var $paneBody = jQuery(this);
                            var urlValue = $paneBody.find('.UrlValue').val();
                            if (urlValue.length > 0)
                            {
                                if (searchLink.length > 0)
                                {
                                    searchLink += '&';
                                }
                                searchLink += urlValue;
                            }
                        });
                        if (addPath)
                        {
                            if (options.TourSearchPath.indexOf('?') == -1)
                            {
                                searchLink = '?' + searchLink;
                            }
                            return options.TourSearchPath + searchLink;
                        }
                        else
                        {
                            return searchLink;
                        }
                    }

                    var CheckHotelPaneVisibility = function ()
                    {
                        //Show hotels pane only if any destination selected
                        if ($this.find('.PaneBody > .ControlContainer.Destination').find('.UrlValue').val() === '')
                        {
                            $this.find('.PaneHead.Hotel').addClass('Hidden');
                            $this.find('.PaneBody.Hotel').addClass('Hidden');
                        }
                        else
                        {
                            $this.find('.PaneHead.Hotel').removeClass('Hidden');
                            $this.find('.PaneBody.Hotel').removeClass('Hidden');
                        }
                    }

                    var ClearExtendedParameters = function ()
                    {
                        $this.find('.PaneBody > .ControlContainer.MealType').find('.UrlValue').val('');
                        $this.find('.PaneBody > .ControlContainer.PriceRange').find('.UrlValue').val('');
                        $this.find('.PaneBody > .ControlContainer.TourType').find('.UrlValue').val('');
                        $this.find('.PaneBody > .ControlContainer.Hotel').find('.UrlValue').val('');
                        $this.find('.PaneBody > .ControlContainer.MealType').CTSMealTypePicker().Initialize(settings);
                        $this.find('.PaneBody > .ControlContainer.PriceRange').CTSPriceRangePicker().Initialize(settings);
                        $this.find('.PaneBody > .ControlContainer.TourType').CTSTourTypePicker().Reset();
                        $this.find('.PaneBody > .ControlContainer.Hotel').CTSHotelPicker().Reset();
                    }

                    var HasExtendedParameters = function ()
                    {
                        var has = false;
                        if ($this.find('.PaneBody > .ControlContainer.MealType').find('.UrlValue').val().length > 0 ||
                                $this.find('.PaneBody > .ControlContainer.PriceRange').find('.UrlValue').val().length > 0 ||
                                $this.find('.PaneBody > .ControlContainer.TourType').find('.UrlValue').val().length > 0 ||
                                $this.find('.PaneBody > .ControlContainer.Hotel').find('.UrlValue').val().length > 0)
                        {
                            has = true;
                        }
                        return has;
                    }

                    var Setup = function ()
                    {
                        CheckHotelPaneVisibility();
                        $this.find('input[id$="SearchLink"]').attr('href', that.GenerateSearchLink(false));
                        $this.find('.SearchButton').attr('href', that.GenerateSearchLink(true));
                    }

                    var InitializeNormal = function ()
                    {
                        $this.find('.ToggleExtendedParameters .Expand').click(function ()
                        {
                            $this.find('.ToggleExtendedParameters .Expand').hide();
                            $this.find('.ToggleExtendedParameters .Collapse').show();
                            that.ToggleExtendedParameters(true);
                        });

                        $this.find('.ToggleExtendedParameters .Collapse').click(function ()
                        {
                            $this.find('.ToggleExtendedParameters .Expand').show();
                            $this.find('.ToggleExtendedParameters .Collapse').hide();
                            ClearExtendedParameters();
                            that.ToggleExtendedParameters(false);
                        });

                        if (HasExtendedParameters())
                        {
                            ExpandExtendedParameters();
                            $this.find('.ToggleExtendedParameters .Expand').hide();
                            $this.find('.ToggleExtendedParameters .Collapse').show();
                        }
                    }

                    var InitializeCalendar = function ()
                    {
                        //ExpandExtendedParameters();
                        $this.find('.Extended.PaneHead').show();

                        //Hide extended parameters triggers
                        $this.find('.ToggleExtendedParameters').hide();

                        //Hide unneeded panels
                        //$this.find('.PaneHead.DepartureCity').hide();
                        //$this.find('.PaneHead.Destination').hide();
                        $this.find('.PaneHead.DepartureDate').hide();
                        //$this.find('.PaneHead.NightCount').hide();
                        //$this.find('.PaneHead.Traveller').hide();
                        //$this.find('.PaneHead.HotelCategory').hide();
                        //$this.find('.PaneHead.MealType').hide();
                        $this.find('.PaneHead.PriceRange').hide();
                        $this.find('.PaneHead.TourType').hide();
                        $this.find('.PaneHead.Hotel').hide();
                    }

                    //Control initialization
                    this.Initialize = function ()
                    {
                        //Initialize accordion - jQuery.UI Accordion
                        $this.find('.PickersAccordion').accordion({
                            collapsible: true,
                            active: false,
                            autoHeight: false
                        });

                        $this.find('.ControlContainer').show();

                        $this.find('.PaneBody > .ControlContainer.DepartureCity').CTSDepartureCityPicker().Initialize(settings);
                        $this.find('.PaneBody > .ControlContainer.Destination').CTSDestinationPicker().Initialize(settings);
                        $this.find('.PaneBody > .ControlContainer.DepartureDate').CTSDepartureDatePicker().Initialize(settings);
                        $this.find('.PaneBody > .ControlContainer.NightCount').CTSNightCountPicker().Initialize(settings);
                        $this.find('.PaneBody > .ControlContainer.Traveller').CTSTravellerPicker().Initialize(settings);
                        $this.find('.PaneBody > .ControlContainer.HotelCategory').CTSHotelCategoryPicker().Initialize(settings);
                        $this.find('.PaneBody > .ControlContainer.MealType').CTSMealTypePicker().Initialize(settings);
                        $this.find('.PaneBody > .ControlContainer.PriceRange').CTSPriceRangePicker().Initialize(settings);
                        $this.find('.PaneBody > .ControlContainer.TourType').CTSTourTypePicker().Initialize(settings);
                        $this.find('.PaneHead.TourType').click(function ()
                        {
                            if (jQuery(this).hasClass('ui-state-active'))
                            {
                                $this.find('.PaneBody > .ControlContainer.TourType').CTSTourTypePicker().LoadTourTypes();
                            }
                        });
                        $this.find('.PaneBody > .ControlContainer.Hotel').CTSHotelPicker().Initialize(settings);
                        $this.find('.PaneHead.Hotel').click(function ()
                        {
                            if (jQuery(this).hasClass('ui-state-active'))
                            {
                                $this.find('.PaneBody > .ControlContainer.Hotel').CTSHotelPicker().LoadHotels();
                            }
                        });

                        if (settings.CalendarMode)
                        {
                            InitializeCalendar();
                        }
                        else
                        {
                            InitializeNormal();
                        }

                        $this.children('.PickersAccordion').show();
                        $this.children('.Actions').show();
                        $this.find('.SearchButton').show();

                        $this.find('.UrlValue').change(function ()
                        {
                            Setup();
                        });

                        Setup();
                    };
                }

                //Add $this parameter to settings to provide easy way to get link to DOM
                settings.$this = jQuery(this);
                data = new ClientTourSearch(settings);
            }
            $(this).data('ClientTourSearch', data);
            return data;
        }
    };

    $.fn.ClientTourSearch = function (method)
    {

        // Method calling logic
        if (methods[method])
        {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method)
        {
            return methods.init.apply(this, arguments);
        } else
        {
            jQuery.error('Method ' + method + ' does not exist on jQuery.ClientTourSearch');
        }

    };

})(jQuery);

//Departure city picker
(function ($) {

    var methods = {
        init: function (options) {
            var settings = {
            };

            // plugin code here

            var $this = jQuery(this);
            var data = $this.data('CTSDepartureCityPicker');

            // If the plugin hasn't been initialized yet
            if (!data) {

                // If options exist, lets merge them
                // with our default settings
                if (options) {
                    jQuery.extend(settings, options);
                }

                //Working class declaration
                function CTSDepartureCityPicker(options) {
                    //Reference to JS object
                    var that = this;
                    //Reference to DOM container
                    var $this = options.$this;

                    //Control initialization
                    this.Initialize = function (options) 
                    {
                        var $container = $this.parents('.PaneBody').parent();
                        //Title                        
                        var $paneHead = $this.parents('.PickersAccordion:first').find('.PaneHead.DepartureCity');
                            
                        //Find controls
                        var $items = $this.find('.Items');
                        var $doNotNeedTicket = $this.find('input[id$="DoNotNeedTicket"]');
                        var $anyCity = $this.find('input[id$="AnyCity"]');
                        var $urlValue = $this.find('.UrlValue');

                        var urlParam = options.QueryDepartureCity ? options.QueryDepartureCity + '=' : 'townid=';

                        //Utilities
                        function GetCityCount() 
                        {
                            return $items.find('input[type="checkbox"]').length;
                        };

                        function GetCheckedCount() 
                        {
                            var res = 0;
                            $items.find('input[type="checkbox"]').each( function() 
                            {
                                if (jQuery(this).prop('checked') == true)
                                {
                                    res++;
                                }
                            });
                            return res;
                        };

                        function SetupPaneText()
                        {                            
                            var newValue = "";
                            if (GetCityCount() == GetCheckedCount()) 
                            { //Any city
                                newValue = "Любой город";
                            }
                            else if (GetCheckedCount() == 0) 
                            { //Don't need any ticket
                                newValue = "Билет не нужен";
                            }
                            else 
                            { //Any city/cities
                                $items.find('input[type="checkbox"]').each( function() 
                                {
                                    var $checkbox = jQuery(this);
                                    if ($checkbox.prop('checked') == true) 
                                    {
                                        if (newValue.length > 0) 
                                        {
                                            newValue += ', ';
                                        }
                                        newValue += $checkbox.parent().find('label').html();
                                    }
                                });
                            }
                            $paneHead.find('.Text').html(newValue);
                        }

                        function SetupUrlValue()
                        {
                            var newValue = "";
                            if (GetCheckedCount() == 0) { //Don't need any ticket
                                newValue = urlParam + "-1";
                            }
                            else 
                            { //Any/all cities
                                $items.find('input[type="checkbox"]').each( function() 
                                {
                                    var $checkbox = jQuery(this);
                                    if ($checkbox.prop('checked') == true) 
                                    {
                                        if (newValue.length > 0) 
                                        {
                                            newValue += ',';
                                        }
                                        else
                                        {
                                            newValue += urlParam;
                                        }
                                        var $hiddenField = $checkbox.parent().find('input[id$="CityID"]');
                                        newValue += $hiddenField.val();
                                    }
                                });
                            }
                            $urlValue.val(newValue);
                            $urlValue.change();
                        }

                        function SetupAll()
                        {
                            SetupCheckboxes();
                            SetupUrlValue();
                            SetupPaneText();
                        }

                        //Setup checkboxes checked states
                        function SetupCheckboxes() 
                        {
                            //Event occured
                            if (GetCityCount() == GetCheckedCount()) 
                            { //Any city
                                $doNotNeedTicket.prop('checked', false);
                                //$anyCity.prop('checked', true);
                            }
                            else if (GetCheckedCount() == 0) 
                            { //Don't need any ticket
                                $doNotNeedTicket.prop('checked', true);;
                                $anyCity.prop('checked', false);
                            }
                            else 
                            { //Any city/cities
                                $doNotNeedTicket.prop('checked', false);
                                $anyCity.prop('checked', false);
                            }
                        }

                        //Controls initialization

                        //Parse UrlValue
                        var urlValue = jQuery.trim($urlValue.val().replace(urlParam,''));
                        if (urlValue.length > 0)
                        {
                            $items.find('input[type="checkbox"]').prop('checked', false);
                            var ids = urlValue.split(',');
                            if (ids.length > 0)
                            {
                                var noAviaFound = false;
                                for (var i = 0; i < ids.length; i++) {
                                    if (ids[i] == -1)
                                    {
                                        noAviaFound = true;
                                    }    
                                }
                                if (noAviaFound)
                                {
                                    $doNotNeedTicket.prop('checked', true);
                                }
                                else
                                {
                                    var $inputs = $items.find('input[type="hidden"]');
                                    for (var k = 0; k < ids.length; k++) {
                                        for (var j = 0; j < $inputs.length; j++) {
                                            var $item = jQuery($inputs[j]);
                                            if ($item.val() == ids[k])
                                            {
                                                $item.parent().find('input[type="checkbox"]').prop('checked', true);
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                $items.find('input[type="checkbox"]:first').prop('checked', true);
                            }
                        }
                        else
                        {
                            $items.find('input[type="checkbox"]:first').prop('checked', true);
                        }

                        //Don't need any ticket
                        if ($doNotNeedTicket.prop('checked') == true) {
                            $anyCity.prop('checked', false);
                            $items.find('input[type="checkbox"]').each( function() {
                                jQuery(this).prop('checked', false);
                            });
                        }
                        //Any city
                        if ($anyCity.prop('checked') == 'checked') {
                            $doNotNeedTicket.prop('checked', false);
                            $items.find('input[type="checkbox"]').each( function() {
                                jQuery(this).prop('checked', true);
                            });
                        }

                        //User actions

                        //Unvind all old events
                        $items.unbind();
                        $doNotNeedTicket.unbind();
                        $anyCity.unbind();
                        //Bind events
                        $items.find('input[type="checkbox"]').change( function() 
                        {
                            SetupAll();
                        });
                        $doNotNeedTicket.change( function() 
                        {
                            $anyCity.prop('checked', false);
                            $items.find('input[type="checkbox"]').each( function() 
                            {
                                jQuery(this).prop('checked', false);
                            });
                            SetupAll();
                        });
                        $anyCity.change( function() 
                        {
                            $doNotNeedTicket.prop('checked', false);
                            $items.find('input[type="checkbox"]').each( function() 
                            {
                                jQuery(this).prop('checked', true);
                            });
                            SetupAll();
                        });

                        SetupAll();
                    };
                }

                //Add $this parameter to settings to provide easy way to get link to DOM
                settings.$this = jQuery(this);
                data = new CTSDepartureCityPicker(settings);
            }
            $(this).data('CTSDepartureCityPicker', data);
            return data;
        }
    };

    $.fn.CTSDepartureCityPicker = function (method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            jQuery.error('Method ' + method + ' does not exist on jQuery.CTSDepartureCityPicker');
        }

    };

})(jQuery);

//Destination Picker
(function ($) {

    var methods = {
        init: function (options) {
            var settings = {
            };

			// plugin code here

			var $this = jQuery(this);
			var data = $this.data('CTSDestinationPicker');

			// If the plugin hasn't been initialized yet
			if (!data) {

				// If options exist, lets merge them
				// with our default settings
				if (options) {
					jQuery.extend(settings, options);
				}

				//Working class declaration
				function CTSDestinationPicker(options) {
					//Reference to JS object
					var that = this;
					//Reference to DOM container
					var $this = options.$this;
					
					//Control initialization
					this.Initialize = function (initSettings) {
						
                        //Find controls
                        var $items = $this.find('.Items > .DestinationsTree');
                        var $anyDestination = $this.find('input[id$="AnyDestination"]');
                        var $urlValue = $this.find('.UrlValue');
                        var urlParam = options.QueryDestination ? options.QueryDestination + '=' : 'destinationid=';
                        var defaultTitle = 'Любая страна, курорт';
                        var $paneTitle = $this.parents('.PickersAccordion:first').find('.PaneHead.Destination > .Text');

                        var singleCountryMode = $anyDestination.length == 0;

                        //Utilities

                        function GetNodeTitle($checkbox)
                        {
                            if ($checkbox.prop('checked'))
                            {
                                return $checkbox.next().html();
                            }
                            else
                            {
                                var $nextDiv = $checkbox.parents('table:first').next();
                                if ($nextDiv.length > 0 && $nextDiv[0].tagName === 'DIV')
                                {
                                    var $children = $nextDiv.find('input');
                                    if ($children.length > 0)
                                    {
                                        $children = $nextDiv.children('table').find('input');
                                        var result = [];
                                        $children.each(function() 
                                        {
                                            var title = GetNodeTitle(jQuery(this));
                                            if (title.length > 0)
                                            {
                                                result[result.length] = title;
                                            }
                                        });
                                        var resultStr = result.join(', ');
                                        return resultStr;
                                    }
                                    else
                                    {
                                        return '';
                                    }
                                }
                                else
                                {
                                    return '';
                                }
                            }
                        }

                        function SetupTitle()
                        {
                            var newValue = "";
                            
                            if (!$anyDestination.prop('checked'))
                            {
                                var $topItems = $items.children('table').find('input[type="checkbox"]');

                                $topItems.each( function() {
                                    var $item = jQuery(this);
                                    var tmp = GetNodeTitle($item);
                                    if (tmp.length > 0)
                                    {
                                        if (newValue.length > 0)
                                        {
                                            newValue += ', ';
                                        }
                                    
                                        newValue += tmp;
                                    }
                                });
                            }
                            else
                            {
                                newValue = defaultTitle;
                            }

                            $paneTitle.html(newValue);
                        }

                        function SetupUrlValue()
                        {
                            var newValue = "";
                            
                            if (!$anyDestination.prop('checked'))
                            {
                                //var $selectedItems = $items.find('input:checked');
                                
                                function GetRootSelectedElements($tables, $output)
                                {                                    
                                    var $checked = $tables.find('input:checked');

                                    $output = $output
                                        ? $output.add($checked)
                                        : $checked;

                                    var $tablesToCheck = null;
                                    $tables.each( function()
                                    {
                                        var $table = jQuery(this);
                                        if ($table.find('input:checked').length == 0)
                                        {
                                            var $next = $table.next();
                                            if ($next.length > 0 && $next[0].tagName.toLowerCase() == 'div')
                                            {
                                                $tablesToCheck = $tablesToCheck
                                                    ? $tablesToCheck.add($next.children('table'))
                                                    : $next;
                                            }
                                        }
                                    });

                                    if ($tablesToCheck)
                                    {
                                        $output = GetRootSelectedElements($tablesToCheck, $output);
                                    }

                                    return $output;
                                }

                                var $selectedItems = GetRootSelectedElements($items.children('table'), $selectedItems);

                                $selectedItems.each( function() {
                                    var $item = jQuery(this);
                                    var $idControl = $item.next();
                                    var tmp = $idControl.attr('href');
                                    var id = tmp.substr(tmp.lastIndexOf('/') + 1, tmp.length);
                                    //check if isn't number
                                    if (!isNaN(parseInt(id)))
                                    {
                                        if (newValue.length > 0)
                                        {
                                            newValue += ',';
                                        }

                                        newValue += id;
                                    }
                                });
                                if (newValue.length > 0)
                                {
                                    newValue = urlParam + newValue;
                                }
                            }

                            $urlValue.val(newValue);
                            $urlValue.change();
                        }

                        function SetupAll()
                        {
                            SetupTitle();
                            SetupUrlValue();
                        };

                        //Controls initialization

                        //Parse UrlValue
                        var urlValue = jQuery.trim($urlValue.val().replace(urlParam,''));
                        if (urlValue.length > 0)
                        {
                            var ids = urlValue.split(',');
                            if (ids.length > 0)
                            {
                                $anyDestination.prop('checked', false);
                                for (var i = 0; i < ids.length; i++) {
                                    var $item = $items.find('span[href="http://' + ids[i] +'"]').prev().prop('checked', true);
                                }
                            }
                            else
                            {
                                $anyDestination.prop('checked', true);
                            }
                        }

                        //Select/deselect child/parent nodes on click
                        function ProcessSelectionChange($checkbox, checkChildren)
                        {   
                            //select/deselect children    
                            if (checkChildren)
                            {               
                                var $table = $checkbox.parents('table');
                                var $children = $table.next();
                                if ($children.length > 0 && $children[0].tagName === 'DIV')
                                {
                                    $children.find('input[type="checkbox"]').prop('checked', $checkbox.prop('checked'));
                                }
                            }
                            //check/uncheck parent
                            var $div = $checkbox.parents('div:first');
                            var $tables = $div.children('table');
                            var checkedCount = $tables.find('input:checked').length;
                            var allChecked = $tables.length == checkedCount;

                            if ($div.hasClass('DestinationsTree'))
                            {
                                if (allChecked)
                                {
                                    $anyDestination.prop('checked', true);
                                    $items.find('input[type="checkbox"]').prop('checked', false);
                                }
                                else
                                {
                                    var globalCheckedCount = $items.find('input:checked').length;
                                    $anyDestination.prop('checked', globalCheckedCount == 0);
                                }
                            }
                            else
                            {
                                var $parentTable = $div.prev();
                                ProcessSelectionChange($parentTable.find('input[type="checkbox"]').prop('checked', allChecked), false);
                            }
                        }

                        //User actions

                        var $currentTopItem = null;

                        //Unbind all old events
                        $items.find('table td span').unbind();
                        $items.find('table td input[type="checkbox"]').unbind();
                        $anyDestination.unbind();
                        $items.find('table td span').click(function () 
                        {
                            //select "tr", containing current destination
                            var $parent = jQuery(this).parent().parent();
                            //toggle checkbox
                            $parent.find('input[type="checkbox"]:first').click();
//                            var $checkbox = $parent.find('input[type="checkbox"]:first');
//                            $checkbox.prop('checked', !$checkbox.prop('checked'));
//                            ProcessSelectionChange($checkbox, true);
//                            SetupAll();
                        });
                        $items.find('table td input[type="checkbox"]').change( function()
                        {
                            var $changed = jQuery(this);
                            if (singleCountryMode)
                            {                               
                                //Find all checked destinations
                                var $checked = $items.find('input[type="checkbox"]:checked');
                                if ($checked.length == 0)
                                {
                                    $checked = $changed;
                                }

                                //Get changed checkbox country
                                var $newTopItem = $changed;

                                while (!$newTopItem.parents('div:first').hasClass('DestinationsTree')) 
                                {
                                    $newTopItem = $newTopItem.parents('div:first').prev().find('input[type="checkbox"]');
                                }

                                if ($checked.length == 0) //Prevent deselection of all destinations 1
                                {
                                    $changed.click();
                                    return;
                                }
                                else if ($currentTopItem[0] == $changed[0]) //Prevent deselection of all destinations 2
                                {
                                    if ($changed.prop('checked') == false) //Deselecting
                                    {
                                        $changed.prop('checked', true);
                                    }
                                    else //Selecting
                                    {
                                        ProcessSelectionChange($changed, true);
                                        SetupAll();
                                    }
                                    return false;
                                }
                                else if (
                                    $changed.parents('div:first').children('table').find('input[type="checkbox"]:checked').length == 0
                                    && $changed.parents('div:first').find('table + div').prev().find('input[type="checkbox"]:checked').length == 0
                                    && $newTopItem.parents('div:first').children('table, div').find('input[type="checkbox"]:checked').length == 0
                                    && $currentTopItem[0] == $newTopItem[0])// Try to deselect last resort in country
                                {
                                    $changed.prop('checked', true);
                                    return false;
                                }
                                else
                                {
                                    //Detect if checkbox was checked in other country
                                    var checkedInOtherCountry = false;
                                    var $topItems = $items.children('table').find('input[type="checkbox"]');

                                    if ($currentTopItem[0] != $newTopItem[0])
                                    {
                                        checkedInOtherCountry = true;
                                        $currentTopItem = $newTopItem;
                                    }

                                    //Process click in other country
                                    if (checkedInOtherCountry)
                                    {
                                        $items.find('input[type="checkbox"]').prop('checked', false);

                                        $changed.prop('checked', true);
                                        ProcessSelectionChange($changed, true);
                                        SetupAll();
                                        return;
                                    }
                                }
                                SetupAll();
                            }
                            ProcessSelectionChange($changed, true);
                            SetupAll();
                        });
                        $anyDestination.click( function(){
                            if (!$anyDestination.prop('checked'))
                            {
                                return false;
                            }
                            else
                            {
                                $anyDestination.prop('checked', true);
                                $items.find('input[type="checkbox"]').prop('checked', false);
                            }
                            SetupAll();
                        });

                        SetupAll();

                        if (singleCountryMode)
                        {
                            var $defaultCountry = $items.find('input[type="checkbox"]:checked:first');
                            if ($defaultCountry.length == 0)
                            {
                                $defaultCountry = $items.find('input[type="checkbox"]:first');
                            }
                            $defaultCountry.prop('checked', true);
                            
                            $currentTopItem = $items.find('input[type="checkbox"]:checked:first');

                            while (!$currentTopItem.parents('div:first').hasClass('DestinationsTree')) 
                            {
                                $currentTopItem = $currentTopItem.parents('div:first').prev().find('input[type="checkbox"]');
                            }

                            $defaultCountry.click().click();
                        }
					};
				}

				//Add $this parameter to settings to provide easy way to get link to DOM
                settings.$this = jQuery(this);
                data = new CTSDestinationPicker(settings);
            }
            $(this).data('CTSDestinationPicker', data);
            return data;
        }
    };

    $.fn.CTSDestinationPicker = function (method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            jQuery.error('Method ' + method + ' does not exist on jQuery.CTSDestinationPicker');
        }

    };

})(jQuery);

//Departure date picker
(function ($) {

    var methods = {
        init: function (options) {
            var settings = {
            };

			// plugin code here

			var $this = jQuery(this);
			var data = $this.data('CTSDepartureDatePicker');

			// If the plugin hasn't been initialized yet
			if (!data) {

				// If options exist, lets merge them
				// with our default settings
				if (options) {
					jQuery.extend(settings, options);
				}

				//Working class declaration
				function CTSDepartureDatePicker(options) {
					//Reference to JS object
					var that = this;
					//Reference to DOM container
					var $this = options.$this;
					
					//Control initialization
					this.Initialize = function (initSettings) {
                        var $paneBody = $this.parents('.PaneBody');
                        
                        //Setting default values
                        var currentDate = new Date();

                        var currentMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
                        var startSelectedDate = null;
                        var endSelectedDate = null;
                        var selectedDay = null;
                        var maxDate = new Date(currentDate.getFullYear() + 20, currentDate.getMonth(), currentDate.getDate());
                        var minDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate() + 1);

                        function ChecksForLastDayInMonth()
                        {
                            if (minDate.getMonth() > currentMonth.getMonth())
                            {
                                currentMonth.setMonth(currentMonth.getMonth() + 1);
                            }
                        }
                        ChecksForLastDayInMonth();

                        var $prevMonthButton = $paneBody.find('.MonthsScroller.Top > img');
                        var $nextMonthButton = $paneBody.find('.MonthsScroller.Bottom > img');
                        var $dateFromTextBox = $paneBody.find('.TextBox.From');
                        var $dateToTextBox = $paneBody.find('.TextBox.To');

                        var $currentMonth = $paneBody.find('.Calendar.CurrentMonth');
                        var $nextMonth = $paneBody.find('.Calendar.NextMonth');

                        var lastChange = 'end';

                        var $clearCalendars = $this.find('a.ClearCalendars');
                        
                        //Url and PaneTitle
                        var $urlValue = $this.find('.UrlValue');
                        var defaultTitle = 'Любая дата вылета';
                        var $paneTitle = $this.parents('.PickersAccordion:first').find('.PaneHead.DepartureDate > .Text');

                        var calendarMonth = '';

                        function RenderCalendar(month) 
                        {
                            function FillDate(
                                currentDate,
                                currentMonth) 
                            {
                                var result = [];
                                result['Date'] = currentDate.toString();
                                var t1 = currentDate.getMonth();
                                var t2 = currentMonth.getMonth();
                                if (currentDate.getMonth() == currentMonth.getMonth()) {
                                    result['Day'] = currentDate.getDate()
                                    result['Class'] = 'Regular';
                                    if (startSelectedDate != null) 
                                    {
                                        if (endSelectedDate != null) 
                                        {
                                            if (currentDate.getTime() <= endSelectedDate.getTime() 
                                                && currentDate.getTime() >= startSelectedDate.getTime()) 
                                            {
                                                result['Class'] = 'Selected';
                                            }
                                            else 
                                            {
                                                result['Class'] = 'Regular';
                                            }
                                        }
                                        else 
                                        {
                                            if (currentDate.getTime() == startSelectedDate.getTime()) 
                                            {
                                                result['Class'] = 'Selected';
                                            } 
                                        }
                                    }
                                    else 
                                    {
                                        if (endSelectedDate != null) 
                                        {
                                            if (currentDate.getTime() <= endSelectedDate.getTime()) 
                                            {
                                                result['Class'] = 'Selected';
                                            }
                                            else 
                                            {
                                                result['Class'] = 'Regular';
                                            }
                                        }
                                        else 
                                        {
                                            if (selectedDay != null && selectedDay != NaN) 
                                            {
                                                if (currentDate.getTime() == selectedDay.getTime()) 
                                                {
                                                    result['Class'] = 'Selected';
                                                }
                                                else 
                                                {
                                                    result['Class'] = 'Regular';
                                                }
                                            }
                                        }
                                    }

                                    var isDateInArr = function (date, arr) 
                                    {
                                        for (var i = 0; i < arr.length; i++) 
                                        {
                                            if (date.getTime() == arr[i].getTime()) 
                                            {
                                                return true;
                                            }
                                        }
                                        return false;
                                    }


                                    if ((maxDate != null && currentDate > maxDate) ||
				                        (minDate != null && currentDate < minDate)) 
                                    {
                                        result['En'] = false;
                                    }
                                    else 
                                    {
                                        result['En'] = true;
                                    }
                                    if (!result['En']) 
                                    {
                                        result['Class'] = 'Disabled';
                                    }
                                }
                                else 
                                {
                                    result['Day'] = '';
                                    result['Class'] = 'Empty';
                                    result['En'] = false;
                                }
                                result['Visible'] = (result['Day'] != '');
                                return result;
                            }

                            var MONTH_IMAGE_URL = '/Functions/ClientTourSearch/Images/{0}.png';

                            var delta;
                            switch (month.getDay()) 
                            {
                                case 0:
                                    delta = 1;
                                    break;
                                case 1:
                                    delta = 0;
                                    break;
                                case 2:
                                    delta = -1;
                                    break;
                                case 3:
                                    delta = -2;
                                    break;
                                case 4:
                                    delta = -3;
                                    break;
                                case 5:
                                    delta = -4;
                                    break;
                                case 6:
                                    delta = -5;
                                    break;
                            }

                            var currentDate = new Date(month);
                            currentDate.setDate(currentDate.getDate() + delta - 7);

                            var html = '';

                            html += '<img src="' + MONTH_IMAGE_URL.replace('{0}', month.getMonth() + 1) + '" class="CurrentMonthImage" alt="" />';
                            html += '<table cellspacing="0" cellpadding="0">';
                            for (var week = 0; week < 7; week++) 
                            {
                                var row = '';
                                row += '<tr>';
                                dateParameters = [];
                                for (var day = 0; day <= 6; day++) 
                                {
                                    dateParameters = FillDate(
                                        currentDate,
                                        month);
                                    row += '<td class="' + dateParameters['Class'] + '">';
                                    if (dateParameters['Visible']) 
                                    {
                                        if (dateParameters['En']) 
                                        {
                                            row += '<input type="hidden" value="' + dateParameters['Date'] + '"/>';
                                            row += '<input type="button" value="' + dateParameters['Day'] + '"/>';
                                        }
                                        else 
                                        {
                                            row += '<input type="hidden" value="' + dateParameters['Date'] + '"/>';
                                            row += '<input type="button" value="' + dateParameters['Day'] + '" disabled="disabled" />';
                                        }
                                    }
                                    currentDate.setDate(currentDate.getDate() + 1);
                                    row += '</td>';
                                }
                                row += '</tr>';
                                if (row.search('input') != -1) 
                                {
                                    html += row;
                                }
                            }
                            html += '</table>';
                            return html;
                        }

                        //Url value - start
                        var DATE_FROM = options.QueryDepartureDateFrom ? options.QueryDepartureDateFrom + '=' : 'datefrom=';
                        var DATE_TO = options.QueryDepartureDateTo ? options.QueryDepartureDateTo + '=' : 'dateto=';
                        var CALENDAR_MONTH = options.QueryCalendarMonth ? options.QueryCalendarMonth + '=' : 'calendarmonth=';

                        function SetupUrlValue()
                        {
                            var newValue = '';
                            if (startSelectedDate)
                            {
                                newValue = DATE_FROM + GetShortDateString(startSelectedDate);
                            }
                            if (endSelectedDate)
                            {
                                if (newValue.length > 0)
                                {
                                    newValue += '&';
                                }
                                newValue += DATE_TO + GetShortDateString(endSelectedDate);
                            }
                            //if (currentMonth && (startSelectedDate || endSelectedDate))
                            if (calendarMonth.length > 0)
                            {
                                if (newValue.length > 0)
                                {
                                    newValue += '&';
                                }
                                newValue += calendarMonth; //CALENDAR_MONTH + GetShortDateString(currentMonth);
                            }
                            $urlValue.val(newValue);
                            $urlValue.change();
                        }

                        function GetDateFromServerStringWithDots(dateString)
                        {
                            var parts = jQuery.trim(dateString).split('.');
                            if (parts.length != 3)
                            {
                                return null;
                            }
                            var result = new Date(parts[2], parts[1] - 1, parts[0]);
                            if (result == NaN)
                            {
                                result = null;
                            }
                            return result;
                        }

                        function SetDateFrom(dateString)
                        {
                            startSelectedDate = GetDateFromServerStringWithDots(dateString);
                        }

                        function SetDateTo(dateString)
                        {
                            endSelectedDate = GetDateFromServerStringWithDots(dateString);
                        }

                        function GetParamFromUrlQuery(searchString, queryParam)
                        {
                            var res = '';
                            if (searchString.indexOf(queryParam) > -1)
                            {
                                var tmp = searchString.substr(searchString.indexOf(queryParam));
                                tmp = tmp.substr(0, tmp.indexOf('&') != -1 ? tmp.indexOf('&') : tmp.length);
                                var array = tmp.split('=');
                                if (array.length == 2)
                                {
                                    res = array[1];
                                }
                            }
                            return res;
                        }

                        //Parsing url value
                        var urlValue = jQuery.trim($urlValue.val());
                        if (urlValue.length > 0)
                        {
                            var tmp = GetParamFromUrlQuery(urlValue, DATE_FROM);
                            if (tmp.length > 0)
                            {
                                SetDateFrom(tmp);
                            }
                            tmp = GetParamFromUrlQuery(urlValue, DATE_TO);
                            if (tmp.length > 0)
                            {
                                SetDateTo(tmp);
                            }
                            tmp = GetParamFromUrlQuery(urlValue, CALENDAR_MONTH);
                            if (tmp.length > 0)
                            {
                                //currentMonth = GetDateFromServerStringWithDots(tmp);
                                calendarMonth = CALENDAR_MONTH + tmp;
                            }
                        }
                        //Url value - end

                        function SetupPaneTitle()
                        {
                            if (!startSelectedDate && !endSelectedDate)
                            {
                                //Default value
                                $paneTitle.html(defaultTitle);
                            }
                            else
                            {
                                var newValue = '';
                                if (startSelectedDate)
                                {
                                    newValue = '<span class="Pretext">с:</span><span class="Value">' + GetShortDateString(startSelectedDate) + '</span>';
                                }
                                if (endSelectedDate)
                                {
                                    newValue += '<span class="Pretext">по:</span><span class="Value">' + GetShortDateString(endSelectedDate) + '</span>';
                                }
                                $paneTitle.html(newValue);
                            }
                        }

                        function SetupAll()
                        {
                            SetupUrlValue();
                            SetupPaneTitle();
                        }

                        function Render() 
                        {
                            var tmpDate = new Date(currentMonth.getFullYear(), currentMonth.getMonth(), currentMonth.getDate());
                            $currentMonth.html(RenderCalendar(tmpDate));
                            tmpDate.setMonth(tmpDate.getMonth() + 1);
                            $nextMonth.html(RenderCalendar(tmpDate));

                            $this.find('.Calendar').find('input[type="button"]').click(function () 
                            {
                                var t = jQuery(this).prev().val();
                                if (t != '' && Date.parse(t) != NaN) 
                                {
                                    t = new Date(t);
                                    selectedDay = t;
                                    $dateFromTextBox.removeClass("Selected");
                                    $dateToTextBox.removeClass("Selected");
                                    if (lastChange == 'end' || (startSelectedDate != null && lastChange == 'start' && (t.getTime() >= startSelectedDate.getTime())) || startSelectedDate == null)
                                    {
                                        if (lastChange == 'start') 
                                        {                                        
                                            lastChange ='end';
                                            endSelectedDate = t;
                                            $dateFromTextBox.addClass("Selected");
                                            $dateToTextBox.val(GetShortDateString(t));
                                        }
                                        else if (lastChange == 'end') 
                                        {
                                            lastChange = 'start';
                                            startSelectedDate = t;
                                            $dateToTextBox.addClass("Selected");
                                            $dateFromTextBox.val(GetShortDateString(t));
                                            if (endSelectedDate != undefined && startSelectedDate.getTime() > endSelectedDate.getTime())
                                            {
                                                endSelectedDate = null;
                                                $dateToTextBox.val('');
                                            }
                                        }
                                        else 
                                        {
                                            lastChange = 'start';
                                            startSelectedDate = t;
                                            $dateToTextBox.addClass("Selected");
                                            $dateFromTextBox.val(GetShortDateString(t));
                                        }
                                    }
                                    else
                                    {
                                        lastChange = 'start';
                                        startSelectedDate = t;
                                        endSelectedDate = null;
                                        $dateToTextBox.addClass("Selected");
                                        $dateFromTextBox.val(GetShortDateString(t));
                                        $dateToTextBox.val('');
                                    }
                                }
                                Render();
                            });

                            SetupAll();
                        }

                        /* Month scroller */

                        function SetMonthScrollerVisibility() 
                        {
                            if (currentMonth < new Date()) 
                            {
                                $prevMonthButton.hide();
                            }
                            else 
                            {
                                $prevMonthButton.show();
                            }
                        }

                        /* Events */

                        $prevMonthButton.unbind();
                        $prevMonthButton.click(function () 
                        {
                            currentMonth.setMonth(currentMonth.getMonth() - 1);
                                    
                            Render();
  
                            SetMonthScrollerVisibility();
                        });

                        $nextMonthButton.unbind();
                        $nextMonthButton.click(function () 
                        {
                            currentMonth.setMonth(currentMonth.getMonth() + 1);
                                    
                            Render();
  
                            SetMonthScrollerVisibility();
                        });                        

                        $dateFromTextBox.click(function () 
                        {
                            $dateFromTextBox.removeClass("Selected");
                            $dateToTextBox.removeClass("Selected");
                            lastChange = 'end';
                            $dateFromTextBox.addClass("Selected");
                        });

                        function ParseFromInput()
                        {
                            var value = $dateFromTextBox.val();

                            var date = GetDateFromServerStringWithDots(value);
                            if (date != null)
                            {
                                if (endSelectedDate != null && date.getTime() > endSelectedDate.getTime())
                                {
                                    date = endSelectedDate;
                                    $dateFromTextBox.val(GetShortDateString(date));
                                }
                                if (date.getTime() >= minDate.getTime())
                                {
                                    startSelectedDate = date;
                                    selectedDay = date;
                                    Render();
                                }
                            }
                        }

                        $dateFromTextBox.change(function() {
                            ParseFromInput();
                        });

                        $dateToTextBox.click(function () 
                        {
                            $dateFromTextBox.removeClass("Selected");
                            $dateToTextBox.removeClass("Selected");
                            lastChange = 'start';
                            $dateToTextBox.addClass("Selected");
                        });

                        function ParseToInput()
                        {
                            var value = $dateToTextBox.val();

                            var date = GetDateFromServerStringWithDots(value);
                            if (date != null)
                            {
                                if (startSelectedDate != null && date.getTime() < startSelectedDate.getTime())
                                {
                                    date = startSelectedDate;
                                    $dateToTextBox.val(GetShortDateString(date));
                                }
                                endSelectedDate = date;
                                selectedDay = date;
                                Render();
                            }
                        }

                        $dateToTextBox.change(function() 
                        {
                            ParseToInput();
                        });

                        $clearCalendars.click( function()
                        {
                            $dateFromTextBox.val('');
                            $dateToTextBox.val('');
                            currentMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
                            ChecksForLastDayInMonth();
                            lastChange = 'end';
                            startSelectedDate = null;
                            endSelectedDate = null;
                            selectedDay = null;
                            Render();
                        });

                        /* Misc */
                        function GetShortDateString(dateTime)
                        {
                            if (!dateTime)
                            {
                                return '';
                            }
                            var date = dateTime.getDate();
                            if (date < 10)
                            {
                                date = '0' + date;
                            }
                            var month = (dateTime.getMonth() + 1);
                            if (month < 10)
                            {
                                month = '0' + month;
                            }
                            return (date + '.' + month  + '.' + dateTime.getFullYear());
                        }

                        // Check if is needed to scroll calendar to future dates
                        var tmpDate1 = new Date();
                        tmpDate1 = new Date(tmpDate1.getFullYear(), tmpDate1.getMonth(), 1);
                        var tmpDate2 = new Date(startSelectedDate.getFullYear(), startSelectedDate.getMonth(), 1);

                        if (
                            (
                                tmpDate2.getFullYear() == tmpDate1.getFullYear() &&
                                tmpDate2.getMonth() - tmpDate1.getMonth() >= 2
                            ) 
                            ||
                            (
                                tmpDate2.getFullYear() > tmpDate1.getFullYear() &&
                                tmpDate2.getMonth() >= 1 || 
                                tmpDate1.getMonth() < 11
                            )
                           )
                        {
                            currentMonth = tmpDate2;
                        }

                        Render();

                        if (startSelectedDate)
                        {
                            $dateFromTextBox.val(GetShortDateString(startSelectedDate));
                        }
                        if (endSelectedDate)
                        {
                            $dateToTextBox.val(GetShortDateString(endSelectedDate));
                        }

                        SetMonthScrollerVisibility();
                        SetupAll();
					};
				}

				//Add $this parameter to settings to provide easy way to get link to DOM
                settings.$this = jQuery(this);
                data = new CTSDepartureDatePicker(settings);
            }
            $(this).data('CTSDepartureDatePicker', data);
            return data;
        }
    };

    $.fn.CTSDepartureDatePicker = function (method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            jQuery.error('Method ' + method + ' does not exist on jQuery.CTSDepartureDatePicker');
        }

    };

})(jQuery);

//Nights count

(function ($) {

    var methods = {
        init: function (options) {
            var settings = {
            };

			// plugin code here

			var $this = jQuery(this);
			var data = $this.data('CTSNightCountPicker');

			// If the plugin hasn't been initialized yet
			if (!data) {

				// If options exist, lets merge them
				// with our default settings
				if (options) {
					jQuery.extend(settings, options);
				}

				//Working class declaration
				function CTSNightCountPicker(options) {
					//Reference to JS object
					var that = this;
					//Reference to DOM container
					var $this = options.$this;
					
					//Control initialization
					this.Initialize = function (initSettings) {
						
                        //Url and PaneTitle
                        var $urlValue = $this.find('.UrlValue');
                        var defaultTitle = 'Любое количество ночей';
                        var $paneTitle = $this.parents('.PickersAccordion:first').find('.PaneHead.NightCount > .Text'); 

                        var multiplier = 10; //Used to fix rounding in different browsers to avoid background slide.
                        var startValue = initSettings.PassedNightStartValue * multiplier;
                        var endValue = initSettings.PassedNightEndValue * multiplier;

                        var $slider = $this.find('.Slider');
                        var $from = $this.find('.TextBox.From');
                        var $to = $this.find('.TextBox.To');

                        var minimumValue = 3;
                        var maximumValue = 21;
                        var stepValue = 1;                        

                        var maxValue = (maximumValue + stepValue) * multiplier;
                        var minValue = minimumValue * multiplier;
                        var step = stepValue * multiplier;    

                        //Utilities

                        function CorrectMatchingMinMax()
                        {
                            if (startValue == endValue) 
                            {
                                if (startValue > minValue) 
                                {
                                    startValue = startValue - step;
                                    $slider.slider('values', 0, startValue);
                                }
                                else 
                                {
                                    endValue = startValue + step;
                                    $slider.slider('values', 1, endValue);
                                }
                            }
                        }

                        function SetupTitle()
                        {
                            var newValue = '{0} - {1} ночей';
                            newValue = newValue.replace('{0}', $from.val());
                            newValue = newValue.replace('{1}', $to.val());
                            $paneTitle.html(newValue);
                        }

                        var NIGHTS_FROM = options.QueryNightCountFrom ? options.QueryNightCountFrom + '=' : 'nightcountfrom=';
                        var NIGHTS_TO = options.QueryNightCountTo ? options.QueryNightCountTo + '=' : 'nightcountto=';
                        function SetupUrlValue()
                        {
                            var newValue = '';
                            if (startValue)
                            {
                                var tmp = startValue == maxValue ? maxValue + 1 : startValue;
                                newValue = NIGHTS_FROM + tmp / multiplier;
                            }
                            if (endValue)
                            {
                                if (newValue.length > 0)
                                {
                                    newValue += '&';
                                }
                                var tmp = endValue == maxValue ? maxValue + 1 : endValue;
                                newValue += NIGHTS_TO + tmp / multiplier;
                            }
                            $urlValue.val(newValue);
                            $urlValue.change();
                        }

                        function SetupAll()
                        {
                            SetupTitle();
                            SetupUrlValue();
                            CorrectMatchingMinMax();
                        }

                        function SetupDirectInput()
                        {
                            var fromValue = startValue / multiplier;
                            if (startValue >= maxValue) 
                            {
                                fromValue = ((endValue / multiplier) - step / multiplier) + '+';
                            }
                            //Tweak to different browser behavior
                            if (fromValue == '20.9+')
                            {
                                fromValue = '21+';
                            }
                            $from.val(fromValue);

                            var toValue = endValue / multiplier;
                            if (endValue >= maxValue) 
                            {
                                toValue = ((endValue / multiplier) - step / multiplier) + '+';
                            }
                            //Tweak to different browser behavior
                            if (toValue == '20.9+')
                            {
                                toValue = '21+';
                            }
                            $to.val(toValue);
                        }

                        //Parsing url value
                        var urlValue = jQuery.trim($urlValue.val());
                        if (urlValue.length > 0)
                        {
                            var counts = urlValue.split('&');
                            if (counts.length > 1)
                            {
                                startValue = counts[0].replace(NIGHTS_FROM, '') * multiplier;
                                endValue = counts[1].replace(NIGHTS_TO, '') * multiplier;
                            }
                            else
                            {
                                if (counts[0].indexOf(NIGHTS_FROM) != -1)
                                {
                                    startValue = counts[0].replace(NIGHTS_FROM, '') * multiplier;
                                }
                                else
                                {
                                    endValue = counts[0].replace(NIGHTS_TO, '') * multiplier;
                                }
                            }
                            $slider.slider('values', 0, startValue);
                            $slider.slider('values', 1, endValue);
                        }

                        //Events

                        function ParseFromInput()
                        {
                            var value = $from.val();
                            if (value == '21+')
                            {
                                value = '22';
                            }
                            var tmp = parseInt(value, 10);
                            if (tmp != NaN)
                            {
                                if (tmp < minimumValue)
                                {
                                    tmp = minimumValue;
                                }
                                if (tmp > maximumValue + stepValue)
                                {
                                    tmp = maximumValue + stepValue;
                                }                                
                                if (tmp * multiplier > endValue)
                                {
                                    tmp = endValue / multiplier;
                                }
                                startValue = tmp * multiplier;
                                if (tmp != maximumValue + stepValue)
                                {
                                    $from.val(tmp);
                                }
                                else
                                {
                                    $from.val('21+');
                                }
                                $slider.slider('values', 0, startValue);

                                SetupAll();
                            }
                        }

                        $from.change(function () {
                            ParseFromInput();
                        });

                        function ParseToInput()
                        {
                            var value = $to.val();
                            if (value == '21+')
                            {
                                value = '22';
                            }
                            var tmp = parseInt(value, 10);
                            if (tmp != NaN)
                            {
                                if (tmp < minimumValue)
                                {
                                    tmp = minimumValue;
                                }
                                if (tmp > maximumValue + stepValue)
                                {
                                    tmp = maximumValue + stepValue;
                                }
                                if (tmp * multiplier < startValue)
                                {
                                    tmp = startValue / multiplier;
                                }
                                endValue = tmp * multiplier;
                                if (tmp != maximumValue + stepValue)
                                {
                                    $to.val(tmp);
                                }
                                else
                                {
                                    $to.val('21+');
                                }
                                $slider.slider('values', 1, endValue);

                                SetupAll();
                            }
                        }

                        $to.change(function () {
                            ParseToInput();
                        });

                        //Initialization                                                

                        maxValue--;

                        $slider.slider({
                            range: true,
                            min: minValue,
                            max: maxValue,
                            step: step,
                            values: [startValue, endValue],
                            slide: function (event, ui) {
                                startValue = ui.values[0];
                                endValue = ui.values[1];
                                SetupDirectInput();
                            },
                            stop: function (event, ui) {
                                SetupAll();
                            }
                        });

                        SetupDirectInput();
                        SetupAll();
					};
				}

				//Add $this parameter to settings to provide easy way to get link to DOM
                settings.$this = jQuery(this);
                data = new CTSNightCountPicker(settings);
            }
            $(this).data('CTSNightCountPicker', data);
            return data;
        }
    };

    $.fn.CTSNightCountPicker = function (method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            jQuery.error('Method ' + method + ' does not exist on jQuery.CTSNightCountPicker');
        }

    };

})(jQuery);

//Price range

(function ($) {

    var methods = {
        init: function (options) {
            var settings = {
            };

			// plugin code here

			var $this = jQuery(this);
			var data = $this.data('CTSPriceRangePicker');

			// If the plugin hasn't been initialized yet
			if (!data) {

				// If options exist, lets merge them
				// with our default settings
				if (options) {
					jQuery.extend(settings, options);
				}

				//Working class declaration
				function CTSPriceRangePicker(options) {
					//Reference to JS object
					var that = this;
					//Reference to DOM container
					var $this = options.$this;
					
					//Control initialization
					this.Initialize = function (initSettings) {
						
                        //Url and PaneTitle
                        var $urlValue = $this.find('.UrlValue');
                        var defaultTitle = 'Любая стоимость';
                        var defaultMinSum = 10000;
                        var defaultMaxSum = 210000;
                        var $paneTitle = $this.parents('.PickersAccordion:first').find('.PaneHead.PriceRange > .Text'); 

                        var multiplier = 10; //Used to fix rounding in different browsers to avoid background slide.
                        var startValue = defaultMinSum * multiplier;
                        var endValue = defaultMaxSum * multiplier;

                        var $slider = $this.find('.Slider');
                        var $from = $this.find('.TextBox.From');
                        var $to = $this.find('.TextBox.To');

                        var minimumValue = 10000;
                        var maximumValue = 200000;
                        var stepValue = 10000;                        

                        var maxValue = (maximumValue + stepValue) * multiplier;
                        var minValue = minimumValue * multiplier;
                        var step = stepValue * multiplier;    

                        //Utilities

                        function CorrectMatchingMinMax()
                        {
                            if (startValue == endValue) 
                            {
                                if (startValue > minValue) 
                                {
                                    startValue = startValue - step;
                                    $slider.slider('values', 0, startValue);
                                }
                                else 
                                {
                                    endValue = startValue + step;
                                    $slider.slider('values', 1, endValue);
                                }
                            }
                        }

                        function SetupTitle()
                        {
                            if (startValue / multiplier == defaultMinSum && endValue / multiplier == defaultMaxSum)
                            {
                                $paneTitle.html(defaultTitle);
                            }
                            else
                            {
                                var newValue = '{0} - {1} рублей';
                                newValue = newValue.replace('{0}', $from.val());
                                newValue = newValue.replace('{1}', $to.val());
                                $paneTitle.html(newValue);
                            }
                        }

                        var SUM_FROM = options.QueryPriceRangeFrom ? options.QueryPriceRangeFrom + '=' : 'sumfrom=';
                        var SUM_TO = options.QueryPriceRangeTo ? optionsQueryPriceRangeTo + '=' : 'sumto=';
                        function SetupUrlValue()
                        {
                            if (startValue / multiplier == defaultMinSum && endValue / multiplier == defaultMaxSum)
                            {
                                $urlValue.val('');
                                return;
                            }
                            var newValue = '';
                            if (startValue)
                            {
                                var tmp = startValue == maxValue ? maxValue + 1 : startValue;
                                if (tmp > minValue)
                                {
                                    newValue = SUM_FROM + tmp / multiplier;
                                }
                            }
                            if (endValue)
                            {
                                var tmp = endValue == maxValue ? maxValue + 1 : endValue;
                                if (tmp < maxValue + 1)
                                {
                                    if (newValue.length > 0)
                                    {
                                        newValue += '&';
                                    }
                                    newValue += SUM_TO + tmp / multiplier;
                                }
                            }
                            $urlValue.val(newValue);
                            $urlValue.change();
                        }

                        function SetupAll()
                        {
                            SetupTitle();
                            SetupUrlValue();
                            CorrectMatchingMinMax();
                        }

                        function SetupDirectInput()
                        {
                            var fromValue = startValue / multiplier;
                            if (startValue >= maxValue) 
                            {
                                fromValue = ((endValue / multiplier) - step / multiplier) + '+';
                            }
                            //Tweak to different browser behavior
                            if (fromValue == '199999.9+')
                            {
                                fromValue = '200000+';
                            }
                            $from.val(fromValue);

                            var toValue = endValue / multiplier;
                            if (endValue >= maxValue) 
                            {
                                toValue = ((endValue / multiplier) - step / multiplier) + '+';
                            }
                            //Tweak to different browser behavior
                            if (toValue == '199999.9+')
                            {
                                toValue = '200000+';
                            }
                            $to.val(toValue);
                        }

                        //Parsing url value
                        var urlValue = jQuery.trim($urlValue.val());
                        if (urlValue.length > 0)
                        {
                            var counts = urlValue.split('&');
                            if (counts.length > 1)
                            {
                                startValue = counts[0].replace(SUM_FROM, '') * multiplier;
                                endValue = counts[1].replace(SUM_TO, '') * multiplier;
                            }
                            else
                            {
                                if (counts[0].indexOf(SUM_FROM) != -1)
                                {
                                    startValue = counts[0].replace(SUM_FROM, '') * multiplier;
                                }
                                else
                                {
                                    endValue = counts[0].replace(SUM_TO, '') * multiplier;
                                }
                            }
                            $slider.slider('values', 0, startValue);
                            $slider.slider('values', 1, endValue);
                        }

                        //Events

                        function ParseFromInput()
                        {
                            var value = $from.val();
                            if (value == '200000+')
                            {
                                value = '210000';
                            }
                            var tmp = parseInt(value, 10);
                            if (tmp != NaN)
                            {
                                if (tmp < minimumValue)
                                {
                                    tmp = minimumValue;
                                }
                                if (tmp > maximumValue + stepValue)
                                {
                                    tmp = maximumValue + stepValue;
                                }                                
                                if (tmp * multiplier > endValue)
                                {
                                    tmp = endValue / multiplier;
                                }
                                startValue = tmp * multiplier;
                                if (tmp != maximumValue + stepValue)
                                {
                                    $from.val(tmp);
                                }
                                else
                                {
                                    $from.val('200000+');
                                }
                                $slider.slider('values', 0, startValue);

                                SetupAll();
                            }
                        }

                        $from.change(function () {
                            ParseFromInput();
                        });

                        function ParseToInput()
                        {
                            var value = $to.val();
                            if (value == '200000+')
                            {
                                value = '210000';
                            }
                            var tmp = parseInt(value, 10);
                            if (tmp != NaN)
                            {
                                if (tmp < minimumValue)
                                {
                                    tmp = minimumValue;
                                }
                                if (tmp > maximumValue + stepValue)
                                {
                                    tmp = maximumValue + stepValue;
                                }
                                if (tmp * multiplier < startValue)
                                {
                                    tmp = startValue / multiplier;
                                }
                                endValue = tmp * multiplier;
                                if (tmp != maximumValue + stepValue)
                                {
                                    $to.val(tmp);
                                }
                                else
                                {
                                    $to.val('200000+');
                                }
                                $slider.slider('values', 1, endValue);

                                SetupAll();
                            }
                        }

                        $to.change(function () {
                            ParseToInput();
                        });

                        //Initialization                                                

                        maxValue--;

                        $slider.slider({
                            range: true,
                            min: minValue,
                            max: maxValue,
                            step: step,
                            values: [startValue, endValue],
                            slide: function (event, ui) {
                                startValue = ui.values[0];
                                endValue = ui.values[1];
                                SetupDirectInput();
                            },
                            stop: function (event, ui) {
                                SetupAll();
                            }
                        });

                        SetupDirectInput();
                        SetupAll();
					};
				}

				//Add $this parameter to settings to provide easy way to get link to DOM
                settings.$this = jQuery(this);
                data = new CTSPriceRangePicker(settings);
            }
            $(this).data('CTSPriceRangePicker', data);
            return data;
        }
    };

    $.fn.CTSPriceRangePicker = function (method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            jQuery.error('Method ' + method + ' does not exist on jQuery.CTSPriceRangePicker');
        }

    };

})(jQuery);

//Traveller count picker
(function ($) {

    var methods = {
        init: function (options) {
            var settings = {
            };

			// plugin code here

			var $this = jQuery(this);
			var data = $this.data('CTSTravellerPicker');

			// If the plugin hasn't been initialized yet
			if (!data) {

				// If options exist, lets merge them
				// with our default settings
				if (options) {
					jQuery.extend(settings, options);
				}

				//Working class declaration
				function CTSTravellerPicker(options) {
					//Reference to JS object
					var that = this;
					//Reference to DOM container
					var $this = options.$this;
					
					//Control initialization
					this.Initialize = function (initSettings) {
						var $urlValue = $this.find('.UrlValue');
                        var defaultTitle = 'Любое количество туристов';
                        var $paneTitle = $this.parents('.PickersAccordion:first').find('.PaneHead.Traveller > .Text'); 

                        var defaultAdultCount = 2;
                        var defaultChildrenCount = 0;

                        var adultCount = defaultAdultCount;
                        var childrenString = defaultChildrenCount;
                        var childrenCount = 0;

                        var $adultCount = $this.find('.AdultsCount');
                        var $childrenCount = $this.find('.ChildrenCount');
                        var $childrenContainer = $this.find('.Children');
                        var $childTemplate = $this.find('.ChildTemplate > .Row');

                        var childrenAges = [];

                        //Utilities

                        var ADULT_COUNT = options.QueryAdultCount ? options.QueryAdultCount + '=' : 'adultcount=';
                        var CHILDREN = options.QueryKidAges ? options.QueryKidAges + '=' : 'children=';

                        function GetChildrenAges()
                        {
                            childrenAges = [];
                            $childrenContainer.find('.ChildAge').each( function() {
                                var childAge = jQuery(this).val();
                                if (childAge != -1)
                                {
                                    childrenAges[childrenAges.length] = childAge;
                                }
                            });
                        }

                        function RenderChildren()
                        {
                            $childrenContainer.find('.Row:gt(0)').remove();
                            for (var i = 0; i < childrenCount; i++) {
                                $childrenContainer.find('.Row:last').after($childTemplate.clone());
                                var $last = $childrenContainer.find('.Row:last').find('span');
                                $last.html($last.html().replace('{0}', (i+1)));
                                if (childrenAges[i])
                                {
                                    $last = $childrenContainer.find('.Row:last').find('select');
                                    $last.val(childrenAges[i]);
                                }
                            }
                            $childrenContainer.find('.ChildAge').change( function() {
                                SetupAll();
                            });
                        }

                        function SetupTitle()
                        {
                            var newValue = '';
                            var adultCount = $adultCount.val() * 1;
                            newValue = '';

                            switch (adultCount) {
                                case 0:
                                    newValue += 'Без взрослых';
                                    break;
                                case 1:
                                    newValue += adultCount + ' взрослый';
                                    break;
                                default:
                                    newValue += adultCount + ' взрослых';
                                    break;
                            }

                            var tmp = childrenAges.length > childrenCount ? childrenCount : childrenAges.length;

                            if (tmp > 0)
                            {
                                newValue += ', ' + tmp + ' ';
                                switch (tmp) {
                                    case 1:
                                        newValue += 'ребёнок';
                                        break;
                                    default:
                                        newValue += 'детей';
                                        break;
                                }
                            }

                            $paneTitle.html(newValue);
                        }

                        function SetupUrlValue()
                        {
                            var newValue = ADULT_COUNT + $adultCount.val();
                            var childrenAgePickers = $childrenContainer.find('.ChildAge');
                            if (childrenAgePickers.length > 0)
                            {
                                var childrenString = '';
                                for (var i = 0; i < childrenAgePickers.length; i++) 
                                {                              
                                    var picker = jQuery(childrenAgePickers[i]);
                                    if (picker.val() != "-1")
                                    {
                                        if (childrenString.length > 0)
                                        {
                                            childrenString += ',';
                                        }
                                        childrenString += picker.val();
                                    }
                                }
                                if (childrenString.length > 0)
                                {
                                    newValue += '&' + CHILDREN;
                                    newValue += childrenString;
                                }                       
                            }

                            $urlValue.val(newValue);
                            $urlValue.change();
                        }

                        function SetupAll(skipUrlValue)
                        {
                            childrenCount = $childrenCount.val();

                            if (childrenCount > 0)
                            {
                                $childrenContainer.addClass('Active');
                            }
                            else
                            {
                                $childrenContainer.removeClass('Active');
                            }
                            
                            GetChildrenAges();
                            SetupTitle();
                            if(!skipUrlValue)
                            {
                                SetupUrlValue();
                            }
                        }

                        function CheckNoAdult()
                        {
                            var adultCount = $adultCount.val();
                            if (adultCount == 0)
                            {
                                var tmpChildrenCount = $childrenCount.val(); 
                                if (tmpChildrenCount == 0)
                                {
                                    tmpChildrenCount = 1;
                                    childrenCount = 1;
                                    RenderChildren();
                                    $childrenContainer
                                        .find('.ChildAge:first')
                                        .val(0);
                                }
                                $childrenContainer
                                    .find('.ChildAge:first')
                                    .find('option[value="-1"]')
                                    .remove();
                                $childrenCount
                                    .val(tmpChildrenCount)
                                    .find('option[value="0"]')
                                    .remove();
                            }
                            else
                            {
                                if ($childrenCount.find('option[value="0"]').length == 0)
                                {
                                    $childrenCount.find('option:first').before('<option value="0"></option>');
                                }
                                if ($childrenContainer.find('.ChildAge:first').find('option[value="-1"]').length == 0)
                                {
                                    $childrenContainer.find('.ChildAge:first').find('option:first').before('<option value="-1"></option>');
                                }
                            }
                        }

                        //Url parsing

                        var urlValue = jQuery.trim($urlValue.val());
                        if (urlValue.length > 0)
                        {
                            var counts = urlValue.split('&');
                            if (counts.length > 1)
                            {
                                adultCount = counts[0].replace(ADULT_COUNT, '');
                                childrenString = counts[1].replace(CHILDREN, '');
                            }
                            else
                            {
                                adultCount = counts[0].replace(ADULT_COUNT, '');
                            }
                            $adultCount.val(adultCount);
                            if (childrenString.length > 0)
                            {
                                var ages = childrenString.split(',');
                                childrenAges = [];
                                for (var i = 0; i < ages.length; i++) {
                                    childrenAges[childrenAges.length] = ages[i];
                                }
                                childrenCount = ages.length;
                                $childrenCount.val(childrenCount);
                                $childrenContainer.addClass('Active');
                            }
                        }

                        //Events

                        $adultCount.change( function () {
                            CheckNoAdult();
                            SetupAll();
                        });

                        $childrenCount.change( function () 
                        {
                            SetupAll(true);
                            RenderChildren();
                            CheckNoAdult();
                            SetupUrlValue();
                        });

                        //Initialization                   
                        RenderChildren();
                        CheckNoAdult();
                        SetupAll();
					};
				}

				//Add $this parameter to settings to provide easy way to get link to DOM
                settings.$this = jQuery(this);
                data = new CTSTravellerPicker(settings);
            }
            $(this).data('CTSTravellerPicker', data);
            return data;
        }
    };

    $.fn.CTSTravellerPicker = function (method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            jQuery.error('Method ' + method + ' does not exist on jQuery.CTSTravellerPicker');
        }

    };

})(jQuery);

//Hotel categories

(function ($) {

    var methods = {
        init: function (options) {
            var settings = {
            };

			// plugin code here

			var $this = jQuery(this);
			var data = $this.data('CTSHotelCategoryPicker');

			// If the plugin hasn't been initialized yet
			if (!data) {

				// If options exist, lets merge them
				// with our default settings
				if (options) {
					jQuery.extend(settings, options);
				}

				//Working class declaration
				function CTSHotelCategoryPicker(options) {
					//Reference to JS object
					var that = this;
					//Reference to DOM container
					var $this = options.$this;
					
					//Control initialization
					this.Initialize = function (initSettings) {
						
                        var $urlValue = $this.find('.UrlValue');
                        var defaultTitle = 'Категория не важна';
                        var $paneTitle = $this.parents('.PickersAccordion:first').find('.PaneHead.HotelCategory > .Text');

                        var $anyCategory = $this.find('.AnyCategory > input[type="checkbox"]');
                        var $categoriesContainer = $this.find('.Categories');

                        var CATEGORIES_PARAM = options.QueryHotelCategory ? options.QueryHotelCategory + '=' : 'rating=';

                        //Utilities

                        function SetupTitle()
                        {
                            var newValue = '';

                            var $checkedItems = $categoriesContainer.find('input[type="checkbox"]:checked');
                            if ($checkedItems.length > 0)
                            {
                                var stars = [];
                                $checkedItems.each( function() {
                                    if (newValue.length > 0)
                                    {
                                        newValue += ', ';
                                    }
                                    $hidden = jQuery(this).parent().find('input[type="hidden"]');
                                    if ($hidden.attr('title') == 'Star')
                                    {
                                        stars[stars.length] = $hidden.val();
                                    }
                                    else
                                    {
                                        newValue += $hidden.attr('title');
                                    }
                                });
                                if (stars.length > 0)
                                {
                                    if (stars.length == 1)
                                    {
                                        if(stars[0] == 5)
                                        {
                                            if (newValue.length > 0)
                                            {
                                                newValue = '5 звезд, ' + newValue;
                                            }
                                            else
                                            {
                                                newValue = '5 звезд';
                                            }
                                        }
                                        else if(stars[0] == 1)
                                        {
                                            if (newValue.length > 0)
                                            {
                                                newValue = '1 звезда, ' + newValue;
                                            }
                                            else
                                            {
                                                newValue = '1 звезда';
                                            }
                                        }
                                         else if(stars[0] == 2)
                                        {
                                            if (newValue.length > 0)
                                            {
                                                newValue = '2 звезды, ' + newValue;
                                            }
                                            else
                                            {
                                                newValue = '2 звезды';
                                            }
                                        }
                                         else if(stars[0] == 3)
                                        {
                                            if (newValue.length > 0)
                                            {
                                                newValue = '3 звезды, ' + newValue;
                                            }
                                            else
                                            {
                                                newValue = '3 звезды';
                                            }
                                        }
                                         else if(stars[0] == 4)
                                        {
                                            if (newValue.length > 0)
                                            {
                                                newValue = '4 звезды, ' + newValue;
                                            }
                                            else
                                            {
                                                newValue = '4 звезды';
                                            }
                                        }
                                    }
                                    else
                                    {
                                        var starsString = '';
                                        for (var i = 0; i < stars.length; i++) 
                                        {
                                            if (starsString.length > 0)
                                            {
                                                starsString += ',';
                                            }
                                            starsString += stars[i];
                                        }
                                        newValue = starsString + ' звезды' + (newValue.length != 0 ? ', ' : '') + newValue;
                                    }
                                }
                            }

                            $paneTitle.html(newValue.length > 0 ? newValue : defaultTitle);
                        }

                        function SetupUrlValue()
                        {
                            var newValue = '';
                            var $checkedItems = $categoriesContainer.find('input[type="checkbox"]:checked');
                            if ($checkedItems.length > 0)
                            {
                                $checkedItems.each ( function() {
                                    if (newValue.length > 0)
                                    {
                                        newValue += ',';
                                    }
                                    newValue += jQuery(this).parent().find('input[type="hidden"]').val();
                                });
                                newValue = CATEGORIES_PARAM + newValue;
                            }
                            $urlValue.val(newValue);
                            $urlValue.change();
                        }

                        function SetupSelectedCss()
                        {
                            var $cbs = $categoriesContainer.find('input[type="checkbox"]');
                            $cbs.each( function() {
                                if (jQuery(this).prop('checked'))
                                {
                                    jQuery(this).parent().addClass('Selected');
                                }
                                else
                                {
                                    jQuery(this).parent().removeClass('Selected');
                                }
                            });
                        }

                        function SetupAll()
                        {
                            SetupTitle();
                            SetupUrlValue();
                            SetupSelectedCss();
                        }

                        function AreNoneClicked()
                        {
                            return $categoriesContainer.find('input[type="checkbox"]:checked').length == 0;
                        }

                        function AreAllClicked()
                        {   
                            return $categoriesContainer.find('input[type="checkbox"]:checked').length == $categoriesContainer.find('input[type="checkbox"]').length;
                        }

                        //Parse url

                        var urlValue = jQuery.trim($urlValue.val());
                        if (urlValue.length > 0)
                        {
                            $anyCategory.prop('checked', false);
                            var ratings = urlValue.replace(CATEGORIES_PARAM, '').split(',');
                            if (ratings.length > 0)
                            {
                                for (var i = 0; i < ratings.length; i++) 
                                {
                                    $categoriesContainer.find('input[type="hidden"][value="' + ratings[i] + '"]').parent().find('input[type="checkbox"]').prop('checked', true);
                                }
                            }
                        }

                        //Events

                        $anyCategory.unbind();
                        $anyCategory.change( function() {
                            $categoriesContainer.find('input[type="checkbox"]').prop('checked', false);
                            SetupAll();
                        });

                        $categoriesContainer.find('input[type="checkbox"]').unbind();
                        $categoriesContainer.find('input[type="checkbox"]').change( function() {
                            if (/*AreAllClicked() || */AreNoneClicked())
                            {
                                $anyCategory.prop('checked', true);
                                $categoriesContainer.find('input[type="checkbox"]').prop('checked', false);
                            }
                            else
                            {
                                $anyCategory.prop('checked', false);
                            }
                            SetupAll();
                        });

                        //Initialization
                        SetupAll();
					};
				}

				//Add $this parameter to settings to provide easy way to get link to DOM
                settings.$this = jQuery(this);
                data = new CTSHotelCategoryPicker(settings);
            }
            $(this).data('CTSHotelCategoryPicker', data);
            return data;
        }
    };

    $.fn.CTSHotelCategoryPicker = function (method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            jQuery.error('Method ' + method + ' does not exist on jQuery.CTSHotelCategoryPicker');
        }

    };

})(jQuery);

//Meal type

(function ($) {

    var methods = {
        init: function (options) {
            var settings = {
            };

			// plugin code here

			var $this = jQuery(this);
			var data = $this.data('CTSMealTypePicker');

			// If the plugin hasn't been initialized yet
			if (!data) {

				// If options exist, lets merge them
				// with our default settings
				if (options) {
					jQuery.extend(settings, options);
				}

				//Working class declaration
				function CTSMealTypePicker(options) {
					//Reference to JS object
					var that = this;
					//Reference to DOM container
					var $this = options.$this;
					
					//Control initialization
					this.Initialize = function (initSettings) {
						
                        var $urlValue = $this.find('.UrlValue');
                        var defaultTitle = 'Любой тип питания';
                        var $paneTitle = $this.parents('.PickersAccordion:first').find('.PaneHead.MealType > .Text');

                        var $anyCategory = $this.find('.AnyCategory > input[type="checkbox"]');
                        var $categoriesContainer = $this.find('.Categories');

                        var CATEGORIES_PARAM = options.QueryMealType ? options.QueryMealType + '=' : 'mealstype=';

                        //Utilities

                        function SetupTitle()
                        {
                            var newValue = '';

                            var $checkedItems = $categoriesContainer.find('input[type="checkbox"]:checked');
                            if ($checkedItems.length > 0)
                            {
                                var stars = [];
                                $checkedItems.each( function() {
                                    if (newValue.length > 0)
                                    {
                                        newValue += ', ';
                                    }
                                    newValue += jQuery(this).parent().find('input[type="hidden"]').attr('title');
                                });
                            }

                            $paneTitle.html(newValue.length > 0 ? newValue : defaultTitle);
                        }

                        function SetupUrlValue()
                        {
                            var newValue = '';
                            var $checkedItems = $categoriesContainer.find('input[type="checkbox"]:checked');
                            if ($checkedItems.length > 0)
                            {
                                $checkedItems.each ( function() {
                                    if (newValue.length > 0)
                                    {
                                        newValue += ',';
                                    }
                                    newValue += jQuery(this).parent().find('input[type="hidden"]').val();
                                });
                                newValue = CATEGORIES_PARAM + newValue;
                            }
                            $urlValue.val(newValue);
                            $urlValue.change();
                        }

                        function SetupSelectedCss()
                        {
                            var $cbs = $categoriesContainer.find('input[type="checkbox"]');
                            $cbs.each( function() {
                                if (jQuery(this).prop('checked'))
                                {
                                    jQuery(this).parent().addClass('Selected');
                                }
                                else
                                {
                                    jQuery(this).parent().removeClass('Selected');
                                }
                            });
                        }

                        function SetupAll()
                        {
                            SetupTitle();
                            SetupUrlValue();
                            SetupSelectedCss();
                        }

                        function AreNoneClicked()
                        {
                            return $categoriesContainer.find('input[type="checkbox"]:checked').length == 0;
                        }

                        function AreAllClicked()
                        {   
                            return $categoriesContainer.find('input[type="checkbox"]:checked').length == $categoriesContainer.find('input[type="checkbox"]').length;
                        }

                        //Parse url

                        var urlValue = jQuery.trim($urlValue.val());
                        if (urlValue.length > 0)
                        {
                            var ratings = urlValue.replace(CATEGORIES_PARAM, '').split(',');
                            if (ratings.length > 0)
                            {
                                for (var i = 0; i < ratings.length; i++) 
                                {
                                    $categoriesContainer.find('input[type="hidden"][value="' + ratings[i] + '"]').parent().find('input[type="checkbox"]').prop('checked', true);
                                }
                            }
                        }

                        //Events

                        $anyCategory.unbind();
                        $anyCategory.change( function() {
                            $categoriesContainer.find('input[type="checkbox"]').prop('checked', false);
                            SetupAll();
                        });

                        $categoriesContainer.find('input[type="checkbox"]').unbind();
                        $categoriesContainer.find('input[type="checkbox"]').change( function() {
                            if (/*AreAllClicked() || */AreNoneClicked())
                            {
                                $anyCategory.prop('checked', true);
                                $categoriesContainer.find('input[type="checkbox"]').prop('checked', false);
                            }
                            else
                            {
                                $anyCategory.prop('checked', false);
                            }
                            SetupAll();
                        });

                        //Initialization
                        SetupAll();

					};
				}

				//Add $this parameter to settings to provide easy way to get link to DOM
                settings.$this = jQuery(this);
                data = new CTSMealTypePicker(settings);
            }
            $(this).data('CTSMealTypePicker', data);
            return data;
        }
    };

    $.fn.CTSMealTypePicker = function (method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            jQuery.error('Method ' + method + ' does not exist on jQuery.CTSMealTypePicker');
        }

    };

})(jQuery);

//Tour types

(function ($) {

    var methods = {
        init: function (options) {
            var settings = {
            };

			// plugin code here

			var $this = jQuery(this);
			var data = $this.data('CTSTourTypePicker');

			// If the plugin hasn't been initialized yet
			if (!data) {

				// If options exist, lets merge them
				// with our default settings
				if (options) {
					jQuery.extend(settings, options);
				}

				//Working class declaration
				function CTSTourTypePicker(options) {
					//Reference to JS object
					var that = this;
					//Reference to DOM container
					var $this = options.$this;

                    var $template = $this.find('.Template > .Item');
                    var $itemsContainer = $this.find('.Items');

                    var oldSearchString = '';

                    var $contents = $this.find('.Contents');
                    var $spinner = $this.find('.Spinner');

					var $urlValue = $this.find('.UrlValue');
                    var defaultTitle = 'Любой тип отдыха';
                    var $paneTitle = $this.parents('.PickersAccordion:first').find('.PaneHead.TourType > .Text');
                    var $anyTourType = $this.find('.AnyTourType > input[type="checkbox"]');
					
                    var TOURTYPES_PARAM = options.QueryTourType ? options.QueryTourType + '=' : 'tourtypeid=';

                    var SetupUrlValue = function ()
                    {
                        var $items = $itemsContainer.find('.Item');
                        var $checked = $items.find('input[type="checkbox"]:checked');
                        if ($checked.length > 0)
                        {
                            var newValue = '';
                            $checked.each( function () 
                            {
                                if (newValue.length > 0)
                                {
                                    newValue += ',';
                                }
                                newValue += jQuery(this).prev().val();
                            });
                            $urlValue.val(TOURTYPES_PARAM + newValue);
                            $urlValue.change();
                        }
                        else
                        {
                            $urlValue.val('');
                            $urlValue.change();
                        }
                    }

                    var SetupTitle = function ()
                    {
                        var $items = $itemsContainer.find('.Item');
                        var $checked = $items.find('input[type="checkbox"]:checked');
                        if ($checked.length > 0)
                        {
                            var newValue = '';
                            $checked.each( function () 
                            {
                                if (newValue.length > 0)
                                {
                                    newValue += ', ';
                                }
                                newValue += jQuery(this).next().next().html();
                            });
                            $paneTitle.html(newValue);
                        }
                        else
                        {
                            $paneTitle.html(defaultTitle);
                        }
                    }

                    var CheckAnyState = function()
                    {
                        var $items = $itemsContainer.find('.Item');
                        if ($items.find('input[type="checkbox"]:checked').length == 0)
                        {
                            $anyTourType.prop('checked', true);
                            $items.find('input[type="checkbox"]').prop('checked', false);
                        }
                        else
                        {
                            $anyTourType.prop('checked', false);
                        }
                    }

                    var SetSelectedTourTypesStyles = function()
                    {
                        $itemsContainer.find('input[type="checkbox"]').each( function() 
                        {
                            var $cb = jQuery(this);
                            if ($cb.prop('checked'))
                            {
                                $cb.parent().addClass('Selected');
                            }
                            else
                            {
                                $cb.parent().removeClass('Selected');
                            }
                        });
                    }

                    var SetupAll = function()
                    {
                        CheckAnyState();
                        SetSelectedTourTypesStyles();

                        SetupTitle();
                        SetupUrlValue();
                    }

                    var ParseUrlValue = function ()
                    {
                        var urlValue = jQuery.trim($urlValue.val());
                        if (urlValue.length > 0)
                        {
                            var tts = urlValue.replace(TOURTYPES_PARAM, '').split(',');
                            if (tts.length > 0)
                            {
                                for (var i = 0; i < tts.length; i++) 
                                {
                                    $itemsContainer.find('input[type="hidden"][value="' + tts[i] + '"]').next().prop('checked', true);
                                }
                            }
                        }
                    }

                    this.LoadTourTypes = function ()
                    {
                        var searchString = $this.parents('.ClientTourSearch:first').ClientTourSearch().GenerateSearchLink(false);
                        if (searchString == oldSearchString)
                        {
                            return;
                        }
                        else
                        {
                            oldSearchString = searchString;
                            $spinner.show();
                            $contents.hide();
                        }

                        function RenderTourTypes(tourTypes)
                        {
                            var uniquePrefix = 'cb' + new Date().getTime() + '_';
                            var $items = $itemsContainer.find('.Item');

                            for (var i = 0; i < tourTypes.length; i++)
                            {
                                $items.remove();
                                for (var i = 0; i < tourTypes.length; i++) 
                                {
                                    $itemsContainer.append($template.clone());
                                    var $last = $itemsContainer.find('.Item:last');
                                    $last.find('input[type="hidden"]').val(tourTypes[i].ID);                                    
                                    $last.find('input[type="checkbox"]').prop('id', uniquePrefix + tourTypes[i].ID);
                                    $last.find('label').attr('for', uniquePrefix + tourTypes[i].ID).html(tourTypes[i].Name);
                                    $last.find('img').prop('src', tourTypes[i].URL);
                                }
                                $itemsContainer.find('input[type="checkbox"]').change( function() 
                                {
                                    SetupAll();
                                });
                                $itemsContainer.find('img').click( function() 
                                {
                                    var $clicked = jQuery(this);
                                    //Change corresponding checkbox
                                    $clicked.prev().click();
                                });
                            }
                        }

                        function GetAvailableTourTypes()
                        {
                            var clientTourSearchServiceUrl = '/Functions/ClientTourSearch/WebServices/ClientTourSearch.asmx/GetAvailableTourTypes';
                            jQuery.ajax(clientTourSearchServiceUrl, {
                                data: "{'searchLink':'" + searchString + "'}",
                                type: 'POST',
                                dataType: 'JSON',
                                contentType: 'application/json; charset=utf-8',
                                success: function (msg) {
                                    RenderTourTypes(msg.d);
                                    ParseUrlValue();
                                    $spinner.hide();
                                    $contents.show();
                                    SetupAll();
                                },
                                error: function (msg) {
                                    ParseUrlValue();
                                }
                            });
                        }

                        GetAvailableTourTypes(); 
                    }

                    this.Reset = function()
                    {
                        $itemsContainer.find('.Item').find('input[type="checkbox"]').prop('checked', false);
                        SetupAll();
                        $urlValue.change();
                    }

					//Control initialization
					this.Initialize = function (initSettings) 
                    {
                        //Events

                        $anyTourType.change(function() 
                        {
                            $itemsContainer.find('.Item').find('input[type="checkbox"]').prop('checked', false);
                            SetupAll();
                        });

                        //Initialization
                        if ($urlValue.val().length > 0)
                        {
                            $paneTitle.html('Загрузка...');
                            that.LoadTourTypes();
                        }
                        else
                        {
                            SetupAll();
                        }
					};
				}

				//Add $this parameter to settings to provide easy way to get link to DOM
                settings.$this = jQuery(this);
                data = new CTSTourTypePicker(settings);
            }
            $(this).data('CTSTourTypePicker', data);
            return data;
        }
    };

    $.fn.CTSTourTypePicker = function (method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            jQuery.error('Method ' + method + ' does not exist on jQuery.CTSTourTypePicker');
        }

    };

})(jQuery);

//Hotels

(function ($) {

    var methods = {
        init: function (options) {
            var settings = {
            };

			// plugin code here

			var $this = jQuery(this);
			var data = $this.data('CTSHotelPicker');

			// If the plugin hasn't been initialized yet
			if (!data) {

				// If options exist, lets merge them
				// with our default settings
				if (options) {
					jQuery.extend(settings, options);
				}

				//Working class declaration
				function CTSHotelPicker(options) {
					//Reference to JS object
					var that = this;
					//Reference to DOM container
					var $this = options.$this;

                    var $template = $this.find('.Template > .Item');
                    var $itemsContainer = $this.find('.Items');

                    var oldSearchString = '';

                    var $contents = $this.find('.Contents');
                    var $spinner = $this.find('.Spinner');

					var $urlValue = $this.find('.UrlValue');
                    var defaultTitle = 'Любой отель';
                    var $paneTitle = $this.parents('.PickersAccordion:first').find('.PaneHead.Hotel > .Text');
                    var $anyHotel = $this.find('.AnyHotel > input[type="checkbox"]');
					
                    var HOTELS_PARAM = options.QueryHotel ? options.QueryHotel + '=' : 'hotelid=';

                    var SetupUrlValue = function ()
                    {
                        var $items = $itemsContainer.find('.Item');
                        var $checked = $items.find('input[type="checkbox"]:checked');
                        if ($checked.length > 0)
                        {
                            var newValue = '';
                            $checked.each( function () 
                            {
                                if (newValue.length > 0)
                                {
                                    newValue += ',';
                                }
                                newValue += jQuery(this).prev().val();
                            });
                            $urlValue.val(HOTELS_PARAM + newValue);
                            $urlValue.change();
                        }
                        else
                        {
                            $urlValue.val('');
                            $urlValue.change();
                        }
                    }

                    var SetupTitle = function ()
                    {
                        $paneTitle.parent().find('.MoreCount').remove();
                        $paneTitle.parent().find('.ClearHotels').remove();
                        var $items = $itemsContainer.find('.Item');
                        var $checked = $items.find('input[type="checkbox"]:checked');
                        if ($checked.length > 0)
                        {
                            var newValue = '';
                            var moreCountValue = 0;
                            $checked.each( function () 
                            {
                                if (newValue.length > 0)
                                {
                                    newValue += ', ';
                                    moreCountValue++;
                                }
                                newValue += jQuery(this).next().text();
                            });
                            if (newValue.length > 14)
                            {
                                newValue = newValue.substring(0, 14) + '...';  
                            }
                            if (moreCountValue > 0)
                            {
                                $paneTitle.after('<div class="MoreCount">+' + moreCountValue + '</div>');
                            }
                            $paneTitle.after('<div class="ClearHotels">Сбросить</div>');
                            $paneTitle.parent().find('.ClearHotels').click( function()
                            {
                                $itemsContainer.find('input[type="checkbox"]').prop('checked', false);
                                SetupAll();
                                return false;
                            });
                            $paneTitle.html(newValue);
                        }
                        else
                        {
                            $paneTitle.html(defaultTitle);
                        }
                    }

                    var CheckAnyState = function()
                    {
                        var $items = $itemsContainer.find('.Item');
                        if ($items.find('input[type="checkbox"]:checked').length == $items.find('input[type="checkbox"]').length ||
                            $items.find('input[type="checkbox"]:checked').length == 0)
                        {
                            $anyHotel.prop('checked', true);
                            $items.find('input[type="checkbox"]').prop('checked', false);
                        }
                        else
                        {
                            $anyHotel.prop('checked', false);
                        }
                    }

                    var SetSelectedTourTypesStyles = function()
                    {
                        $itemsContainer.find('input[type="checkbox"]').each( function() 
                        {
                            var $cb = jQuery(this);
                            if ($cb.prop('checked'))
                            {
                                $cb.parent().addClass('Selected');
                            }
                            else
                            {
                                $cb.parent().removeClass('Selected');
                            }
                        });
                    }

                    var SetupAll = function()
                    {
                        CheckAnyState();
                        SetSelectedTourTypesStyles();

                        SetupTitle();
                        SetupUrlValue();
                    }

                    var ParseUrlValue = function ()
                    {
                        var urlValue = jQuery.trim($urlValue.val());
                        if (urlValue.length > 0)
                        {
                            var tts = urlValue.replace(HOTELS_PARAM, '').split(',');
                            if (tts.length > 0)
                            {
                                for (var i = 0; i < tts.length; i++) 
                                {
                                    $itemsContainer.find('input[type="hidden"][value="' + tts[i] + '"]').next().prop('checked', true);
                                }
                            }
                        }
                    }

                    this.LoadHotels = function ()
                    {
                        var searchString = $this.parents('.ClientTourSearch:first').ClientTourSearch().GenerateSearchLink(false);
                        if (searchString == oldSearchString)
                        {
                            return;
                        }
                        else
                        {
                            oldSearchString = searchString;
                            $spinner.show();
                            $contents.hide();
                        }

                        function RenderHotels(hotels)
                        {
                            var uniquePrefix = 'cbh' + new Date().getTime() + '_';
                            var $items = $itemsContainer.find('.Item');
                            $items.remove();

                            for (var i = 0; i < hotels.length; i++) 
                            {
                                $itemsContainer.append($template.clone());
                                var $last = $itemsContainer.find('.Item:last');
                                $last.find('input[type="hidden"]').val(hotels[i].ID);                                    
                                $last.find('input[type="checkbox"]').prop('id', uniquePrefix + hotels[i].ID);
                                $last.find('label').attr('for', uniquePrefix + hotels[i].ID).html(hotels[i].Name);
                            }

                            $itemsContainer.find('input[type="checkbox"]').change( function() 
                            {
                                SetupAll();
                            });
                        }

                        function GetAvailableHotels()
                        {
                            var clientTourSearchServiceUrl = '/Functions/ClientTourSearch/WebServices/ClientTourSearch.asmx/GetAvailableHotels';
                            jQuery.ajax(clientTourSearchServiceUrl, {
                                data: "{'searchLink':'" + searchString + "'}",
                                type: 'POST',
                                dataType: 'JSON',
                                contentType: 'application/json; charset=utf-8',
                                success: function (msg) {
                                    RenderHotels(msg.d);
                                    ParseUrlValue();
                                    $spinner.hide();
                                    $contents.show();
                                    SetupAll();
                                },
                                error: function (msg) {
                                    ParseUrlValue();
                                }
                            });
                        }

                        GetAvailableHotels(); 
                    }

                    this.Reset = function()
                    {
                        $itemsContainer.find('.Item').find('input[type="checkbox"]').prop('checked', false);
                        SetupAll();
                        $urlValue.change();
                    }

					//Control initialization
					this.Initialize = function (initSettings) 
                    {
                        //Events

                        $anyHotel.change(function() 
                        {
                            $itemsContainer.find('.Item').find('input[type="checkbox"]').prop('checked', false);
                            SetupAll();
                        });

                        var $searchText = $this.find('.SearchHotel > input[type="text"]');
                        var $searchUp = $this.find('.SearchHotel > .SearchHotelUp');
                        var $searchDown = $this.find('.SearchHotel > .SearchHotelDown');
                        var $searchClear = $this.find('.SearchHotel > .SearchHotelCross');
                        var $searchCounter = $this.find('.SearchHotel > .SearchHotelCounter');

                        var counterCurrent = 1;
                        var counterMax = 23;

                        function SetSearchNavigation()
                        {
                            $searchText.removeClass('Error');
                            //$searchClear.hide();
                            $searchCounter.hide();
                            $searchDown.hide();
                            $searchUp.hide();

                            if ($searchText.val() == '')
                            {
                                $itemsContainer.find('.Item').removeClass('Highlighted');
                            }
                            else
                            {
                                var $highlighted = $itemsContainer.find('.Item.Highlighted');
                                if ($highlighted.length > 0)
                                {
                                    counterMax = $highlighted.length;
                                    $searchCounter.html(counterCurrent + ' из ' + counterMax);

                                    $searchClear.show();
                                    $searchCounter.show();
                                    $searchDown.show();
                                    $searchUp.show();
                                }
                                else
                                {
                                    $searchText.addClass('Error');
                                }
                            }
                        }

                        $searchText.keyup(function(event) 
                        {
                            counterCurrent = 1;
                            var searchValue = jQuery(this).val();
                            if (searchValue.length > 0)
                            {
                                var $items = $itemsContainer.find('.Item');
                                $items.each(function ()
                                {
                                    var $item = jQuery(this);
                                    var $label = $item.find('label');
                                    if ($label.html().toUpperCase().indexOf(jQuery.trim(searchValue).toUpperCase()) != -1)
                                    {
                                        $item.addClass('Highlighted');
                                    }
                                    else
                                    {
                                        $item.removeClass('Highlighted');
                                    }
                                });
                            }
                            SetSearchNavigation();
                        });

                        $searchClear.click( function() 
                        {
                            $searchText.val('');
                            SetSearchNavigation();
                        });

                        function ScrollToHotel() {
                            var $highlighted = $itemsContainer.find('.Highlighted');
                            if ($highlighted.length != counterMax)
                            {
                                return;
                            }
                            var $current = jQuery($highlighted[counterCurrent - 1]);
                            var $items = $itemsContainer.find('.Item');

                            var index = 0;
                            for (index = 0; index < $items.length; index++) 
                            {
                                if ($items[index] === $current[0])
                                {
                                    break;
                                }
                            }

                            var newScroll = 0;
                            var $upper = $itemsContainer.find('.Item:lt(' + index + ')');
                            $upper.each (function () 
                            {
                                newScroll += jQuery(this).outerHeight();
                                newScroll += jQuery(this).css('margin-bottom').replace('px', '') * 1;
                            });
                            $itemsContainer.scrollTop(newScroll+1);                           
                        }

                        $searchUp.click( function () 
                        {
                            if (counterCurrent > 1)
                            {
                                counterCurrent--;
                            }
                            ScrollToHotel();
                            SetSearchNavigation();
                        });

                        $searchDown.click(function ()
                        {
                            if (counterCurrent < counterMax)
                            {
                                counterCurrent++;
                            }
                            ScrollToHotel();
                            SetSearchNavigation();
                        });

                        //Initialization
                        if ($urlValue.val().length > 0)
                        {
                            $paneTitle.html('Загрузка...');
                            that.LoadHotels();
                        }
                        else
                        {
                            SetupAll();
                        }
					};
				}

				//Add $this parameter to settings to provide easy way to get link to DOM
                settings.$this = jQuery(this);
                data = new CTSHotelPicker(settings);
            }
            $(this).data('CTSHotelPicker', data);
            return data;
        }
    };

    $.fn.CTSHotelPicker = function (method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            jQuery.error('Method ' + method + ' does not exist on jQuery.CTSHotelPicker');
        }

    };

})(jQuery);

