/**
 * 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) {
           var_temp =  this.element.value.split(',');
		this.value = value;
                if(var_temp.length==1){
                    if($(this.options.key_field_id).get('name')=='hotel_id')
                        this.element.set('value', value);
                    else
                        this.element.set('value', value+",");
                         autocomp_count_param=1;
                        lenght_temp = value;
                        value1 = value;
//                        this.onFired.delay(this.options.delay, this);
                }
                if(var_temp.length==2)
                {
                    if($(this.options.key_field_id).get('name')=='hotel_id')
                        this.element.set('value', var_temp[0]+', '+value);
                    else
                        this.element.set('value', var_temp[0]+', '+value+",");
                    lenght_temp = var_temp[0]+','+value;
                    autocomp_count_param=2;
                    value2=value;
//                    this.onFired.delay(this.options.delay, this);
                }
                if(var_temp.length==3){
                        this.element.set('value', var_temp[0]+','+var_temp[1]+', '+value);
                        lenght_temp = var_temp[0]+','+var_temp[1]+','+value;
                    autocomp_count_param=3;
                    value3=value;
                }
                this.element.setSelectionRange(this.element.value.length,this.element.value.length);
                this.element.focus();
		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: true,
            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, {
                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);
/**
 * 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: {
        'scrollStep'       : 50,
        'offsetTop'        : 20
	},


	initialize: function(scrollToId, options){
        this.setOptions(options);

        if ($defined(scrollToId)){
            var posit = window.getScroll();
            var koordiv = $(scrollToId).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);
                }
            }
        }
	}

});
/**
 * Определение переменных для работы 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':''
};
/**
 * Определение переменных для работы 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'
};

/**
 * class RIA Hotel, add block info to search/hotels pages via HTML Request
 * 
 * @class      Ria_Hotel_UnsetDetailRequest
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    
 * @author     Andrey Kotulskiy
 */
var Ria_Hotel_UnsetDetailRequest = new Class({
	
	options: {
		target: 'main',
		event: ''
	},

	/**
	 * @param {String} id id объекта, который будет обновлен по приходу ответа от сервера  
	 * @raram {Array} options параметры для построения запроса
	 */
	initialize: function(ids, options){
		$(ids.Id_div).empty();
                $(ids.spantext).set('text', Lang.show_prices);
		$(ids.Id_button).removeEvents('click');
		$(ids.Id_button).addEvent('click', function(){
				Ria_Hotel_Load.TimeoutFlag = '2';
                new Ria_Hotel_GetHotelBlockDetailRequest(ids,options);
                });
		}
});

/**
 * Класс прорисовывает анимированный 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);
            }
        }
		
    }
	
});

/**
 * @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);
    }
});
/**
 * Description
 *
 * @class Ria_Common_Datext
 * @copyright  2010 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 */
var Ria_Common_Datext = new Class({

    initialize: function(){

    },

    getDatext: function(numeric, one, two, many){
        numeric = Math.abs(numeric*1);
        if ( numeric % 100 == 1 || (numeric % 100 > 20) && ( numeric % 10 == 1 ) ) return one;
        if ( numeric % 100 == 2 || (numeric % 100 > 20) && ( numeric % 10 == 2 ) ) return two;
        if ( numeric % 100 == 3 || (numeric % 100 > 20) && ( numeric % 10 == 3 ) ) return two;
        if ( numeric % 100 == 4 || (numeric % 100 > 20) && ( numeric % 10 == 4 ) ) return two;
        return many;
    }
});


/**
* 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({

    options: {
        id1: 'NameBooker',
        id2: 'LastNameBooker',
        email: 'email',
        id3: 'guest_city',
        id4: 'guest_country',
        id5: 'guest_telephone'

    },

    /**
* @param {String} id id объекта, который будет обновлен по приходу ответа от сервера  
* @raram {Array} options массив Id которые нужно проверить
*/
    initialize: function(id, options){
        var id1s = $(options.id1).get('value');
        var id2s = $(options.id2).get('value');
        var id3s = $(options.id3).get('value');
        var id5s = $(options.id5).get('value');
        if($(options.id1).get('value') != ''&&
            $(options.id2).get('value') != ''&&
            $(options.id3).get('value') != ''&&
            $(options.id4).get('value') != ''&&
            id5s.length >= '7'&&
            $(options.email).get('value') != ''){
            $(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');
        }
    }
});

/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


