/**
 * Observer - Observe formelements for changes
 *
 * - Additional code from clientside.cnet.com
 *
 * @version		1.1
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */
var Ria_Hotel_Autocompleter_Observer = new Class({

	Implements: [Options, Events],

	options: {
		periodical: false,
		delay: 1000
	},

	initialize: function(el, onFired, options){
		this.element = $(el) || $$(el);
		this.addEvent('onFired', onFired);
		this.setOptions(options);
		this.bound = this.changed.bind(this);
		this.resume();
	},

	changed: function() {
		var value = this.element.get('value');
		if ($equals(this.value, value)) return;
		this.clear();
		this.value = value;
		this.timeout = this.onFired.delay(this.options.delay, this);
	},

	setValue: function(value) {
        this.value = value;
		this.element.set('value', value);
		return this.clear();
	},

	onFired: function() {
		this.fireEvent('onFired', [this.value, this.element]);
	},

	clear: function() {
		$clear(this.timeout || null);
		return this;
	},

	pause: function(){
		if (this.timer) $clear(this.timer);
		else this.element.removeEvent('keyup', this.bound);
		return this.clear();
	},

	resume: function(){
		this.value = this.element.get('value');
		if (this.options.periodical) this.timer = this.changed.periodical(this.options.periodical, this);
		else this.element.addEvent('keyup', this.bound);
		return this;
	}

});

var $equals = function(obj1, obj2) {
	return (obj1 == obj2 || JSON.encode(obj1) == JSON.encode(obj2));
};
    // Calendar: a Javascript class for Mootools that adds accessible and unobtrusive date pickers to your form elements <http://electricprism.com/aeron/calendar>
    // Calendar RC4, Copyright (c) 2007 Aeron Glemann <http://electricprism.com/aeron>, MIT Style License.
    // Mootools 1.2 compatibility by Davorin Šego
    // This Class was modified by ANDREY KOTULSKIY last changes was made by 26.03.2009
    // Added notSelected options for calendar with non selected date by dafault,
    // added metod readnonselect: that set default date after first click (year set in fullyar format)


    var Calendar = new Class({

        Implements: Options,

        options: {
            blocked: [], // blocked dates
            classes: [], // ['calendar', 'prev', 'next', 'month', 'year', 'today', 'invalid', 'valid', 'inactive', 'active', 'hover', 'hilite']
            days: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'], // days of the week starting at sunday
            direction: 0, // -1 past, 0 past + future, 1 future
            draggable: false,
            months: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
            nazvaday:['День'],
            navigation: 1, // 0 = no nav; 1 = single nav for month; 2 = dual nav for month and year
            offset: 0, // first day of the week: 0 = sunday, 1 = monday, etc..
            onHideStart: Class.empty,
            onHideComplete: Class.empty,
            onShowStart: Class.empty,
            onShowComplete: Class.empty,
            pad: 1, // padding between multiple calendars
            tweak: {
                x: 0,
                y: 0,
                sdvig: 0
            }, // tweak calendar positioning (sdvig - na ckolyko sdvigaty kalendary chtob on ne otkrivalsya nige okna brouzera)
            positionAfter: 0, // position 0 - Before element, 1- AfterElement
            notSelected: 0
        },

        // initialize: calendar constructor
        // @param obj (obj) a js object containing the form elements and format strings { id: 'format', id: 'format' etc }
        // @param props (obj) optional properties

        initialize: function(obj, options) {

            // basic error checking
            if (!obj) {
                return false;
            }

            this.setOptions(options);
            //this.option = options;

            // create our classes array
            var keys = ['calendar', 'prev', 'next', 'month', 'year', 'today', 'invalid', 'valid', 'inactive', 'active', 'hover', 'hilite'];

            var values = keys.map(function(key, i) {
                if (this.options.classes[i]) {
                    if (this.options.classes[i].length) {
                        key = this.options.classes[i];
                    }
                }
                return key;
            }, this);

            this.classes = values.associate(keys);

            // create cal element with css styles required for proper cal functioning
            this.calendar = new Element('div', {
                'styles': {
                    left: '-1000px',
                    opacity: 0,
                    position: 'absolute',
                    top: '-1000px',
                    zIndex: 1000
                }
            }).addClass(this.classes.calendar).injectInside(document.body);

            // iex 6 needs a transparent iframe underneath the calendar in order to not allow select elements to render through
            if (window.ie6) {
                this.iframe = new Element('iframe', {
                    'styles': {
                        left: '-1000px',
                        position: 'absolute',
                        top: '-1000px',
                        zIndex: 999
                    }
                }).injectInside(document.body);
                this.iframe.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
            }

            // initialize fade method
            this.fx = new Fx.Tween(this.calendar, {
                duration: 200,
                onStart: function() {
                    if (this.calendar.getStyle('opacity') == 0) { // show
                        if (window.ie6) {
                            this.iframe.setStyle('display', 'block');
                        }
                        this.calendar.setStyle('display', 'block');
                        this.fireEvent('onShowStart', this.element);
                    }
                    else { // hide
                        this.fireEvent('onHideStart', this.element);
                    }
                }.bind(this),
                onComplete: function() {
                    if (this.calendar.getStyle('opacity') == 0) { // hidden
                        this.calendar.setStyle('display', 'none');
                        if (window.ie6) {
                            this.iframe.setStyle('display', 'none');
                        }
                        this.fireEvent('onHideComplete', this.element);
                    }
                    else { // shown
                        this.fireEvent('onShowComplete', this.element);
                    }
                }.bind(this)
            });

            // initialize drag method
            if (window.Drag && this.options.draggable) {
                this.drag = new Drag.Move(this.calendar, {
                    onDrag: function() {
                        if (window.ie6) {
                            this.iframe.setStyles({
                                left: this.calendar.style.left,
                                top: this.calendar.style.top
                            });
                        }
                    }.bind(this)
                });
            }

            // create calendars array
            this.calendars = [];

            var id = 0;
            var d = new Date(); // today

            d.setDate(d.getDate() + this.options.direction.toInt()); // correct today for directional offset

            for (var i in obj) {
                var buttonid = 'button'+ id;
                var cal = {
                    button: new Element('button', {
                        'type': 'button',
                        'id': buttonid,
                        'onclick':'return false;'
                    }),
                    el: $(i),
                    els: [],
                    id: id++,
                    month: d.getMonth(),
                    visible: false,
                    year: d.getFullYear()
                };


                // fix for bad element (naughty, naughty element!)
                if (!this.element(i, obj[i], cal)) {
                    continue;
                }

                cal.el.addClass(this.classes.calendar);

                // create cal button.
                //If you want to add Calendar button before input elements use injectBefore
                //If you want use Callendar button after input elements use injectAfter
                //alert (cal.el);
                if (this.options.positionAfter) {
                    cal.button.addClass(this.classes.calendar).addEvent('click', function(cal) {
                        this.toggle(cal);
                    }.pass(cal, this)).injectAfter(cal.el);
                } else{
                    cal.button.addClass(this.classes.calendar).addEvent('click', function(cal) {
                        this.toggle(cal);
                    }.pass(cal, this)).injectBefore(cal.el);
                }

                // read in default value
                cal.val = this.read(cal);

                $extend(cal, this.bounds(cal)); // abs bounds of calendar

                $extend(cal, this.values(cal)); // valid days, months, years

                this.rebuild(cal);

                this.calendars.push(cal); // add to cals array
            }
        },


        // blocked: returns an array of blocked days for the month / year
        // @param cal (obj)
        // @returns blocked days (array)

        blocked: function(cal) {
            var blocked = [];
            var offset = new Date(cal.year, cal.month, 1).getDay(); // day of the week (offset)
            var last = new Date(cal.year, cal.month + 1, 0).getDate(); // last day of this month

            this.options.blocked.each(function(date){
                var values = date.split(' ');

                // preparation
                for (var i = 0; i <= 3; i++){
                    if (!values[i]){
                        values[i] = (i == 3) ? '' : '*';
                    } // make sure blocked date contains values for at least d, m and y
                    values[i] = values[i].contains(',') ? values[i].split(',') : new Array(values[i]); // split multiple values
                    var count = values[i].length - 1;
                    for (var j = count; j >= 0; j--){
                        if (values[i][j].contains('-')){ // a range
                            var val = values[i][j].split('-');
                            for (var k = val[0]; k <= val[1]; k++){
                                if (!values[i].contains(k)){
                                    values[i].push(k + '');
                                }
                            }
                            values[i].splice(j, 1);
                        }
                    }
                }

                // execution
                if (values[2].contains(cal.year + '') || values[2].contains('*')){
                    if (values[1].contains(cal.month + 1 + '') || values[1].contains('*')){
                        values[0].each(function(val){ // if blocked value indicates this month / year
                            if (val > 0){
                                blocked.push(val.toInt());
                            } // add date to blocked array
                        });

                        if (values[3]){ // optional value for day of week
                            for (var i = 0; i < last; i++){
                                var day = (i + offset) % 7;

                                if (values[3].contains(day + '')){
                                    blocked.push(i + 1); // add every date that corresponds to the blocked day of the week to the blocked array
                                }
                            }
                        }
                    }
                }
            }, this);

            return blocked;
        },


        // bounds: returns the start / end bounds of the calendar
        // @param cal (obj)
        // @returns obj

        bounds: function(cal) {

            // 1. first we assume the calendar has no bounds (or a thousand years in either direction)

            // by default the calendar will accept a millennium in either direction
            var start = new Date(1000, 0, 1); // jan 1, 1000
            var end = new Date(2999, 11, 31); // dec 31, 2999

            // 2. but if the cal is one directional we adjust accordingly
            var date = new Date().getDate() + this.options.direction.toInt();

            if (this.options.direction > 0) {
                //            alert (">");
                start = new Date();
                start.setDate(date + this.options.pad * cal.id);
            }

            if (this.options.direction < 0) {
                //            alert ("<");
                end = new Date();
                end.setDate(date - this.options.pad * (this.calendars.length - cal.id - 1));
            }

            // 3. then we can further filter the limits by using the pre-existing values in the selects
            cal.els.each(function(el) {
                if (el.get('tag') == 'select') {
                    if (el.format.test('(y|Y)')) { // search for a year select
                        var years = [];

                        el.getChildren().each(function(option) { // get options
                            var values = this.unformat(option.value, el.format);

                            if (!years.contains(values[0])) {
                                years.push(values[0]);
                            } // add to years array
                        }, this);

                        years.sort(this.sort);

                        if (years[0] > start.getFullYear()) {
                            d = new Date(years[0], start.getMonth() + 1, 0); // last day of new month

                            if (start.getDate() > d.getDate()) {
                                start.setDate(d.getDate());
                            }

                            start.setYear(years[0]);
                        }

                        if (years.getLast() < end.getFullYear()) {
                            d = new Date(years.getLast(), end.getMonth() + 1, 0); // last day of new month

                            if (end.getDate() > d.getDate()) {
                                end.setDate(d.getDate());
                            }

                            end.setYear(years.getLast());
                        }
                    }

                    if (el.format.test('(F|m|M|n)')) { // search for a month select
                        var months_start = [];
                        var months_end = [];

                        el.getChildren().each(function(option) { // get options
                            var values = this.unformat(option.value, el.format);

                            if ($type(values[0]) != 'number' || values[0] == years[0]) { // if it's a year / month combo for curr year, or simply a month select
                                if (!months_start.contains(values[1])) {
                                    months_start.push(values[1]);
                                } // add to months array
                            }

                            if ($type(values[0]) != 'number' || values[0] == years.getLast()) { // if it's a year / month combo for curr year, or simply a month select
                                if (!months_end.contains(values[1])) {
                                    months_end.push(values[1]);
                                } // add to months array
                            }
                        }, this);

                        months_start.sort(this.sort);
                        months_end.sort(this.sort);

                        if (months_start[0] > start.getMonth()) {
                            d = new Date(start.getFullYear(), months_start[0] + 1, 0); // last day of new month

                            if (start.getDate() > d.getDate()) {
                                start.setDate(d.getDate());
                            }

                            start.setMonth(months_start[0]);
                        }

                        if (months_end.getLast() < end.getMonth()) {
                            d = new Date(start.getFullYear(), months_end.getLast() + 1, 0); // last day of new month

                            if (end.getDate() > d.getDate()) {
                                end.setDate(d.getDate());
                            }

                            end.setMonth(months_end.getLast());
                        }
                    }
                }
            }, this);

            return {
                'start': start,
                'end': end
            };
        },


        // caption: returns the caption element with header and navigation
        // @param cal (obj)
        // @returns caption (element)

        caption: function(cal) {
            // start by assuming navigation is allowed
            var navigation = {
                prev: {
                    'month': true,
                    'year': true
                },
                next: {
                    'month': true,
                    'year': true
                }
            };

            // if we're in an out of bounds year
            if (cal.year == cal.start.getFullYear()) {
                navigation.prev.year = false;
                if (cal.month == cal.start.getMonth() && this.options.navigation == 1) {
                    navigation.prev.month = false;
                }
            }
            if (cal.year == cal.end.getFullYear()) {
                navigation.next.year = false;
                if (cal.month == cal.end.getMonth() && this.options.navigation == 1) {
                    navigation.next.month = false;
                }
            }

            // special case of improved navigation but months array with only 1 month we can disable all month navigation
            if ($type(cal.months) == 'array') {
                if (cal.months.length == 1 && this.options.navigation == 2) {
                    navigation.prev.month = navigation.next.month = false;
                }
            }

            var caption = new Element('caption');

            var prev = new Element('a').addClass(this.classes.prev).appendText('\x3c'); // <
            var next = new Element('a').addClass(this.classes.next).appendText('\x3e'); // >

            if (this.options.navigation == 2) {
                var month = new Element('span').addClass(this.classes.month).injectInside(caption);

                if (navigation.prev.month) {
                    prev.clone().addEvent('click', function(cal) {
                        this.navigate(cal, 'm', -1);
                    }.pass(cal, this)).injectInside(month);
                }

                month.adopt(new Element('span').appendText(this.options.months[cal.month]));

                if (navigation.next.month) {
                    next.clone().addEvent('click', function(cal) {
                        this.navigate(cal, 'm', 1);
                    }.pass(cal, this)).injectInside(month);
                }

                var year = new Element('span').addClass(this.classes.year).injectInside(caption);

                if (navigation.prev.year) {
                    prev.clone().addEvent('click', function(cal) {
                        this.navigate(cal, 'y', -1);
                    }.pass(cal, this)).injectInside(year);
                }

                year.adopt(new Element('span').appendText(cal.year));

                if (navigation.next.year) {
                    next.clone().addEvent('click', function(cal) {
                        this.navigate(cal, 'y', 1);
                    }.pass(cal, this)).injectInside(year);
                }
            }
            else { // 1 or 0
                if (navigation.prev.month && this.options.navigation) {
                    prev.clone().addEvent('click', function(cal) {
                        this.navigate(cal, 'm', -1);
                    }.pass(cal, this)).injectInside(caption);
                }

                caption.adopt(new Element('span').addClass(this.classes.month).appendText(this.options.months[cal.month]));

                caption.adopt(new Element('span').addClass(this.classes.year).appendText(cal.year));

                if (navigation.next.month && this.options.navigation) {
                    next.clone().addEvent('click', function(cal) {
                        this.navigate(cal, 'm', 1);
                    }.pass(cal, this)).injectInside(caption);
                }

            }

            return caption;
        },


        // changed: run when a select value is changed
        // @param cal (obj)

        changed: function(cal) {

            cal.val = this.read(cal); // update calendar val from inputs

            if (!cal.val) {
                cal.val = this.readnonselect(cal);
            }

            $extend(cal, this.values(cal)); // update bounds - based on curr month

            this.rebuild(cal); // rebuild days select
            // in case the same date was clicked the cal has no set date we should exit

            if (cal.val.getDate() < cal.days[0]) {
                cal.val.setDate(cal.days[0]);
            }
            if (cal.val.getDate() > cal.days.getLast()) {
                cal.val.setDate(cal.days.getLast());
            }

            cal.els.each(function(el) {	// then we can set the value to the field
                el.value = this.format(cal.val, el.format);
            }, this);

            this.check(cal); // checks other cals

            this.calendars.each(function(kal) { // update cal graphic if visible
                if (kal.visible) {
                    this.display(kal);
                }
            }, this);
        },


        // check: checks other calendars to make sure no overlapping values
        // @param cal (obj)

        check: function(cal) {


            this.calendars.each(function(kal, i) {
                //            alert (i);
                if (!kal.val){
                    kal.val=cal.start;
                }
                if (kal.val) { // if calendar has value set
                    var change = false;
                    if (i < cal.id) { // preceding calendar
                        var bound = new Date(Date.parse(cal.val));

                        bound.setDate(bound.getDate() - (this.options.pad * (cal.id - i)));
                        if (bound < kal.val) {
                            change = true;
                        }
                    }
                    if (i > cal.id) { // following calendar
                        var bound = new Date(Date.parse(cal.val));

                        bound.setDate(bound.getDate() + (this.options.pad * (i - cal.id)));
                        if (bound > kal.val) {
                            change = true;
                        }
                    }

                    if (change) {
                        if (kal.start > bound) {
                            bound = kal.start;
                        }
                        if (kal.end < bound) {
                            bound = kal.end;
                        }

                        kal.month = bound.getMonth();
                        kal.year = bound.getFullYear();

                        $extend(kal, this.values(kal));

                        // TODO - IN THE CASE OF SELECT MOVE TO NEAREST VALID VALUE
                        // IN THE CASE OF INPUT DISABLE

                        // if new date is not valid better unset cal value
                        // otherwise it would mean incrementally checking to find the nearest valid date which could be months / years away
                        kal.val = kal.days.contains(bound.getDate()) ? bound : null;

                        this.write(kal);

                        if (kal.visible) {
                            this.display(kal);
                        } // update cal graphic if visible
                    }
                    else{
                        var bound = new Date(Date.parse(cal.val));
                    }
                }
                else {
                    kal.month = cal.month;
                    kal.year = cal.year;
                }
            }, this);
        },


        // clicked: run when a valid day is clicked in the calendar
        // @param cal (obj)

        clicked: function(td, day, cal) {
            cal.val = (this.value(cal) == day) ? null : new Date(cal.year, cal.month, day); // set new value - if same then disable

            this.write(cal);

            // ok - in the special case that it's all selects and there's always a date no matter what (at least as far as the form is concerned)
            // we can't let the calendar undo a date selection - it's just not possible!!
            //		if (!cal.val) { cal.val = this.read(cal); }

            if (cal.val) {
                this.check(cal); // checks other cals
                this.toggle(cal); // hide cal
            }
            else { // remove active class and replace with valid
                td.addClass(this.classes.valid);
                td.removeClass(this.classes.active);
            }
        },


        // display: create calendar element
        // @param cal (obj)

        display: function(cal) {

            // 1. header and navigation
            this.calendar.empty(); // init div

            this.calendar.className = this.classes.calendar + ' ' + this.options.months[cal.month].toLowerCase();

            var div = new Element('div').injectInside(this.calendar); // a wrapper div to help correct browser css problems with the caption element

            var table = new Element('table').injectInside(div).adopt(this.caption(cal));

            // 2. day names
            var thead = new Element('thead').injectInside(table);

            var tr = new Element('tr').injectInside(thead);

            for (var i = 0; i <= 6; i++) {
                var th = this.options.days[(i + this.options.offset) % 7];

                tr.adopt(new Element('th', {
                    'title': th
                }).appendText(th.substr(0, 1)));
            }

            // 3. day numbers
            var tbody = new Element('tbody').injectInside(table);
            var tr = new Element('tr').injectInside(tbody);

            var d = new Date(cal.year, cal.month, 1);
            var offset = ((d.getDay() - this.options.offset) + 7) % 7; // day of the week (offset)
            var last = new Date(cal.year, cal.month + 1, 0).getDate(); // last day of this month
            var prev = new Date(cal.year, cal.month, 0).getDate(); // last day of previous month
            var active = this.value(cal); // active date (if set and within curr month)
            var valid = cal.days; // valid days for curr month
            var inactive = []; // active dates set by other calendars
            var hilited = [];
            this.calendars.each(function(kal, i) {
                if (kal != cal && kal.val) {
                    if (cal.year == kal.val.getFullYear() && cal.month == kal.val.getMonth()) {
                        inactive.push(kal.val.getDate());
                    }

                    if (cal.val) {
                        for (var day = 1; day <= last; day++) {
                            d.setDate(day);

                            if ((i < cal.id && d > kal.val && d < cal.val) || (i > cal.id && d > cal.val && d < kal.val)) {
                                if (!hilited.contains(day)) {
                                    hilited.push(day);
                                }
                            }
                        }
                    }
                }
            }, this);
            var d = new Date();
            var today = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); // today obv

            for (var i = 1; i < 43; i++) { // 1 to 42 (6 x 7 or 6 weeks)
                if ((i - 1) % 7 == 0) {
                    tr = new Element('tr').injectInside(tbody);
                } // each week is it's own table row

                var td = new Element('td').injectInside(tr);

                var day = i - offset;
                var date = new Date(cal.year, cal.month, day);

                var cls = '';

                if (day === active) {
                    cls = this.classes.active;
                } // active
                else if (inactive.contains(day)) {
                    cls = this.classes.inactive;
                } // inactive
                else if (valid.contains(day)) {
                    cls = this.classes.valid;
                } // valid
                else if (day >= 1 && day <= last) {
                    cls = this.classes.invalid;
                } // invalid

                if (date.getTime() == today) {
                    cls = cls + ' ' + this.classes.today;
                } // adds class for today

                if (hilited.contains(day)) {
                    cls = cls + ' ' + this.classes.hilite;
                } // adds class if hilited

                td.addClass(cls);

                if (valid.contains(day)) { // if it's a valid - clickable - day we add interaction
                    td.setProperty('title', this.format(date, 'D M jS Y'));

                    td.addEvents({
                        'click': function(td, day, cal) {
                            this.clicked(td, day, cal);
                        }.pass([td, day, cal], this),
                        'mouseover': function(td, cls) {
                            td.addClass(cls);
                        }.pass([td, this.classes.hover]),
                        'mouseout': function(td, cls) {
                            td.removeClass(cls);
                        }.pass([td, this.classes.hover])
                    });
                }

                // pad calendar with last days of prev month and first days of next month
                if (day < 1) {
                    day = prev + day;
                }
                else if (day > last) {
                    day = day - last;
                }

                td.appendText(day);
            }
        },


        // element: helper function
        // @param el (string) element id
        // @param f (string) format string
        // @param cal (obj)

        element: function(el, f, cal) {
            if ($type(f) == 'object') { // in the case of multiple inputs per calendar
                for (var i in f) {
                    if (!this.element(i, f[i], cal)) {
                        return false;
                    }
                }

                return true;
            }

            el = $(el);

            if (!el) {
                return false;
            }

            el.format = f;

            if (el.get('tag') == 'select') { // select elements allow the user to manually set the date via select option
                el.addEvent('change', function(cal) {
                    this.changed(cal);
                }.pass(cal, this));
            }
            else { // input (type text) elements restrict the user to only setting the date via the calendar
                el.readOnly = true;
                el.addEvent('focus', function(cal) {
                    this.toggle(cal);
                }.pass(cal, this));
            }

            cal.els.push(el);

            return true;
        },


        // format: formats a date object according to passed in instructions
        // @param date (obj)
        // @param f (string) any combination of punctuation / separators and d, j, D, l, S, m, n, F, M, y, Y
        // @returns string

        format: function(date, format) {
            var str = '';

            if (date) {
                var j = date.getDate(); // 1 - 31
                var w = date.getDay(); // 0 - 6
                var l = this.options.days[w]; // Sunday - Saturday
                var n = date.getMonth() + 1; // 1 - 12
                var f = this.options.months[n - 1]; // January - December
                var y = date.getFullYear() + ''; // 19xx - 20xx

                for (var i = 0, len = format.length; i < len; i++) {
                    var cha = format.charAt(i); // format char

                    switch(cha) {
                        // year cases
                        case 'y': // xx - xx
                            y = y.substr(2);
                        case 'Y': // 19xx - 20xx
                            str += y;
                            break;

                        // month cases
                        case 'm': // 01 - 12
                            if (n < 10) {
                                n = '0' + n;
                            }
                        case 'n': // 1 - 12
                            str += n;
                            break;

                        case 'M': // Jan - Dec
                            f = f.substr(0, 3);
                        case 'F': // January - December
                            str += f;
                            break;

                        // day cases
                        case 'd': // 01 - 31
                            if (j < 10) {
                                j = '0' + j;
                            }
                        case 'j': // 1 - 31
                            str += j;
                            break;

                        case 'D': // Sun - Sat
                            l = l.substr(0, 3);
                        case 'l': // Sunday - Saturday
                            str += l;
                            break;

                        case 'N': // 1 - 7
                            w += 1;
                        case 'w': // 0 - 6
                            str += w;
                            break;

                        case 'S': // st, nd, rd or th (works well with j)
                            if (j % 10 == 1 && j != '11') {
                                str += 'st';
                            }
                            else if (j % 10 == 2 && j != '12') {
                                str += 'nd';
                            }
                            else if (j % 10 == 3 && j != '13') {
                                str += 'rd';
                            }
                            else {
                                str += 'th';
                            }
                            break;

                        default:
                            str += cha;
                    }
                }
            }

            return str; //  return format with values replaced
        },


        // navigate: calendar navigation
        // @param cal (obj)
        // @param type (str) m or y for month or year
        // @param n (int) + or - for next or prev

        navigate: function(cal, type, n) {
            switch (type) {
                case 'm': // month
                    if ($type(cal.months) == 'array') {
                        var i = cal.months.indexOf(cal.month) + n; // index of current month

                        if (i < 0 || i == cal.months.length) { // out of range
                            if (this.options.navigation == 1) { // if type 1 nav we'll need to increment the year
                                this.navigate(cal, 'y', n);
                            }

                            i = (i < 0) ? cal.months.length - 1 : 0;
                        }

                        cal.month = cal.months[i];
                    }
                    else {
                        var i = cal.month + n;

                        if (i < 0 || i == 12) {
                            if (this.options.navigation == 1) {
                                this.navigate(cal, 'y', n);
                            }

                            i = (i < 0) ? 11 : 0;
                        }

                        cal.month = i;
                    }
                    break;

                case 'y': // year
                    if ($type(cal.years) == 'array') {
                        var i = cal.years.indexOf(cal.year) + n;

                        cal.year = cal.years[i];
                    }
                    else {
                        cal.year += n;
                    }
                    break;
            }

            $extend(cal, this.values(cal));

            if ($type(cal.months) == 'array') { // if the calendar has a months select
                var i = cal.months.indexOf(cal.month); // and make sure the curr months exists for the new year

                if (i < 0) {
                    cal.month = cal.months[0];
                } // otherwise we'll reset the month
            }


            this.display(cal);
        },


        // read: compiles cal value based on array of inputs passed in
        // @param cal (obj)
        // @returns date (obj) or (null)

        read: function(cal) {
            var arr = [null, null, null];

            cal.els.each(function(el) {
                // returns an array which may contain empty values
                var values = this.unformat(el.value, el.format);

                values.each(function(val, i) {
                    if ($type(val) == 'number') {
                        arr[i] = val;
                    }

                });
            }, this);

            // we can update the cals month and year values
            if ($type(arr[0]) == 'number') {
                cal.year = arr[0];
            }
            if ($type(arr[1]) == 'number') {
                cal.month = arr[1];
            }
            //        if (cal.notSelected == 1) { cal.month = cal.month;}

            var val = null;

            if (arr.every(function(i) {
                return $type(i) == 'number';
            })) { // if valid date
                var last = new Date(arr[0], arr[1] + 1, 0).getDate(); // last day of month

                if (arr[2] > last) {
                    arr[2] = last;
                } // make sure we stay within the month (ex in case default day of select is 31 and month is feb)

                val = new Date(arr[0], arr[1], arr[2]);
            }

            return (cal.val == val) ? null : val; // if new date matches old return null (same date clicked twice = disable)
        },

        // read: compiles cal value based on array of inputs passed in
        // @param cal (obj)
        // @returns date (obj) or (null)

        readnonselect: function(cal) {
            var arr = [null, null, null];

            cal.els.each(function(el) {
                // returns an array which may contain empty values
                var values = this.unformat(el.value, el.format);

                values.each(function(val, i) {
                    if ($type(val) == 'number') {
                        arr[i] = val;
                    }

                });
            }, this);

            // we can update the cals month and year values
            if ($type(arr[0]) == 'number') {
                cal.year = arr[0];
            }
            if ($type(arr[1]) == 'number') {
                cal.month = arr[1];
            }
            if ($type(arr[0]) != 'number') {
                cal.year = cal.start.getFullYear();
                arr[0] = cal.start.getFullYear();
            }
            if ($type(arr[1]) != 'number') {
                cal.month = cal.start.getMonth();
                arr[1] = cal.start.getMonth();
            }
            if ($type(arr[2]) != 'number') {
                cal.dey = cal.start.getDate();
                arr[2] = cal.start.getDate();
            }

            var val = null;

            if (arr.every(function(i) {
                return $type(i) == 'number';
            })) { // if valid date
                var last = new Date(arr[0], arr[1] + 1, 0).getDate(); // last day of month

                if (arr[2] > last) {
                    arr[2] = last;
                } // make sure we stay within the month (ex in case default day of select is 31 and month is feb)

                val = new Date(arr[0], arr[1], arr[2]);
            }

            return (cal.val == val) ? null : val; // if new date matches old return null (same date clicked twice = disable)
        },


        // rebuild: rebuilds days + months selects
        // @param cal (obj)

        rebuild: function(cal) {
            cal.els.each(function(el) {
                /*
    if (el.get('tag') == 'select' && el.format.test('^(F|m|M|n)$')) { // special case for months-only select
    if (!cal.options) { cal.options = el.clone(); } // clone a copy of months select

    var val = (cal.val) ? cal.val.getMonth() : el.value.toInt();

    el.empty(); // initialize select

    cal.months.each(function(month) {
    // create an option element
    var option = new Element('option', {
    'selected': (val == month),
    'value': this.format(new Date(1, month, 1), el.format);
    }).appendText(day).injectInside(el);
    }, this);
    }
    */

                if (el.get('tag') == 'select' && el.format.test('^(d|j)$')) { // special case for days-only select
                    var d = this.value(cal);

                    if (!d) {
                        d = el.value.toInt();
                    } // if the calendar doesn't have a set value, try to use value from select

                    el.empty(); // initialize select
                    if (this.options.notSelected == 1){
                        var option = new Element('option', {
                            'selected': '',
                            'value': ''
                        }).appendText(this.options.nazvaday).injectInside(el);
                    }

                    cal.days.each(function(day) {
                        // create an option element
                        var option = new Element('option', {
                            'selected': (d == day),
                            'value': ((el.format == 'd' && day < 10) ? '0' + day : day)
                        }).appendText(day).injectInside(el);
                    }, this);
                }
            }, this);
        },


        // sort: helper function for numerical sorting

        sort: function(a, b) {
            return a - b;
        },


        // toggle: show / hide calendar
        // @param cal (obj)

        toggle: function(cal) {
            document.removeEvent('mousedown', this.fn); // always remove the current mousedown script first

            if (cal.visible) { // simply hide curr cal
                cal.visible = false;
                cal.button.removeClass(this.classes.active); // active

                this.fx.start('opacity', 1, 0);
            }
            else { // otherwise show (may have to hide others)
                // hide cal on out-of-bounds click
                this.fn = function(e, cal) {
                    var e = new Event(e);

                    var el = e.target;

                    var stop = false;

                    while (el != document.body && el.nodeType == 1) {
                        if (el == this.calendar) {
                            stop = true;
                        }
                        this.calendars.each(function(kal) {
                            if (kal.button == el || kal.els.contains(el)) {
                                stop = true;
                            }
                        });

                        if (stop) {
                            e.stop();
                            return false;
                        }
                        else {
                            el = el.parentNode;
                        }
                    }

                    this.toggle(cal);
                }.create({
                    'arguments': cal,
                    'bind': this,
                    'event': true
                });

                document.addEvent('mousedown', this.fn);

                this.calendars.each(function(kal) {
                    if (kal == cal) {
                        kal.visible = true;
                        kal.button.addClass(this.classes.active); // css c-icon-active
                    }
                    else {
                        kal.visible = false;
                        kal.button.removeClass(this.classes.active); // css c-icon-active
                    }
                }, this);

                var size = window.getScrollSize();

                var coord = cal.button.getCoordinates();

                var x = coord.right + this.options.tweak.x;
                var y = coord.top + this.options.tweak.y;

                //Меняем положение календаря если он будет
                //открыт вне окна
                if (window.ie6) {

                }else{
                    var posit = window.getScroll();
                    var calposit = $(cal.el).getCoordinates();
                    var vindow = window.getSize();
                    var visible = calposit.top - posit.y + 160;
                    if (visible > vindow.y ){
                        var y = coord.top + this.options.tweak.y - this.options.tweak.sdvig;
                    }
                }
                //
                // make sure the calendar doesn't open off screen
                if (!this.calendar.coord) {
                    this.calendar.coord = this.calendar.getCoordinates();
                }

                if (x + this.calendar.coord.width > size.x) {
                    x -= (x + this.calendar.coord.width - size.x);
                }
                if (y + this.calendar.coord.height > size.y) {
                    y -= (y + this.calendar.coord.height - size.y);
                }

                this.calendar.setStyles({
                    left: x + 'px',
                    top: y + 'px'
                });

                if (window.ie6) {
                    this.iframe.setStyles({
                        height: this.calendar.coord.height + 'px',
                        left: x + 'px',
                        top: y + 'px',
                        width: this.calendar.coord.width + 'px'
                    });
                }

                this.display(cal);

                this.fx.start('opacity', 0, 1);
            }
        },


        // unformat: takes a value from an input and parses the d, m and y elements
        // @param val (string)
        // @param f (string) any combination of punctuation / separators and d, j, D, l, S, m, n, F, M, y, Y
        // @returns array

        unformat: function(val, f) {
            f = f.escapeRegExp();

            var re = {
                d: '([0-9]{2})',
                j: '([0-9]{1,2})',
                D: '(' + this.options.days.map(function(day) {
                    return day.substr(0, 3);
                }).join('|') + ')',
                l: '(' + this.options.days.join('|') + ')',
                S: '(st|nd|rd|th)',
                F: '(' + this.options.months.join('|') + ')',
                m: '([0-9]{2})',
                M: '(' + this.options.months.map(function(month) {
                    return month.substr(0, 3);
                }).join('|') + ')',
                n: '([0-9]{1,2})',
                Y: '([0-9]{4})',
                y: '([0-9]{2})'
            }

            var arr = []; // array of indexes

            var g = '';

            // convert our format string to regexp
            for (var i = 0; i < f.length; i++) {
                var c = f.charAt(i);

                if (re[c]) {
                    arr.push(c);

                    g += re[c];
                }
                else {
                    g += c;
                }
            }

            // match against date
            var matches = val.match('^' + g + '$');

            var dates = new Array(3);

            if (matches) {
                matches = matches.slice(1); // remove first match which is the date

                arr.each(function(c, i) {
                    i = matches[i];

                    switch(c) {
                        // year cases
                        case 'y':
                            i = '19' + i; // 2 digit year assumes 19th century (same as JS)
                        case 'Y':
                            dates[0] = i.toInt();
                            break;

                        // month cases
                        case 'F':
                            i = i.substr(0, 3);
                        case 'M':
                            i = this.options.months.map(function(month) {
                                return month.substr(0, 3);
                            }).indexOf(i) + 1;
                        case 'm':
                        case 'n':
                            dates[1] = i.toInt() - 1;
                            break;

                        // day cases
                        case 'd':
                        case 'j':
                            dates[2] = i.toInt();
                            break;
                    }
                }, this);
            }

            return dates;
        },


        // value: returns day value of calendar if set
        // @param cal (obj)
        // @returns day (int) or null

        value: function(cal) {
            var day = null;

            if (cal.val) {
                if (cal.year == cal.val.getFullYear() && cal.month == cal.val.getMonth()) {
                    day = cal.val.getDate();
                }
            }

            return day;
        },


        // values: returns the years, months (for curr year) and days (for curr month and year) for the calendar
        // @param cal (obj)
        // @returns obj

        values: function(cal) {
            var years, months, days;

            cal.els.each(function(el) {
                if (el.get('tag') == 'select') {
                    if (el.format.test('(y|Y)')) { // search for a year select
                        years = [];

                        el.getChildren().each(function(option) { // get options
                            var values = this.unformat(option.value, el.format);

                            if (!years.contains(values[0])) {
                                years.push(values[0]);
                            } // add to years array
                        }, this);

                        years.sort(this.sort);
                    }

                    if (el.format.test('(F|m|M|n)')) { // search for a month select
                        months = []; // 0 - 11 should be

                        el.getChildren().each(function(option) { // get options
                            var values = this.unformat(option.value, el.format);

                            if ($type(values[0]) != 'number' || values[0] == cal.year) { // if it's a year / month combo for curr year, or simply a month select
                                if (!months.contains(values[1])) {
                                    months.push(values[1]);
                                } // add to months array
                            }
                        }, this);

                        months.sort(this.sort);
                    }

                    if (el.format.test('(d|j)') && !el.format.test('^(d|j)$')) { // search for a day select, but NOT a days only select
                        days = []; // 1 - 31

                        el.getChildren().each(function(option) { // get options
                            var values = this.unformat(option.value, el.format);

                            // in the special case of days we dont want the value if its a days only select
                            // otherwise that will screw up the options rebuilding
                            // we will take the values if they are exact dates though
                            if (values[0] == cal.year && values[1] == cal.month) {
                                if (!days.contains(values[2])) {
                                    days.push(values[2]);
                                } // add to days array
                            }
                        }, this);
                    }
                }
            }, this);

            // we start with what would be the first and last days were there no restrictions
            var first = 1;
            var last = new Date(cal.year, cal.month + 1, 0).getDate(); // last day of the month

            // if we're in an out of bounds year
            if (cal.year == cal.start.getFullYear()) {
                // in the special case of improved navigation but no months array, we'll need to construct one
                if (months == null && this.options.navigation == 2) {
                    months = [];

                    for (var i = 0; i < 12; i ++) {
                        if (i >= cal.start.getMonth()) {
                            months.push(i);
                        }
                    }
                }

                // if we're in an out of bounds month
                if (cal.month == cal.start.getMonth()) {
                    first = cal.start.getDate(); // first day equals day of bound
                }
            }
            if (cal.year == cal.end.getFullYear()) {
                // in the special case of improved navigation but no months array, we'll need to construct one
                if (months == null && this.options.navigation == 2) {
                    months = [];

                    for (var i = 0; i < 12; i ++) {
                        if (i <= cal.end.getMonth()) {
                            months.push(i);
                        }
                    }
                }

                if (cal.month == cal.end.getMonth()) {
                    last = cal.end.getDate(); // last day equals day of bound
                }
            }

            // let's get our invalid days
            var blocked = this.blocked(cal);

            // finally we can prepare all the valid days in a neat little array
            if ($type(days) == 'array') { // somewhere there was a days select
                days = days.filter(function(day) {
                    if (day >= first && day <= last && !blocked.contains(day)) {
                        return day;
                    }
                });
            }
            else { // no days select we'll need to construct a valid days array
                days = [];

                for (var i = first; i <= last; i++) {
                    if (!blocked.contains(i)) {
                        days.push(i);
                    }
                }
            }

            days.sort(this.sort); // sorting our days will give us first and last of month

            return {
                'days': days,
                'months': months,
                'years': years
            };
        },


        // write: sets calendars value to form elements
        // @param cal (obj)

        write: function(cal) {
            this.rebuild(cal);	 // in the case of options, we'll need to make sure we have the correct number of days available

            cal.els.each(function(el) {	// then we can set the value to the field
                el.value = this.format(cal.val, el.format);
            }, this);
        }
    });

    Calendar.implement(new Events, new Options);