var Ria_Hotel_BookingManager = new Class(
{
    initialize: function(host) {
        $('email').addEvent('change', function() {
            new Ria_Hotel_BookerInfo({'host':host, 'email':$('email').value});
        });
        
        $('divreserve').addEvent('mouseover', function() {
            new Ria_Hotel_CheckForm({
                    Id: 'reserve'
                }, {
                    id1: 'NameBooker',
                    id2: 'LastNameBooker',
                    email: 'email',
                    id3: 'search_city',
                    id4: 'guest_country',
                    id5: 'guest_telephone1'
            });
        });

    }

});
/**
 * 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_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_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 $
 */
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){
                        winAll=window.getScrollSize();
			winH = winAll.y;
			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){
                var em = $(emId);
		var fem = $(femId);
                
                em.setStyle('visibility', 'hidden');
                fem.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');
		});
	}
});
/**
 * RIA_Hotel_DisableOptgroup class disable selectrd <options> group 
 * 
 * 
 */

var Ria_Hotel_DisableOptgroup = new Class({
	Implements: Options,
	
	initialize: function(id, checked){
		this.id = id;
		this.checked = checked;
		this.build();
	},
	build: function(){
		var codeForDiv = 'disabled';
		if(!this.checked){$(this.id).setStyle('display','block')};
		if(this.checked){$(this.id).setStyle('display','none')};
	}	
	
});

/**
 * Класс прорисовывает анимированный gif в указанном div элементе   
 *
 * @class Ria_Common_StatusImageManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
*/
var Ria_Common_StatusImageManager = new Class({
	
    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(elementId, status, fadeEffect){
        this.elementId = elementId;
        this.status = status;
        this.fadeEffect = fadeEffect;
	
        this.showStatusImg();
    },
	
    showStatusImg:function (){
        var imgSrc = '';
        if (this.status == 'spinner'){
            imgSrc = this.spinnerImg;
        } else if (this.status == 'check'){
            imgSrc = this.checkImg;
        } else if (this.status == 'error'){
            imgSrc = this.errorImg;
        }
		
        if (imgSrc){
            var statusDiv = $(this.elementId).empty();

            var element = new Element('img', {
                'src': imgSrc
            }).injectTop(statusDiv);

            if (this.fadeEffect){
                new Fx.Style(element, 'opacity', {
                    duration:3000
                }).addEvent('complete', function() {
                    $(this.elementId).empty();
                }.bind(this)).start(1, 0);
            }
        }
		
    }
	
});
/**
 * 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
    },

    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.element.value != this.opted) return true;
                    if (this.selected && this.visible) {
                        this.choiceSelect(this.selected);
                        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');
                        $('target').set('value','search');
                        $('event').set('value','city');
                        autocomp_region_id = 0;
                        autocomp_city_id = 0;
                    }
                    if(str_lenght == 2)
                    {
                        $('target').set('value','search');
                        $('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)
                    {
                        $('target').set('value','search');
                        $('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) {
        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';
            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) {
        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 {
            if (this.options.maxChoices < tokens.result.length && !this.options.overflow) {
            //tokens.length = this.options.maxChoices;
            }

            $each(tokens.result, function(item){
                if($defined(item.autcomp_region))
                {
                   $(this.options.key_field_id).set('value',item.autcomp_region.aut_region_id);
                   $(this.options.key_field_id).set('name','region_id');
                   $('event').set('value','hotel');
                   autocomp_region_id = item.autcomp_region.aut_region_id;
                }
                if($defined(item.autcomp_city))
                {
                   $(this.options.key_field_id).set('value',item.autcomp_city.aut_city_id);
                   $(this.options.key_field_id).set('name','city_id');
                   autocomp_city_id = item.autcomp_city.aut_city_id;
                }
                if($defined(item.autcomp_hotel))
                {
                        $(this.options.key_field_id).set('value',item.autcomp_hotel.aut_hotel_id);
                        $(this.options.key_field_id).set('name','hotel_id');
                       $('target').set('value','view');
                       $('event').set('value','hotel');
                }
//                if($defined(item.not_hotel))
//                {
//                    if(item.not_hotel==1){
//                        alert('ok');
//                        $('key_field_id').set('value',"");
//                        $('key_field_id').set('name','city_id');
//                    }
//                }

                //alert(item.city_name);
                var html = '';
                var target = '';
                var event = '';
                var key_field_name = '';
                var key_field_value = '';
//                var var_temp =  this.element.value.split(',');
                if (item.objectType == 'city') {
                    
                    
                    html = item.city_name + ', ' + item.country_name;
                    if (this.options.withObjectType) html += ' <span class="DropMenuItemFeature">город</span>';
                    target = 'search';
                    event = 'hotel';
                    key_field_name = 'city_id';
                    key_field_value = item.city_id;
                } else if (item.objectType == 'hotel') {
                    //(var_temp[0] == item.hotel_name && var_temp.length==1 && var_temp[0] != item.city_name) || 
                   
                    
                    html = item.hotel_name + ', ' + item.city_name;
                    if (this.options.withObjectType) html += ' <span class="DropMenuItemFeature">отель</span>';
                    target = 'view';
                    event = 'hotel';
                    key_field_name = 'hotel_id';
                    key_field_value = item.hotel_id;
                } else if (item.objectType == 'region') {
                    html = item.name;
                    if (this.options.withObjectType)
                    {
                        if(item.region_type == "province")
                            html += ' <span class="DropMenuItemFeature">область</span>';
                        else if(item.region_type == "area")
                            html += ' <span class="DropMenuItemFeature">регион</span>';
                    }
                    target = 'search';
                    event = 'hotel';
                    key_field_name = 'region_id';
                    key_field_value = item.region_id;
                }
//                if(var_temp[0] == item.name && var_temp.length==1)
//                    {
//                        //alert('ok1');
//                        $('key_field_id').set('value',item.region_id);
//                        $('key_field_id').set('name','region_id');
//                        autocomp_region_id = item.region_id;
//                        autocomp_count_param=1;
//                    }
//                    else if((var_temp[0] == item.city_name && var_temp.length == 1) || (var_temp[1] == item.city_name && var_temp.length == 2))
//                    {
//                       // alert(item.city_id);
//                        $('key_field_id').set('value',item.city_id);
//                        $('key_field_id').set('name','city_id');
//                        autocomp_city_id = item.city_id;
//                        if(autocomp_count_param==1)
//                            autocomp_count_param=2;
//                        else
//                            autocomp_count_param=1;
//                    }
//                    else if((var_temp.length==2 && var_temp[0] == item.city_name && var_temp[1] == item.hotel_name) || (var_temp[2] == item.hotel_name && var_temp.length==3))
//                    {
//                        //alert(item.city_name);
//                        $('key_field_id').set('value',item.hotel_id);
//                        $('key_field_id').set('name','hotel_id');
//                        if(autocomp_count_param==2)
//                            autocomp_count_param=3;
//                        else
//                            autocomp_count_param=2;
//                    }
//                    else if((var_temp.length==1 && var_temp[0]!=item.hotel_name && var_temp[0]!=item.city_name && var_temp[0]!=item.name && $('key_field_id').value=="") || ($('key_field_id').value!="" && var_temp[0]==item.name))
//                {
//                    //alert('ok2');
//                    $('key_field_id').set('value','');
//                        $('key_field_id').set('name','city_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'
                });

                if (item.objectType == 'city') choice.inputValue = item.city_name;
                else if (item.objectType == 'hotel') choice.inputValue = item.hotel_name;
                else if (item.objectType == 'region') choice.inputValue = item.name;

                this.addChoiceEvents(choice).inject(this.choices);
            }.bind(this));


            //			tokens.each(this.options.injectChoice || function(token){
            //				var choice = new Element('li', {'html': this.markQueryValue(token)});
            //				choice.inputValue = token;
            //				this.addChoiceEvents(choice).inject(this.choices);
            //			}, 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);
        }
        //if (this.selectMode) this.setSelection();
    },

    choiceSelect: function(choice) {
//        alert(choice.getProperty('key_field_name')+' => '+choice.getProperty('key_field_value'));
//        alert(choice.getProperty('target'));
//        alert(choice.getProperty('event'));
        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');
            
            $('target').setProperty('value', choice.getProperty('target'));
            $('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();
        this.element.setSelectionRange(this.element.value.length,this.element.value.length);
                this.element.focus();
    },

    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: {
		target: 'main',
		event: ''
	},

	/**
	 * @param {String} id id объекта, который будет обновлен по приходу ответа от сервера  
	 * @raram {Array} options параметры для построения запроса
	 */
	initialize: function(id, options){
		this.setOptions(options);
		$(id).load(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_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, 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'
        });