/**
* @class      Ria_Hotel_TipManager
*/
var Ria_Hotel_FormTips = new Class({
    
    Implements: Options,
    
    options: {
        id: null,
        el: null,
        closeBtn: false,
        className: 'tool-popup tool-popup_left',
        offset:{
            x: 0,
            y: 0
        },
        width: '250px',
        text: 'Сюда нада текст...',
        callback: function () {
            
        }
    },
    prefix: 'tip-',
    
    initialize: function(options){
        if (!options.el) {
            return false;
        }
        this.setOptions(options);
        this.elCoor = this.options.el.getPosition();
        this.options.offset.x = this.options.offset.x + this.elCoor.x + this.options.el.getWidth();
        this.options.offset.y = this.elCoor.y - this.options.el.getHeight() - this.options.offset.y;
        this.prepareTip();
    },
    prepareTip: function () {
        if ($defined($(this.options.id))) {
            return false;
        }
        this.tip = new Element('div',{
            id: this.options.id,
            'class': this.options.className,
            styles:{
                'opacity': 0,
                'position': 'absolute',
                'visibility': 'hidden',
                'width': this.options.width
            }
        }).setPosition(this.options.offset);
        var text = new Element('div', {
            html: this.options.text
        }).inject(this.tip);
        if (this.options.closeBtn) {
            var closeIco = new Element('div', {
                'class': 'close-butt',
                styles: {
                    'position': 'absolute',
                    'right': 0,
                    'z-index': '5',
                    'top': 0
                },
                events: {
                    click: function () {
                        this.hide();
                    }.bind(this)
                }
            }).inject(this.tip);
        }
        this.tip.inject(document.body);
    },
    
    show: function () {
        if ($defined(this.tip)) {
            this.tip.setStyle('opacity', 1);
        } else if($defined($(this.options.id))) {
            $(this.options.id).setStyle('opacity', 1);
        }
        
    },
    
    hide: function () {
         if ($defined(this.tip)) {
            this.tip.set('style', '');
            this.tip.dispose();
            this.options.callback();
        } else if($defined($(this.options.id))) {
            $(this.options.id).setStyle('opacity', 1);
            $(this.options.id).set('style', '');
            $(this.options.id).dispose();
        }
    }
});
/**
 * Description
 *
 * @class Ria_Core_Common_ScrollingManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 */
var Ria_Common_ScrollingManager = new Class({

    Implements: Options,

    options: {
        'duration'         : 333,
        'scrollStep'       : 50,
        'offsetTop'        : 20
    },

    initialize: function(scrollToId, options){
        this.setOptions(options);
        this.el = scrollToId;

        if ($defined($(this.el))){
            if ($defined(Fx)){
                 this.fxScroll();
            } else {
                this.devScroll();
            }
        }
    },
    
    fxScroll: function(){
        var scroll = new Fx.Scroll(document, {
            wait: false, 	
            duration: this.options.duration, 	
            transition: Fx.Transitions.Quad.easeInOut
        });
        $(this.el).measure(function(){
            scroll.toElement(this.el).start();
        }.bind(this));
    },
    
    devSrcoll:function(){
        var posit = window.getScroll();
        var koordiv = $(this.el).getCoordinates();
        var koord = koordiv.top - this.options.offsetTop;

        var currentY = posit.y;
        if (currentY < koord){
            while (currentY < koord){
                currentY = currentY + this.options.scrollStep;
                if (currentY > koord) currentY = koord;
                self.scroll(1, currentY);
            }
        }
        if (currentY > koord){
            while (currentY > koord){
                currentY = currentY - this.options.scrollStep;
                if (currentY < koord) currentY = koord;
                self.scroll(1, currentY);
            }
        }
    }

});
/**
 * Определение переменных для работы Ajax RIA Framework
 *
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    $Id: Ajax.js,v 1.2 2009/03/09 13:17:34 demonit Exp $
 */
var Ria_Ajax = {
	'script': 'ajax.php'
};

/**
 * Класс прорисовывает анимированный gif в указанном div элементе   
 *
 * @class Ria_Common_StatusImageManager2
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
*/
var Ria_Common_StatusImageManager2 = new Class({

    Implements: Options,

    options: {
        'elementId'         : null,
        'status'            : 'spinner',
        'fadeEffect'        : false,

        'spinnerImg'        : 'http://css.ria.ua/icons/gifs/spinner_grey.gif',
        'checkImg'          : 'http://css.ria.ua/icons/gifs/checkbullet.gif',
        'errorImg'          : 'http://css.ria.ua/icons/gifs/error_bang.gif'
    },
	
    initialize: function(options){
        this.setOptions(options);

        if (this.options.elementId) this.showStatusImg();
    },
	
    showStatusImg:function (){
        var imgSrc = '';
        if (this.options.status == 'spinner'){
            imgSrc = this.options.spinnerImg;
        } else if (this.options.status == 'check'){
            imgSrc = this.options.checkImg;
        } else if (this.options.status == 'error'){
            imgSrc = this.options.errorImg;
        }
		
        if (imgSrc){
            var statusDiv = $(this.options.elementId).empty();

            var element = new Element('img', {
                'src': imgSrc
            }).injectTop(statusDiv);

            if (this.options.fadeEffect){
                new Fx.Style(element, 'opacity', {
                    duration:3000
                }).addEvent('complete', function() {
                    $(this.options.elementId).empty();
                }.bind(this)).start(1, 0);
            }
        }
		
    }
	
});
/**
 * Определение переменных для работы GetHotelBlockDetail
 *
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    $Id: Load.js,v 1.1 2008/10/28 13:19:20 kotulski Exp $
 */
var Ria_Hotel_Load = {
	'TimeoutFlag': '1',
	'IdKnopka':'',
	'Krutilka':'',
	'Text':''
};
/**
 * Description
 *
 * @class Ria_Hotel_TabSwitcher
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 */
var Ria_Hotel_TabSwitcher = new Class({

    Implements: Options,
    
    initialize: function(activeTab, options){
        this.setOptions(options);
        this.setupTabEvents();
        this.switchTab(activeTab, false);
    },

    setupTabEvents: function(){
        $each(this.options, function(value, key){
            $(key).addEvent('click', function(ext) {
                if ($type(ext) == 'event') ext=false;
                this.switchTab(key, ext);
            }.bind(this));
        }, this);
    },

    switchTab: function(activeTab, ext){
        $each(this.options, function(value, key){
            if (activeTab == key){
                value.activateClassName = value.activateClassName || 'tabs-horiz-li-link_active';
                $(value.tabDiv).setStyle('display', 'block');
                $(key).setProperty('class', value.tabClass +' '+ value.activateClassName);
                if (!ext){
                    if ($chk($(value.extendedTab))){
                        $(value.extendedTab).fireEvent('click', true);
                    }
                }
            } else {
                $(value.tabDiv).setStyle('display', 'none');
                $(key).setProperty('class', value.tabClass);
            }
        });
    }
});
/**
 * Класс для добавления в избранное
 *
 * @class      Ria_Hotel_AddFavorite
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    
 */
var Ria_Hotel_AddFavorite = new Class({


    initialize: function (button){
        this.add2Fav(button);
    },
         
       add2Fav:function (x){
       if (navigator.userAgent.indexOf('Chrome')>=0){
            alert('К сожалению, в Google Chrome нет метода для программного добавления в Закладки... нажмите CTRL+D');
            return false;
       };
       
        if (document.all && !window.opera) {
            if (typeof window.external == "object") {
                window.external.AddFavorite(document.location, document.title);
                return true;
            }
            else return false;

        }
        else{
            x.href=document.location;
            x.title=document.title;
            x.rel = "sidebar";
            return true;
        }
    }
});


/**
    * class RIA Hotel, add block info to search/hotels pages via HTML Request
    *
    * @class      Ria_Hotel_PageTrackerManager
    * @copyright  2008 IT RIA
    * @license    GNU GPL v2
    * @version
    */
var Ria_Hotel_PageTrackerManager = new Class({

    initialize: function(APPLICATION_ENV){
        this.applicationEnv = APPLICATION_ENV;
    },

    trackEvent : function (category, event, label){
        if (this.applicationEnv == 'production' && $defined(pageTracker)) {
            pageTracker._trackEvent(category, event, label || '');
        }
    },

    trackSocial : function (network, socialAction, opt_target, opt_pagePath){
        if (this.applicationEnv == 'production' && $defined(pageTracker)) {
            pageTracker._trackSocial(network, socialAction, opt_target, opt_pagePath || '');
        }
    }
});

/**
 * Ria_Common_Tip
 *
 * @class Ria_Common_Tip
 * @copyright  2010 IG RIA
 * @version    ID:
 */

var Ria_Hotel_Images_Tip=new Class ({
    Implements : [Events, Options],
    options : {
        onShow : function (){
            this.tip.setStyle("display", "block");
        },
        onHide : function (){
            this.tip.setStyle("display", "none");
        },
        onComplete : function (){
        },

        title : "title",
        text : function (b){
            return b.get("rel") || b.get("href");
        },
        showDelay : 100,
        hideDelay : 100,
        className : "tip",
        hideFlash : false,
        showEvent : "mouseover",
        withoutEvent:false,
        offset : {
            x : 10,
            y : 15
        },
        windowPadding : {
            x : 0,
            y : 0
        }
    },

    initialize : function () {
        var b=Array.link(arguments, {
            options : Object.type,
            elements : $defined
        });
        this.setOptions(b.options);
        if (b.elements && this.options.withoutEvent==false) this.attach(b.elements);
        this.tip=new Element("div", {
            "class" : this.options.className,
            styles:{
                display:"none",
                'z-index': 1000,
                position: "absolute"
            }
        })
        if ($defined(this.options.id)) this.tip.setProperty('id', this.options.id);
    },

    attach : function (elements) {
        $$(elements).each(function (element){
            element.addEvent(this.options.showEvent, function(){
                this.isElementOver=true;
                this.show(element)
            }.bind(this))
        }, this)
        return this
    },

    destroy : function (){
        this.tip.dispose()
    },

    show : function (element){
        this.tip.empty();
        new Element("div", {
            "class" : "tip-top"
        }).inject(this.tip);
        ["title", "text"].each(function (type){
            var attribute=element.getProperty(eval('this.options.'+type));
            if (attribute) {
                new Element("div", {
                    "class" : "tip-" + type,
                    "html" : attribute
                }).inject(this.tip)
            }
        }, this)
        new Element("div", {
            "class" : "tip-bottom"
        }).inject(this.tip)
        this.tip.inject(document.body);
        this.tip.addEvent("mouseover", function(){
            this.isTipOver=true
        }.bind(this))
        this.tip.addEvent("mouseout", function(){
            this.isTipOver=false;
            element.fireEvent("mouseout")
        }.bind(this))
        $clear(this.timer);
        this.timer=(function (){
            this.fireEvent("show");
            this.position({
                page : element.getPosition()
            });
            if (this.options.hideFlash && !Browser.Engine.trident) this.hideFlash();
            this.fireEvent("complete");
            element.addEvent("mouseout", function(){
                this.isElementOver=false;
                $clear(this.timerHide);
                this.timerHide=(function (){
                    if (!this.isElementOver && !this.isTipOver){
                        this.fireEvent("hide")
                    }
                }.bind(this)).delay(this.options.hideDelay, this)
            }.bind(this))
        }).delay(this.options.showDelay, this)

    },

    hideFlash : function () {
        var clearRect=this.tip.getCoordinates();
        clearRect.left -= 10;
        clearRect.top -= 10;
        clearRect.right += 10;
        clearRect.bottom += 10;
        $$('object').each(function (element){
            var delRect=element.getCoordinates();
            delRect.right=delRect.left + element.getProperty('width').toInt();
            delRect.bottom=delRect.top + element.getProperty('height').toInt();
            if (this.inRectangle(clearRect, delRect)) element.setStyle('visibility', 'hidden')
        }, this)
    },

    inRectangle : function (R1, R2){
        return ((
            ((R1.left <= R2.left) && (R1.right >= R2.left)) ||
            ((R2.left <= R1.left) && (R2.right >= R1.left))
            ) && (
            ((R1.top <= R2.top) && (R1.bottom >= R2.top)) ||
            ((R2.top <= R1.top) && (R2.bottom >= R1.top))
            ))
    },

    hide : function () {
        this.fireEvent("hide");
        this.tip.dispose()
    },

    position : function (element) {

        var windowSize=window.getSize(), scroll=window.getScroll(),
        offset={
            x : this.tip.offsetWidth,
            y : this.tip.offsetHeight
        },
        properties={
            x : "left",
            y : "top"
        },
        style={};
        for (var styleProperty in properties) {
            style[properties[styleProperty]]=element.page[styleProperty] + this.options.offset[styleProperty];
        }
        this.tip.setStyles(style);
    }
});
/**
 * 
 * @class      Ria_Hotel_ShowOrHideBlock
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    
 */