//        console.log(this.options.host + Ria_Ajax.script + '?' + Hash.toQueryString(this.options));
        $(parentId).load(this.options.host + 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"
                                    });

            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)
    {
        $(this.parentId).set('html', responseHTML);
        eval(responseJavaScript);
    },
    
    setCurrHotelId: function(currHotelId)
    {
        this.currHotelId = currHotelId;
    }


   
});
/**
 * @param {String} id - id элемента на странице, в котором будет карта
 * @param {Array} options - требуется указать масштаб карты, и координаты. также принимает все параметры,
 *          которые указаны в 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(){
    //        console.log($(this.config.divId).getCoordinates());
    //        console.log('north east:');
    //        console.log(this.map.getBounds().getNorthEast().lat());
    //        console.log(this.map.getBounds().getNorthEast().lng());
    //        console.log('south west:');
    //        console.log(this.map.getBounds().getSouthWest().lat());
    //        console.log(this.map.getBounds().getSouthWest().lng());
    //        console.log('zoom:')
    //        console.log(this.getZoom());
    },


    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){
        //        console.log(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(){
            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;
        //        console.log(req);
        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_SelectRoomManager
 * @copyright  2010 IT RIA
 * @license    GNU GPL v2
 * @version
 * @requires   Ria_Common_Datext
 */
var Ria_Hotel_SelectRoomManager = new Class(
{
    Implements: Options,

    options: {        
    },

    formSelected : new Hash(),
    formMoney  : new Hash(),
    Datext : new Ria_Common_Datext(),


    initialize: function(options) {
        this.setOptions(options);
        this.informerText = 'Вы бронируете: ';
    },


    addSelectListener:function(block) {
        $('selekt'+block).addEvent('change',function(){
            if ($('selekt'+block).value > 0) {
                this.formSelected.set(block, $('selekt'+block).value);
                this.formMoney.set(block, this.getPriceOf(block,$('selekt'+block).value));
                this.toggleButtons(block, true);
            } else {
                this.formMoney.erase(block);
                this.formSelected.erase(block);
                this.toggleButtons(block, false);
            }
        }.bind(this));


        $('more'+block).addEvent('click',function() {
            this.toggleButtons(block, false);
            return false;
        }.bind(this));


        $('clean'+block).addEvent('click',function() {
            $('selekt'+block).selectedIndex = 0;
            var active = this.findPrevSelected(block);
            this.formSelected.erase(block);
            this.formMoney.erase(block);
            if (active != -1){
                this.toggleButtons(active, true);
            } else {
                this.toggleButtons(block, false);
            }
            return false;
        }.bind(this));

    },

    getPriceOf:function(block, value){
        var price = 0;
        $('selekt'+block).getElements('option').each(function(item, index){
            if (index == value){
                price = item.get('price');
            }
        });
        return price;
    },

    findPrevSelected:function(block){
        var length = this.formSelected.getLength();
        if (length == 1) return -1;
        var keys = this.formSelected.getKeys().sort(this.sIncrease);
        var current = keys.indexOf(block);
        if (length == 1){
            return keys[0];
        } else {
            return keys[current-1];
        }
    },

    /*
    findNextSelected:function(block){
        var length = this.formSelected.getLength();         
        if (length == 0) return 0;                          
        var keys = this.formSelected.getKeys().sort(this.sIncrease);
        var current = keys.indexOf(block);
        if (current != length-1){
            current = (keys[(current+1)])*1;
        } else {                                            
            current = (keys[0])*1;
        }
        return current;
    },
     */

    /*
    findNextNotSelected:function(block){
        var i = block * 1;
        while (true){
            if (!$defined($('selekt'+i)))
                if (!$defined($('selekt'+(block*1+1)))){
                    return 0;
                } else {
                    return block*1+1;
                }
            if (!this.formSelected.get(i)){
                return i;
            }
            i++;
        }
        return 0;
    },
     */
    toggleButtons:function(block, flag) {
        $$('.help_buttons').setStyle('display','none');
        var buttonContent = this.getButtonContent();
        var summaryText =   buttonContent.get('room') +
        this.Datext.getDatext(buttonContent.get('room'),' комнату', ' комнаты', ' комнат') +
        ' ('+buttonContent.get('summ')+'грн.)';
        $('informer'+block).set('text', this.informerText + summaryText);
        if (flag){
            $('btn'+block).setStyle('display', 'block');
        }
    },

    focusTo:function(block) {
        $('selekt'+block).focus();
        new Ria_Common_ScrollingManager('btn'+block);
    },

    getButtonContent:function() {
        var result = new Hash();
        var summ = new Number();
        var rooms = new Number();
        this.formMoney.getValues().each(function(item, index){
            summ+=(item*1);
        });
        this.formSelected.getValues().each(function(item, index){
            rooms+=(item*1);
        });
        result.set('summ', summ);
        result.set('room', rooms);
        return result;
    },

    sIncrease:function(i, ii) {
        i *= 1;
        ii *= 1;
        if (i > ii) {
            return 1;
        }
        else if (i < ii) {
            return -1;
        }
        else {
            return 0;
        }
    }
});
    /**
    * 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
    * @requires   Ria_Hotel_UnsetDetailRequest
    */
    var Ria_Hotel_GetHotelRooms = new Class(
    {

        Extends: Ria_HtmlRequest,

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

        /**
    * @param {String} id id объекта, который будет обновлен по приходу ответа от сервера
    * @raram {Array} options параметры для построения запроса
    */
        initialize: function(ids, options)
        {
            this.parentDivId = ids.Id_div;
            this.buttonId = ids.Id_button;
            this.spanTextId = ids.spantext;
            this.ids = ids;
            this.options = options;
            
            this.setOptions(options);
            Ria_Hotel_Load.parentDivId = ids.Id_div;
            Ria_Hotel_Load.IdKnopka = ids.Id_button;
            Ria_Hotel_Load.Text = ids.spantext;
            Ria_Hotel_Load.Ids = ids;
            Ria_Hotel_Load.Options = options;
            
            $(ids.Id_button).removeClass(ids.stile);
            $(ids.Id_button).addClass(ids.stileload);

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

        },

        onGetResponse: function(responseTree, responseElements, responseHTML, responseJavaScript)
        {
            $(this.parentDivId).set('html', responseHTML);
            eval(responseJavaScript);
            $(this.buttonId).removeEvents('click');
            $(this.buttonId).addEvent('click', function()
            {
                $(Ria_Hotel_Load.parentDivId).empty();
                $(Ria_Hotel_Load.Text).set('text', Lang.show_prices);
                if($(Ria_Hotel_Load.IdKnopka).hasClass('hide-the-prices'))
                {
                    $(Ria_Hotel_Load.IdKnopka).removeClass('hide-the-prices');
                    $(Ria_Hotel_Load.IdKnopka).set('class', 'show-the-prices');
                }

		$(Ria_Hotel_Load.IdKnopka).removeEvents('click');
		$(Ria_Hotel_Load.IdKnopka).addEvent('click', function()
                {
                    
                    new Ria_Hotel_GetHotelRooms(Ria_Hotel_Load.Ids, Ria_Hotel_Load.Options);
                });
		
            });
           

            $(Ria_Hotel_Load.Text).set('text', Lang.hide_prices);

           
        }
    });