var Ria_Hotel_ShowOrHideBlock = new Class ({
    Implements: [Options],
    options: {
        first: 'Скрыть',
        second: 'Подробнее...',
        appText:''
    },
    initialize : function (options)
    {   
        this.setOptions(options);
        this.options.el = new Element('span', {
            id: 'appText',
            html: this.options.appText
        });
    },
    doIt : function (link, item) {
        var self = this;
        link.addEvent('click', function (e){
            if (item.isDisplayed()) {
                item.addClass('displayNoneRule');
                link.set('html', self.options.second);
                self.options.el.inject(item.getParent().getFirst())
            } else {
                item.removeClass('displayNoneRule');
                link.set('html', self.options.first);
                if ($defined($('appText'))){
                    $('appText').dispose();
                }
            }
        });
    }
});
/**
Script: Slideshow.js
	Slideshow - A javascript class for Mootools to stream and animate the presentation of images on your website.

License:
	MIT-style license.

Copyright:
	Copyright (c) 2011 [Aeron Glemann](http://www.electricprism.com/aeron/).

Dependencies:
	Mootools 1.3.1 Core: Fx.Morph, Fx.Tween, Selectors, Element.Dimensions.
	Mootools 1.3.1.1 More: Assets.
*/
(function(){
	WhenPaused = 1 << 0;
	WhenPlaying = 1 << 1;
	OnStart = 1 << 2;
	
	Ria_Hotel_Images_Slideshow = new Class({
		Implements: [Chain, Events, Options],

		options: {/*
			onComplete: $empty,
			onEnd: $empty,
			onStart: $empty,*/
		    accesskeys: {'first': {'key': 'shift left', 'label': 'Shift + Leftwards Arrow'}, 'prev': {'key': 'left', 'label': 'Leftwards Arrow'}, 'pause': {'key': 'p', 'label': 'P'}, 'next': {'key': 'right', 'label': 'Rightwards Arrow'}, 'last': {'key': 'shift right', 'label': 'Shift + Rightwards Arrow'}},
			captions: true,
			center: true,
			classes: [/*'slideshow', 'first', 'prev', 'play', 'pause', 'next', 'last', 'images', 'captions', 'controller', 'thumbnails', 'hidden', 'visible', 'inactive', 'active', 'loader'*/],
			controller: true,
			data: null,
			delay: 2000,
			duration: 1000,//скорость смены картинки через прозрачность предыдущей
			fast: false, //переключать картинки быстро не используя duration
			height: false,//высота
			href: 'http://hotels24.ua',//URL на который будут вести ссылки на картинки у которых нет ссылок 
			hu: '',
			linked: false,// если true то картинка используется как ссылка на картинку    
			loader: true,
			loop: true,//крутить с начала
			match: /\?slide=(\d+)$/,
			overlap: true,//Смена картинок без наплыва (сначала картинка полностью прячется, а потом новая показуется ) 
			paused: false,
			random: false,
			replace: [/(\.[^\.]+)$/, 't$1'],
			resize: 'fill',
			slide: 0,//Номер астивного слайда
			thumbnails: true,// показывать кантинки внизу или нет
			titles: false,
			transition: 'sine:in:out',
			width: false
		},

	/**
	Constructor: initialize
		Creates an instance of the Slideshow class.

	Arguments:
		element - (element) The wrapper element.
		data - (array or object) The images and optional thumbnails, captions and links for the show.
		options - (object) The options below.

	Syntax:
		var myShow = new Slideshow(element, data, options);
	*/

		initialize: function(el, data, options){
			this.setOptions(options);
			this.el = document.id(el);
                        
			if (!this.el) 
				return;
			var match = window.location.href.match(this.options.match);
			this.slide = this._slide = this.options.match && match ? match[1].toInt() 
				: this.options.slide;
			this.counter = this.timeToNextTransition = this.timeToTransitionComplete = 0;
			this.direction = 'left';
			this.cache = {};
			this.paused = false;
			if (!this.options.overlap)
				this.options.duration *= 2;
			var anchor = this.el.getElement('a') || new Element('a');
			if (!this.options.href)
				this.options.href = anchor.get('href') || '';
			if (this.options.hu.length && !this.options.hu.test(/\/$/)) 
				this.options.hu += '/';
			if (this.options.fast === true)
				this.options.fast = WhenPaused | WhenPlaying;

			// styles

			var keys = 'slideshow first prev play pause next last images captions controller thumbnails hidden visible inactive active loader book'.split(' '),
				values = keys.map(function(key, i){
					return this.options.classes[i] || key;
				}, this);
			this.classes = values.associate(keys);
			this.classes.get = function(){
				var str = '.' + this.slideshow;
				for (var i = 0, l = arguments.length; i < l; i++)
					str += '-' + this[arguments[i]];
				return str;
			}.bind(this.classes);

			// data	
			
			if (!data){
				this.options.hu = '';
				data = {};
				var thumbnails = this.el.getElements(this.classes.get('thumbnails') + ' img');
				this.el.getElements(this.classes.get('images') + ' img').each(function(img, i){
					var src = img.src,
						caption = img.alt || img.title,
						href = img.getParent().href,
						thumbnail = thumbnails[i] ? thumbnails[i].src 
							: '';
					data[src] = {'caption': caption, 'href': href, 'thumbnail': thumbnail};
				});
			}
			var loaded = this.load(data);
			if (!loaded)
				return; 

			// events

			this.events = {};
			this.events.push = function(type, fn){
				if (!this[type])
					this[type] = [];
				this[type].push(fn);
				document.addEvent(type, fn);
				return this;
			}.bind(this.events);

			this.accesskeys = {};
			for (action in this.options.accesskeys){
				var obj = this.options.accesskeys[action];
				this.accesskeys[action] = accesskey = {'label': obj.label};
				['shift', 'control', 'alt'].each(function(modifier){
					var re = new RegExp(modifier, 'i');
					accesskey[modifier] = obj.key.test(re);
					obj.key = obj.key.replace(re, '');
				});
				accesskey.key = obj.key.trim();
			}

			this.events.push('keyup', function(e){
				Object.each(this.accesskeys, function(accesskey, action){
					if (e.key == accesskey.key && e.shift == accesskey.shift && e.control == accesskey.control && e.alt == accesskey.alt)
						this[action]();
				}, this);			
			}.bind(this));	 

			// required elements

			var el = this.el.getElement(this.classes.get('images')),
				img = this.el.getElement('img') || new Element('img'),
				images = el ? el.empty() 
					: new Element('div', {'class': this.classes.get('images').substr(1)}).inject(this.el),
				div = images.getSize();
			this.height = this.options.height || div.y;		
			this.width = this.options.width || div.x;
			images.set({'styles': {'height': this.height, 'width': this.width}});
			this.el.store('images', images);
			this.a = this.image = img;
			if (Browser.ie && Browser.version >= 7)
				this.a.style.msInterpolationMode = 'bicubic';
			this.a.set('styles', {'display': 'none'});
			this.b = this.a.clone();
			[this.a, this.b].each(function(img){
				anchor.clone().cloneEvents(anchor).grab(img).inject(images);
			});

			// optional elements

			this.options.captions && new Caption(this);
			this.options.controller && new Controller(this);
			this.options.loader && new Loader(this);
			this.options.thumbnails && new Thumbnails(this);
                        this.options.book && new Book(this);
			// begin show

			this._preload(this.options.fast & OnStart);
		},

	/**
	Public method: go
		Jump directly to a slide in the show.

	Arguments:
		n - (integer) The index number of the image to jump to, 0 being the first image in the show.

	Syntax:
		myShow.go(n);	
	*/

		go: function(n, direction){
			var nextSlide = (this.slide + this.data.images.length) % this.data.images.length;
			if (n == nextSlide || Date.now() < this.timeToTransitionComplete)
				return;		
			clearTimeout(this.timer);
			this.timeToNextTransition = 0;		
			this.direction = direction ? direction 
				: n < this._slide ? 'right' 
				: 'left';
			this.slide = this._slide = n;
			if (this.preloader) 
				this.preloader = this.preloader.destroy();
			this._preload((this.options.fast & WhenPlaying) || (this.paused && this.options.fast & WhenPaused));
		},

	/**
	Public method: first
		Goes to the first image in the show.

	Syntax:
		myShow.first();	
	*/

		first: function(){
			this.prev(true); 
		},

	/**
	Public method: prev
		Goes to the previous image in the show.

	Syntax:
		myShow.prev();	
	*/

		prev: function(first){
			var n = 0;
			if (!first){
				if (this.options.random){
					if (this.showed.i < 2)
						return;
					this.showed.i -= 2;
					n = this.showed.array[this.showed.i];
				}
				else
					n = (this.slide - 1 + this.data.images.length) % this.data.images.length;									
			}
			this.go(n, 'right');
		},

	/**
	Public method: pause
		Toggles play / pause state of the show.

	Arguments:
		p - (undefined, 1 or 0) Call pause with no arguments to toggle the pause state. Call pause(1) to force pause, or pause(0) to force play.

	Syntax:
		myShow.pause(p);	
	*/

		pause: function(p){
			if (p != undefined)
				this.paused = p ? false 
					: true;
			if (this.paused){ // play
				this.paused = false;
				this.timeToTransitionComplete = Date.now() + this.timeToTransitionComplete;		
				this.timer = this._preload.delay(50, this);
				[this.a, this.b].each(function(img){
					['morph', 'tween'].each(function(p){
						if (this.retrieve(p)) this.get(p).resume();
					}, img);
				});
				this.controller && this.el.retrieve('pause').getParent().removeClass(this.classes.play);
			} 
			else { // pause
				this.paused = true;
				this.timeToTransitionComplete = this.timeToTransitionComplete - Date.now();
				clearTimeout(this.timer);
				[this.a, this.b].each(function(img){
					['morph', 'tween'].each(function(p){
						if (this.retrieve(p)) this.get(p).pause();
					}, img);
				});
				this.controller && this.el.retrieve('pause').getParent().addClass(this.classes.play);
			}
		},

	/**
	Public method: next
		Goes to the next image in the show.

	Syntax:
		myShow.next();	
	*/

		next: function(last){
			var n = last ? this.data.images.length - 1 
				: this._slide;
			this.go(n, 'left');
		},

	/**
	Public method: last
		Goes to the last image in the show.

	Syntax:
		myShow.last();	
	*/

		last: function(){
			this.next(true); 
		},

	/**
	Public method: load
		Loads a new data set into the show: will stop the current show, rewind and rebuild thumbnails if applicable.

	Arguments:
		data - (array or object) The images and optional thumbnails, captions and links for the show.

	Syntax:
		myShow.load(data);
	*/

		load: function(data){
			this.firstrun = true;
			this.showed = {'array': [], 'i': 0};
			if (typeOf(data) == 'array'){
				this.options.captions = false;			
				data = new Array(data.length).associate(data.map(function(image, i){return image + '?' + i})); 
			}
			this.data = {'images': [], 'captions': [], 'hrefs': [], 'thumbnails': [], 'targets': [], 'titles': []};

                        for (var image in data){
				var obj = data[image] || {},
					image = this.options.hu + image,
					caption = obj.caption ? obj.caption.trim() 
						: '',
					href = obj.href ? obj.href.trim() 
						: this.options.linked ? image 
						: this.options.href,
					target = obj.target ? obj.target.trim() 
						: '_self',
					thumbnail = obj.thumbnail ? this.options.hu + obj.thumbnail.trim() 
						: image.replace(this.options.replace[0], this.options.replace[1]),
					title = caption.replace(/<.+?>/gm, '').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, "'");
				this.data.images.push(image);
				this.data.captions.push(caption);
				this.data.hrefs.push(href);
				this.data.targets.push(target);
				this.data.thumbnails.push(thumbnail);
				this.data.titles.push(title);
			}
			if (this.options.random)
				this.slide = this._slide = Number.random(0, this.data.images.length - 1);

			// only run when data is loaded dynamically into an existing slideshow instance

			if (this.options.thumbnails && this.el.retrieve('thumbnails'))
				this._thumbnails();
			if (this.el.retrieve('images')){
				[this.a, this.b].each(function(img){
					['morph', 'tween'].each(function(p){
						if (this.retrieve(p)) this.get(p).cancel();
					}, img);
				});
				this.slide = this._slide = this.timeToTransitionComplete = 0;
				this.go(0);		
			}
			return this.data.images.length;
		},

	/**
	Public method: destroy
		Destroys a Slideshow instance.

	Arguments:
		p - (string) The images and optional thumbnails, captions and links for the show.

	Syntax:
		myShow.destroy(p);
	*/

		destroy: function(p){
			Object.each(this.events, function(array, e){
				if ('each' in array)
					array.each(function(fn){document.removeEvent(e, fn);});
			});
			this.pause(1);
			'caption loader thumbnails'.split(' ').each(function(i, timer){
				this.options[i] && (timer = this[i].retrieve('timer')) && clearTimeout(timer);
			}, this);
			typeOf(this.el[p]) == 'function' && this.el[p]();
			delete this.el.uid;
		},
                
        free:function(){
           this.destroy();
           children = $(this.el.id).getChildren();
           children.each(function(child){
               child.dispose();
           });
           delete window.slideshow;
        },
	/**
	Private method: preload
		Preloads the next slide in the show, once loaded triggers the show, updates captions, thumbnails, etc.
	*/

		_preload: function(fast){
			var src = this.data.images[this._slide].replace(/([^?]+).*/, '$1'),
				cached = loaded = !!this.cache[src];
			if (!cached){
				if (!this.preloader)
				 	this.preloader = new Asset.image(src, {
						'onerror': function(){
							// do something
						},
						'onload': function(){
							this.store('loaded', true);
						}
					});
				loaded = this.preloader.retrieve('loaded') && this.preloader.get('width');
			}
			if (loaded && Date.now() > this.timeToNextTransition && Date.now() > this.timeToTransitionComplete){
				var src = this.data.images[this._slide].replace(/([^?]+).*/, '$1');
				if (this.preloader){
					this.cache[src] = {
						'height': this.preloader.get('height'),
						'src': src,
						'width': this.preloader.get('width')
					}
				}
				if (this.stopped){
					if (this.options.captions)
						this.caption.get('morph').cancel().start(this.classes.get('captions', 'hidden'));
					this.pause(1);
					if (this.end)
						this.fireEvent('end');
					this.stopped = this.end = false;
					return;				
				}
				this.image = this.counter % 2 ? this.b 
					: this.a;
				this.image.set('styles', {'display': 'block', 'height': null, 'visibility': 'hidden', 'width': null, 'zIndex': this.counter});
				this.image.set(this.cache[src]);
				this.image.width = this.cache[src].width;
				this.image.height = this.cache[src].height;
				this.options.resize && this._resize(this.image);
				this.options.center && this._center(this.image);
				var anchor = this.image.getParent();
				if (this.data.hrefs[this._slide]){
					anchor.set('href', this.data.hrefs[this._slide]);
					anchor.set('target', this.data.targets[this._slide]);			
				} 
				else {
					anchor.erase('href');
					anchor.erase('target');
				}
				var title = this.data.titles[this._slide];
				this.image.set('alt', title);		
				this.options.titles && anchor.set('title', title);
				this.options.loader && this.loader.fireEvent('hide');
				this.options.captions && this.caption.fireEvent('update', fast);				
				this.options.thumbnails && this.thumbnails.fireEvent('update', fast); 			
				this._show(fast);
				this._loaded(fast);
			} 
			else {
				if (Date.now() > this.timeToNextTransition && this.options.loader)
					this.loader.fireEvent('show');
				this.timer = this._preload.delay(50, this, fast); 
			}
		},

	/**
	Private method: show
		Does the slideshow effect.
	*/

		_show: function(fast){
			if (!this.image.retrieve('morph')){
				var options =  this.options.overlap ? {'link': 'cancel'} : {'link': 'chain'};
				$$(this.a, this.b).set('morph', Object.merge(options, {'duration': this.options.duration, 'onStart': this._start.bind(this), 'onComplete': this._complete.bind(this), 'transition': this.options.transition}));
			}
			var hidden = this.classes.get('images', (this.direction == 'left' ? 'next' 
				: 'prev')),
				visible = this.classes.get('images', 'visible'),
				img = this.counter % 2 ? this.a 
					: this.b;
			if (fast){			
				img.get('morph').cancel().set(hidden);
				this.image.get('morph').cancel().set(visible); 			
			} 
			else {
				if (this.options.overlap){
					img.get('morph').set(visible);
					this.image.get('morph').set(hidden).start(visible);
				} 
				else {
					var fn = function(visible){
						this.image.get('morph').start(visible);
					}.pass(visible, this);
					if (this.firstrun)
						return fn();
					hidden = this.classes.get('images', (this.direction == 'left' ? 'prev' 
						: 'next'));
					this.image.get('morph').set(hidden);				
					img.get('morph').set(visible).start(hidden).chain(fn);
				}
			}
		},

	/**
	Private method: loaded
		Run after the current image has been loaded, sets up the next image to be shown.
	*/

		_loaded: function(fast){
			this.counter++;
			this.timeToNextTransition = Date.now() + this.options.duration + this.options.delay;
			this.direction = 'left';			
			this.timeToTransitionComplete = fast ? 0 
				: Date.now() + this.options.duration;
			if (this._slide == (this.data.images.length - 1) && !this.options.loop && !this.options.random)
				this.stopped = this.end = true;
			if (this.options.random){
				this.showed.i++;
				if (this.showed.i >= this.showed.array.length){
					var n = this._slide;
					if (this.showed.array.getLast() != n) this.showed.array.push(n);
					while (this._slide == n)
						this.slide = this._slide = Number.random(0, this.data.images.length - 1);				
				}
				else
					this.slide = this._slide = this.showed.array[this.showed.i];
			}
			else {
				this.slide = this._slide;
				this._slide = (this.slide + 1) % this.data.images.length;
			}
			if (this.image.getStyle('visibility') != 'visible')
				(function(){this.image.setStyle('visibility', 'visible');}).delay(1, this);			
			if (this.preloader) 
				this.preloader = this.preloader.destroy();
			this.paused || this._preload();
		},

	/**
	Private method: center
		Center an image.
	*/

		_center: function(img){
			var size = img.getSize(), 
				h = size.y, w = size.x; 
			img.set('styles', {'left': (w - this.width) / -2, 'top': (h - this.height) / -2});
		},

	/**
	Private method: resize
		Resizes an image.
	*/

		_resize: function(img){
			var h = img.get('height').toFloat(), w = img.get('width').toFloat(),
				dh = this.height / h, dw = this.width / w;
			if (this.options.resize == 'fit')
				dh = dw = dh > dw ? dw 
					: dh;
			if (this.options.resize == 'fill')
				dh = dw = dh > dw ? dh 
					: dw;
			img.set('styles', {'height': Math.ceil(h * dh), 'width': Math.ceil(w * dw)});
		},

	/**
	Private method: start
		Callback on start of slide change.
	*/

		_start: function(){		
			this.fireEvent('start');
		},

	/**
	Private method: complete
		Callback on start of slide change.
	*/

		_complete: function(){
			if (this.firstrun && this.options.paused)
				this.pause(1);
			this.firstrun = false;
			this.fireEvent('complete');
		}	
	});

	/**
	Private method: captions
		Builds the optional caption element, adds interactivity.
		This method can safely be removed if the captions option is not enabled.
	*/

	var Caption = new Class({
		Implements: [Chain, Events, Options],

		options: {/*
			duration: 500,
			fps: 50,
			transition: 'sine:in:out',
                        unit: true,*/
			delay: 0,
			link: 'cancel'			
		},

		initialize: function(slideshow){
			if (!slideshow)
				return;
			var options = slideshow.options.captions;
			if (options === true)
				options = {};
			this.setOptions(options);
			var el = slideshow.el.getElement(slideshow.classes.get('captions')),
				caption = el ? el.dispose().empty()
					: new Element('div', {'class': slideshow.classes.get('captions').substr(1)});
			slideshow.caption = caption;
			caption.set({
		    	'aria-busy': false,
		    	'aria-hidden': false,
				'events': {'update': this.update.bind(slideshow)},
				'morph': this.options,
				'role': 'description'
			}).store('delay', this.options.delay);
		    if (!caption.get('id'))
		    	caption.set('id', 'Slideshow-' + Date.now());
		    slideshow.el.retrieve('images').set('aria-labelledby', caption.get('id'));
			caption.inject(slideshow.el);
		},

		update: function(fast){
		    var empty = !this.data.captions[this._slide].length, timer;
			if (timer = this.caption.retrieve('timer'))
				clearTimeout(timer);
		    if (fast){
		      var p = empty ? 'hidden' 
				: 'visible';
		      this.caption.set({'aria-hidden': empty, 'html': this.data.captions[this._slide]}).get('morph').cancel().set(this.classes.get('captions', p));
		    }
		    else {
		      var fn1 = empty ? function(){} 
				: function(caption){
				this.caption.store('timer', setTimeout(function(caption){
                                this.caption.set('html', caption).morph(this.classes.get('captions', 'visible'));
                            }.pass(caption, this), this.caption.retrieve('delay')));
		      }.pass(this.data.captions[this._slide], this);    
		      var fn2 = function(){ 
		        this.caption.set('aria-busy', false); 
		      }.bind(this);
		      this.caption.set('aria-busy', true).get('morph').cancel().start(this.classes.get('captions', 'hidden')).chain(fn1, fn2);
		    }
		}
	});

	/**
	Private method: controller
	  Builds the optional controller element, adds interactivity.
	  This method can safely be removed if the controller option is not enabled.
	*/

	var Controller = new Class({
		Implements: [Chain, Events, Options],

		options: {/*
			duration: 500,
			fps: 50,
			transition: 'sine:in:out',
			unit: false, */
			link: 'cancel'			
		},

		initialize: function(slideshow){
			if (!slideshow)
				return;
			var options = slideshow.options.captions;
			if (options === true)
				options = {};
			this.setOptions(options);
			var el = slideshow.el.getElement(slideshow.classes.get('controller')),
				controller = el ? el.dispose().empty()
					: new Element('div', {'class': slideshow.classes.get('controller').substr(1)});
			slideshow.controller = controller;
			controller.set({
				'aria-hidden': false, 
				'role': 'menubar'
			});
			var ul = new Element('ul', {'role': 'menu'}).inject(controller),
				i = 0;
			Object.each(slideshow.accesskeys, function(accesskey, action){
				var li = new Element('li', {
					'class': (action == 'pause' && this.options.paused) ? this.classes.play + ' ' + this.classes[action] 
						: this.classes[action]
				}).inject(ul);
				var a = this.el.retrieve(action, new Element('a', {
					'role': 'menuitem', 'tabindex': i++, 'title': accesskey.label
				}).inject(li));
				a.set('events', {
					'click': function(action){
						this[action]()
					}.pass(action, this),
					'mouseenter': function(active){
						this.addClass(active)
					}.pass(this.classes.active, a),
					'mouseleave': function(active){
						this.removeClass(active)
					}.pass(this.classes.active, a)
				});		
			}, slideshow);
			controller.set({
				'events': {
					'hide': this.hide.pass(slideshow.classes.get('controller', 'hidden'), controller),
					'show': this.show.pass(slideshow.classes.get('controller', 'visible'), controller)
				},
				'morph': this.options
			}).store('hidden', false);
			slideshow.events
				.push('keydown', this.keydown.bind(slideshow))
				.push('keyup',	this.keyup.bind(slideshow))
				.push('mousemove',	this.mousemove.bind(slideshow));
			controller.inject(slideshow.el).fireEvent('hide');
		},

		hide: function(hidden){
			if (this.get('aria-hidden') == 'false')
				this.set('aria-hidden', true).morph(hidden);
		},

		keydown: function(e){
			Object.each(this.accesskeys, function(accesskey, action){
				if (e.key == accesskey.key && e.shift == accesskey.shift && e.control == accesskey.control && e.alt == accesskey.alt){
					if (this.controller.get('aria-hidden') == 'true')
						this.controller.get('morph').set(this.classes.get('controller', 'visible'));
					this.el.retrieve(action).fireEvent('mouseenter');
				}					
			}, this);		
		},

		keyup: function(e){
			Object.each(this.accesskeys, function(accesskey, action){
				if (e.key == accesskey.key && e.shift == accesskey.shift && e.control == accesskey.control && e.alt == accesskey.alt){
					if (this.controller.get('aria-hidden') == 'true')
						this.controller.set('aria-hidden', false).fireEvent('hide'); 
					this.el.retrieve(action).fireEvent('mouseleave');
				}					
			}, this);			
		},

		mousemove: function(e){
			var images = this.el.retrieve('images').getCoordinates(),
				action = (e.page.x > images.left && e.page.x < images.right && e.page.y > images.top && e.page.y < images.bottom) ? 'show' 
					: 'hide';
			this.controller.fireEvent(action);
		},

		show: function(visible){
			if (this.get('aria-hidden') == 'true')
				this.set('aria-hidden', false).morph(visible);
		}
	});

	/**
	Private method: loader
		Builds the optional loader element, adds interactivity.
		This method can safely be removed if the loader option is not enabled.
	*/

	var Loader = new Class({
		Implements: [Chain, Events, Options],

		options: {/*
			duration: 500,
			transition: 'sine:in:out',
			unit: false, */
			fps: 20,
			link: 'cancel'			
		},

		initialize: function(slideshow){
			if (!slideshow)
				return;
			var options = slideshow.options.loader;
			if (options === true)
				options = {};
			this.setOptions(options);
			var loader = new Element('div', {
				'aria-hidden': false,
				'class': slideshow.classes.get('loader').substr(1),				
				'morph': this.options,
				'role': 'progressbar'
			}).store('animate', false).store('i', 0).store('delay', 1000 / this.options.fps).inject(slideshow.el);
			slideshow.loader = loader;
			var url = loader.getStyle('backgroundImage').replace(/url\(['"]?(.*?)['"]?\)/, '$1').trim();
			if (url){
				if (url.test(/\.png$/) && Browser.ie && Browser.version < 7)
					loader.setStyles({'backgroundImage': 'none', 'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + url + '", sizingMethod="crop")'});					
				new Asset.image(url, {'onload': function(){
					var size = loader.getSize(),
						width = this.get('width'), 
						height = this.get('height');
					if (width > size.x)
						loader.store('x', size.x).store('animate', 'x').store('frames', (width / size.x).toInt());
					if (height > size.y)
						loader.store('y', size.y).store('animate', 'y').store('frames', (height / size.y).toInt());
				}});
			}
			loader.set('events', {
				'animate': this.animate.bind(loader),
				'hide': this.hide.pass(slideshow.classes.get('loader', 'hidden'), loader),
				'show': this.show.pass(slideshow.classes.get('loader', 'visible'), loader)
			});
			loader.fireEvent('hide');
		},

		animate: function(){
			var animate = this.retrieve('animate');
			if (!animate)
				return;
			var i = (this.retrieve('i').toInt() + 1) % this.retrieve('frames');
			this.store('i', i);
			var n = (i * this.retrieve(animate)) + 'px';
			if (animate == 'x')
				this.setStyle('backgroundPosition', n + ' 0px');			
			if (animate == 'y')
				this.setStyle('backgroundPosition', '0px ' + n);			
		},

		hide: function(hidden){
			if (this.get('aria-hidden') == 'false'){
				this.set('aria-hidden', true).morph(hidden);
				if (this.retrieve('animate'))
					clearTimeout(this.retrieve('timer'));
			}
		},

		show: function(visible){
			if (this.get('aria-hidden') == 'true'){
				this.set('aria-hidden', false).morph(visible);
				if (this.retrieve('animate')){
					this.store('timer', function(){ 
						this.fireEvent('animate') 
					}.periodical(this.retrieve('delay'), this));			
				}
			}
		}
	});

	/**
	Private method: thumbnails
		Builds the optional thumbnails element, adds interactivity.
		This method can safely be removed if the thumbnails option is not enabled.
	*/

	var Thumbnails = new Class({
		Implements: [Chain, Events, Options],

		options: {/*
			duration: 500,
			transition: 'sine:in:out',
			unit: false, */
			columns: null,
                        duration: 500,
			fps: 100,
			link: 'cancel',
			position: 'left',
			rows: 2,
			scroll: null
		},

		initialize: function(slideshow){
			var options = (slideshow.options.thumbnails === true) ? {} 
				: slideshow.options.thumbnails;
			this.setOptions(options);
			var el = slideshow.el.getElement(slideshow.classes.get('thumbnails')),
				thumbnails = el ? el.empty() 
					: new Element('div', {'class': slideshow.classes.get('thumbnails').substr(1)});
			slideshow.thumbnails = thumbnails;
			thumbnails.set({'role': 'menubar', 'styles': {'overflow': 'hidden'}});
			var uid = thumbnails.retrieve('uid', 'Slideshow-' + Date.now()),
				ul = new Element('ul', {'role': 'menu', 'styles': {'left': 0, 'position': 'absolute', 'top': 0}, 'tween': {'link': 'cancel'}}).inject(thumbnails);
			slideshow.data.thumbnails.each(function(thumbnail, i){
				var li = new Element('li', {'id': uid + i}).inject(ul),
					a = new Element('a', {
						'class': slideshow.classes.get('thumbnails', 'hidden').substr(1),
						'events': {
							'click': this.click.pass(i, slideshow)
						},
						'href': slideshow.data.images[i],
						'morph': this.options,
						'role': 'menuitem',
						'tabindex': i
					}).store('uid', i).inject(li);
				if (slideshow.options.titles)
					a.set('title', slideshow.data.titles[i]);
				new Asset.image(thumbnail, {
					'onload': this.onload.pass(i, slideshow)
				}).inject(a);
			}, this);
			thumbnails.set('events', {
				'scroll': this.scroll.bind(thumbnails),
				'update': this.update.bind(slideshow)
			});
			var coords = thumbnails.getCoordinates();
			if (!options.scroll)
				options.scroll = (coords.height > coords.width) ? 'y' 
					: 'x';
			var props = (options.scroll == 'y') ? 'top bottom height y width'.split(' ') 
				: 'left right width x height'.split(' ');
			thumbnails.store('props', props).store('delay', 1000 / this.options.fps);
			slideshow.events.push('mousemove', this.mousemove.bind(thumbnails));
			thumbnails.inject(slideshow.el);
		},

		click: function(i){
			this.go(i); 
			return false; 
		},

		mousemove: function(e){
			var coords = this.getCoordinates();
                if (e.page.x > coords.left && e.page.x < coords.right && e.page.y > coords.top && e.page.y < coords.bottom){
				this.store('page', e.page);	
				if (!this.retrieve('mouseover')){
					this.store('mouseover', true);
					this.store('timer', function(){this.fireEvent('scroll');}.periodical(this.retrieve('delay'), this));
				}
			}
			else {
				if (this.retrieve('mouseover')){
					this.store('mouseover', false);				
					clearTimeout(this.retrieve('timer'));
				}
			}			
		},

		onload: function(i){
			var thumbnails = this.thumbnails,
				a = thumbnails.getElements('a')[i];
			if (a){
				(function(a){
					var visible = i == this.slide ? 'active' 
						: 'inactive';					
					a.store('loaded', true).get('morph').set(this.classes.get('thumbnails', 'hidden')).start(this.classes.get('thumbnails', visible));	
				}).delay(Math.max(1000 / this.data.thumbnails.length, 100), this, a);
			}					
			if (thumbnails.retrieve('limit'))
				return;
			var props = thumbnails.retrieve('props'), 
				options = this.options.thumbnails,
				pos = props[1], 
				length = props[2], 
				width = props[4],
				li = thumbnails.getElement('li:nth-child(' + (i + 1) + ')').getCoordinates();
			if (options.columns || options.rows){
				thumbnails.setStyles({'height': this.height, 'width': this.width});
				if (options.columns.toInt())
					thumbnails.setStyle('width', li.width * options.columns.toInt());
				if (options.rows.toInt())
					thumbnails.setStyle('height', li.height * options.rows.toInt());
			}
			var div = thumbnails.getCoordinates();
			if (options.position){
				if (options.position.test(/bottom|top/))
					thumbnails.setStyles({'bottom': 'auto', 'top': 'auto'}).setStyle(options.position, -div.height);
				if (options.position.test(/left|right/))
					thumbnails.setStyles({'left': 'auto', 'right': 'auto'}).setStyle(options.position, -div.width);
			}
			var units = Math.floor(div[width] / li[width]),
				x = Math.ceil(this.data.images.length / units),
				r = this.data.images.length % units,
				len = x * li[length],
				ul = thumbnails.getElement('ul').setStyle(length, len);
			ul.getElements('li').setStyles({'height': li.height, 'width': li.width});
			thumbnails.store('limit', div[length] - len);
		},

		scroll: function(n, fast){
			var div = this.getCoordinates(),
				ul = this.getElement('ul').getPosition(),
				props = this.retrieve('props'),
				axis = props[3], delta, pos = props[0], size = props[2], value,			
				tween = this.getElement('ul').set('tween', {'property': pos}).get('tween');	
			if (n != undefined){
				var uid = this.retrieve('uid'),
					li = document.id(uid + n).getCoordinates();
				delta = div[pos] + (div[size] / 2) - (li[size] / 2) - li[pos];
				value = (ul[axis] - div[pos] + delta).limit(this.retrieve('limit'), 0);
				tween[fast ? 'set' : 'start'](value);
			}
			else{
				var area = div[props[2]] / 3, 
					page = this.retrieve('page'), 
					velocity = -(this.retrieve('delay') * 0.01);			
				if (page[axis] < (div[pos] + area))
					delta = (page[axis] - div[pos] - area) * velocity;
				else if (page[axis] > (div[pos] + div[size] - area))
					delta = (page[axis] - div[pos] - div[size] + area) * velocity;			
				if (delta){			
					value = (ul[axis] - div[pos] + delta).limit(this.retrieve('limit'), 0);
					tween.set(value);
				}
			}
		},

		update: function(fast){
			var thumbnails = this.thumbnails,
				uid = thumbnails.retrieve('uid');
			thumbnails.getElements('a').each(function(a, i){
				if (a.retrieve('loaded')){
					if (a.retrieve('uid') == this._slide){
						if (!a.retrieve('active', false)){
							a.store('active', true);
							var active = this.classes.get('thumbnails', 'active');							
							if (fast) a.get('morph').set(active);
							else a.morph(active);
						}
					} 
					else {
						if (a.retrieve('active', true)){
							a.store('active', false);
							var inactive = this.classes.get('thumbnails', 'inactive');						
							if (fast) a.get('morph').set(inactive);
							else a.morph(inactive);
						}
					}
				}
			}, this);
			if (!thumbnails.retrieve('mouseover'))
				thumbnails.fireEvent('scroll', [this._slide, fast]);
		}
	});
        
       var Book = new Class({
         
         Implements: [Chain, Events, Options],

		options: {/*
			duration: 500,
			transition: 'sine:in:out',
			unit: false, */
			fps: 20,
			link: 'cancel'			
		},

		initialize: function(slideshow){
			if (!slideshow)
				return;
			var options = slideshow.options.book;
			if (options === true)
				options = {};
			this.setOptions(options);
			var book = new Element('div', {
				'aria-hidden': false,
				'class': slideshow.classes.get('book').substr(1),				
				'morph': this.options,
				'role': 'progressbar'
			}).store('animate', false).store('i', 0).store('delay', 1000 / this.options.fps).inject(slideshow.caption);
		
                        book.set('events', {
//				'scroll': this.scroll.bind(),
				'update': this.update.bind(fast)
			});

                    slideshow.book = book;
//                        console.log(slideshow.caption);
		}
                
       });
})();
/**
 *
 * @class      Ria_Hotel_Alert
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 */
var Ria_Hotel_Alert = new Class({

    Implements: Options,

	options: {},

	initialize: function openwindow(emId, femId){
		var em = $(emId);
		var fem = $(femId);

                em.setStyle('visibility', 'visible');
                fem.setStyle('visibility', 'visible');
		var allAnsc = $(document.body).getElements("embed");
                allAnsc.each(function(item){
                        item.setStyle('visibility', 'hidden');
		});
		var allAnsc2 = $(document.body).getElements("object");
		allAnsc2.each(function(item){
                        item.setStyle('visibility', 'hidden');
		});
                var myFx = new Fx.Tween(fem);
                myFx.start('opacity', '0','0.5');
                if(Browser.Engine.trident){
                        var winAll=window.getScrollSize();
			var winH = winAll.y;
			var winW = winAll.x;
                               
				var allAnchors = $(document.body).getElements('select');
				allAnchors.each(function(item, index){
					item.setStyle('visibility','hidden');
				});
		} else {
                        em.setStyle('position', 'fixed');
                        fem.setStyle('position', 'fixed');
		};
	}
});
/**
 * Класс для работы с календариком
 *
 * @class      Ria_Hotel_AlertClose
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Id: Calendar.js,v 1.2 2008-11-10 07:46:05 simpl Exp $
 */
var Ria_Hotel_AlertClose = new Class({

    Implements: Options,

    options: {},

    initialize: function closewindow(emId, femId, slider){
        var em = $(emId);
        var fem = $(femId);
                
        fem.setStyle('visibility', 'hidden');
        em.setStyle('visibility', 'hidden');
        var allAnsc = $(document.body).getElements("embed");
        allAnsc.each(function(item){
            item.setStyle('visibility', 'visible');
        });
        var allAnsc2 = $(document.body).getElements("object");
        allAnsc2.each(function(item){
            item.setStyle('visibility', 'visible');
        });
        if(!!slider){
            this.hideSlider();
        }
    },
    hideSlider: function(){
        $('rightGalleryCloseDiv').dispose();
        $('leftGalleryDiv').dispose();
        $('gal-close-btn').dispose();
        $('imageGallery').set('html','');
        $('body').set('style', '');
        window.removeEvent('resize');
        return false;
    }
});

/**
 * @class Ria_Hotel_QueryManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 */
var Ria_Hotel_QueryManager = new Class(
{
    initialize: function(ajaxObject)
    {
        this.ajaxObject = ajaxObject;
    },

    startQuery: function()
    {
        var ajaxObject = this.ajaxObject;
        var repeatRequest = function()
        {
            ajaxObject.sendQuery();
        };

        this.repeatRequestObj = repeatRequest.periodical(10000, ajaxObject);
    },

    stopQuery: function()
    {
        $clear(this.repeatRequestObj);
    }
});
/**
 * Класс для работы с календариком
 *
 * @class      Ria_Hotel_Rotator
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Id: Calendar.js,v 1.2 2008-11-10 07:46:05 simpl Exp $
 */
var Ria_Hotel_Rotator = new Class(
{
    initialize : function (options)
    {   
        rotator_images = new $H(options);
        temp_img_arc = new $H(options);
        current_image = 0;
        images_total = 0;
        isStop = 0;
        this.preloadImages();
    },
    stop : function ()
    {
        rotator_images = new $H();
        isStop = 1;
    },
    pause : function ()
    {
        temp_img_arc = rotator_images;
        rotator_images = new $H();
    },
    play : function ()
    {
        if (!isStop) {
            rotator_images = temp_img_arc;
        }
        $(selected).setProperty('class', 'tMainBpagerA');
    },
    preloadImages : function ()
    {
        var imgList = new Array();
        thisArea = this;
        rotator_images.each(function (item, index)
        {
            image = item.image;
            imgList.include(['http://img.20.ua/photos/' + image]);
        });


        var myImages = new Asset.images(imgList, {
            onComplete : function ()
            {
                thisArea.changeImg.periodical(4000);
            }
        });
    },
    changeImg : function ()
    {
        rotator_images.each(function (item, index)
        {
            if (index == current_image)
            {
                $(selected).setProperty('class', '');
                selected = 'l_' + item.id;
                var image = item.image;
                image = 'http://img.20.ua/photos/' + image;
                $('tMainBpager').setStyle('background', 'url(' + image + ')');
                $('l_' + item.id).setProperty('class', 'tMainBpagerA');
                $('btn').set('href', item.link);
            }
            images_total = index;
        });
        if (current_image != images_total) {
            current_image++;
        }
        else {
            current_image = 0;
        }
    }
});


/**
* class RIA Hotel, add block info to search/hotels pages via HTML Request
* 
* @class      Ria_Hotel_CheckForm
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    
* @author     Andrey Kotulskiy
* @requires   
*/
var Ria_Hotel_CheckForm = new Class({

    /**
* @param {String} id id объекта, который будет обновлен по приходу ответа от сервера  
* @raram {Array} options массив Id которые нужно проверить
*/
    initialize: function(id, options, success, failed){
        if(
            $(options.id1).get('value') != '' && 
            $(options.id2).get('value') != ''&& 
            $(options.id3).get('value') != ''&&
            $(options.id5).get('value').length >= '7'&&
            $(options.email).get('value') != ''
        ) {
            success();
        }else{
            failed();
        }
    }
});
/**
 * class RIA Hotel, add block info to search/hotels pages via HTML Request
 * 
 * @class      Ria_Hotel_CheckFormCredit
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    
 * @author     Andrey Kotulskiy
 * @requires   
 */
var Ria_Hotel_CheckFormCredit = new Class({
			
	options: {
		id6: 'cc_number',
		id7: 'cc_cardholder',
		id8: 'cc_cvc'
	},

	/**
	 * @param {String} id id объекта, который будет обновлен по приходу ответа от сервера  
	 * @raram {Array} options массив Id которые нужно проверить
	 */
	initialize: function(id, options){
//		alert ('ytghjshol');
		 if($(options.id9).get('value') == '0' )
			{
			$(id.AlertId).fade('in');
			}
         if($(options.id9).get('value') != '0' )
			{
			$(id.AlertId).fade('out');
            
			}
         if($(options.id6).get('value') != ''&&
			$(options.id7).get('value') != ''&& 
		   	$(options.id8).get('value') != ''&&
            $(options.id9).get('value') != '0')
			{
			$(id.Id).removeProperty('disabled');
			$(id.Id).set('class','button button_214');
			}else{
			$(id.Id).disabled = 'true';
			$(id.Id).set('class','button button_214 no_activ');
			}
	}
});

/**
 * Класс для работы с датами
 *
 * @class      Ria_Hotel_DateFormat
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * 
 */

        
        
 /*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var Ria_Hotel_DateFormat = new Class(
{
	

        initialize: function()
        {
          

 dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};   
        
        
        }


});


/**
 * Autocompleter
 *
 * http://digitarald.de/project/autocompleter/
 *
 * @version		1.1.2
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 * @requires    Ria_Hotel_Autocompleter_Observer
 */

var Ria_Hotel_Autocompleter_Autocompleter = new Class({

    Implements: [Options, Events],

    options: {/*
		onOver: $empty,
		onSelect: $empty,
		onSelection: $empty,
		onShow: $empty,
		onHide: $empty,
		onBlur: $empty,
		onFocus: $empty,*/
        withObjectType: 1,
        minLength: 1,
        markQuery: true,
        width: 'inherit',
        maxChoices: 10,
        injectChoice: null,
        customChoices: null,
        emptyChoices: null,
        visibleChoices: true,
        className: 'autocompleter-choices',
        zIndex: 42,
        delay: 400,
        observerOptions: {},
        fxOptions: {},

        autoSubmit: false,
        overflow: false,
        overflowMargin: 25,
        selectFirst: false,
        filter: null,
        filterCase: false,
        filterSubset: false,
        forceSelect: false,
        selectMode: true,
        choicesMatch: null,

        multiple: false,
        separator: ', ',
        separatorSplit: /\s*[,;]\s*/,
        autoTrim: false,
        allowDupes: false,

        cache: true,
        relative: false,
        displacement:{
            x:0,
            y:0
        }
    },

    initialize: function(element, options) {
        this.element = $(element);
        this.setOptions(options);
        this.build();
        this.observer = new Ria_Hotel_Autocompleter_Observer(this.element, this.prefetch.bind(this), $merge({
            'delay': this.options.delay,
            'key_field_id' : this.options.key_field_id
        }, this.options.observerOptions));
        this.queryValue = null;
        if (this.options.filter) this.filter = this.options.filter.bind(this);
        var mode = this.options.selectMode;
        this.typeAhead = (mode == 'type-ahead');
        this.selectMode = (mode === true) ? 'selection' : mode;
        this.cached = [];
    },

    /**
	 * build - Initialize DOM
	 *
	 * Builds the html structure for choices and appends the events to the element.
	 * Override this function to modify the html generation.
	 */
    build: function() {
        if ($(this.options.customChoices)) {
            this.choices = this.options.customChoices;
        } else {
            this.choices = new Element('ul', {
                'class': this.options.className,
                'styles': {
                    'zIndex': this.options.zIndex
                }
            }).inject(document.body);
            this.relative = false;
            if (this.options.relative) {
                this.choices.inject(this.element, 'after');
                this.relative = this.element.getOffsetParent();
            }
            this.fix = new OverlayFix(this.choices);
        }
        if (!this.options.separator.test(this.options.separatorSplit)) {
            this.options.separatorSplit = this.options.separator;
        }
        this.fx = (!this.options.fxOptions) ? null : new Fx.Tween(this.choices, $merge({
            'property': 'opacity',
            'link': 'cancel',
            'duration': 200
        }, this.options.fxOptions)).addEvent('onStart', Chain.prototype.clearChain).set(0);
        this.element.setProperty('autocomplete', 'off')
        .addEvent((Browser.Engine.trident || Browser.Engine.webkit) ? 'keydown' : 'keypress', this.onCommand.bind(this))
        .addEvent('click', this.onCommand.bind(this, [false]))
        .addEvent('focus', this.toggleFocus.create({
            bind: this,
            arguments: true,
            delay: 100
        }))
        .addEvent('blur', this.toggleFocus.create({
            bind: this,
            arguments: false,
            delay: 100
        }));
    },

    destroy: function() {
        if (this.fix) this.fix.destroy();
        this.choices = this.selected = this.choices.destroy();
    },

    toggleFocus: function(state) {
        this.focussed = state;
        if (!state) this.hideChoices(true);
        this.fireEvent((state) ? 'onFocus' : 'onBlur', [this.element]);
    },

    onCommand: function(e) {
        if (!e && this.focussed) return this.prefetch();
        if (e && e.key && !e.shift) {
            switch (e.key) {
                case 'enter':
                    if (this.selected && this.visible) {
                        this.choiceSelect(this.selected);
                        return !!(this.options.autoSubmit);
                    } else {
                        this.choiceSelect(this.choices.getChildren('li')[0]);
                        return !!(this.options.autoSubmit);
                    }
                    break;
                case 'up': case 'down':
                    if (!this.prefetch() && this.queryValue !== null) {
                        var up = (e.key == 'up');
                        this.choiceOver((this.selected || this.choices)[
                            (this.selected) ? ((up) ? 'getPrevious' : 'getNext') : ((up) ? 'getLast' : 'getFirst')
                            ](this.options.choicesMatch), true);
                    }
                    return false;
                case 'esc': case 'tab':
                    this.hideChoices(true);
                    break;
                case 'backspace':
                    var_temp =  this.element.value.split(',');
                    var str_lenght = var_temp.length;
                    var kol_symb = this.element.value.length;
                    if(this.element.value[kol_symb-1]==',') {
                        str_lenght = str_lenght-1;
                    }
                    if(str_lenght == 1) {
                        $(this.options.key_field_id).set('value','');
                        $(this.options.key_field_id).set('name','city_id');
                        if ($defined($('target'))) {
                            $('target').set('value','search');
                        }
                        if ($defined($('event'))) {
                            $('event').set('value','city');
                        }
                        autocomp_region_id = 0;
                        autocomp_city_id = 0;
                    }
                    if(str_lenght == 2) {
                        if($(this.options.key_field_id).value!="") {
                            if ($defined($('target'))) {
                                $('target').set('value','search');
                            }
                            if ($defined($('event'))) {
                                $('event').set('value','hotel');
                            }
                        }
                        if(autocomp_region_id != 0) {
                            autocomp_city_id = 0;
                            $(this.options.key_field_id).set('value',autocomp_region_id);
                            $(this.options.key_field_id).set('name','region_id');
                        } else if(autocomp_city_id != 0) {
                            $(this.options.key_field_id).set('value',autocomp_city_id);
                            $(this.options.key_field_id).set('name','city_id');
                        } else {
                            $(this.options.key_field_id).set('value','');
                            $(this.options.key_field_id).set('name','city_id');
                        }
                    }
                    if(str_lenght == 3) {
                        if ($defined($('target'))) {
                            $('target').set('value','search');
                        }
                        if ($defined($('event'))) {
                            $('event').set('value','hotel');
                        }
                        if(autocomp_city_id!=0)
                            $(this.options.key_field_id).set('value',autocomp_city_id);
                        else
                            $(this.options.key_field_id).set('value','');
                        $(this.options.key_field_id).set('name','city_id');
                    }
                    break;
            }
        }
        return true;
    },

    setSelection: function(finish) {
        this.queryValue = this.queryValue+'';// Приводим к строке чтобы toLowerCase не проваливался
        var input = this.selected.inputValue, value = input;
        var start = this.queryValue.length, end = input.length;
        if (input.substr(0, start).toLowerCase() != this.queryValue.toLowerCase()) start = 0;
        if (this.options.multiple) {
            var split = this.options.separatorSplit;
            value = this.element.value;
            start += this.queryIndex;
            end += this.queryIndex;
            var old = value.substr(this.queryIndex).split(split, 1)[0];
            value = value.substr(0, this.queryIndex) + input + value.substr(this.queryIndex + old.length);
            if (finish) {
                var tokens = value.split(this.options.separatorSplit).filter(function(entry) {
                    return this.test(entry);
                }, /[^\s,]+/);
                if (!this.options.allowDupes) tokens = [].combine(tokens);
                var sep = this.options.separator;
                value = tokens.join(sep) + sep;
                end = value.length;
            }
        }
        this.observer.setValue(value);
        this.opted = value;
        if (finish || this.selectMode == 'pick') start = end;
        this.element.selectRange(start, end);
        this.fireEvent('onSelection', [this.element, this.selected, value, input]);
    },

    showChoices: function() {
        var match = this.options.choicesMatch, first = this.choices.getFirst(match);
        this.selected = this.selectedValue = null;
        if (this.fix) {
            var pos = this.element.getCoordinates(this.relative), width = this.options.width || 'auto';
            pos.left = pos.left + this.options.displacement.y;
            pos.bottom = pos.bottom + this.options.displacement.x;
            this.choices.setStyles({
                'left': pos.left,
                'top': pos.bottom,
                'width': (width === true || width == 'inherit') ? pos.width : width
            });
        }
        if (!first) return;
        if (!this.visible) {
            this.visible = true;
            this.choices.setStyle('display', '');
            if (this.fx) this.fx.start(1);
            this.fireEvent('onShow', [this.element, this.choices]);
        }
        if (this.options.selectFirst || this.typeAhead || first.inputValue == this.queryValue) this.choiceOver(first, this.typeAhead);
        var items = this.choices.getChildren(match), max = this.options.maxChoices;
        var styles = {
            'overflowY': 'hidden',
            'height': ''
        };
        this.overflown = false;
        if (items.length > max) {
            var item = items[max - 1];
            styles.overflowY = 'scroll';
            styles.height = item.getCoordinates(this.choices).bottom;
            this.overflown = true;
        };
        this.choices.setStyles(styles);
        this.fix.show();
        if (this.options.visibleChoices) {
            var scroll = document.getScroll(),
            size = document.getSize(),
            coords = this.choices.getCoordinates();
            if (coords.right > scroll.x + size.x) scroll.x = coords.right - size.x;
            if (coords.bottom > scroll.y + size.y) scroll.y = coords.bottom - size.y;
            window.scrollTo(Math.min(scroll.x, coords.left), Math.min(scroll.y, coords.top));
        }
    },

    hideChoices: function(clear) {
        if (clear) {
            var value = this.element.value;
            if (this.options.forceSelect) value = this.opted;
            if (this.options.autoTrim) {
                value = value.split(this.options.separatorSplit).filter($arguments(0)).join(this.options.separator);
            }
        //this.observer.setValue(value);
        }
        if (!this.visible) return;
        this.visible = false;
        if (this.selected) this.selected.removeClass('autocompleter-selected');
        this.observer.clear();
        var hide = function(){
            this.choices.setStyle('display', 'none');
            this.fix.hide();
        }.bind(this);
        if (this.fx) this.fx.start(0).chain(hide);
        else hide();
        this.fireEvent('onHide', [this.element, this.choices]);
    },

    prefetch: function() {
        var value = this.element.value, query = value;
        if (this.options.multiple) {
            var split = this.options.separatorSplit;
            var values = value.split(split);
            var index = this.element.getSelectedRange().start;
            var toIndex = value.substr(0, index).split(split);
            var last = toIndex.length - 1;
            index -= toIndex[last].length;
            query = values[last];
        }
        if (query.length < this.options.minLength) {
            this.hideChoices();
        } else {
            if (query === this.queryValue || (this.visible && query == this.selectedValue)) {
                if (this.visible) return false;
            //                if($(this.options.key_field_id).get('name')!='hotel_id')
            //                    this.showChoices();
            } else {
                this.queryValue = query;
                this.queryIndex = index;
                if (!this.fetchCached()) this.query();
            }
        }
        return true;
    },

    fetchCached: function() {
        return false;
        if (!this.options.cache
            || !this.cached
            || !this.cached.length
            || this.cached.length >= this.options.maxChoices
            || this.queryValue) return false;
        this.update(this.filter(this.cached));
        return true;
    },

    update: function(tokens) {

        //       Устанавливаем значения по умолчанию
        if ($defined($("target"))){
            $("target").set("value","search");
        }
        if ($defined($("event"))){
            $("event").set("value","city");
        }


        this.choices.empty();
        this.cached = tokens.result;
        var type = tokens.result && $type(tokens.result);
        if (!type || (type == 'array' && !tokens.result.length) || (type == 'hash' && !tokens.result.getLength())) {
            (this.options.emptyChoices || this.hideChoices).call(this);
        } else {

            $each(tokens.result, function(item){
                var html = '';
                var target = '';
                var event = '';
                var key_field_name = '';
                var key_field_value = '';
                if (item.objectType == 'region') {
                    html = item.completeName;
                    if (this.options.withObjectType) html += ' <span class="DropMenuItemFeature">'+ item.completeRight +'</span>';
                    target = 'search';
                    event = 'hotel';
                    key_field_name = 'region_id';
                    key_field_value = item.region_id;
                } else if (item.objectType == 'city') {
                    html = item.completeName;
                    if (this.options.withObjectType) html += ' <span class="DropMenuItemFeature">'+ item.completeRight +'</span>';
                    target = 'search';
                    event = 'hotel';
                    key_field_name = 'city_id';
                    key_field_value = item.city_id;
                } else if (item.objectType == 'hotel') {
                    html = item.completeName;
                    if (this.options.withObjectType) html += ' <span class="DropMenuItemFeature">'+ item.completeRight +'</span>';
                    target = 'view';
                    event = 'hotel';
                    key_field_name = 'hotel_id';
                    key_field_value = item.hotel_id;
                }

                var choice = new Element('li', {
                    'target':target,
                    'html': this.markQueryValue(html),
                    'event':event,
                    'key_field_name':key_field_name,
                    'key_field_value':key_field_value,
                    'class':'DropMenuItem'
                });

                choice.inputValue = item.completeName;

                this.addChoiceEvents(choice).inject(this.choices);
            }.bind(this));

            this.showChoices();

        }
    },

    choiceOver: function(choice, selection) {
        if (!choice || choice == this.selected) return;
        if (this.selected) this.selected.removeClass('autocompleter-selected');
        this.selected = choice.addClass('autocompleter-selected');
        this.fireEvent('onSelect', [this.element, this.selected, selection]);
        if (!this.selectMode) this.opted = this.element.value;
        if (!selection) return;
        this.selectedValue = this.selected.inputValue;
        if (this.overflown) {
            var coords = this.selected.getCoordinates(this.choices), margin = this.options.overflowMargin,
            top = this.choices.scrollTop, height = this.choices.offsetHeight, bottom = top + height;
            if (coords.top - margin < top && top) this.choices.scrollTop = Math.max(coords.top - margin, 0);
            else if (coords.bottom + margin > bottom) this.choices.scrollTop = Math.min(coords.bottom - height + margin, bottom);
        }
    },

    choiceSelect: function(choice) {
        if (choice) {
            if(choice.getProperty('key_field_name')=='region_id') {
                autocomp_region_id = choice.getProperty('key_field_value');
            }
            if(choice.getProperty('key_field_name')=='city_id') {
                autocomp_city_id = choice.getProperty('key_field_value');
            }

            if ($defined($('target'))){
                $('target').setProperty('value', choice.getProperty('target'));
            }
            if ($defined($('event'))){
                $('event').setProperty('value', choice.getProperty('event'));
            }

            $(this.options.key_field_id).setProperties({
                'name': choice.getProperty('key_field_name'),
                'value': choice.getProperty('key_field_value')
            });
            this.choiceOver(choice);
        }
        this.setSelection(true);
        this.queryValue = false;
        this.hideChoices();

        //Fix IE Bug with setSelectionRange function
        if (this.element.setSelectionRange) {
            this.element.setSelectionRange(this.element.get('value').length, this.element.get('value').length);
            this.element.focus();
        } else if (this.element.createTextRange) {
            var range = this.element.createTextRange();
            range.collapse(true);
            range.moveEnd('character', this.element.get('value').length);
            range.moveStart('character', this.element.get('value').length);
            range.select();
        }
    },

    filter: function(tokens) {
        return (tokens || this.tokens).filter(function(token) {
            return this.test(token);
        }, new RegExp(((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp(), (this.options.filterCase) ? '' : 'i'));
    },

    /**
	 * markQueryValue
	 *
	 * Marks the queried word in the given string with <span class="autocompleter-queried">*</span>
	 * Call this i.e. from your custom parseChoices, same for addChoiceEvents
	 *
	 * @param		{String} Text
	 * @return		{String} Text
	 */
    markQueryValue: function(str) {
        return (!this.options.markQuery || !this.queryValue) ? str
        : str.replace(new RegExp('(' + ((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp() + ')', (this.options.filterCase) ? '' : 'i'), '<span class="autocompleter-queried">$1</span>');
    },

    /**
	 * addChoiceEvents
	 *
	 * Appends the needed event handlers for a choice-entry to the given element.
	 *
	 * @param		{Element} Choice entry
	 * @return		{Element} Choice entry
	 */
    addChoiceEvents: function(el) {
        return el.addEvents({
            'mouseover': this.choiceOver.bind(this, [el]),
            'click': this.choiceSelect.bind(this, [el])
        });
    }
});

var OverlayFix = new Class({

    initialize: function(el) {
        if (Browser.Engine.trident) {
            this.element = $(el);
            this.relative = this.element.getOffsetParent();
            this.fix = new Element('iframe', {
                'frameborder': '0',
                'scrolling': 'no',
                'src': 'javascript:false;',
                'styles': {
                    'position': 'absolute',
                    'border': 'none',
                    'display': 'none',
                    'filter': 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'
                }
            }).inject(this.element, 'after');
        }
    },

    show: function() {
        if (this.fix) {
            var coords = this.element.getCoordinates(this.relative);
            delete coords.right;
            delete coords.bottom;
            this.fix.setStyles($extend(coords, {
                'display': '',
                'zIndex': (this.element.getStyle('zIndex') || 1) - 1
            }));
        }
        return this;
    },

    hide: function() {
        if (this.fix) this.fix.setStyle('display', 'none');
        return this;
    },

    destroy: function() {
        if (this.fix) this.fix = this.fix.destroy();
    }

});

Element.implement({

    getSelectedRange: function() {
        if (!Browser.Engine.trident) return {
            start: this.selectionStart,
            end: this.selectionEnd
        };
        var pos = {
            start: 0,
            end: 0
        };
        var range = this.getDocument().selection.createRange();
        if (!range || range.parentElement() != this) return pos;
        var dup = range.duplicate();
        if (this.type == 'text') {
            pos.start = 0 - dup.moveStart('character', -100000);
            pos.end = pos.start + range.text.length;
        } else {
            var value = this.value;
            var offset = value.length - value.match(/[\n\r]*$/)[0].length;
            dup.moveToElementText(this);
            dup.setEndPoint('StartToEnd', range);
            pos.end = offset - dup.text.length;
            dup.setEndPoint('StartToStart', range);
            pos.start = offset - dup.text.length;
        }
        return pos;
    },

    selectRange: function(start, end) {
        if (Browser.Engine.trident) {
            var diff = this.value.substr(start, end - start).replace(/\r/g, '').length;
            start = this.value.substr(0, start).replace(/\r/g, '').length;
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', start + diff);
            range.moveStart('character', start);
            range.select();
        } else {
            this.focus();
            this.setSelectionRange(start, end);
        }
        return this;
    }

});

/* compatibility */

Ria_Hotel_Autocompleter_Autocompleter.Base = Ria_Hotel_Autocompleter_Autocompleter;

/**
 * Abstract class RIA Framework HTML Request
 * 
 * @class      RIA_HtmlRequest
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Revision: 1.2 $
 * @author     <a href="mailto:Oleg.Cherniy@gmail.com">Oleg Cherniy</a>
 * @requires   Ria_Ajax
 */
var Ria_HtmlRequest = new Class({

	Implements: Options,
	
	options: {
        host:   '',
		target: 'main',
		event: ''
	},

	/**
	 * @param {String} id id объекта, который будет обновлен по приходу ответа от сервера  
	 * @raram {Array} options параметры для построения запроса
	 */
	initialize: function(id, options){
		this.setOptions(options);
		$(id).load(this.options.host + Ria_Ajax.script + '?' + Hash.toQueryString(this.options));
	}
});
/**
 * Abstract class RIA Framework JSON Request
 *
 * @class      RIA_JsonRequest
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Revision: 1.2 $
 * @author     <a href="mailto:Oleg.Cherniy@gmail.com">Oleg Cherniy</a>
 * @requires   Ria_Ajax
 */

var Ria_JsonRequest = new Class({

    Implements: Options,
	
    options: {
        host:   '',
        target: 'main',
        event:  ''
    },

    /**
	 * @raram {Array} options параметры для построения запроса
	 */
    initialize: function(options){
        this.setOptions(options);
        new Request.JSON({
            url: this.options.host + Ria_Ajax.script,
            onComplete: this.onGetResponse.bind(this)
        }).get(this.options);
    },
	
    /**
	 * Метод, который будет выполнен после получения
	 * ответа на Ajax-запрос.
	 * Вам  нужно его переопредплить.
	 * 
	 * @param {Object} jsonObj Объект с данными из JSON-ответа
	 */
    onGetResponse: function(jsonObj) {}
});

/**
    * class RIA Hotel, add block info to search/hotels pages via HTML Request
    *
    * @class      Ria_Hotel_GetHotelRooms
    * @copyright  2008 IT RIA
    * @license    GNU GPL v2
    * @version
    * @author     Andrey Kotulskiy
    * @requires   Ria_Hotel_Load
    * @requires   Ria_HtmlRequest
    */
var Ria_Hotel_GetHotelRooms = new Class(
{

    Extends: Ria_HtmlRequest,

    options:
    {
        host: '',
        target: 'main',
        event: ''
    },

    /**
    * @param {String} id id объекта, который будет обновлен по приходу ответа от сервера
    * @raram {Array} options параметры для построения запроса
    */
    initialize: function(ids)
    {
        $(ids.Id_button).dispose();
        $(ids.Id_div).toggleClass('display_none');
    }
    
});
    
    
    
    

/**
 * Класс добавляющий Id объявления в блокнот залогиненого 
 * пользователя посредством JSON-запроса   
 *
 * @class Ria_Hotel_Notepad_AddUserNoteRequest
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_JsonRequest
 */
var Ria_Hotel_Notepad_AddUserNoteRequest = new Class({
    Implements : Options,
    Extends: Ria_JsonRequest,
	
    options: {
        host :      '',
        target :    'notepad',
        event :     'addhotel'
    },
	
     idPreffix: 'link_add_to_notepad_',
        
    onGetResponse: function(jsonObj) {
        this.json = jsonObj;

        if (jsonObj.result>0){
            var star = '<i class="icon-check_green"></i>';
            var className = 'button_small_adding';
            var notepadAnchor = $(this.idPreffix+this.options.hotelId);
             notepadAnchor.set('html',star + Lang.addeded_to_notepad);
             notepadAnchor.addClass(className);
             // обновляем количество в хедере
             this.animateAddingToNote();
        } else {
            alert(Lang.error);
        }
    },
    animateAddingToNote: function () {
            var event = this.options.mouseEvent;
            event.stop();
            // `this` refers to the element with the .item class
            var hotelImg = this.options.itemId ? $(this.options.itemId) : $('hotel_img_'+this.options.hotelId);
            var clone = hotelImg.clone().setStyles(hotelImg.getCoordinates()).setStyles({
                opacity: 0.7,
                position: 'absolute'
            });
            clone.inject(document.body);
            
            // prepare effects
            var duration = 450;
            var tweenHeight = new Fx.Tween(clone, {duration: duration});
            var tweenWidth = new Fx.Tween(clone, {duration: duration});
            
            var mover = new Fx.Move(clone, {
                relativeTo: $('userNotepadCount'),
                duration: duration, 
                position: 'upperRight',
                onComplete: function (el) {
                    el.dispose();
                    var count = $('userNotepadCount').get('html').replace(/\D+/g,"");
                    count = count*1 + 1;
                    if (!$('userNotepadCount').hasClass('notepad_count')) {
                        $('userNotepadCount').addClass('notepad_count');
                    }
                    $('userNotepadCount').set('html', count);
                    // burn effect
                    this.burnEffect();
                    // END burn effect
                    $(this.idPreffix+this.options.hotelId).removeEvents('click');
                }.bind(this)
            });
            
            // starting effects
            tweenHeight.start('height', 120, 12);
            tweenWidth.start('width', 160, 16);
            mover.start();
    },
    
    burnEffect: function () {
        var highlight = new Fx.Morph($('userNotepadCount'), {
            duration: 700,
            transition: 'quad:out',
            onComplete: function () {
                $('userNotepadCount').set('style','');
            }
        }).start({
            backgroundColor: ['#fff36f', '#fff'],
            opacity: [1, 0.7]
        });
    }
	
});
/**
 * FastBookButton
 *
 *
 *
 * @version		1.1.2
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 * @requires   Ria_Ajax
 */

Ria_Hotel_FastBookRequest = new Class ({

    Implements: Options,

    options:
    {
        target:     'booking',
        event:      'fast_book_button'
    },

    initialize: function(options)
    {
        this.setOptions(options);
        new Request.HTML({
            url: Ria_Ajax.script,
            onComplete: this.onGetResponse
        }).get(this.options);

    },

    onGetResponse: function(responseTree, responseElements, responseHTML, responseJavaScript) {
        $('fast_book_confirmation').set('html', responseHTML);
        $('fast_book_close_confirm').addEvent('click', function() {
            $('fast_book_div_form').setStyle('display', 'none');
        });
    }

});
/**
 * FastBookButton
 * @version		1.1.2
 *
 * @copyright	Author
 * @requires   Ria_Common_StatusImageManager2
 * @requires   Ria_Ajax
 * @requires   Ria_Common_ScrollingManager
 */

Ria_Hotel_Paginator_PaginatorRequest = new Class ({

    Implements: Options,

    options: {
        target:     '',
        event:      ''
    },

    initialize: function(paginatorManager, paginatorDivId, options) {
        this.paginatorManager = paginatorManager;
        this.parentId = paginatorDivId;
        options.page = paginatorManager.page;
        this.setOptions(options);

        new Ria_Common_StatusImageManager2({
            'elementId'         : paginatorDivId,
            'status'            : 'spinner',
            'spinnerImg'        : 'http://hotels24.ua/img/spinner.gif'
        });

        new Request.HTML({
            url: this.options.host + Ria_Ajax.script,
            evalScripts : false,
            onComplete: this.onGetResponse.bind(this)
        }).get(this.options);
    },

    onGetResponse: function(responseTree, responseElements, responseHTML, responseJavaScript) {
        if ($defined(responseHTML)){

            $(this.parentId).set('html', responseHTML);

            if ($defined($('id-search-search_hotel_list_header'))){
                $('id-search-search_hotel_list_header').set('html', $('id-search-search_hotel_list_header_paginator').get('html'));
                $('id-search-search_hotel_list_header_paginator').dispose();
            }

            if ($defined($('id-common-common_hotel_facilities'))){
                $('id-common-common_hotel_facilities').set('html', $('id-common-common_hotel_facilities_paginator').get('html'));
                $('id-common-common_hotel_facilities_paginator').dispose();
                this.paginatorManager.addFacilityChangeEvent();
                this.paginatorManager.addStarChangeEvent();
            }

            if ($defined($('id-search-search_hotel_list_sort'))){
                $('id-search-search_hotel_list_sort').set('html', $('id-search-search_hotel_list_sort_paginator').get('html'));
                $('id-search-search_hotel_list_sort_paginator').dispose();
                this.paginatorManager.addSortChangeEvent();
            }

            document.fireEvent('refresh');

            eval(responseJavaScript);

            if (responseHTML.contains('forPaginatorId')) {
                this.paginatorManager.setRequestedPage(this.options.page);
            }
        }
    }

});

var showHideFasilitiesFn = function(){
    if(this.clicked) {
        $$('.facilityHotel_'+this.id).addClass('display_none');
        this.set('text','и другие');
        this.clicked=false;
    } else {
        $$('.facilityHotel_'+this.id).removeClass('display_none');
        this.set('text','спрятать');
        this.clicked=true;
    }
};
/**
 * FastBookButton
 *
 *
 *
 * @version		1.1.2
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 * @requires   Ria_Ajax
 */

Ria_Hotel_Subscribe = new Class ({

    Implements: Options,

    options: {
        target:     'main',
        event:      'getSubscribeForm',
        mail:       '',
        subscribe:  ''

    },

    initialize: function(options) {
        $('mc-embedded-subscribe-form').addEvent('submit', function(){
            if ($defined($('mce-NAME'))) {
                if ($('mce-NAME').get('value').length < 2) {
                    alert("Имя должно быть содержать более двух символов");
                    return false;
                }
                this.options.name = $('mce-NAME').value;
            }
            this.options.mail = $('mce-EMAIL').value;
            this.options.subscribe = $('mce-EMAILTYPE-0').value;
            this.setOptions(options);


            new Request.HTML({
                url: Ria_Ajax.script,
                onComplete: this.onGetResponse
            }).get(this.options);

            return false;
        }.bind(this));

    },

    onGetResponse: function(responseTree, responseEl, responseHTML, responseJavaScript) {
        console.log(responseHTML);
        $('text-medium-float-l').set('html', responseHTML);
    }


});
/**
 * Класс для работы с Slideshow
 *
 * @class      Ria_Hotel_HotelImgSlider
 * @copyright  2011 RIA MULTIMEDIA
 * @license    GNU GPL v2
 * @requires   Ria_Hotel_Images_Slideshow
 * @requires   Ria_Ajax
 * @requires   Ria_Hotel_Alert
 * @requires   Ria_Hotel_AlertClose
 */
var Ria_Hotel_HotelImgSlider = new Class(
{
    Extends: Ria_JsonRequest,
    Implements: Options,

    options:
    {
        target:     'search',
        event:      'getHotelImages'
    },

    initialize: function(options)
    {
        this.setOptions(options);
        new Ria_Hotel_Alert('slideshowContainer', 'slideshowFon');

        new Request.HTML({
            url: Ria_Ajax.script,
            evalScripts : false,
            onComplete: this.onGetResponse.bind(this)
        }).get(this.options);

    },

    onGetResponse: function(responseTree, responseElements, responseHTML, responseJavaScript) {
        $('imageGallery').set('html', responseHTML);
        eval(responseJavaScript);
    },

    prepareData:function(JSON){
        images = JSON.images;
        var mainPhoto = images.mainHotelPhoto.mainHotelPhoto.replace('.jpg','mx.jpg');
        var link = images.mainHotelPhoto.link_word;
        data = new Object();

        if(mainPhoto != 'undefined')
            data[mainPhoto] = {
                caption: images.mainHotelPhoto.hotel_name,
                href: link
            } ;

        images.otherHotelPhoto.each(function(el){
            if(el.otherHotelPhoto != 'undefined')
                data[el.otherHotelPhotos.replace('.jpg','mx.jpg')] = {
                    caption: el.hotel_name,
                    href:link
                };
        });

        images.roomsHotelPhoto.each(function(el){
            if(el.roomHotelPhoto != 'undefined'){
                data[el.roomHotelPhoto.replace('.jpg','mx.jpg')] = {
                    caption: el.room_name ,
                    href:link
                };
            }
        });
        return data;
    },

    destroy:function () {
        $('imageGallery').set('html','');
        return false;
    }
});


/**
 * Галерейка
 *
 * @class      Ria_Hotel_Images_ImageGallery
 * @copyright  2011 IT RIA
 * @requires Ria_Hotel_AlertClose
 */
var Ria_Hotel_Images_ImageGallery = new Class({
    Implements:Options,
    options:{
        'type': 'full',
        'hotelData': {},
        'loadingMask':'#000', //color of the mask overlay during loading of the big images
        'loadingOpacity':0.6, //opacity of the border div during loading (including the mask)
        'selectSpeed':150, //the duration of the select effect in ms (high values will make it look ugly)
        'fadeSpeed':200, //the duration of the image fading effect in ms
        'pageSpeed':800, //the duration of the change page effect in ms
        'prevHandle':null, //if you pass a previous page handle in here, it will be hidden if it's not needed
        'nextHandle':null, //like above, but for next page
        'titleTarget':null, //target HTML element where image texts are copied into
        'bookingPlace':null,
        'initialIndex':-1, //which thumb to select after init. you could create deep links with it.
        'maxOpacity':0.8            //maximum opacity before cursor reaches prev/next control, then it will be set to 1 instantly.
    },
    navOpacity:{
        hover:0.7,
        simple: 0.4
    },
    /**
     *    Constructor. Starts up the whole thing :-)
     *
     *    This script is free to use. It has been created by http://www.aplusmedia.de and
     *    can be downloaded on http://www.esteak.net.
     *    License: GNU GPL 2.0: http://creativecommons.org/licenses/GPL/2.0/
     *    Example on: http://blog.aplusmedia.de/moo-gallery2
     *    Known issues:
     *    - preloading does not care about initialIndex param
     *    - hovering to a control over the border of the big image will make the other one flickering
     *    - if you enter and leave the control area very quickly, the control flickers sometimes
     *    - does not work in IE6
     *
     *     @param {Array} thumbs, An array of HTML elements
     *    @param {HTMLelement} bigImageContainer, the full size image
     *    @param {HTMLelement} pageContainer, If you have several pages, put them in this container
     *    @param {Object} options, You have to pass imagesPerPage if you have more than one!
     */
    initialize:function (thumbs, bigImageContainer, pageContainer, options) {
        this.currentPageNumber = 0;
        this.loadedImages = 0;
        this.blockKeys = false;
        this.imagesPerPage = pageContainer.getFirst().getChildren().length;
        this.setOptions(options);
        this.thumbs = thumbs;
        this.bigImage = bigImageContainer;
        this.pageContainer = pageContainer;
        this.manager();
    },
    
    manager: function (){
        this.convertThumbs();
        if (this.options.type == 'full') {
            this.createControls();
            this.createControlsLikeVk();
            this.positionGallery();
            this.galleryEvents();
        } else {
            // делаем чтоб листалось не по пейджах, а по картинке
            this.options.prevHandle.addEvent('click', this.prevImage.bind(this));
            this.options.nextHandle.addEvent('click', this.nextImage.bind(this));
            // END   делаем чтоб листалось не по пейджах, а по картинке
        }
        if (this.options.initialIndex != -1 || this.options.initialIndex == 0) {
            this.selectByIndex(this.options.initialIndex);
        } else {
            this.gotoPage(0);
        }
        this.loadNextImage();
    },
    /**
     *    Creates the previous and next links over the big image.
     */
    createControls:function () {
        this.prevLink = new Element('a', {
            events:{
                'mouseleave':this.mouseLeaveHandler.bindWithEvent(this),
                'click':this.prevImage.bindWithEvent(this)
            },
            styles:{
                'width':'80px',
                'display':'block',
                'position':'absolute',
                'top':0,
                'height':'400px',
                'opacity': 0,
                'visibility': 'hidden',
                'background':'url(/img/gallery/prev_image.png) no-repeat 0 50%',
                'outline':'none'
            },
            'href':'#'
        }).injectInside(this.bigImage.getParent());
        this.prevLink.addEvent('mouseover', this.focusControl.bindWithEvent(this, this.prevLink));
        this.nextLink = this.prevLink.clone().injectAfter(this.prevLink).set({
            'events':{
                'mouseleave':this.mouseLeaveHandler.bindWithEvent(this),
                'click':this.nextImage.bindWithEvent(this)
            },
            'styles':{
                'right':0,
                'background-image':'url(/img/gallery/next_image.png)'
            }
        });
        this.prevLink.setStyle('left', 0);
        this.nextLink.addEvent('mouseover', this.focusControl.bindWithEvent(this, this.nextLink));
        this.bigImage.getParent().addEvents({
            'mousemove':this.mouseOverHandler.bindWithEvent(this),
            'mouseleave':this.mouseLeaveHandler.bindWithEvent(this)
        });
        document.addEvent('keydown', this.keyboardHandler.bindWithEvent(this));
        this.mouseLeaveHandler();
    },
    /**
     * Focuses one control
     *
     * @param {Event} event
     * @param {HTMLElement} control
     */
    focusControl:function (event, control) {
        control.set('opacity', 1);
    //будем делать
    //        control.setStyle('background', 'url(http://cdn4.iconfinder.com/data/icons/bitcons/blue/32x32/arrow1_e.gif) no-repeat scroll 0 50% transparent');
    },
    /**
     *    Handles mouse movement over the big image.
     * @param {Event} event
     */
    mouseOverHandler:function (event) {
        var currentIndex = this.thumbs.indexOf(this.selectedContainer);
        //this makes the control on the other side fade out in just the moment when you reach one
        var activeRange = this.bigImage.getParent().getSize().x;
        var op = 0;
        if (currentIndex < this.thumbs.length - 1) {
            //            op = this.options.maxOpacity - this.getDistanceToMouse(this.nextLink, event) / activeRange;
            op = 1;
        }
        this.nextLink.set('opacity', op);
        op = 0;
        if (currentIndex > 0) {
            //            op = this.options.maxOpacity - this.getDistanceToMouse(this.prevLink, event) / activeRange;
            op = 1;
        }
        this.prevLink.set('opacity', op);
    },
    /**
     * Hides the controls.
     */
    mouseLeaveHandler:function () {
        this.nextLink.set('opacity', 0);
        this.prevLink.set('opacity', 0);
    // будем делать
    //        this.nextLink.setStyle('background', 'url(/img/gallery/next_image.png) no-repeat scroll 0 50% transparent');
    //        this.prevLink.setStyle('background', 'url(/img/gallery/prev_image.png) no-repeat scroll 0 50% transparent');
    },
    /**
     * Handles keyboard interactions.
     * @param {Event} event
     */
    keyboardHandler:function (event) {
        if (!this.blockKeys) {
            if (event.code >= 49 && event.code <= 57) {
                this.gotoPage(event.key - 1);
            } else if (event.key == "left") {
                this.prevImage(event);
            } else if (event.key == "right") {
                this.nextImage(event);
            }
        }
    },
    /**
     *    Returns the distance to the mouse from the middle of a given element.
     *    @param {HTMLelement} element
     *    @param {Event} event
     *     @return integer
     */
    getDistanceToMouse:function (element, event) {
        var s = element.getSize();
        var xDiff = Math.abs(event.client.x - (element.getLeft() + s.x / 2));
        var yDiff = Math.abs(event.client.y - (element.getTop() + s.y / 2));
        return Math.sqrt(Math.pow(xDiff, 2) + Math.pow(yDiff, 2));
    },
    /**
     *     Adds the border to the thumbs and so on. (conversion of static thumbs)
     */
    convertThumbs:function () {
        this.thumbs.each(function (thumbContainer, count) {
            this.convertThumb(thumbContainer, count);
        }, this);
    },
    /**
     * Converts one single thumb.
     * @param {HTMLelement} thumbContainer
     * @param {Integer} count
     */
    convertThumb:function (thumbContainer, count) {
        if (!$defined(thumbContainer)) {
            return;
        }
        thumbContainer.addEvent('click', this.select.bind(this, thumbContainer)).setStyle('position', 'relative').set('counter', count);
        var bigImage = thumbContainer.getFirst().set('href', 'javascript: void(0);').get('rel');
        var border = new Element('div', {
            'rel':bigImage,
            'description':thumbContainer.getElements('img')[0].get('title')
        });
        border.injectTop(thumbContainer).set('opacity', this.options.loadingOpacity);
        thumbContainer.getElements('img')[0].set('title', '');
    },
    /**
     *     Removes key blocking.
     */
    unBlockKeys:function () {
        this.blockKeys = false;
    },
    /**
     *    Selects a certain image. (You have to pass the outer container of the image)
     *    @param {HTMLelement} container
     */
    select:function (container) {
        if (this.blockKeys || !$defined(container)) {
            return false;
        }
        this.blockKeys = true;
        if ($defined(this.selectedContainer)) {
            //this prevents an ugly effect if you click on the currently selected item
            if (container == this.selectedContainer) {
                this.unBlockKeys();
                return false;
            }
            this.deselect(this.selectedContainer);
        }
        //if target image is not on current page, we have to go there first
        var targetPage = Math.floor(container.get('counter') / this.imagesPerPage);
        if (this.currentPageNumber != targetPage) {
            this.gotoPage(targetPage, container);
        }
        //
        this.options.hotelData.photoId  = container.get('id').replace(/\D+/g, '');
        this.selectedContainer = container;
        //make calculations a bit more handy
        var s = container.getSize();
        container.addClass('galery-page-item_active');
        var source = container.getFirst();
        this.setImage(source.get('rel'), source.get('description'));
        var self = this;
        if (this.options.bookingPlace) {
            self.showBookingTitle(container.getChildren('input')[0]);
        }
    },
    /**
     * Preloads one big image
     */
    loadNextImage:function () {
        var thumbContainer = this.thumbs[this.loadedImages].getFirst();
        //        if ($defined(this.options.loadingImage)) {
        //            new Element('img', {'src':this.options.loadingImage}).injectTop(thumbContainer);
        //        }
        var imageToLoad = thumbContainer.get('rel');
        new Asset.image(imageToLoad, {
            onload:this.imageLoaded.bind(this, this.thumbs[this.loadedImages])
        });
    },
    /**
     * Callback after an image has been successfully preloaded.
     * Removes the loading effects from the border div.
     * @param {HTMLElement} thumbContainer the thumb wrapper div
     */
    imageLoaded:function (thumbContainer) {
        this.loadedImages++;
        //        if ($defined(this.options.loadingImage)) {
        //            //remove loading gif
        //            thumbContainer.getFirst().getFirst().destroy();
        //        }
        //remove loading styles
        thumbContainer.getFirst().setStyle('background-color', 'transparent').setOpacity(1);
        if (this.loadedImages < this.thumbs.length) {
            this.loadNextImage();
        }
    },
    /**
     * Selects an image by its thumbnail index.
     * @param {integer} index of the thumbnail, starting with 0
     */
    selectByIndex:function (index) {
        if (index < 0 || this.thumbs.length < index) {
            index = 0;
        } else if (this.thumbs.length == index){
            return false;
        }
        var targetPage = Math.floor(this.thumbs[index].get('counter') / this.imagesPerPage);
        this.gotoPage(targetPage, this.thumbs[index]);
    },
    /**
     *    Opposite to method above.
     *    @param {HTMLelement} container
     */
    deselect:function (container) {
        container.removeClass('galery-page-item_active');
    },
    /**
     *    Changes the full size image to given one.
     *    @param {String} newSrc, new target of the full size image
     *    @param {String} newText, new text for the info element
     */
    setImage:function (newSrc, newText) {
        var effect = new Fx.Tween(this.bigImage, {
            duration:this.options.fadeSpeed, 
            transition:Fx.Transitions.Quad.easeOut
            });
        effect.start('opacity', 0).chain(function () {
            this.bigImage.set('src', newSrc);
            if ($defined($(this.options.titleTarget))) {
                $(this.options.titleTarget).set('html', newText);
            }
            if (this.options.type == 'full') {
//                this.mouseLeaveHandler();
            } else {
                this.openFullGallery();
            }
            effect.start('opacity', 1).chain(this.unBlockKeys.bind(this));
        }.bind(this));
    },
    /**
     *    Navigates to previous page.
     */
    prevPage:function () {
        this.gotoPage(this.currentPageNumber - 1);
    },
    /**
     *    Navigates to next page.
     */
    nextPage:function () {
        this.gotoPage(this.currentPageNumber + 1);
    },
    /**
     *    Selects the previous image.
     */
    prevImage:function (e) {
        e = new Event(e).stop();
        this.selectByIndex(this.thumbs.indexOf(this.selectedContainer) - 1);
    },
    /**
     *    Selects the next image.
     */
    nextImage:function (e) {
        e = new Event(e).stop();
        this.selectByIndex(this.thumbs.indexOf(this.selectedContainer) + 1);
    },
    /**
     *    Navigates to given page and selects the first image of it.
     *    Also hides the handles (if set).
     *    @param {Integer} pageNumber, index of the target page (0-n)
     *  @param {HTMLElement} selectImage, optionally receives a particular image to select
     */
    gotoPage:function (pageNumber, selectImage) {
        //if we like to select another image on that page than the first one
        selectImage = $pick(selectImage, this.thumbs[pageNumber * this.imagesPerPage]);
        var lastPage = Math.ceil(this.thumbs.length / this.imagesPerPage);
        if (pageNumber >= 0 && pageNumber < lastPage) {
            this.pageContainer.set('tween', {
                duration:this.options.pageSpeed,
                transition:Fx.Transitions.Quint.easeInOut
            });
            this.pageContainer.tween('margin-left', this.pageContainer.getFirst().getSize().x * pageNumber * -1);
            this.currentPageNumber = pageNumber;
            this.select(selectImage);

            //update handles
            if (pageNumber == 0) {
                this.options.prevHandle.setStyle('opacity', 0);
            } else{
                if ($defined(this.options.prevHandle)) {
                    new Fx.Tween(this.options.prevHandle, {
                        duration:this.options.fadeSpeed * 2
                    }).start('opacity', pageNumber == 0 ? 0 : 1);
                }
            }
            
            if (pageNumber == lastPage - 1)  {
                this.options.nextHandle.setStyle('opacity', 0);
            } else {
                if ($defined(this.options.nextHandle)) {
                    new Fx.Tween(this.options.nextHandle, {
                        duration:this.options.fadeSpeed * 2
                    }).start('opacity', pageNumber == lastPage - 1 ? 0 : 1);
                }
            }
        }
    },
    showBookingTitle: function(titleData){
        this.options.bookingPlace.getChildren('div').dispose();
        var myTitle = new Element('div', {
            html: titleData.value
        }).addClass('galery-booking-text');
        myTitle.injectInside(this.options.bookingPlace);
    },
    openFullGallery: function () {
        var self = this;
        self.options.hotelData.type = 'full'; 
        self.bigImage.getParent().removeEvents('click');
        self.bigImage.getParent().addEvent('click', function (e){
            new Ria_Hotel_HotelImgSlider(self.options.hotelData);
            e.stopPropagation();
        });
    },
    galleryEvents: function () {
        var self = this;
        document.addEvent('domready', function () {
            this.addEvents({
                // закрываем при нажатии Esc
                keydown: function(e){
                    if (e.code == 27) {self.closeGallery();}
                }
            });
            // закрываем при нажатии на крестик или справа от галереи
            $$('.closeSlideshow').addEvent('click', function(){
                self.closeGallery();
            });
            // позиционируем при resize окна
            window.addEvent('resize', function (e) {
                self.positionGallery();
            });
            $('body').setStyle('overflow', 'hidden');
        }, this);
    },
    closeGallery: function () {
        new Ria_Hotel_AlertClose("slideshowContainer","slideshowFon", true);
    },
    positionGallery: function () {
        var windowSize = window.getSize();
        var gallerySize = $('imageGallery').getSize();
        this.marginX = (windowSize.x - gallerySize.x) / 2;
        this.marginY = (windowSize.y - gallerySize.y) / 2;
        this.marginX = (this.marginX < 0) ? 20*2 : this.marginX;
        this.marginY = (this.marginY < 0) ? 20 : this.marginY;
        $('slideShow').setStyle('margin', this.marginY+'px '+this.marginX+'px');
        $('leftGalleryDiv').setStyles({
            'width': this.marginX+'px',
            'height': gallerySize.y+'px'
        });
        $('rightGalleryCloseDiv').setStyles({
            'width': this.marginX-10+'px',
            'height': gallerySize.y+'px'
        });
    },
    
    createControlsLikeVk: function () {
        this.addCloseDiv();
        this.addLeftDiv();
        this.addCloseBtn();
        this.bigImage.addEvent('click', function (e) {
            e = new Event(e).stop();
            this.nextImage(e);
        }.bind(this));
    },
    
    addCloseDiv: function () {
         var closeIco = new Element('div', {
            'class':'gal-close-ico'
        });
        var rightCloseDiv = new Element('div', {
            id: 'rightGalleryCloseDiv',
            'class': 'closeSlideshow',
            styles: {
                width: this.marginX+'px',
                cursor: 'pointer'
            }
        }).addClass('gal-close-div');
        closeIco.inject(rightCloseDiv);
        rightCloseDiv.inject($('slideshowContainer'));
    },
    
    addCloseBtn: function () {
        var parentEl = new Element('div', {
            id: 'gal-close-btn',
            styles:{
                'position': 'relative'
            }
        });
        var btn = new Element('a', {
            'class': 'close-butt',
            styles: {
                'position': 'absolute',
                'right': '-15px',
                'z-index': '5',
                'top': '-5px'
            }
        }).addClass('closeSlideshow');
        
        btn.inject(parentEl);
        parentEl.inject($('imageGallery'), 'before');
    },
    
    addLeftDiv: function () {
        var leftIco = new Element('div', {
            id: 'id-gal-prev-ico',
            'class': 'gal-prev-ico'
        });
        var leftDiv = new Element('div', {
            id: 'leftGalleryDiv',
            'class': 'gal-prev-div',
            styles: {
                width: this.marginX+'px',
                cursor: 'pointer'
            },
            events:{
                click: function (e) {
                    this.prevImage(e);
                }.bind(this)
            }
        });
        leftIco.inject(leftDiv);
        leftDiv.inject($('slideshowContainer'));
    }
});
/**
 *
 *
 * @class      Ria_Hotel_SelectRoomManager
 * @copyright  2010 IT RIA
 * @license    GNU GPL v2
 * @version
 * @requires Ria_Hotel_HotelImgSlider
 */
var Ria_Hotel_SelectRoomManager = new Class({

    tourSelected : 0,

    addRoomEvents:function(blockIter) {
        $('ajaxButonMoreInfo' + blockIter).addEvent('click', function() {
            $('ajaxInfoBlock' + blockIter).removeClass('display_none');
            $('ajaxDivMorInfo' + blockIter).setStyle('display','none');
            $('ajaxDivLessInfo' + blockIter).setStyle('display','block');
        });
        $('ajaxButonLessInfo' + blockIter).addEvent('click', function() {
            $('ajaxInfoBlock' + blockIter).addClass('display_none');
            $('ajaxDivMorInfo' + blockIter).setStyle('display','block');
            $('ajaxDivLessInfo' + blockIter).setStyle('display','none');
        });

        $('ajaxNameInfo' + blockIter).addEvent('mouseover', function() {
            if($defined($('roominfo2' + blockIter))){
                var tex123 = $('roominfo2' + blockIter).get('text');
                if (tex123 != '') {
                    $('ajaxSmollInfo' + blockIter).setStyle('display','block');
                }
           }
        });
        
        $('ajaxNameInfo' + blockIter).addEvent('mouseout', function() {
            $('ajaxSmollInfo' + blockIter).setStyle('display','none');
        });
    },

    addRoomPhotoEvents:function(imgElementId, photoSrc, slideOpt) {
        var imgElement = $(imgElementId);
        imgElement.addEvent('mouseover', function() {
            imgElement.setStyle('cursor','pointer');
            imgElement.setStyle('outline','2px solid #ffcc00');
            var position = imgElement.getPosition();
            $('imageconteyner').setStyles({
                display: 'inline',
                left: position['x']+100,
                top: position['y']+25
            });
            $('imgnomera').set('src', photoSrc);
            $('loadimgnomera').setStyles({
                display: 'inline',
                width: 300,
                height: 300
            });
        });

        imgElement.addEvent('mouseout', function() {
            imgElement.setStyle('outline','none');
            $('imageconteyner').setStyle('display','none');
        });
        imgElement.addEvent('click', function() {
             new Ria_Hotel_HotelImgSlider({
                hotel_id: slideOpt.hotel_id,
                photoId: slideOpt.photoId,
                getSlideType: 'room',
                type: 'full'
             });
        });
    },

    checkTourRoom: function(tourEl) {
        needAlert = false;
        var selectedTourId = tourEl.getProperty('tourId');
        if (this.tourSelected != selectedTourId && tourEl.value > 0) {
            $$('.selectTourClass').each(function(selectEl, index) {
                if (selectEl.getProperty('tourId') != selectedTourId && selectEl.value > 0) {
                    selectEl.value = 0;
                    needAlert = true;
                }
            });
            this.tourSelected = selectedTourId;
        }

        if ($defined($('tourSelectedId'))){
            $('tourSelectedId').value = this.tourSelected;
        }

        if (needAlert){
            alert('Допустимо бронирование номеров не учавствующих в турах,\nлибо номеров из одного тура...');
        }

    },
    
    setMaxPeopleCountEvent: function(){
         $$('.roomCountSelector ').addEvent('change',function(el){
             this.setMaxPeopleCount(el.target);
             this.calculateSumm(el.target.getParent('tr'));
          }.bind(this));
    },
    
    setMaxPeopleCount:function(roomSelector){
        var selectedRoomCount = roomSelector.value;
            
        var roomId = this.getIdFromString(roomSelector.id);

        var maxPeopleCountInRoom = $('maxOccupancy_'+roomId).value;
        var peoppleCountSelector = $('peopleCount_'+roomId).getChildren();
        var maxPeopleInSelectedRooms = maxPeopleCountInRoom * selectedRoomCount;

        $each(peoppleCountSelector,function(el){
            el.removeClass('display_none');

            if(el.value == maxPeopleInSelectedRooms){
                el.setProperty('selected','selected');
            }

            if(el.value > maxPeopleInSelectedRooms&& !!maxPeopleInSelectedRooms){
                el.addClass('display_none');
            }
        }.bind(roomSelector));
         this.toggleSelectedClass(roomSelector);
    },
    
    calculateSumm:function(parent){
        var roomCountSelector = parent.getElements('.roomCountSelector').pop();
        var priceDiv = parent.getElements('.price').pop();
        if(roomCountSelector.value > 1){
            var totalcost = parent.getElements('.totalcost').pop().value;
            var sum = totalcost * roomCountSelector.value;
            this[roomCountSelector.id] = priceDiv.get('html');
            priceDiv.set('html','<div class="price-new">'+sum+' грн</div>');
        }else{
            if($defined(this[roomCountSelector.id])){
                priceDiv.set('html',this[roomCountSelector.id]);
            }
        }
    },
    
    getIdFromString:function(id){
        var idArray = id.split('_');
        return idArray.pop(); 
    },
    
   setRoomCountEvent: function(){
      $$('.peoppleCountInRoom').addEvent('change',function(el){
           this.setRoomCount(el);
           this.calculateSumm(el.target.getParent('tr'));
      }.bind(this));
   },
   
   setRoomCount:function(el){
           var peoppleInRoomSelector = el.target;
           var selectedRoomCount = peoppleInRoomSelector.value;
           var roomId = this.getIdFromString(peoppleInRoomSelector.id);
           var roomCountSelector = $('blockCountSelector_'+roomId).getChildren(); 
           var maxPeopleCountInRoom = $('maxOccupancy_'+roomId).value;
           var nededRoomsCount = this.calculateCountRoomsByPeopleCount(selectedRoomCount,maxPeopleCountInRoom);

           $each(roomCountSelector,function(el){
               if(el.value == nededRoomsCount){
                   el.setProperty('selected','selected');  
               };
           }.bind(this));
            this.toggleSelectedClass(peoppleInRoomSelector);
       },
   
   calculateCountRoomsByPeopleCount:function(peoppleCount,maxCountInRoom){
       return Math.ceil(peoppleCount/maxCountInRoom);
   },
   
   
   toggleSelectedClass:function(element){
       var parrentTr = element.getParent('tr');
       if(element.value > 0){
           parrentTr.addClass('hotel-price-table-tr_active');
       }else{
            parrentTr.removeClass('hotel-price-table-tr_active');
       }
   },
   
   fireSelectOneRoom:function(){
       $$('.bookButtonId').addEvent('click', function(el){
           var bookButton = el.target;
           var notSingleRoomChosen = true;
            $$('.roomCountSelector').each(function(selectEl, index){
                if(selectEl.value > 0 ){
                    notSingleRoomChosen = false;
                }
            });
               
           if(notSingleRoomChosen){
             var clickedSelector = bookButton.getParent('tr').getElements('.roomCountSelector').pop();
             clickedSelector.value=1;
             clickedSelector.fireEvent('change',{target:clickedSelector});
           }    
       }.bind(this));
   }
   
});
/**
 * @class      Ria_Hotel_ScrollUp
 * @requires   Ria_Common_ScrollingManager
 */
var Ria_Hotel_ScrollUp = new Class({

    Implements: Options,

    options: {
        duration: 0
    },
    default_koef: 1.1,

    initialize: function (options){
        this.setOptions(options);
        this.prepareElement();
        this.calculate();
        this.process();
        this.addWindowEvents();
    },
    prepareElement: function () {
        this.el = new Element('div', {
            id : 'scroll_up-div',
            'class': 'scroll-up',
            styles: {
                height: '100%'
            }
        });
        this.subEl = new Element('div', {
            id : 'sub-scroll_up-div',
            'class': 'sub-scroll-up'
        }).inject(this.el);
        this.el.addEvents({
            click: function (e) {
                this.el.dispose();
                new Ria_Common_ScrollingManager('top_of_page', {
                    duration: this.options.duration
                });
            }.bind(this)
        });
    },
    process: function () {
        if (this.koef > this.default_koef){
            if (!$defined($('scroll_up-div'))) {
                this.el.inject($('layout-sidebar'));
            }
            this.el.setStyles({
                height: this.heightPercent+"%"
            });
        } else {
            if ($defined(this.el)){
                this.el.dispose();
            }
        }
    },
    calculate: function () {
        this.sidebarEndPosition = $('sidebar-end').getPosition();
        this.footerPosition = $('id-layout-footer').getPosition();
        this.footerSize = $('id-layout-footer').getSize();
        this.windowSize = document.getSize();
        this.scroll = document.getScroll();
        this.dynamicFooterSize = (this.windowSize.y - this.footerSize.y)+this.scroll.y;
        this.dynamicFooterSize = (this.footerPosition.y - this.dynamicFooterSize) - this.footerSize.y;
        if (this.dynamicFooterSize <= 0) {
            this.dynamicFooterSize *= -1;
            this.heightPercent = (100-((this.dynamicFooterSize / this.windowSize.y)*100)).toFixed(2);
        } else {
            this.heightPercent = 100;
        }
        this.koef = this.scroll.y / this.sidebarEndPosition.y;
        
    },
    addWindowEvents: function () {
        document.addEvents({
            refresh: function(){
                this.refresh();
            }.bind(this),
            scroll: function(){
                this.fireEvent('refresh');
            }
        });
    },
    refresh: function () {
        this.calculate();
        this.process();
    }
});
    /**
    * class RIA Hotel, add block info to search/hotels pages via HTML Request
    *
    * @class      Ria_Hotel_DisplayRoomInfo.js
    * @copyright  2009 IT RIA
    * @license    GNU GPL v2
    * @version
    * @author     Vitaliy Maryan
    * @requires   Ria_HtmlRequest
    */
    var Ria_Hotel_DisplayRoomInfo = new Class({

        Extends: Ria_HtmlRequest,

        options: {
            target: 'main',
            event: ''
        },

   /**
    * @param {String} id  объекта, который будет обновлен по приходу ответа от сервера
    * @raram {Array} options параметры для построения запроса
    */
        initialize: function(parentId, options){
          this.setOptions(options);
          $(parentId).empty();
          $(parentId).load(Ria_Ajax.script + '?' + Hash.toQueryString(this.options));
        }
    });

/**
 * 
 *
 * @class      Ria_Hotel_TopHotels
 * @copyright  2010 IT RIA
 * @license    GNU GPL v2
 * @version    
 * @requires   Ria_HtmlRequest
 * @requires   Ria_Common_StatusImageManager2
 */
var Ria_Hotel_TopHotels = new Class(
{
    Extends: Ria_HtmlRequest,
    Implements: Options,

    options: {
        
    },

    initialize: function(parentId, spinnerId, options){
        this.setOptions(options);
        this.parentId = parentId;
        this.spinnerId = spinnerId;
    },

    sendQuery: function(currHotelId){
        this.options['currHotelId'] = this.currHotelId;
        this.setOptions(this.options);

        if ($defined($(this.spinnerId))){
            $(this.spinnerId).setStyles({"background-color": "#D2D2D2",
                                        "opacity": "0.3",
                                        "width": "343px",
                                        "height": "140px",
                                        "position": "absolute",
                                        "top": "55px",
                                        "left": "22px",
                                        "padding-top": "75px",
                                        "padding-left": "275px",
                                        'display':'block'
                                    });

            new Ria_Common_StatusImageManager2({
                'elementId': this.spinnerId,
                'spinnerImg': 'http://hotels24.ua/img/loader/ajax-loader.gif'
            });

            new Request.HTML({
                url: Ria_Ajax.script,
                evalScripts : false,
                onComplete: this.onGetResponse.bind(this)
            }).get(this.options);
        }
        
    },

    onGetResponse: function(responseTree, responseElements, responseHTML, responseJavaScript){
        if ($defined(responseHTML)){
            if (responseHTML.indexOf( 'id-common-best_presents_common') > 0){
                $(this.parentId).set('html', responseHTML);
                eval(responseJavaScript);
                return 0;
            }
        }
        $(this.spinnerId).setStyle('display','none');
    },
    
    setCurrHotelId: function(currHotelId)
    {
        this.currHotelId = currHotelId;
    }


   
});
/**
 * http://code.google.com/intl/ru-RU/apis/maps/documentation/javascript/reference.html#MapOptions
 *
 * @requires   Ria_Ajax
 *
 */



var Ria_Map_GoogleMaps = new Class({
    Implements: Options,
    map : false,
    min_lat:0,
    min_lng:0,
    max_lat:0,
    max_lng:0,

    Ria_Maps_MARKER_GROUP : 1,
    Ria_Maps_MARKER_ITEM : 2,

    Ria_Maps_MARKER_TYPE_HOTEL : 255,

    Ria_Maps_MAPS_MIN_ZOOM : 6,
    Ria_Maps_MAPS_MAX_ZOOM : 19,


    markersArray : new Array(),

    cache : new Hash(),

    options : {},

    hiddenMarkerTypes : new Array(),
    hiddenMarkerCategory : new Array(),
    typeToShow : new Array(),
    categoryToShow : new Array(),

    config : new Hash({
        host : ''
    }),

    initialize : function (divId, mapOptions, config) {
        this.options  = {
            map_zoom: 6,
            map_latitude: 31,
            map_longitude: 49,
            streetViewControl: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                position: google.maps.ControlPosition.TOP_RIGHT
            },
            navigationControl: true,
            navigationControlOptions: {
                style: google.maps.NavigationControlStyle.DEFAULT
            },
            scaleControl : true,
            scrollwheel : false
        };
        this.setOptions(mapOptions);

        this.options.center = new google.maps.LatLng(this.options.map_latitude, this.options.map_longitude);
        this.options.zoom = this.options.map_zoom;

        this.config = new Hash(config);
        this.config.divId = divId;
        this.create();

    },

    create : function(){

        this.map = new google.maps.Map($(this.config.divId), this.options);

        google.maps.event.addListener(this.map, 'zoom_changed', function(){
            this.onLoad('zoom_changed');
        }.bind(this));

        google.maps.event.addListener(this.map, 'dragend', function(){
            if (this.isNeedRefresh()){
                this.loadMarkers();
            }
        }.bind(this));

        google.maps.event.addListenerOnce(this.map, 'tilesloaded', function(){
            this.onLoad('tilesloaded');
        }.bind(this));
    },

    getConfig : function(type) {
        if (this.config.has(type)) {
            return this.config.get(type);
        } else {
            return '';
        }
    },
    //
    //   MAP
    //

    getInfo : function(){
    },


    onLoad : function(event){
        this.getInfo();
        this.extendPosition();
        this.clearMarkers();
        if ($defined(this.infowindow)){
            this.infowindow.close();
        }
        if (this.getZoom() >= this.Ria_Maps_MAPS_MIN_ZOOM-1){
            this.loadMarkers();
        }
    },

    getZoom : function(){
        return this.map.getZoom();
    },

    setZoom : function(zoom) {
        zoom = (zoom > this.Ria_Maps_MAPS_MAX_ZOOM) ? this.Ria_Maps_MAPS_MAX_ZOOM : zoom;
        this.map.setZoom(zoom);
    },

    extendPosition : function(){
        this.min_lat = this.map.getBounds().getSouthWest().lat();
        this.min_lng = this.map.getBounds().getSouthWest().lng();
        this.max_lat = this.map.getBounds().getNorthEast().lat();
        this.max_lng = this.map.getBounds().getNorthEast().lng();

        var offset_lat = (this.max_lat - this.min_lat)/2;
        var offset_lng = (this.max_lng - this.min_lng)/2;

        this.min_lat = this.min_lat - offset_lat;
        this.min_lng = this.min_lng - offset_lng;

        this.max_lat = this.max_lat + offset_lat;
        this.max_lng = this.max_lng + offset_lng;
    },

    isNeedRefresh : function() {
        if (this.config.norefresh){
            return false;
        }
        var northEast = this.map.getBounds().getNorthEast();
        var southWest = this.map.getBounds().getSouthWest();

        if ((northEast.lat() > this.max_lat) ||
            (northEast.lng() > this.max_lng) ||
            (southWest.lat() < this.min_lat) ||
            (southWest.lng() < this.min_lng)) {
            this.extendPosition();
            return true;
        }
    },

    clearMarkers : function(){
        if (this.markersArray) {
            this.markersArray.each(function(item){
                item.setMap(null);
            })
            this.markersArray.length = 0;
        }
    },

    showGroup : function(lat, lng, zoom){
        if (!zoom || zoom > this.Ria_Maps_MAPS_MAX_ZOOM){
            zoom = this.getZoom() + 4;
        }
        this.clearMarkers();
        this.map.setCenter(new google.maps.LatLng(lat, lng));
        this.setZoom(zoom);
        this.loadMarkers();
    },

    getFromCache : function(data){
        var textId = 'obj_'+this.getZoom()+'_'+data.id;
        if (this.cache.has(textId)){
            return this.cache.get(textId+'');
        }
        return false;
    },

    toCache : function(data){
        var textId = 'obj_'+this.getZoom()+'_'+data.id;
        if (!this.cache.has(textId)){
            this.loadMarkerInfo(data);
        }
    },

    isInCache : function (data) {
        return (this.cache.has('obj_'+this.getZoom()+'_'+data.id));
    },

    addInCache : function(data){ // {zoom:int, id:text, content:text}
        this.cache.set('obj_'+this.getZoom()+'_'+data.id, data.content);
    },

    isHidden: function (id, type){
        if (type == 'cat'){
            return (this.hiddenMarkerCategory.contains(id*1));
        }
        return (this.hiddenMarkerTypes.contains(id*1));
    },

    setHidden : function(id, type){
        if (!this.isHidden(id, type)){
            if (type == 'cat'){
                this.hiddenMarkerCategory.push(id);
            } else {
                this.hiddenMarkerTypes.push(id);
            }
        }
    },

    setVisible : function (id, type){
        if (this.isHidden(id, type)){
            if (type == 'cat'){
                this.hiddenMarkerCategory.splice(this.hiddenMarkerCategory.indexOf(id*1),1);
            } else {
                this.hiddenMarkerTypes.splice((this.hiddenMarkerTypes.indexOf(id*1)),1);
            }
        }
    },

    addMarkersType : function (type){
        this.showMarkers(type);
        if (!this.typeToShow.contains(type)){
            this.typeToShow.push(type);
        }
        this.loadSights();
    },

    hideMarkers : function (type){
        this.setHidden(type);
        if (this.markersArray) {
            for (i in this.markersArray){
                if (this.markersArray[i].type_id == type){
                    this.markersArray[i].setVisible(false);
                }
            }
        }
    },

    addMarkerCategory : function (cat){
        this.showMarkers(cat, 'cat');
        if (!this.categoryToShow.contains(cat)){
            this.categoryToShow.push(cat);
        }
        this.loadSights();
    },

    hideMarkerCategory : function (cat){
        this.setHidden(cat, 'cat');
        if (this.markersArray) {
            for (i in this.markersArray){
                if (this.markersArray[i].category_id == cat){
                    this.markersArray[i].setVisible(false);
                }
            }
        }
    },
    //
    //   markers
    //
    generateRequestForSights : function (){
        var req = false;
        if (this.typeToShow.length){
            req = '&idlist='+this.typeToShow.join(',');
        }
        if (this.categoryToShow.length){
            req = (req ? req : '') + '&catlist='+this.categoryToShow.join(',') ;
        }
        return req;
    },

    getQuery : function(){

        var query = '';
        query  += '&zoom=' + this.getZoom();
        query  += (!this.max_lat) ? '' : '&max_ltt='  + this.max_lat;
        query  += (!this.max_lng) ? '' : '&max_lngt=' + this.max_lng;
        query  += (!this.min_lat) ? '' : '&min_ltt='  + this.min_lat;
        query  += (!this.min_lng) ? '' : '&min_lngt=' + this.min_lng;

        if (this.getConfig('filterType')){
            query  += '&filter_type='+this.getConfig('filterType')+'&filter_id='+this.getConfig('filterId');
        }

        if (this.getConfig('start_id')){
            query  += '&start_id=' + this.getConfig('start_id');
        }

        return query;
    },

    getScreen : function(){
        var screen = $(this.config.divId).getCoordinates();
        return '&width='+screen.width+'&height='+screen.height;
    },

    loadSights : function (){
        if (this.getZoom() < this.config.zoom2){
            return;
        }
        var types = this.generateRequestForSights();
        if (!types){
            return
        } else {
            types = '&idlist='+ types;
        }

        var MapRequest = new Request.JSON({
            method: 'get',
            url: this.getConfig('host') + Ria_Ajax.script,
            onComplete: function(txt){
                this.extractMarkersFromResponce(txt);
            }.bind(this)
        });
        var req = 'target=map&event=getsights&core_rewrite_off=1';
        MapRequest.send(req+this.getQuery()+types);
    },

    loadMarkers : function() {
        var MapRequest = new Request.JSON({
            method: 'get',
            url: this.getConfig('host') + Ria_Ajax.script,
            onComplete: function(txt){
                this.extractMarkersFromResponce(txt);
            }.bind(this)
        });
        var req = 'target=map&event=getgroup&core_rewrite_off=1';
        MapRequest.send(req+this.getQuery());
        this.loadSights();
    },

    showMarkers : function (id, type){
        this.setVisible(id, type);
        if (this.markersArray) {
            this.markersArray.each(function(item){
                if (type == 'cat'){
                    if (item.category_id == id && !item.getVisible())
                        item.setVisible(true);
                } else {
                    if (item.type_id == id && !item.getVisible())
                        item.setVisible(true);
                }
            })
        }
    },

    extractMarkersFromResponce : function(responce) {
        $each(responce, function(data, key){
            data.each(function(points){
                this.addRequestMarker(points);
            }.bind(this));
        }.bind(this));
    },

    addRequestMarker : function(marker){
        if (!marker.points[0].latitude || !marker.points[0].longitude){
            return;
        }
        var item_id = 0;
        if (marker.item_id){
            item_id = marker.item_id;
        }

        var zIndex = 0;
        if (this.getConfig('start_id') == marker.item_id){
            zIndex = 255;
        }

        marker = new google.maps.Marker({
            position: new google.maps.LatLng(
                marker.points[0].latitude,
                marker.points[0].longitude
                ),
            map: this.map,
            icon : new google.maps.MarkerImage(
                marker.icon.src,
                new google.maps.Size(
                    marker.icon.width,
                    marker.icon.height
                    )
                //                new google.maps.Point(-5,0)
                ),
            shadow: marker.icon.shadow,
            visible: !this.isHidden(marker.type_id),
            id: marker.points[0].point_id,
            flat: false,
            type_id: marker.type_id,
            category_id: marker.container_id,
            is_group: marker.is_group,
            item_id: item_id,
            zIndex : zIndex
        });

        google.maps.event.addListener(marker, 'click', function(){
            if ($defined(pageTracker)){
                pageTrackerManager.trackEvent('mapEvents', 'openInfoWindowForMarker');
            }
            this.openInfoWindowsForMarker(marker);
        }.bind(this));
        this.markersArray.push(marker);
    },

    addMarker : function(markerConfig){                                         // require
        marker = new google.maps.Marker({                                       // is_group = 1 or 0
            position: markerConfig.position,                                    // type_id - objectId, hotel - 255, other - sights
            map: this.map                                                       // item_id - id in base
        });                                                                     //
        this.markersArray.push(marker);
    },

    loadMarkerInfo : function (marker){
        if (this.isInCache(marker)){
            this.createInfoWindow(this.getFromCache(marker), marker);
            return;
        }
        var MapRequest = new Request({
            method: 'get',
            url: this.getConfig('host') + Ria_Ajax.script,
            onComplete: function(markerInfo){
                this.createInfoWindow(markerInfo, marker);
            }.bind(this)
        });

        var target = 'target=map';
        var event  = '&event=description';
        var rewrite = '&core_rewrite_off=1';

        var object_id = '';
        var object_type = '';

        var name = '';
        if (this.getConfig('thisName')){
            name = '&callfrom='+this.getConfig('thisName');
        } else {
            name = '';
        }

        switch(marker.type_id * 1){
            case this.Ria_Maps_MARKER_TYPE_HOTEL:
                if (marker.is_group*1 == this.Ria_Maps_MARKER_GROUP){
                    object_type= '&object=hotels_group';
                    object_id = '&object_id='+marker.id+'&zoom='+this.getZoom()+this.getScreen();
                } else if (marker.is_group == this.Ria_Maps_MARKER_ITEM){
                    var extinfo = '';
                    if (this.getConfig('extinfo')){
                        extinfo = '&extinfo=1';
                    }
                    object_type= '&object=hotel';
                    object_id = '&object_id='+marker.item_id+extinfo;
                }
                break;
            default:
                if (marker.is_group*1 == this.Ria_Maps_MARKER_GROUP){
                    object_type = '&object=sights_group'
                    object_id = '&object_id='+marker.id;
                } else if (marker.is_group == this.Ria_Maps_MARKER_ITEM){
                    object_type= '&object=sight';
                    object_id = object_id = '&object_id='+marker.item_id;
                }
                break;
        }

        var req = target + event + rewrite + object_type + object_id + name;
        MapRequest.send(req);

    },

    createInfoWindow : function(markerInfo, markerData){
        this.infowindow = new google.maps.InfoWindow({
            content: markerInfo,
            position: markerData.getPosition()
        });
        this.infowindow.open(this.map);
        this.addInCache({
            zoom:this.getZoom(),
            id:markerData.id,
            content:markerInfo
        })
    },

    //
    //   info window
    //
    openInfoWindowsForMarker : function(marker){
        if ($defined(this.infowindow))
            this.infowindow.close();
        this.loadMarkerInfo(marker);
    }
});
/**
    * class RIA Hotel, add block info to search/hotels pages via HTML Request
    *
    * @class      Ria_Hotel_RightDiscountRequest
    * @copyright  2008 IT RIA
    * @license    GNU GPL v2
    * @version
    * @requires   Ria_HtmlRequest
    * @requires   Ria_Common_StatusImageManager2
    */
var Ria_Hotel_SpeclistRequest = new Class({

    Extends: Ria_HtmlRequest,

    options: {
        host: '',
        target: 'main',
        event: 'speclist_request'
    },

    /**
    * @param {String} id id объекта, который будет обновлен по приходу ответа от сервера
    * @raram {Array} options параметры для построения запроса
    */
    initialize: function(parentId, options){
        this.setOptions(options);
        this.parentId=parentId;
        $(parentId).empty();

        new Element('div', {
            'id': 'discountSpinner',
            'styles': {
                'text-align': 'center'
            }
        }).inject(parentId);


        new Ria_Common_StatusImageManager2({
            'elementId': 'discountSpinner',
            'spinnerImg': 'http://hotels24.ua/img/loader/ajax-loader.gif'
        });
        

        new Request.HTML({
            url: Ria_Ajax.script,
//            evalScripts : false,
            onComplete: this.onGetResponse.bind(this)
        }).get(this.options);

    },

        onGetResponse: function(responseTree, responseElements, responseHTML, responseJavaScript){
        if ($defined(responseHTML)){
//            if (responseHTML.indexOf( 'regionSmallList') > 0){
                $(this.parentId).set('html', responseHTML);
                eval(responseJavaScript);
                return 0;
//            }
        }
    }
});

/**
 * Класс для работы с календариком
 *
 * @class      Ria_Hotel_AddAffiliate
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @requires   Ria_JsonRequest
 */
var Ria_Hotel_AddAffiliate = new Class(
{
	Extends: Ria_JsonRequest,

        options: {

		target: 'main',
                event: 'add_affiliate'
	},

        initialize: function(options)
        {
            this.setOptions(options);
            this.parent(this.options);
        },

        onGetResponse: function(jsonObj)
        {
                this.json = jsonObj;
                if(jsonObj.result['result']==0)
                {
                    if(jsonObj.result['isset_email']==1)
                        $('affiliate_isset_email').setStyle('display', 'block');
                    else if(jsonObj.result['phone']==1)
                        $('affiliate_phone_empty').setStyle('display', 'block');
                    else if(jsonObj.result['email']==1)
                        $('affiliate_email_empty').setStyle('display', 'block');

                     $('affiliate_allregistration_form').setStyle('display','block');
                     $('affiliate_spiner').setStyle('display','none');
                     $('affiliate_button_form').setStyle('margin-top','33px');

                }
                else if(jsonObj.result['result']==1)
                {


                    $('affiliate_alias_tbody').destroy();
                    $('affiliate_spiner').setStyle('display','none');
                    $('affiliate_backbut2').setStyle('display', 'block');
                    $('affiliate_regist_succs').setStyle('display', 'block');
                    $('affiliate_isset_email').setStyle('display', 'none');
                    $('affiliate_phone_empty').setStyle('display', 'none');
                    $('affiliate_email_empty').setStyle('display', 'none');
                    $('affiliate_window_size').setStyles({'width':'935px', 'height':'auto'});
                    $('affiliate_fio').set('text',jsonObj.result['fio']);
                    if(jsonObj.result['isset_affiliate_domen'])
                    {
                        $('isset_affiliate_domen').setStyle('display','block');
                        $('isset_affiliate_domen').set('text','Указанные Вами домены: '+jsonObj.result['isset_affiliate_domen']+' были зарегестрированы в системе ранее');
                    }
                    $('affiliate_surname').value='';
                    $('affiliate_name').value='';
                    $('affiliate_lastname').value='';
                    $('affiliate_domen').value='';
                    $('affiliate_email').value='';
                    $('affiliate_phone').value='';

                }
        }
});


/**
 * Класс для работы с партнерами
 *
 * @class      Ria_Hotel_AffiliateRegistration
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @requires   Ria_JsonRequest
 */

var Ria_Hotel_AffiliateRegistration = new Class(
{
    initialize: function()
    {

        $('affiliates_registration_parner').addEvent('click', function(e)
        {
                e.preventDefault();
                affiliate_alias_id = 1;
                affiliate_alias_count = 0;
                var tbody = new Element('tbody', {'id' : 'affiliate_alias_tbody'});
                tbody.inject($('affiliate_alias_site_coobrand'));
                $('affiliate_allregistration_form').setStyle('display','block');
                $('affiliate_add_alias').setStyle('display','block');
                $('registration_coobrend_form').setStyle('display','block');
                $('affiliate_button_form').setStyle('margin-top','40px');
                $('affiliate_window_size').setStyles({'width':'935px', 'height':'375px'});

                $('isset_affiliate_domen').setStyle('display','none');
                $('affiliate_isset_email').setStyle('display', 'none');
                $('affiliate_phone_empty').setStyle('display', 'none');
                $('affiliate_email_empty').setStyle('display', 'none');
                $('affiliate_backbut2').setStyle('display', 'none');
                $('affiliate_regist_succs').setStyle('display', 'none');




                $('affiliate_surname').set('value','');
                $('affiliate_name').set('value','');
                $('affiliate_lastname').set('value','');
                $('affiliate_domen').set('value','http://');
                $('affiliate_email').set('value','');
                $('affiliate_phone').set('value','');
                $('affiliate_icq').set('value','');
                $('affiliate_description').set('value','');
                $('affiliate_subdomen').set('value','http://');


                new Ria_Hotel_Alert('myElement', 'fonmyElement');
                return false;

        }
        );

            $('aff_reg_button').addEvent('click',function(e)
            {
                $('affiliate_allregistration_form').setStyle('display','none');
                $('registration_coobrend_form').setStyle('display','none');
                $('affiliate_spiner').setStyle('display','block');
                $('affiliate_isset_email').setStyle('display', 'none');
                $('affiliate_phone_empty').setStyle('display', 'none');
                $('affiliate_email_empty').setStyle('display', 'none');

                var alias_sites = new Array(20);
                var i=0;
                var elements = $$('.alias_site');
                $each(elements,function(value)
                {

                    alias_sites[i] = value.getProperty('value');
                    i++;

                 });

                //if($('affiliate_coobr_checkbox').get('checked'))
                //    var affiliate_coobr_checkbox = 1;
                //else
                //    var affiliate_coobr_checkbox = 0;
                new Ria_Hotel_AddAffiliate(
                {
                    'affiliate_surname':$('affiliate_surname').value,
                    'affiliate_name':$('affiliate_name').value,
                    'affiliate_lastname':$('affiliate_lastname').value,
                    'affiliate_domen':$('affiliate_domen').value,
                    'affiliate_email':$('affiliate_email').value,
                    'affiliate_phone':$('affiliate_phone').value,
                    'affiliate_icq':$('affiliate_icq').value,
                    'affiliate_description':$('affiliate_description').value,
                    'affiliate_subdomen':$('affiliate_subdomen').value,
                    //'affiliate_coobr_checkbox':affiliate_coobr_checkbox,
                    'affiliate_alias': alias_sites
               }
                );
            }
        );

    }


});
/**
 * Класс для работы с БлокамиКобренда
 *
 * @class      Ria_Hotel_GetCoobBlock
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @requires   Ria_JsonRequest
 */
var Ria_Hotel_GetCoobBlock = new Class(
{
	Extends: Ria_JsonRequest,

        options: {

		target: 'main',
                event: 'get_affiliate_block'
	},

        initialize: function(options)
        {
            this.setOptions(options);
            this.parent(this.options);
        },

        onGetResponse: function(jsonObj)
        {
                this.json = jsonObj;
                    $('affiliate_block_value').set('value',jsonObj.result);
                    $('affiliate_chblock_coob_form').setStyle('display','block');
                    $('affiliate_block_spiner').setStyle('display','none');
        }
});


/**
 * Класс для работы с БлокамиКобренда
 *
 * @class      Ria_Hotel_SetCoobBlock
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @requires   Ria_JsonRequest
 */
var Ria_Hotel_SetCoobBlock = new Class(
{
//	Extends: Ria_JsonRequest,
//
//        options: {
//
//		target: 'main',
//                event: 'set_affiliate_block'
//	},

        initialize: function(options)
        {
//            this.setOptions(options);
//            this.parent(this.options);

            var myRequest = new Request({
                url : 'ajax.php?target=main&event=set_affiliate_block',

                 method : 'post',
                 onComplete : this.onGetResponse.bind(this),
                 data : {
                    'block_id':options['block_id'],
                    'site_id':options['site_id'],
                    'site_id_vn':options['site_id_vn'],
                    'block_name_vn':options['block_name_vn'],
                    'affiliate_block_value':options['affiliate_block_value']
                    }
            });
            myRequest.send();


        },

        onGetResponse: function(jsonObj)
        {
            var result = JSON.decode(jsonObj);
            if(result['result']['result'] == 1)
            {
                //$('affiliate_block_value').set('value',jsonObj.result);
                if(result['result']['without_moderation']==0)
                   $('affiliate_without').setStyle('display','block');
                else
                   $('affiliate_without').setStyle('display','none');

                $('affiliate_chblock_coob_form').setStyle('display','none');
                $('affiliate_block_spiner').setStyle('display','none');
                $('affiliate_block_backbut2').setStyle('display','block');
                $('affiliate_block_save_succs').setStyle('display','block');

            }
        }
});




/**
    * class RIA Hotel, add block info to search/hotels pages via HTML Request
    *
    * @class      Ria_Hotel_DisplayHotelReviews.js
    * @copyright  2009 IT RIA
    * @license    GNU GPL v2
    * @version
    * @author     Vitaliy Maryan
    * @requires   Ria_HtmlRequest
    * @requires   Ria_Common_StatusImageManager2
    */
var Ria_Hotel_DisplayHotelReviews = new Class({

    Extends: Ria_HtmlRequest,

    options: {
        host: '',
        target: 'main',
        event: ''
    },

    /**
    * @param {String} id  объекта, который будет обновлен по приходу ответа от сервера
    * @raram {Array} options параметры для построения запроса
    */
    initialize: function(parentId, options) {
        this.setOptions(options);
        $(parentId).empty();
        new Ria_Common_StatusImageManager2({
            'elementId': parentId,
            'spinnerImg': 'http://hotels24.ua/img/loader/ajax-loader.gif'
        });
        $(parentId).load(this.options.host + Ria_Ajax.script + '?' + Hash.toQueryString(this.options));
    }
});

/**
    * class RIA Hotel, add block info to search/hotels pages via HTML Request
    *
    * @class      Ria_Hotels_GetHotelBlockDetailRequest
    * @copyright  2008 IT RIA
    * @license    GNU GPL v2
    * @version
    * @author     Sergey Dobrovolsky
    * @requires   Ria_HtmlRequest
    */
var Ria_Hotel_GetHotelBlockDetailRequest = new Class({

    Extends: Ria_HtmlRequest,

    options: {
        host: '',
        target: 'main',
        event: ''
    },

    /**
    * @param {String} id id объекта, который будет обновлен по приходу ответа от сервера
    * @raram {Array} options параметры для построения запроса
    */
    initialize: function(parentId, options) {
        this.parentId = parentId;
        this.setOptions(options);

        new Ria_Common_StatusImageManager2({
            'elementId': this.parentId,
            'spinnerImg': 'http://hotels24.ua/img/loader/ajax-loader.gif'
        });

        new Request.HTML({
            url: this.options.host + Ria_Ajax.script,
            evalScripts : false,
            onComplete: this.onGetResponse.bind(this)
        }).get(this.options);


    },

    onGetResponse: function(responseTree, responseElements, responseHTML, responseJavaScript) {
        if ($defined(responseHTML)){
            $(this.parentId).set('html', responseHTML);
            eval(responseJavaScript);
            if(this.options.callbackFn){
                this.options.callbackFn();
            }
            
        }
        
        
        
    }
    
});

/**
 *
 * @class      Ria_Hotel_SlideHotelInformationManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version
 * @param incom.titleClass string required
 * @param incom.options object
 * @requires Ria_Common_ScrollingManager
 */
var Ria_Hotel_SlideHotelInformationManager = new Class ({
    Implements: [Options],
    options:{
        titleClass: null,
        duration: 200,
        transition: Fx.Transitions.Pow.easeOut,
        expandTitle: 0,
        expFlag: [],
        ready: false,
        textSelection: false
    },
    list:[],

    initialize : function (options)
    {
        var self = this;
        if (!options.titleClass){return false;}
        if (options.transition) {
            switch (options.transition) {
                case 'cubic':options.transition = Fx.Transitions.Cubic.easeOut;break;
                case 'bounce':options.transition = Fx.Transitions.Bounce.easeOut;break;
                case 'linear':options.transition = Fx.Transitions.Linear;break;
                case 'elastic':options.transition = Fx.Transitions.Elastic.easeOut;break;
                case 'quad':options.transition = Fx.Transitions.Quad.easeOut;break;
                case 'quart':options.transition = Fx.Transitions.Quart.easeOut;break;
                case 'expo':options.transition = Fx.Transitions.Expo.easeOut;break;
                case 'circ':options.transition = Fx.Transitions.Circ.easeOut;break;
                case 'sine':options.transition = Fx.Transitions.Sine.easeOut;break;
                case 'back':options.transition = Fx.Transitions.Back.easeOut;break;
                case 'pow':options.transition = Fx.Transitions.Pow.easeOut;break;
                case 'quint':options.transition = Fx.Transitions.Quint.easeOut;break;
            }
        }
        this.setOptions(options);
        this.list = new Hash($$(this.options.titleClass));
        self.freeAll();
        this.list.addEvent('click', function (e) {
            var itemScope = this;
            e.stop();
            var eff = new Fx.Slide(itemScope.get('id') + '-content', {
                duration: self.options.duration,
                transition: self.options.transition,
                onComplete: function (e) {
                    itemScope.st = 'free';
                }
            });
            if (self.options.ready) {
                if (itemScope.st !== 'free') {
                    return false;
                }
                eff.toggle();
                self.changeIconArrow(itemScope);
            }
        });
        self.makeAnchors();
        self.options.ready = true;
    },
    freeAll: function() {
        var self = this;
        this.list.each(function(item, i) {
            item.st = 'free';
            self.expandDefault(item, i);
        });
    },
    expandDefault:function (obj, i) {
        var children = obj.getChildren('i');
        if (i != this.options.expandTitle) {
            $(obj.id + '-content').slide('out');
            children.removeClass('icon-circle-arrow_bottom');
            children.addClass('icon-circle-arrow_right');
        }
    },
    changeIconArrow:function (obj) {
        obj.st = 'buzzy';
        if (obj.getChildren('i').get('class') == 'icon-circle-arrow_bottom') {
            obj.getChildren('i').erase('class');
            obj.getChildren('i').set('class', 'icon-circle-arrow_right');
        } else {
            obj.getChildren('i').erase('class');
            obj.getChildren('i').set('class', 'icon-circle-arrow_bottom');
        }
    },
    anchorExpand: function(id) {
        var self = this;
        this.list.each(function(item, i) {
            var children = item.getChildren('i');
            if (item.get('id') == id) {
                $(item.get('id') + '-content').set('slide', {duration:0});
                $(item.get('id') + '-content').slide('in');
                children.removeClass('icon-circle-arrow_right');
                children.addClass('icon-circle-arrow_bottom');
            } else {
                $(item.get('id') + '-content').set('slide', {duration:0});
                $(item.get('id') + '-content').slide('out');
                children.removeClass('icon-circle-arrow_bottom');
                children.addClass('icon-circle-arrow_right');
            }
        });
    },
    makeAnchors: function () {
        var self = this;
        var childs = $('anchors').getChildren('li');
        childs.addEvent('click', function (e) {
            var id = e.target.get('id').replace('-anchor', '');
            self.anchorExpand(id);
            self._scroll.delay(self.options.duration, id);
        });
    },
    _scroll: function () {
        new Ria_Common_ScrollingManager(this);
    }
});
/**
 * class RIA Hotel, add block info to search/hotels pages via HTML Request
 * 
 * @class      Ria_Hotel_CheckCaptcha
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    
 * @author     Andrey Kotulskiy
 * @requires   Ria_JsonRequest
 */
var Ria_Hotel_CheckCaptcha = new Class({
	
	Extends: Ria_JsonRequest,
	
	options: {
	target: 'booking',
	event: 'checkimg'
	},

	/**
	 * @raram {Array} options параметры для построения запроса
	 */
	initialize: function(id,options){
		this.id = id;
		this.setOptions(options);
		new Request.JSON({url: Ria_Ajax.script, 
			onComplete: this.onGetResponse.bind(this)
		}).get(this.options);
	},
	
	/**
	 * Метод, который будет выполнен после получения
	 * ответа на Ajax-запрос.
	 * Вам  нужно его переопредплить.
	 * 
	 * @param {Object} jsonObj Объект с данными из JSON-ответа
	 */
	onGetResponse: function(jsonObj) {
		this.json = jsonObj;
		if (jsonObj.result==1){
			$(this.id.id).set('value', '1');
		} else {
			$(this.id.id).set('value', '');
		}
	}
});

/**
 * class RIA Hotel, fill the form if user has previos booking
 * 
 * @class      Ria_Hotel_FillForm
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    
 * @author     Andrey Kotulskiy
 * @requires   Ria_JsonRequest  
 */
var Ria_Hotel_FillForm = new Class({
	Implements: [Options],
	
	options: {
		target: 'booking',
		event: 'fillform'
	},

	/**
	 * @raram {Array} options параметры для построения запроса
	 */
	initialize: function(id,options){
		this.setOptions(options);
		this.id = id;
		new Request.JSON({url: Ria_Ajax.script, 
			onComplete: this.onGetResponse.bind(this)
		}).get(this.options);
	},
	
	/**
	 * 
	 * @param {Object} jsonObj Объект с данными из JSON-ответа
	 */
	onGetResponse: function(jsonObj) {
		this.json = jsonObj;
		var name = $(this.id.id2).get('value');
		var email = $(this.id.id1).get('value');
		if (name ==''){
			
			$(this.id.id2).set('value', jsonObj.result.NameBooker);
			$(this.id.id3).set('value', jsonObj.result.LastNameBooker);
			$(this.id.id4).set('value', jsonObj.result.guest_city);
			if (jsonObj.result.guest_country != '')$(this.id.id5).set('value', jsonObj.result.guest_country);
			$(this.id.id6).set('value', jsonObj.result.guest_telephone);
		}
		
	}
});

/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @class      Ria_Hotel_CountryCities
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_JsonRequest
 */
var Ria_Hotel_BookerInfo = new Class(
{
    Extends: Ria_JsonRequest,

    options: {
        host: '',
        target: 'booking',
        event: 'booker_info'
    },

    initialize: function(options) {
        this.setOptions(options);
        this.parent(this.options);
    },

    onGetResponse: function(jsonObj) {
        this.json = jsonObj;
        if ($defined(jsonObj.BookerInfo)){
            if($('NameBooker').value==null || $('NameBooker').value=="")
                $('NameBooker').set('value',jsonObj.BookerInfo['NameBooker']);
            if($('LastNameBooker').value==null || $('LastNameBooker').value=="")
                $('LastNameBooker').set('value',jsonObj.BookerInfo['LastNameBooker']);
            if($('guest_telephone1').value==null || $('guest_telephone1').value=="" || $('guest_telephone1').value=='+380')
                $('guest_telephone1').set('value',jsonObj.BookerInfo['guest_telephone']);
        }
    }
});


/**
* class RIA Hotel, add block info to search/hotels pages via HTML Request
*
* @class      Ria_Hotel_CheckForm
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version
* @author     Andrey Kotulskiy
* @requires   Ria_Hotel_FormTips
*/
var Ria_Hotel_BookingManager = new Class(
{   
    isValidPhone: false,
    isValidEmail: false,
    valid: false,
    
    initialize: function(host) {
        var self = this;
        $('email').addEvent('change',function () {
                new Ria_Hotel_BookerInfo({
                'host':host,
                'email':$('email').get('value')
            });
        });
        $('bookingDataForm').addEvent('submit', function (e) {
            e.stop();
            e.preventDefault();
            self.validate();
            if (self.valid) {
                $('bookingDataForm').submit();
            }
        });
    },
    validate: function () {
        this.validatePhone($('guest_telephone1').get('value'));
        this.validateEmail($('email').get('value'));
        
        if (this.isValidPhone && this.isValidEmail && $('agree').get('checked')) {
            this.valid = true;
        } else {
            this.valid = false;
            if (!this.isValidPhone) {
                this.makePhoneTip();
            }
            if (!this.isValidEmail){
                this.makeEmailTip();
            }
            if (!$('agree').get('checked')){
                this.makeAgreementTip();
            }
        }
        if ($('agree').get('checked') && $defined($('agreement-tip'))) {
            $('agreement-tip').dispose();
        }
        if (this.isValidEmail && $defined($('email-tip'))) {
            $('email-tip').dispose();
        }
        if (this.isValidPhone && $defined($('phone-tip'))) {
            $('phone-tip').dispose();
        }
    },
    validateEmail: function (email) {
        var reg = new RegExp("[0-9a-z_]+@[0-9a-z_^.]+\\.[a-z]{2,3}", 'i');
        this.isValidEmail = reg.test(email);
    },
    validatePhone: function (phone) {
        phone = phone.replace(/\+/, "");
        var hasChar = phone.match(/\D+/g);
        this.isValidPhone = (phone.length < 10 || hasChar) ? false : true;
    },
    makePhoneTip: function () {
        var phoneTip = new Ria_Hotel_FormTips({
            id: 'phone-tip',
            el: $('guest_telephone1'),
            closeBtn: false,
            text: 'Номер телефона вводите в международном формате, без скобок, пробелов, дефисов и тире.',
            offset : {
                x: 10,
                y: -22
            },
            className : 'tool-popup tool-popup_left',
            closeBtn : false
        });
        phoneTip.show();
    },
    makeEmailTip: function () {
        var emailTip = new Ria_Hotel_FormTips({
            id: 'email-tip',
            el: $('email'),
            closeBtn: false,
            text: 'Эти данние необходимы для получения подтверждения бронирования',
            offset : {
                x: 10,
                y: -8
            },
            className : 'tool-popup tool-popup_left',
            closeBtn : false
        });
        emailTip.show();
    },
    makeAgreementTip: function () {
        var agreementTip = new Ria_Hotel_FormTips({
            id: 'agreement-tip',
            el: $('agree'),
            closeBtn: false,
            text: 'Для того чтоб забронировать номер Вам необходимо подтвердить согласие  с условиями публичной оферты и договора про конфиденциальность',
            offset : {
                x: -295,
                y: -2
            },
            className : 'tool-popup tool-popup_right',
            closeBtn : false
        });
        agreementTip.show();
    }
});
/**
 *
 *
 * @class      Ria_Hotel_BookingRoomSelector
 * @copyright  2010 IT RIA
 * @license    GNU GPL v2
 * @version
 * @requires Ria_JsonRequest
 * @requires Ria_Hotel_SelectRoomManager
 * 
 */
var Ria_Hotel_BookingRoomSelector = new Class({
            Extends: Ria_JsonRequest,
   Implements: Options,


    roomNameIdPrefix :'roomName_',
    blockCountSelectorPrefix : 'blockCountSelector_',
    PRICE_TYPE_PER_PLACE : 2,
    
    freeRoomsCouldTooBook : [],
    allFreeRooms:[],
    bookedRooms:[],
    blockId : 0,
    blockShtraf : 1,
    blockTotalcost : 2,
    blockMaxOccupancy : 3,
    blockCountSelector : 4,
    tour_id:0,
    
    roomNameTr : 0,
    peoppleCountTr : 1,
    numberCountTr : 2,
    
    
    initialize:function(allBlocks,tour_id){
        this.tour_id = +tour_id;
        
        this.setNewAllFreeRooms(allBlocks);
        this.selectRoomManager = new  Ria_Hotel_SelectRoomManager();
        this.selectRoomManager.setMaxPeopleCountEvent();
        this.selectRoomManager.setRoomCountEvent();
        this.changeRoomEvent();
        this.deleteRoomEvent();
        this.hideLastDeleteButton();
        this.addRoomCountChangeEvent();
        this.addPeoppleCountChangeEvent();
        this.setPrepay();
    },
    
    setNewAllFreeRooms:function(allBlocks){
            this.allFreeRooms = allBlocks;
            var freeRoomsCouldTooBook = [];
            var bookedRooms = [];
            $each(this.allFreeRooms, function(room){
                if(!room['selectedRooms']){
                    freeRoomsCouldTooBook.push(room);
                }else{
                    bookedRooms.push(room);
                }
            }.bind(this));
            this.freeRoomsCouldTooBook = freeRoomsCouldTooBook;
            this.bookedRooms = bookedRooms;
    },
    
   addNewRoom:function(){
        this.addNewRoomInTabble();
    },
    
    replaceBookedRooms:function(newRoomId,oldRoomId){
         var newRoom = this.findRomObjectById(newRoomId);
         var oldRoom = this.findRomObjectById(oldRoomId);
         this.bookedRooms = this.deleteRoomFromArray(oldRoomId,this.bookedRooms);
         this.bookedRooms.push(newRoom);
    },
    
    addBookedRoom:function(newRoomId){
         var newRoom = this.findRomObjectById(newRoomId);
         this.setBookedRoomsCount(newRoom,1);
         this.bookedRooms.push(newRoom);
         this.calculateCostOfBookedRooms();
    },
    
    setBookedRoomsCount:function(roomObj,roomCount){
        if(!roomObj.selectedRooms){
            roomObj.selectedRooms = roomObj;
        }
        roomObj.selectedRooms.block_count = roomCount;
    },
    
    deleteRoomFromArray:function(roomId,roomArray){
        var newRooms = [];
        $each(roomArray,function(el){
             if(el.block_id != roomId){
                 newRooms.push(el);
             };
         }.bind(this));
         return newRooms;
    },
    
    deleteBookedRoomFromBookedRooms:function(element){
       var roomId = this.findRoomObjectFromChildElement(element).block_id;
       this.bookedRooms = this.deleteRoomFromArray(roomId,this.bookedRooms);
       this.calculateCostOfBookedRooms();
    },
    
    
    setCostToPage:function(){
        $('totalCostAllRooms').set('text',this.cost);
    },
    
    setPrepay:function(){
        this.prepay = 0;
        var schtrafArray = $$('.shtrafId');
        $each(schtrafArray,function(el){
            var parrent = el.getParent('td');//
            var select = parrent.getChildren('select').pop();
            this.prepay += select.value*el.value ;
        }.bind(this));
        $('prepayOfClient').set('text',this.prepay);
    },
    
    calculateCostOfBookedRooms:function(){
      var cost = +0;
      $each(this.bookedRooms,function(el){
          cost =  cost + this.getRoomPriceFromRoom(el,el.selectedRooms.block_count);
      }.bind(this));
      this.cost = cost;
    },
    
    addNewRoomInTabble:function(){
        this.selectedRoomCount = $$('.selectedRooms').length-1;
        var lastBookedRoom = $$('.selectedRooms').pop();
        this.showDeleteButtons();
        var clone = lastBookedRoom.clone();
        var newAddededRoom = this.getNewRoom();
        this.addBookedRoom(newAddededRoom.block_id);
        this.fillNewRoom(clone,newAddededRoom);
        clone.inject(lastBookedRoom,'after'); 
        this.setPrepay();
        this.hideNotAvaliableRooms();
        this.deleteRoomEvent();
        this.setCostToPage();
        this.addRoomCountChangeEvent();
        this.addPeoppleCountChangeEvent();
        return  clone;
    },
    
    getNewRoom:function() {
        var newAddededRoom = this.freeRoomsCouldTooBook.pop();
        if(this.freeRoomsCouldTooBook.length==0){
            this.hideRoomAddButton();
        }
        return newAddededRoom;
    },
    
    hideRoomAddButton:function(){
        $('addNewRoom').addClass('display_none');
    },

    showRoomAddButton:function(){
        $('addNewRoom').removeClass('display_none');
    },

    fillNewRoom:function(newRoom,newAddededRoom) {
        var roomCount =  this.selectedRoomCount + 1;
        this.setRoomPrice(newAddededRoom,newRoom,1);
       
        var roomCells = newRoom.getChildren();
        
        var roomNameDiv =  roomCells[this.roomNameTr].getChildren();
        var roomNameSelector =  roomNameDiv.pop().getChildren('select');
        
        roomNameSelector.set('id',this.roomNameIdPrefix+newAddededRoom.block_id );
        
        var selector = roomNameSelector.getChildren('option');
        
        
        roomNameSelector.removeEvents('change');
        roomNameSelector.addEvent('change', function(el){
           var element = el.target;
           this.changeRoom(element);
        }.bind(this));
        
        
        $each(selector[0],function(el){
            if(el.value==newAddededRoom.block_id){
                el.set('selected','selected');
            }
        });
        
        var peoppleCountSelector = roomCells[this.peoppleCountTr].getChildren('select').pop();
        peoppleCountSelector.name = this.replaceBlockIterIdInName(this.selectedRoomCount,roomCount,peoppleCountSelector.name,this.tour_id);
        peoppleCountSelector.set('id','peopleCount_'+newAddededRoom.block_id);  
        peoppleCountSelector.removeEvents('change');
        peoppleCountSelector.addEvent('change',function(el){
            this.selectRoomManager.setRoomCount(el);
        }.bind(this));
        
        var roomCountParent = roomCells[this.numberCountTr]; 
        var roomCountElements = roomCountParent.getChildren();
        var blockCountSelector = roomCountParent.getChildren('select').pop(); 
        
        blockCountSelector.removeEvents('change');
        blockCountSelector.addEvent('change',function(el){
            this.selectRoomManager.setMaxPeopleCount(el.target);
        }.bind(this));
        
        blockCountSelector.id = this.blockCountSelectorPrefix+newAddededRoom.block_id;   
        this.fillRoomCount(newAddededRoom,blockCountSelector);
        
        roomCountElements[this.blockId].value = newAddededRoom.block_id ;  
        roomCountElements[this.blockShtraf].value = newAddededRoom['straf']['price'] ;
        roomCountElements[this.blockShtraf].addClass('shtrafId');
        roomCountElements[this.blockTotalcost].value = newAddededRoom['incremental_price']['0']['price'];   
        roomCountElements[this.blockMaxOccupancy].value = newAddededRoom.max_occupancy ; 
        roomCountElements[this.blockMaxOccupancy].id = 'maxOccupancy_'+newAddededRoom.block_id ;    
      
        this.fillPeoppleCount(newAddededRoom,peoppleCountSelector);
        
        $each(roomCountElements,function(el){
            el.name = this.replaceBlockIterIdInName(this.selectedRoomCount,roomCount,el.name,this.tour_id);
        }.bind(this));
    },
    
    fillRoomCount:function(room,newRoomBolock){
         newRoomBolock.empty();
         var roomDeclentions = [['номер','номера','номеров'],['номер','номера','номеров'],['место','места','мест']]
        for(i=1;i <= room.freeRoomsCount;i++){
            var option = new Element('option');
            option.set('value',i);
            option.set('text',i+ ' '+ this.declOfNum(i,roomDeclentions[room.price_type]));
            option.inject(newRoomBolock);
        };
    },
    
    fillPeoppleCount:function(room,newPeoppleBolock){
        newPeoppleBolock.empty();
        var maxPeoppleCount = this.calculatePeoppleAndRoomCountInRoom(room,room.freeRoomsCount);
        for(i=1;i<=maxPeoppleCount;i++){
             var option = new Element('option');
             option.set('value',i);
             option.set('text',i);
             if(room.max_occupancy==i){
                 option.set('selected','selected');
             }
             option.inject(newPeoppleBolock);
        }
    },
    
    calculatePeoppleAndRoomCountInRoom:function(room,roomCount){
        if(this.PRICE_TYPE_PER_PLACE==room.price_type){room.max_occupancy = 1;}
        return roomCount * room.max_occupancy; 
    },
    
    replaceBlockIterIdInName:function(searchId,newId,blockName, tourId){
        if(tourId){
           return blockName.split('tour['+tourId+']['+searchId+']').join('tour['+tourId+']['+newId+']');
        }
        return blockName.split('block['+searchId+']').join('block['+newId+']');
    },
    
    changeRoomEvent: function(){
        $$('.roomName').removeEvents('change');
        $$('.roomName').addEvent('change',function(el){
           var element = el.target;
           this.changeRoom(element);
        }.bind(this));
    },
    
    changeRoom:function(element){
           var selectedRoom = this.findRoomInAllRooms(element.value);
           var previusRoomId = this.selectRoomManager.getIdFromString(element.id);
           var previusRoom = this.findRoomInAllRooms(previusRoomId);
           
           this.freeRoomsCouldTooBook.push(previusRoom);
           this.removeRoomFromFreeRooms(selectedRoom.block_id);
           this.replaceBookedRooms(selectedRoom.block_id,previusRoomId);
           var parrentTr = element.getParent('tr');
           
           this.fillNewRoom(parrentTr,selectedRoom);
           this.hideNotAvaliableRooms();
           this.addRoomCountChangeEvent();
           this.addPeoppleCountChangeEvent();
    },
    
    removeRoomFromFreeRooms:function(id){
      this.freeRoomsCouldTooBook = this.deleteRoomFromArray(id,this.freeRoomsCouldTooBook);
    },
    
    
    setRoomPrice:function(newRoom,parrent,roomCount){
        var priceContainer  = parrent.getElements('.price').pop();
        priceContainer.empty();
        var priceDiv = new Element('div');
        priceDiv.addClass('price-new');
        this.setBookedRoomsCount(newRoom,roomCount);
        this.replaceBookedRooms(newRoom.block_id,newRoom.block_id);
        this.calculateCostOfBookedRooms();
        this.setCostToPage()
        priceDiv.set('text',this.getRoomPriceFromRoom(newRoom,roomCount) + " грн.");
        this.setPrepay();
        priceDiv.inject(priceContainer);
    },
    
    getRoomPriceFromRoom:function(room,count){
        count--;
        if(count<0){
            return 0;
        }else{
            return +room.incremental_price[count].price;
        }
    },
    
    findRoomInAllRooms:function(id){
        var retVar = {};
        $each(this.allFreeRooms,function(el){
            if(id==el.block_id){
                retVar =  el;
            }
        });
        return retVar;
    },
    
    declOfNum:function(number, titles){
        var cases = [2, 0, 1, 1, 1, 2];  
        return titles[ (number%100>4 && number%100<20)? 2 : cases[(number%10<5)?number%10:5] ];  
    },
    
    hideNotAvaliableRooms:function(){
        var roomNameSelectors  = $$('.roomName');
        this.setFreeRoomIdArray();
        $each(roomNameSelectors,function(rooms){
            this.hideNotAvaliableRoomSelector(rooms);
        }.bind(this));
    },
    
    
    setFreeRoomIdArray:function(){
        var freeRoomIdArr = [];
        $each(this.freeRoomsCouldTooBook,function(el){
            freeRoomIdArr.push(el.block_id);
        });
        this.freeRoomIdArr = freeRoomIdArr;
    },
    
    
    hideNotAvaliableRoomSelector:function(roomSelector){
    var roomOption = roomSelector.getChildren();
        $each(roomOption,function(room){
            if(this.freeRoomIdArr.contains(room.value)===false && !room.get('selected')){
                room.addClass('display_none');
            }else{
                room.removeClass('display_none');
            }
        }.bind(this));
    },
    
    showDeleteButtons:function(){
         $$('.deleteRom').removeClass('display_none');
    },
    
    deleteRoomEvent:function(){
      $$('.deleteRom').removeEvents('click');
      $$('.deleteRom').addEvent('click',function(el){
          this.deleteRoom(el.target);
      }.bind(this));  
    },
    
    deleteRoom:function(element){
        this.addDeletedRoomToFreeRooms(element);
        this.deleteBookedRoomFromBookedRooms(element);
        element.getParent('tr').dispose();
        this.hideLastDeleteButton();
        this.showRoomAddButton();
        this.setCostToPage();
         this.setPrepay();
        this.hideNotAvaliableRooms();
    },
    
    hideLastDeleteButton:function(element){
        if($$('.deleteRom').length == 1){
               this.hideDeleteButton();
        }
    },
    
    hideDeleteButton:function(){
          $$('.deleteRom').addClass('display_none');
    },
    
    addDeletedRoomToFreeRooms:function(element){
      this.addRoomToFreeRooms(this.findRoomObjectFromChildElement(element));
    },

    findRoomObjectFromChildElement:function(element){
        return this.findRomObjectById(this.getBlockIdFromChild(element));
    },

    getBlockIdFromChild:function(element){
        return this.selectRoomManager.getIdFromString(element.getParent('tr').getElements('.roomName').pop().id);
    },
    
    findRomObjectById:function(id){
       var retElement = [];
       $each(this.allFreeRooms,function(el){
           if(el.block_id==id){
               retElement = el; 
           }
       }.bind(this));
       return retElement;
    },
    
    addRoomToFreeRooms:function(room){
        this.freeRoomsCouldTooBook.push(room);
    },
    
    addRoomCountChangeEvent:function(){
        $$('.roomCountSelector').removeEvent('change');
        $$('.roomCountSelector').addEvent('change',function(el){
            var element = el.target
            this.setRoomPrice(this.findRoomObjectFromChildElement(element),element.getParent('tr'),element.value);
        }.bind(this));
    },
    
    addPeoppleCountChangeEvent:function(){
        $$('.peoppleCountInRoom').removeEvent('change');
        $$('.peoppleCountInRoom').addEvent('change',function(el){
            var element = el.target;
            var id = this.selectRoomManager.getIdFromString(element.id);
            var maxPeopleCountInRoom = $('maxOccupancy_'+ id).value;
            var roomCount  =  this.selectRoomManager.calculateCountRoomsByPeopleCount(element.value,maxPeopleCountInRoom);
            this.setRoomPrice(this.findRoomObjectFromChildElement(element),element.getParent('tr'),roomCount);
        }.bind(this));
    }
    
//    addTourPreffixIfIsTour:function(){
//        
//    }
    
   });

/**
 * Autocompleter.Request
 *
 * http://digitarald.de/project/autocompleter/
 *
 * @version		1.1.2
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 * @requires   Ria_Hotel_Autocompleter_Autocompleter
 */
var autocomp_region_id = 0;
var autocomp_city_id = 0;
var autocomp_count_param = 0;
var lenght_temp ="";
var value1="";
var value2="";
var value3="";
var temp_city_name;
var temp_region_name;
Ria_Hotel_Autocompleter_Request = new Class({

    Extends: Ria_Hotel_Autocompleter_Autocompleter,

    options: {/*
		indicator: null,
		indicatorClass: null,
		onRequest: $empty,
		onComplete: $empty,*/
        postData: {},
        ajaxOptions: {},
        postVar: 'value'

    },

    query: function(){
        var data = $unlink(this.options.postData) || {};
        data[this.options.postVar] = this.queryValue;
        if(this.queryValue.length >3){
            data['key_field_id'] = $(this.options.key_field_id).value;
            data['key_field_name'] = $(this.options.key_field_id).get('name');
            if($(this.options.key_field_id).get('name')=='region_id'){
                autocomp_region_id = $(this.options.key_field_id).value;
            }
            if($(this.options.key_field_id).get('name')=='city_id'){
                autocomp_city_id = $(this.options.key_field_id).value;
            }
        } else {
            $(this.options.key_field_id).set('value','');
            $(this.options.key_field_id).set('name','city_id');
        }
        var indicator = $(this.options.indicator);
        if (indicator) indicator.setStyle('display', '');
        var cls = this.options.indicatorClass;
        if (cls) this.element.addClass(cls);
        this.fireEvent('onRequest', [this.element, this.request, data, this.queryValue]);
        var str = this.queryValue.split(',');
        if($(this.options.key_field_id).get('name')!='hotel_id'){
            if(str[1]!='' && str.length<=2)
                this.request.send({
                    'data': data
                });
            else if(str[2]!='' && str.length==3)
                this.request.send({
                    'data': data
                });
        }
    },

    /**
	 * queryResponse - abstract
	 *
	 * Inherated classes have to extend this function and use this.parent()
	 */
    queryResponse: function() {
        var indicator = $(this.options.indicator);
        if (indicator) indicator.setStyle('display', 'none');
        var cls = this.options.indicatorClass;
        if (cls) this.element.removeClass(cls);
        return this.fireEvent('onComplete', [this.element, this.request]);
    }

});

Ria_Hotel_Autocompleter_Request.JSON = new Class({

    Extends: Ria_Hotel_Autocompleter_Request,

    initialize: function(el, url, options) {
        this.options.key_field_id=options.key_field_id;
        this.parent(el, options);
        this.request = new Request.JSON($merge({
            'url': url,
            'link': 'cancel'
        }, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
    },

    queryResponse: function(response) {
        this.parent();
                
        this.update(response);
    }

});

Ria_Hotel_Autocompleter_Request.HTML = new Class({

    Extends: Ria_Hotel_Autocompleter_Request,

    initialize: function(el, url, options) {
        this.parent(el, options);
        this.request = new Request.HTML($merge({
            'url': url,
            'link': 'cancel',
            'update': this.choices
        }, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
    },

    queryResponse: function(tree, elements) {
        this.parent();
        if (!elements || !elements.length) {
            this.hideChoices();
        } else {
            this.choices.getChildren(this.options.choicesMatch).each(this.options.injectChoice || function(choice) {
                var value = choice.innerHTML;
                choice.inputValue = value;
                this.addChoiceEvents(choice.set('html', this.markQueryValue(value)));
            }, this);
            this.showChoices();
        }

    }

});

/* compatibility */

Ria_Hotel_Autocompleter_Autocompleter.Ajax = {
    Base: Ria_Hotel_Autocompleter_Request,
    Json: Ria_Hotel_Autocompleter_Request.JSON,
    Xhtml: Ria_Hotel_Autocompleter_Request.HTML
};

/**
 * Класс для инициализации поисковых форм
 *
 * @class      Ria_Hotel_Alert
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Id: Calendar.js,v 1.2 2008-11-10 07:46:05 simpl Exp $
 * @requires   Ria_Hotel_Autocompleter_Request
 * @requires   Calendar
 * @requires   Ria_Hotel_FormTips
 */
var Ria_Hotel_SearchFormManagerNew = new Class({

    initialize: function(withObjectType, autocompleterInit){
        //        Устанавливаем options авто комплитера
        autocompleterParam = {
            postVar: 'city',
            withObjectType: withObjectType,
            key_field_id: 'key_field_id',
            autoSubmit: false,
            onSelection: function (element, selected, value, input){
                $('submit_main').click();
            },
            ajaxOptions:{
                method : 'get'
            }
        };

        this.type = (withObjectType) ? 'main' : 'search';

        autocompleterInit = autocompleterInit || autocompleterParam;
        window.addEvent('domready', function() {
            if ($defined($('search_city'))) {
                $('search_city').setProperty('autocomplete', 'off');
                this.autocompleterRequest = new Ria_Hotel_Autocompleter_Request.JSON('search_city', 'ajax.php?target=main&event=check_cities_hotel', autocompleterInit );
            }
            this.myCal =  new Calendar({
                search_date_begin: {
                    search_date_begin: 'd.m.Y'
                },
                search_date_end: {
                    search_date_end: 'd.m.Y'
                }
            }, {
                offset: 1,
                direction: 0.5,
                tweak: {
                    x: 6,
                    y: 25,
                    sdvig: 225
                },
                pad: 1,
                onHideComplete: function () {
                    if ($('search_date_begin').get('value').length > 0 && $('search_date_end').get('value').length > 0){
                        if ($defined($('date-tip'))) {
                            $('date-tip').dispose();
                        }
                    }
                },
                onShowStart: function () {
                    if (!!$('unknown_dates').get('checked') && !!$('search_date_begin').get('disabled') && !!$('search_date_end').get('disabled')) {
                        $('unknown_dates').removeProperty('checked');
                        $('search_date_begin').removeProperty('disabled');
                        $('search_date_end').removeProperty('disabled');
                    }
                }
            });
        }.bind(this));

        $('unknown_dates').addEvent('change',function(e){
            if($('search_date_begin').get('disabled')){
                $('search_date_begin').removeProperty('disabled');
                $('search_date_end').removeProperty('disabled');
            } else {
                if ($defined($('date-tip'))) {
                    $('date-tip').dispose();
                }
                Cookie.dispose('startDate', {
                    path:'/'
                });
                Cookie.dispose('endDate', {
                    path:'/'
                });
                $('search_date_begin').set('disabled','true');
                $('search_date_end').set('disabled','true');
            }
        });

        this.hideSearchBlock();

        this.IncDecrPeopleCount();

        this.preCheckingEvents();
    },

    hideSearchBlock: function() {
        if ($('searchParamButton') || $('searchParamButtonMain')) {
            $('searchParamButton').addEvent('click', function (event) {
                event.preventDefault();
                $('searchRightParam').toggleClass('displayNoneRule');
                $('searchRightParamMain').toggleClass('displayNoneRule');
            });

            $('searchParamButtonMain').addEvent('click', function (event) {
                event.preventDefault();
                $('searchRightParam').toggleClass('displayNoneRule');
                $('searchRightParamMain').toggleClass('displayNoneRule');
            });
        }
    },
    IncDecrPeopleCount: function () {
        var id = 'search_form_people_count';
        $(id+'_inc').addEvent('click', function (e) {
            var placeCount = $(id).get('value')*1;
            if (placeCount >= 1 && placeCount < 6)
            {
                $(id).set('value', ++placeCount);
            }
        });
        $(id+'_decr').addEvent('click', function (e) {
            var placeCount = $(id).get('value')*1;
            if (placeCount > 1 && placeCount <= 6)
            {
                $(id).set('value', --placeCount);
            }
        });
        $(id).addEvent('change', function (e) {
            var placeCount = $(id).get('value')*1;
            if (placeCount < 1 || placeCount > 6) {
                $(id).set('value', 2);
            }
        });
    },

    preCheckingEvents: function () {
        $('search_form').addEvent('submit', function (e) {
            e.stop();
            var emptyCity = false;
            if ($defined($('search_city'))) {

                if ($('search_city').get('value').length > 0 && $defined(this.cityTip)){
                    this.cityTip.hide();
                    emptyCity = false;
                }
                if ($('search_city').get('value').length < 1) {
                    this.makeCityTip();
                    emptyCity = true;
                }
            }
            if (!$('search_date_begin').get('value') && !$('unknown_dates').checked && !emptyCity){
                this.makeDateTip();
                $('search_date_begin').fireEvent('focus');
                emptyCity = true;
            } else if (!$('search_date_end').get('value') && !$('unknown_dates').checked && !emptyCity){
                this.makeDateTip();
                $('search_date_end').fireEvent('focus');
                emptyCity = true;
            }
            if (!emptyCity){
                $('search_form').submit();
            }

        }.bind(this));
    },

    makeCityTip: function () {
        if (!$defined($('city-tip'))) {
            var options = {
                id: 'city-tip',
                el: $('search_city'),
                closeBtn: false,
                text: 'Пожалуйста, укажите, по крайней мере, часть названия города или гостиницы для начала поиска'
            }
            if ((this.type == 'main')) {
                options.offset = {
                    x: 9,
                    y: -23
                }
            } else {
                options.offset = {
                    x: -508,
                    y: -16
                };
                options.className = 'tool-popup tool-popup_right';
                options.closeBtn = false;
            }
            this.cityTip = new Ria_Hotel_FormTips(options);
            this.cityTip.show();
        }
    },
    makeDateTip: function (event) {
        if (!$defined($('date-tip'))) {
            var options = {
                id: 'date-tip',
                el: $('search_date_end'),
                closeBtn: false,
                text: 'Пожалуйста, укажите даты, чтобы посмотреть цены и наличие свободных номеров.'
            }
            if ((this.type == 'main')) {
                options.offset = {
                    x: 9,
                    y: -28
                }
            } else {
                options.offset = {
                    x: -508,
                    y: 5
                };
                options.className = 'tool-popup tool-popup_right';
                options.closeBtn = false;
            }
            this.dateTip = new Ria_Hotel_FormTips(options);
            this.dateTip.show();
        }
    }
});

/**
    * class RIA Hotel, add block info to search/hotels pages via HTML Request
    *
    * @class      Ria_Hotel_RightDiscountRequest
    * @copyright  2008 IT RIA
    * @license    GNU GPL v2
    * @version
    * @requires   Ria_HtmlRequest
    * @requires   Ria_Common_StatusImageManager2
    */
var Ria_Hotel_RightDiscountRequest = new Class({

    Extends: Ria_HtmlRequest,

    options: {
        host: '',
        target: 'main',
        event: 'right_discount'
    },

    /**
    * @param {String} id id объекта, который будет обновлен по приходу ответа от сервера
    * @raram {Array} options параметры для построения запроса
    */
    initialize: function(parentId, options){
        this.setOptions(options);
        $(parentId).empty();

        new Element('div', {
            'id': 'discountSpinner',
            'styles': {
                'text-align': 'center'
            }
        }).inject(parentId);

        new Ria_Common_StatusImageManager2({
            'elementId': 'discountSpinner',
            'spinnerImg': 'http://hotels24.ua/img/loader/ajax-loader.gif'
        });

        $(parentId).load(this.options.host + Ria_Ajax.script + '?' + Hash.toQueryString(this.options));
    }
});

/**
 * @class Ria_Hotel_PathManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_JsonRequest
 * @requires   Ria_Ajax
 */



var Ria_Hotel_PathManager = new Class({

    Implements: Options,

    options: {
        host :      '',
        target:     'main',
        event:      'path_options'
    },

    delayTime: 150,

    isVisible : false,

    initialize: function(options) {
        this.setOptions(options);
        this.pathStore = new Hash();
    },

    addItem:function(data){
        $(data.id).addEvent('mouseover', function(el){
            if (this.pathStore.get(data.id)){
                this.showHint(data.id,this.delayTime);
            } else {
            if(el.target.id != data.id){
                return true;
            }
                hash = new Hash(data).combine(new Hash(this.options));
                new Request.JSON({
                    url: this.options.host + Ria_Ajax.script,
                    onComplete: this.onGetResponse.bind(this)
                }).get(hash);
            }
        }.bind(this));

        $(data.id).addEvent('mouseout', function(){
            this.hideHint(data.id);
        }.bind(this));

    },

    onGetResponse:function(jsonObj){
        if (jsonObj.result>0) {
            this.pathStore.set(jsonObj.id, jsonObj.response);
            this.createHint(jsonObj.id);
            this.showHint(jsonObj.id);
        }
    },

    createHint:function(id){
        var html = '';
        var data = this.pathStore.get(id);

        var col_count = Math.ceil(data.length/20);

        var average = Math.ceil(data.length/col_count);

        html +='<div id="sub-menu-box_' + id + '" class="sub-menu-box columns-'+col_count+'">';
        html += '<div class="sub-menu-arrow" id="sub-menu-arrow_' + id + '"></div><div class="sub-menu-content" id="subpath_menu"><ul class="li-sub-mebu">';

        $each(data,function(item, index) {
            if (index>0 && (index%average)==0){
                html +='</ul><ul class="li-sub-mebu">';
            }
            html += '<li><a href="'+item.url+'">'+item.name+'</a></li>';

        }.bind(this));
        html += '</ul></div></div>';


        var pathHintDiv = new Element('div', {
            'id': id + 'pathHintDiv',
            'html': html,
            'class':'sub-menu-wrp fly-box-corn shadow-fly-box',
            'styles': {
                'display': 'none'
            }
        }).inject($(id));


//        var size = $('sub-menu-box_' + id).measure(function(){
//            return this.getSize();
//        });
//
//        var correctWidth = Math.ceil(size.x/2) - 30;
//
//        pathHintDiv.setStyle('left', -1 * correctWidth);
//        $('sub-menu-arrow_' + id).setStyle('left', 20 + correctWidth);

    },

    showHint:function(id,delayTime){
        var showHint = function(){
        $(id + 'pathHintDiv').setStyle('display', 'block');
        $(id + 'pathHintDiv').getParent().addClass('link-active')
       };

        showHint.delay(+delayTime);

        if ($defined(id + 'pathHintDiv')) {
            $(id + 'pathHintDiv').addEvent('mouseover', function(){
                this.isVisible = true;
            }.bind(this));

            $(id + 'pathHintDiv').addEvent('mouseout', function(){
                this.isVisible = false;
                this.hideHint(id);
            }.bind(this));
        }
    },

    hideHint:function(id) {
        if (!$defined($(id + 'pathHintDiv'))){
            return false;
        }
        var closePathList = function(){
            if (!this.isVisible){
                $(id + 'pathHintDiv').getParent().removeClass('link-active');
                $(id + 'pathHintDiv').setStyle('display', 'none');
            }
        }.bind(this);

        closePathList.delay(this.delayTime);

        return true;
    }

});

/**
 * Класс добавляющий Id объявления в блокнот не залогиненого 
 * пользователя посредством Cookie   
 *
 * @class Ria_Hotel_Notepad_AddUserNoteAjax
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Hotel_Notepad_AddUserNoteRequest
 */
var Ria_Hotel_Notepad_AddUserNoteAjax = new Class({
	
    Implements: Options,
	
    options: {
        host :          '',
        hotelId :       0,
        rubricArr :     '{}'
    },
	
	
    initialize: function(options){
    	
        this.setOptions(options);
        this.hotelId = this.options['hotelId'];
        
        this.rubricArr = new Hash(this.options['rubricArr']);
		
        if (this.hotelId>0){
            this.setEvent();
        }
		
    },
	
    setEvent:function(){
        var itemId = this.options.itemId ? this.options.itemId : false;
        $('link_add_to_notepad_'+this.hotelId).addEvent('click', function(event){
            new Ria_Hotel_Notepad_AddUserNoteRequest({
                'host':this.options['host'],
                'rubricId':0,
                'hotelId':this.hotelId,
                'mouseEvent': event,
                'itemId': itemId
                });
        }.bind(this));
    }
	
});
/**
 * FastBookManager
 *
 *
 *
 * @version		1.1.2
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 * @requires   Ria_Hotel_FastBookRequest
 * @requires   Ria_Hotel_Autocompleter_Request
 */

Ria_Hotel_FastBookManager = new Class ({

    initialize: function(){

        if ($defined($('fast_city_name'))) {
            $('fast_city_name').setProperty('autocomplete', 'off');
                new Ria_Hotel_Autocompleter_Request.JSON('fast_city_name', 'ajax.php?target=main&event=check_cities_hotel&hideHotels=1', {
                postVar: 'city',
                withObjectType: true,
                key_field_id: 'fast_key_field_id',
                ajaxOptions:{
        //                method : 'get'
                }
            });
        }



//        $('showMoreInfo').addEvent('change',function(){
//            $('moreInfo').toggleClass('display_none');
//        });


        $('fast_book_form').addEvent ('keypress',function(e) {
            if (e.key=="enter") {
                $('form_fast_book_form').fireEvent ('submit');
                return false;
            }
        });
        if ($defined($('fast_book_button_contacts'))) {
            $('fast_book_button_contacts').addEvent('click',function() {
                pageTrackerManager.trackEvent('fastBookForm', 'formShowHotelContact');
                var elementSize = $('fast_book_div_form').measure(function(){
                    return this.getSize();
                });
                var windowSize = window.getSize();
                var positionTop = (windowSize.y / 2) + window.getScroll().y - (elementSize.y / 2);
                $('fast_book_div_form').setStyles({
                  display:'block',
                  top: positionTop + 'px'
                });
                this.showForm();
            }.bind(this));
        }
        $('fast_book_button').addEvent('click',function() {
            pageTrackerManager.trackEvent('fastBookForm', 'formShow');
            this.showForm();
        }.bind(this));

        $('form_fast_book_form').addEvent('submit',function(event) {
            if (this.checkToPhone($("fast_phone_number").value)) {
                pageTrackerManager.trackEvent('fastBookForm', 'formSubmit');
                new Ria_Hotel_FastBookRequest ({
                    "keyFieldName"     : $('fast_key_field_id').get("name"),
                    "keyFieldValue"    : $('fast_key_field_id').get("value"),
                    "search_date_begin": $('fast_book_search_date_begin').value,
                    "search_date_end"  : $('fast_book_search_date_end').value,
                    "hotelId"          : $('fast_key_hotels_id').get("value"),
                    "fio"              : $('fast_book_name').get("value"),
                    "phoneNomber"      : $("fast_phone_number").get("value")
                });

                $('fast_book_form').setStyle ('display', 'none');

                $('fast_book_confirmation').setStyle ('display', 'block');
                new Ria_Common_StatusImageManager2({
                    'elementId': 'fast_book_confirmation',
                    'spinnerImg': 'http://hotels24.ua/img/loader/ajax-loader.gif'
                });

            } else {
                pageTrackerManager.trackEvent('fastBookForm', 'formInvalid');
                alert('Вы ввели неверный номер телефона');
            }
            return false;
        }.bind(this));

        $('close_fast_book_form').addEvent('click',function() {
            pageTrackerManager.trackEvent('fastBookForm', 'formClose');
            $('fast_book_div_form').setStyles({
                'display': 'none',
                'top':'100px'
            });
        }.bind(this));
    },

    checkToPhone:function(text) {
        expr = new RegExp('[^0-9]','g');
        found=text.replace(expr,'');
        if (found.length >= 9 && found.length ) {
            return true;
        }
        else return false;
    },


    showForm:function() {
        $('fast_book_div_form').setStyle('display', 'block');
        $('fast_book_form').setStyle('display', 'block');
        if ($defined($("fast_city_name"))) {
            $("fast_city_name").setProperty ('value','');
        }
        $("fast_phone_number").setProperty('value','');
        $('fast_book_name').setProperty('value','');
        $('fast_book_confirmation').setStyle('display', 'none');
    }
});

/**
 * FastBookManager
 *
 *
 *
 * @version		1.1.2
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 * @requires   Ria_Hotel_Paginator_PaginatorRequest
 */

Ria_Hotel_Paginator_PaginatorManager = new Class ({

    Implements: Options,

    options: {
        searchUrlParam:   {
            hotelCategoryFacility: [],
            stars: []
        },
        globalCount: 0
    },

    page: 0,

    showNextPart: false,

    requestedPage: 0,

    paginatorId: 0,

    paginatorElement: null,

    initialize: function(options){

        this.initClear();

        this.setOptions(options);

        window.addEvent('scroll', function(){
            if ($defined(this.paginatorElement) && this.showNextPart){
                var scroll = window.getScroll();
                var koorElement = this.paginatorElement.getCoordinates();

                if (scroll.y > koorElement.top - koorElement.height){
                    if (this.requestedPage == this.page){
                        this.page = this.requestedPage + 1;
                        new Ria_Hotel_Paginator_PaginatorRequest(this, 'paginatorDiv_' + this.paginatorId, this.options.searchUrlParam);
                    }
                }
            }
        }.bind(this));

        window.addEvent('domready', function(){
            this.addFacilityChangeEvent();
            this.addStarChangeEvent();
            this.addSortChangeEvent();
        }.bind(this));

    },

    initClear: function() {
        this.page = 0;
        this.showNextPart = false;
        this.requestedPage = 0;
    },

    setShowNextPart:function(){
        this.showNextPart = true;
        window.fireEvent('scroll');
    },

    setRequestedPage:function(page){
        this.requestedPage = page;
    },

    setPaginatorId: function(id){
        this.paginatorId = id;
        this.paginatorElement = $('paginatorElement_' + this.paginatorId);
    },

    addFacilityChangeEvent:function(){
        $$('.facility-indificator').addEvent('change', function(event){
            this.options.searchUrlParam.hotelCategoryFacility[event.target.value] = event.target.checked?1:0;
            this.initClear();
            new Ria_Hotel_Paginator_PaginatorRequest(this, 'superPaginatorDiv', this.options.searchUrlParam);
        }.bind(this));
    },

    addStarChangeEvent:function(){
        $$('.facility-star').addEvent('change', function(event){
            this.options.searchUrlParam.stars[event.target.value] = event.target.checked?event.target.value:0;
            this.initClear();
            new Ria_Hotel_Paginator_PaginatorRequest(this, 'superPaginatorDiv', this.options.searchUrlParam);
        }.bind(this));
    },

    addSortChangeEvent:function(){
        var self = this;
        $$('.sort-indificator').addEvent('click', function(event){
            event.stop();
            self.options.searchUrlParam.order_hotel = this.get('sortValue');
            Cookie.write('order_hotel', this.get('sortValue'), {duration: 10, path:'/', domain: '.hotels24.ua'});
            self.initClear();
            new Ria_Hotel_Paginator_PaginatorRequest(self, 'superPaginatorDiv', self.options.searchUrlParam);
        });
    }

});

/**
 * Description
 *
 * @class Ria_Hotel_TabSwitcher
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Common_ScrollingManager
 * @requires   Ria_Hotel_GetHotelBlockDetailRequest
 */
var Ria_Hotel_ViewHotelRoomInfoManager = new Class({

    initialize: function(host, hotelId, ajaxMode){

        this.hotelId = hotelId;
        this.host = host;

        this.setEvents();
    },

    startRequest: function (dateInputs, scrollTo){
        if ($defined(scrollTo)){
            new Ria_Common_ScrollingManager(scrollTo);
        }

        $('search_date_begin1').value = $(dateInputs.search_date_begin).value;
        $('search_date_end1').value = $(dateInputs.search_date_end).value;
        
        if($defined($('statickRoomInfo'))){
            $('statickRoomInfo').addClass('display_none');
        }
        
        new Ria_Hotel_GetHotelBlockDetailRequest('ajaxRoomInfo', {
            host:this.host,
            target: 'view' ,
            event: 'getdetailinfo' ,
            search_date_begin: $(dateInputs.search_date_begin).get('value'),
            search_date_end: $(dateInputs.search_date_end).get('value'),
            hotel_id: this.hotelId,
            callbackFn:this.hideCalendaryPr
        });
    },
    
    hideCalendaryPr:function(){
        $('calendaryPr').setStyle('display', 'none');
        $('dataZaezdaDiv').setStyle('display', 'block');
    },

    setEvents: function(){
        $('info_button').addEvent('click', function(e){
            e.stop();
            if (this.dateIsSet()) {
                this.startRequest({
                    'search_date_begin': 'search_date_begin1',
                    'search_date_end': 'search_date_end1'
                });
            } else {
                this.toggleCalendars();
            }
        }.bind(this));

        $('showDatesLink').addEvent('click', function(){
            $('calendaryPr').setStyle('display', 'block');
            $('dataZaezdaDiv').setStyle('display', 'none');
        }.bind(this));
        
        this.showCalendarsTipEvent();
    },
    
    toggleCalendars:function(){
        if (!$('search_date_begin1').get('value')){
            $('search_date_begin1').fireEvent('focus');
        } else if (!$('search_date_end1').get('value')){
            $('search_date_end1').fireEvent('focus');
        }
    },
    
    showCalendarsTipEvent:function(){
         $$('.scriptShowPricesId').addEvent('click',function(){
            if(this.dateIsSet()){
                 this.startRequest({
                    'search_date_begin': 'search_date_begin1',
                    'search_date_end': 'search_date_end1'
                });
            } else {
                new Ria_Common_ScrollingManager('nomera');
                var width = 250;   
                var dateTip = new Ria_Hotel_FormTips({
                    'className' : 'tool-popup tool-popup_right',
                    'closeBtn' : false,
                    'offset' : {
                        x: -$('calendaryPr').getWidth()-width-25,
                        y: -20
                    },
                    'id': 'date-tip',
                    'el': $('calendaryPr'),
                    'width': width+'px',
                    'text':'Пожалуйста, укажите даты, чтобы посмотреть цены и наличие свободных номеров'
                });
                dateTip.show();
                this.toggleCalendars();
            }    
        }.bind(this));
    },
    
    dateIsSet:function(){
        return (!!$('search_date_begin1').get('value') && !!$('search_date_end1').get('value'));
    }
    
});

/**
 * Класс для инициализации поисковых форм
 *
 * @class      Ria_Hotel_Alert
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Id: Calendar.js,v 1.2 2008-11-10 07:46:05 simpl Exp $
 * @requires   Ria_Hotel_Autocompleter_Request
 * @requires   Calendar
 */
var Ria_Hotel_SpecFormManager = new Class({

    initialize: function(){
        
        window.addEvent('domready', function() {

            myCal = new Calendar({
                specMonthyear1: {
                    specMonthyear1: 'Y-m',
                    specDay1: 'd' },
                specMonthyear2: {
                    specMonthyear2: 'Y-m',
                    specDay2: 'd' }
            },{
                offset: 1,
                direction: 0.5,
                
                tweak: {
                    x: 6,
                    y: 25,
                    sdvig: 225 },
                pad: 1,
                positionAfter: 0,
                notSelected: 1
            });
        });

        $('spec_unknown_dates').addEvent('change',function(e){
            if($('specDay1').get('disabled')){
                $('specDay1').removeProperty('disabled');
                $('specMonthyear1').removeProperty('disabled');
                $('specDay2').removeProperty('disabled');
                $('specMonthyear2').removeProperty('disabled');
            } else {
                $('specDay1').set('disabled','true');
                $('specMonthyear1').set('disabled','true');
                $('specDay2').set('disabled','true');
                $('specMonthyear2').set('disabled','true');
            }
        });
    }
});
/**
 * Autocompleter.Request
 *
 * http://digitarald.de/project/autocompleter/
 *
 * @version		1.1.2
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 * @requires   Ria_Hotel_Autocompleter_Autocompleter
 * @requires   Ria_Hotel_Autocompleter_Request
 */
var autocomp_region_id = 0;
var autocomp_city_id = 0;
var autocomp_count_param = 0;
var lenght_temp ="";
var value1="";
var value2="";
var value3="";
var temp_city_name;
var temp_region_name;
Ria_Hotel_Autocompleter_RequestBus = new Class({

    Extends: Ria_Hotel_Autocompleter_Request,

    options: {/*
		indicator: null,
		indicatorClass: null,
		onRequest: $empty,
		onComplete: $empty,*/
        postData: {},
        ajaxOptions: {},
        postVar: 'value',
        fileFieldId: ''

    },

    query: function(){
        var data = $unlink(this.options.postData) || {};
        data[this.options.postVar] = this.queryValue;
        data['postFile'] = $(this.options.fileNameFieldId).get('value');

        if(this.queryValue.length >3){
            data['key_field_id'] = $(this.options.key_field_id).value;
            data['key_field_name'] = $(this.options.key_field_id).get('name');
            if($(this.options.key_field_id).get('name')=='region_id'){
                autocomp_region_id = $(this.options.key_field_id).value;
            }
            if($(this.options.key_field_id).get('name')=='city_id'){
                autocomp_city_id = $(this.options.key_field_id).value;
            }
        } else {
            $(this.options.key_field_id).set('value','');
            $(this.options.key_field_id).set('name','city_id');
        }
        var indicator = $(this.options.indicator);
        if (indicator) indicator.setStyle('display', '');
        var cls = this.options.indicatorClass;
        if (cls) this.element.addClass(cls);
        this.fireEvent('onRequest', [this.element, this.request, data, this.queryValue]);
        var str = this.queryValue.split(',');
        if($(this.options.key_field_id).get('name')!='hotel_id'){
            if(str[1]!='' && str.length<=2)
                this.request.send({
                    'data': data
                });
            else if(str[2]!='' && str.length==3)
                this.request.send({
                    'data': data
                });
        }
    },

    /**
	 * queryResponse - abstract
	 *
	 * Inherated classes have to extend this function and use this.parent()
	 */
    queryResponse: function() {
        var indicator = $(this.options.indicator);
        if (indicator) indicator.setStyle('display', 'none');
        var cls = this.options.indicatorClass;
        if (cls) this.element.removeClass(cls);
        return this.fireEvent('onComplete', [this.element, this.request]);
    }

});

Ria_Hotel_Autocompleter_RequestBus.JSON = new Class({

    Extends: Ria_Hotel_Autocompleter_RequestBus,

    initialize: function(el, url, options) {
        this.options.key_field_id=options.key_field_id;
        this.parent(el, options);
        this.request = new Request.JSON($merge({
            'url': url,
            'link': 'cancel'
        }, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
    },

    queryResponse: function(response) {
        this.parent();
        
        this.update(response);
    },
    
    choiceSelect: function(choice) {
        if (choice) {
            if(choice.getProperty('key_field_name')=='region_id') {
                autocomp_region_id = choice.getProperty('key_field_value');
            }
            if(choice.getProperty('key_field_name')=='city_id') {
                autocomp_city_id = choice.getProperty('key_field_value');
            }
            
            if($defined(this.options.child_select)){
                child_select = $(this.options.child_select).removeProperty('disabled');
            }
            
            $(this.options.key_field_id).setProperties({
                'name': choice.getProperty('key_field_name'),
                'value': choice.getProperty('key_field_value')
            });
            this.choiceOver(choice);
        }
        
        this.setSelection(true);
        this.queryValue = false;
        this.hideChoices();
        this.element.setSelectionRange(this.element.value.length,this.element.value.length);
        this.element.focus();
    }

});

Ria_Hotel_Autocompleter_RequestBus.HTML = new Class({

    Extends: Ria_Hotel_Autocompleter_Request,

    initialize: function(el, url, options) {
        this.parent(el, options);
        this.request = new Request.HTML($merge({
            'url': url,
            'link': 'cancel',
            'update': this.choices
        }, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
    },

    queryResponse: function(tree, elements) {
        this.parent();
        if (!elements || !elements.length) {
            this.hideChoices();
        } else {
            this.choices.getChildren(this.options.choicesMatch).each(this.options.injectChoice || function(choice) {
                var value = choice.innerHTML;
                choice.inputValue = value;
                this.addChoiceEvents(choice.set('html', this.markQueryValue(value)));
            }, this);
            this.showChoices();
        }

    }

});

/* compatibility */

Ria_Hotel_Autocompleter_Autocompleter.Ajax = {
    Base: Ria_Hotel_Autocompleter_Request,
    Json: Ria_Hotel_Autocompleter_Request.JSON,
    Xhtml: Ria_Hotel_Autocompleter_Request.HTML
};

/**
 * Класс для инициализации поисковых форм
 *
 * @class      Ria_Hotel_Alert
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Id: Calendar.js,v 1.2 2008-11-10 07:46:05 simpl Exp $
 * @requires   Ria_Hotel_Autocompleter_Request
 * @requires   Calendar
 */
var Ria_Hotel_SearchFormManager = new Class({

    initialize: function(withObjectType,autocompleterInit){
        //        Устанавливаем options авто комплитера
        autocompleterParam = {
            postVar: 'city',
            withObjectType: withObjectType,
            key_field_id: 'key_field_id',
            ajaxOptions:{
                method : 'get'
            }
        }
        //
        autocompleterInit = autocompleterInit || autocompleterParam;
        window.addEvent('domready', function() {
            if ($defined($('search_city'))) {
                $('search_city').setProperty('autocomplete', 'off');

                new Ria_Hotel_Autocompleter_Request.JSON('search_city', 'ajax.php?target=main&event=check_cities_hotel',
                    autocompleterInit );
            }

            myCal = new Calendar({
                monthyear1: {
                    monthyear1: 'Y-m',
                    day1: 'd'
                },
                monthyear2: {
                    monthyear2: 'Y-m',
                    day2: 'd'
                }
            },{
                offset:1,
                direction: 0.5,
                tweak: {
                    x: 6,
                    y: 25,
                    sdvig: 225
                },
                pad: 1,
                positionAfter: 0,
                notSelected: 1
            });

        });

        $('unknown_dates').addEvent('change',function(e){
            if($('day1').get('disabled')){
                $('day1').removeProperty('disabled');
                $('monthyear1').removeProperty('disabled');
                $('day2').removeProperty('disabled');
                $('monthyear2').removeProperty('disabled');
            } else {
                Cookie.dispose('startDate', {
                    path:'/'
                });
                Cookie.dispose('endDate', {
                    path:'/'
                });
                $('day1').set('disabled','true');
                $('monthyear1').set('disabled','true');
                $('day2').set('disabled','true');
                $('monthyear2').set('disabled','true');
            }
        });      

    this.hideSearchBlock();
    },
       
    hideSearchBlock: function() {
        if ($('searchParamButton') || $('searchParamButtonMain')) {
            $('searchParamButton').addEvent('click', function (event) {
                event.preventDefault();
                $('searchRightParam').toggleClass('display_none');
                $('searchRightParamMain').toggleClass('display_none'); 
            });

            $('searchParamButtonMain').addEvent('click', function (event) {
                event.preventDefault();
                $('searchRightParam').toggleClass('display_none');
                $('searchRightParamMain').toggleClass('display_none'); 
            });
        }
    }

});

/**
 * Класс для инициализации поисковых форм
 *
 * @class      Ria_Hotel_Alert
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Id: Calendar.js,v 1.2 2008-11-10 07:46:05 simpl Exp $
 * @requires   Ria_Hotel_Autocompleter_RequestBus
 * @requires    Ria_Hotel_DateFormat
 * @requires   Calendar
 */
var Ria_Hotel_SearchBusTicketManager = new Class({

    defaultText: 'Название города',
    noactiveClass: '',
    activeClass: '',
    searchInput:$empty,
    searchInput2:$empty,
    form:$empty,
    
    options: {/*
		indicator: null,
		indicatorClass: null,
		onRequest: $empty,
		onComplete: $empty,*/
        searchString: 'search_city',
        searchString2: 'search_city2',
        key_field_id: 'key_field_id',
        key_field_id2: 'key_field_id2',
        postVar: 'value',
        fileFieldId: '',
        searchInput:$empty,
        searchInput2:$empty,
        key_field:$empty,
        key_field2:$empty,
        submitButon:$empty,
        form:$empty,
        submitBtnId:'busSubmitBtn',
        formId:'formToTickets'
    },
    
    initialize: function(){
    
        this.initOptions();

        this.searchInput.value = this.defaultText;
        
        this.searchInput2.value = this.defaultText;
        this.searchInput2.setProperty('disabled','disabled');
        
        this.searchInput.addEvent('focus',function(){
            this.activateSearch(this.searchInput);
        }.bind(this));
        
        this.searchInput2.addEvent('focus',function(){
            this.activateSearch(this.searchInput2);
        }.bind(this));
        
        
        this.searchInput.addEvent('blur',function(){
            this.deactivateSearch(this.searchInput);
        }.bind(this));
        
            this.searchInput2.addEvent('blur',function(){
            this.deactivateSearch(this.searchInput2);
        }.bind(this));
        
        
        window.addEvent('domready', function() {
            if ($defined(this.searchInput)) {
                this.searchInput.setProperty('autocomplete', 'off');
            this.searchInput.Autocompleter = new Ria_Hotel_Autocompleter_RequestBus.JSON('search_city', 'ajax.php?target=main&event=getBusTicketSities',
                    {
                        postVar: 'city',
                        fileNameFieldId:'startFileName',
                        withObjectType: false,
                        key_field_id: 'key_field_id',
                        ajaxOptions:{
                        method : 'get'
                        },
                        child_select:'search_city2'
                    });
                
               this.searchInput2.Autocompleter = new Ria_Hotel_Autocompleter_RequestBus.JSON('search_city2', 'ajax.php?target=main&event=getBusTicketSities',
                {
                    postVar: 'city',
                    fileNameFieldId:'key_field_id',
                    withObjectType: false,
                    key_field_id: 'key_field_id2',
                    ajaxOptions:{
                    method : 'get'
                    }
                });
            }
            
            this.form.addEvent('submit',function(){
               this.submitForm();
               return false;
            }.bind(this));
            
            this.form.addEvent('keydown',function(event){
                if (event.key=='enter'){
                    return false;
                }
            });
            
            myCal = new Calendar({
                monthyear1: {
                    day1: 'd',
                    monthyear1: 'Y-m'
                }
            },{
                offset: 1,
                direction: 0.5,
                tweak: {
                    x: 6,
                    y: 25,
                    sdvig: 225
                },
                pad: 1,
                positionAfter: 0,
                notSelected: 0
            });
        }.bind(this));

    },
    
    activateSearch:function(search){
          if(search.value==this.defaultText){
              search.value='';
          }
    },
    
    deactivateSearch:function(search){
        if(search.value==''){
              search.value=this.defaultText;
          }
    },
    
    submitForm:function(){
         new Ria_Hotel_DateFormat();
        if(this.key_field.value){
            this.key_field.setProperty('name','point_from');
        }
        else{
            alert('Пункт выезда не выбран');
            return false;
        }
        
        if(this.key_field2.value){
            this.key_field2.setProperty('name','point_to');
        }
        else{
            alert('Пункт назначения не выбран');
            return false;
        }
        dateStr = dateFormat($('monthyear1').value+'-'+$('day1').value,'dd.mm.yy');
        $('date').setProperty('value',dateStr);
        this.form.submit();
    },
    
    initOptions:function(){
        this.searchInput=$(this.options.searchString);
        this.searchInput2=$(this.options.searchString2);
        this.key_field=$(this.options.key_field_id);
        this.key_field2=$(this.options.key_field_id2);
        this.submitButon = $(this.options.submitBtnId);
        this.form = $(this.options.formId);
    }
    
});