/**
 * 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']);
            if($('search_city').value==null || $('search_city').value=="")
                $('search_city').set('value',jsonObj.BookerInfo['guest_city']);
            $('guest_country').set('value',jsonObj.BookerInfo['guest_country']);
        }
    }
});


/**
 * Класс для работы с календариком
 *
 * @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');

                $('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');
                $('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');

            }
        }
});




/**
 * AJAX запрос на изменение ремарки    
 *
 * @class Ria_Hotel_Notepad_ChangeNotepadRemarkRequest
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_JsonRequest
 */
var Ria_Hotel_Notepad_ChangeNotepadRemarkRequest = new Class({
	
	Extends: Ria_JsonRequest, 
	
	options: {
		target: 	'notepad',
		event: 		'changeRemark'
	},
	
	onGetResponse: function(jsonObj) {
		this.json = jsonObj;
		if (jsonObj.result>0){
			var remarkFooterElement = $('remark_footer_'+this.options.realtyId);
			remarkFooterElement.empty();
			
			remarkFooterElement.set('html', jsonObj.remarkText);
			
			if (!jsonObj.remarkText){
				remarkFooterElement.setStyle('display', 'none');
			}
		} else {
			alert(Lang.error);
		}
	}
	
});
/**
 * 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]);
		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();
                var var_temp =  this.element.value.split(',');
                if($(this.options.key_field_id).get('name')!='hotel_id')
                    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, add block info to search/hotels pages via HTML Request
    *
    * @class      Ria_Hotels_GetHotelBlockDetailRequest
    * @copyright  2008 IT RIA
    * @license    GNU GPL v2
    * @version
    * @author     Andrey Kotulskiy
    * @requires   Ria_Hotel_Load
    * @requires   Ria_HtmlRequest
    * @requires   Ria_Hotel_UnsetDetailRequest
    */
    var Ria_Hotel_GetHotelBlockDetailRequest = new Class({

        Extends: Ria_HtmlRequest,

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

        /**
    * @param {String} id id объекта, который будет обновлен по приходу ответа от сервера
    * @raram {Array} options параметры для построения запроса
    */
        initialize: function(ids, options){
            this.setOptions(options);
            Ria_Hotel_Load.IdKnopka = ids.Id_button;
            Ria_Hotel_Load.Text = ids.spantext;
            var DispleyLoad = function(){
                if(Ria_Hotel_Load.TimeoutFlag != '1'){
                    $(ids.Id_button).removeClass(ids.stile);
                    $(ids.Id_button).addClass(ids.stileload);
                }
            };
            var timeoutID = DispleyLoad.delay(200);
            $(ids.Id_div).set('load', {
                evalScripts: true
            });
//            console.log(this.options.host + Ria_Ajax.script + '?' + Hash.toQueryString(this.options));
            $(ids.Id_div).load(this.options.host + Ria_Ajax.script + '?' + Hash.toQueryString(this.options));
            if(ids.Flag !='true'){
                $(ids.Id_button).removeEvents('click');
                $(ids.Id_button).addEvent('click', function(){
                    new Ria_Hotel_UnsetDetailRequest(ids, options);
                });
            }
        }
    });

/**
 * Класс добавляющий 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({
	
    Extends: Ria_JsonRequest,
	
    options: {
        host :      '',
        target :    'notepad',
        event :     'addhotel'
    },
	
    onGetResponse: function(jsonObj) {
        this.json = jsonObj;
        
        if (jsonObj.result>0){
            liElement = $('text_plus_'+this.options.hotelId);
            liElementA = $('link_add_to_notepad_'+this.options.hotelId);
            liElementA.destroy();
            liElement.set('class', 'AddedNotepad_Smoll');
            liElement.set('text', Lang.add_to_notepad);
//            $('blocnot').set('text', ' (' + jsonObj.result + ')');
        } else {
            alert(Lang.error);
        }
    }
	
});
/**
 * Менеджер ремарок
 *
 * @class Ria_Hotel_Notepad_NotepadRemarkManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Hotel_Notepad_ChangeNotepadRemarkRequest
 * @requires   Ria_Common_StatusImageManager
 */
var Ria_Hotel_Notepad_NotepadRemarkManager = new Class({
	
	initialize: function(realtyId){
    	this.realtyId = realtyId;
    	this.setEvent();
    	
	},
	
	setEvent:function(){
		$('remark_link_'+this.realtyId).addEvent('click', function(){
			var remarkFooterElement = $('remark_footer_'+this.realtyId); 
			var remarkText = remarkFooterElement.get('text').trim();
			
            remarkFooterElement.empty();
            remarkFooterElement.setStyle('display', 'block');
            
            var remarkArea = new Element('textarea', {'value': remarkText, 'styles': {'width':'100%'} });
            remarkArea.inject(remarkFooterElement);
			
			var mainButtonDiv = new Element('div', {'styles': {'padding':'5px', 'text-align':'right'} });
			mainButtonDiv.inject(remarkFooterElement);
			
            var saveButton = new Element('input', {'type':'button', 'value': Lang.save_word});
            saveButton.inject(mainButtonDiv);

            remarkArea.addEvent('blur', function(){
            	
    			remarkFooterElement.empty();
    			remarkFooterElement.set('text', remarkArea.get('value'));
    			
    			var statusDiv = new Element('div', {
    				'id': 'notepadRemarkStatusDiv'
    			}).injectTop(remarkFooterElement);
    			
    			new Ria_Common_StatusImageManager('notepadRemarkStatusDiv', 'spinner', false);
    			
            	new Ria_Hotel_Notepad_ChangeNotepadRemarkRequest({'realtyId':this.realtyId, 'remarkText':remarkArea.get('value')});
            }.bind(this));
            
            saveButton.addEvent('click', function(){
            	remarkArea.fireEvent('blur');
            });
            
		}.bind(this));		
	}
	

});
/**
 * Класс добавляющий 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(){
        $('link_add_to_notepad_'+this.hotelId).addEvent('click', function(){
            new Ria_Hotel_Notepad_AddUserNoteRequest({
                'host':this.options['host'],
                'rubricId':0,
                'hotelId':this.hotelId
                });
        }.bind(this));
    }
	
});
