/**
 *
 * Общий класс для представления точки
 *
 * @class Ria_Map_Main_Common_GeoPoint
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 */
 var Ria_Map_Main_Common_GeoPoint = new Class({

	initialize: function(longitude,latitude){
    	this.longitude = longitude;
    	this.latitude = latitude;
	},

	getLongitude : function() {
		return this.longitude;
	},

	getLatitude : function() {
		return this.latitude;
	},

	setLongitude : function(longitude) {
		this.longitude = longitude;
	},

	setLatitude : function(latitude) {
		this.latitude = latitude;
	},

    setPoint : function(lngt,lat) {
        this.longitude = lngt;
        this.latitude = lat;
    },

	convertToMapPoint : function() {
		return RMaps.Config.getDriver().convertToMapPoint(this);
	}

});
    // 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);
/**
 * Определение переменных для работы 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', 'Показать цены');
		$(ids.Id_button).removeEvents('click');
		$(ids.Id_button).addEvent('click', function(){
				Ria_Hotel_Load.TimeoutFlag = '2';
                new Ria_Hotel_GetHotelBlockDetailRequest(ids,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);
                }
            }
        }
	}

});
/**
 * Класс прорисовывает анимированный 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);
            }
        }
		
    }
	
});
/**
 * RIA Framework Map Mamager
 * 
 * @class      Ria_Map_Manager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Revision: 1.5 $
 * @author     <a href="mailto:Oleg.Cherniy@gmail.com">Oleg Cherniy</a>
 */
var Ria_Map_GeoPoint = new Class({

	Engines: {
		1: {
			'name': 'Vizicom',
			'minZoom':0,
			'maxZoom':11
		},
		2: {
			'name': 'Yandex Maps',
			'minZoom':6,
			'maxZoom':17
		},
                3: {
			'name': 'Google Maps',
			'minZoom':6,
			'maxZoom':17
		}
	},
	
	'geo_X' 		: 0,
	'geo_Y' 		: 0,
	'zoom' 			: 0,
	'engineId'	 	: 1,
	
	initialize: function(options){
		//console.log('Ria_Map_GeoPoint');
		if ($defined(options.geo_X)) this.geo_X = options.geo_X; 
		if ($defined(options.geo_Y)) this.geo_Y = options.geo_Y; 
		if ($defined(options.zoom)) this.zoom = options.zoom; 
		if ($defined(options.engineId)) this.engineId = options.engineId; 
	},
	
	convertToEngine:function(toEngineId){
            //console.log('Ria_Map_GeoPoint->convertToEngine');
            if (toEngineId){
                if (this.engineId != toEngineId){
                    kFrom = 100/(this.Engines[this.engineId].maxZoom - this.Engines[this.engineId].minZoom);
                    kTo = 100/(this.Engines[toEngineId].maxZoom - this.Engines[toEngineId].minZoom);
                    this.zoom = Math.round((this.zoom - this.Engines[this.engineId].minZoom) * kFrom / kTo + this.Engines[toEngineId].minZoom);
                    this.engineId = toEngineId;
                }
                if (this.zoom > this.Engines[toEngineId].maxZoom) this.zoom = this.Engines[toEngineId].maxZoom;
                if (this.zoom < this.Engines[toEngineId].minZoom) this.zoom = this.Engines[toEngineId].minZoom;
            }
	}
});
/**
 * Класс прорисовывает анимированный gif в указанном div элементе   
 *
 * @class Ria_Hotel_StatusImageManager
 * @copyright  2009 IT RIA
 * @license    GNU GPL v2
 * @author     Vitaliy Marian
 * @version    ID:
*/
var Ria_Hotel_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',
    spinnerImg2 : './img/loader/ajax-loader.gif',


	initialize: function(elementId, status, fadeEffect, horizontal_align)
        {
		this.elementId = elementId;
		this.status = status;
		this.fadeEffect = fadeEffect;
                this.horizontal_align = horizontal_align;
	
		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;
                else if (this.status == 'spinner2')
			imgSrc = this.spinnerImg2;
		
		
		if (imgSrc)
                {
			var statusDiv = $(this.elementId).empty();

			/*var element = new Element('img',
                        {
				'src': imgSrc
			}).injectTop(statusDiv);*/
                        if(this.horizontal_align)
                        {
                            var elementImg = new Element('img',
                                {
                                    'src': imgSrc
                                }
                            );

                           var elementDiv = new Element('div',
                                {
                                    'align': 'center'
                                }
                            );

                            elementDiv.setStyle('margin', '15px');
                            elementImg.inject(elementDiv);
                            elementDiv.inject(statusDiv);
                        }
                        else
                        {
                            var element = new Element('img',
                            {
				'src': imgSrc
                            }).inject(statusDiv);
                        }

			if (this.fadeEffect){
				new Fx.Style(element, 'opacity', {duration:3000}).addEvent('complete', function() {
					$(this.elementId).empty();
		    	}.bind(this)).start(1, 0);
			}
		}
		
	}
	
});
/**
 * 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')};
	}	
	
});

/**
 * Description
 *
 *
 * @class Ria_Rating_RatingBaseManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
*/
var Ria_Rating_RatingBaseManager = new Class({

    Implements: Options,

    img_off     : 'http://css.ria.ua/icons/ratings/rating_off.gif',
    img_over    : 'http://css.ria.ua/icons/ratings/rating_over.gif',
    img_on      : 'http://css.ria.ua/icons/ratings/rating_on.gif',

    currentValue : 0,

	options: {
        'parentId'      : null,
        'fieldName'     : null,
        'padding'       : '0px 1px 0px 1px',
		'values'        : {1:'1 ball', 2:'2 ball',3:'3 ball', 4:'4 ball', 5:'5 ball'}
	},
    
	initialize: function(options){
        this.setOptions(options);

        if ($defined(options.parentId) && $defined(options.fieldName) ){
            this.initializeRating();
        }
	},

    initializeRating: function(){
        $each(this.options['values'], function(title, value){
            var imgElement = new Element('img', {
                'src': this.img_off,
                'id': 'rating_img_'+this.options['fieldName']+'_'+value,
                'styles': {
                    'cursor': 'pointer',
                    'padding': this.options['padding'],
                    'margin': '0px'
                },
                'title':title,
                'events':{
                    'mouseover': function(){
                        this.eventOver(value);
                    }.bind(this),
                    'mouseout': function(){
                        this.eventOut();
                    }.bind(this),
                    'click': function(){
                        this.eventClick(value);
                    }.bind(this)
                }
            });
            imgElement.inject($(this.options['parentId']));

        }.bind(this));

    },

    eventOver:function(newValue){
        $each(this.options['values'], function(title, value){
            if (value <= newValue) {
                if (this.currentValue >= value) $('rating_img_'+this.options['fieldName']+'_'+value).setProperty('src', this.img_on);
                else $('rating_img_'+this.options['fieldName']+'_'+value).setProperty('src', this.img_over);
            } else $('rating_img_'+this.options['fieldName']+'_'+value).setProperty('src', this.img_off);
        }.bind(this));
    },
	
    eventOut:function(){
        $each(this.options['values'], function(title, value){
            if (value <= this.currentValue) $('rating_img_'+this.options['fieldName']+'_'+value).setProperty('src', this.img_on);
            else $('rating_img_'+this.options['fieldName']+'_'+value).setProperty('src', this.img_off);
        }.bind(this));
    },

    eventClick:function(newValue){
        this.currentValue = newValue;
        $each(this.options['values'], function(title, value){
            if (value <= newValue) $('rating_img_'+this.options['fieldName']+'_'+value).setProperty('src', this.img_on);
            else $('rating_img_'+this.options['fieldName']+'_'+value).setProperty('src', this.img_off);
        }.bind(this));
    }

});
/**
* 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_CheckFormUKR = 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){
        //		alert ('ytghjshol');
        var id1s = $(options.id1).get('value');
        var id2s = $(options.id2).get('value');
        var id3s = $(options.id3).get('value');
        var id5s = $(options.id5).get('value');
        var id5f = id5s ;
        if($(options.id1).get('value') != ''&&
            $(options.id2).get('value') != ''&&
            $(options.id3).get('value') != ''&&
            $(options.id4).get('value') != ''&&
            id5f.length >= '7'&&
            $(options.email).get('value') != ''){
            $(id.Id).removeProperty('disabled');
            $(id.Id).set('class','button button_green_212');
        }else{
            $(id.Id).disabled = 'true';
            $(id.Id).set('class','button button_green_212_no_activ');
        }
    }
});

/**
 * 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_CheckFormCreditUKR = 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_green_212');
			}else{
			$(id.Id).disabled = 'true';
			$(id.Id).set('class','button button_green_212_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;
                                fem.setStyle('width', 'winW');
                                fem.setStyle('height', 'winH');
                                em.setStyle('width', 'winW');
                                em.setStyle('height', 'winH');
				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');
		});
	}
});
/**
* 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){
        //		alert ('ytghjshol');
        var id1s = $(options.id1).get('value');
        var id2s = $(options.id2).get('value');
        var id3s = $(options.id3).get('value');
        var id5s = $(options.id5).get('value');
        var re = /а|б|в|г|д|е|ё|ж|з|и|ё|к|л|м|і|є|ї|ґ|н|о|п|р|с|т|у|ф|х|ц|ч|ш|щ|ъ|ы|й|ь|э|ю|я/gi;

        if (re.test(id1s)) {
            var id1f = id1s.replace(re, '');
            $(options.id1).set('value',id1f);
        }

        if (re.test(id2s)) {
            var id2f = id2s.replace(re, '');

            $(options.id2).set('value',id2f);
        }

        if (re.test(id3s)) {
            var id3f = id3s.replace(re, '');

            $(options.id3).set('value',id3f);
        }else{
            var id5f = id5s ;
        }


        if($(options.id1).get('value') != ''&&
            $(options.id2).get('value') != ''&&
            $(options.id3).get('value') != ''&&
            $(options.id4).get('value') != ''&&
            id5f.length >= '7'&&
            $(options.email).get('value') != ''){
            $(id.Id).removeProperty('disabled');
            $(id.Id).set('class','button button_green_212');
        }else{
            $(id.Id).disabled = 'true';
            $(id.Id).set('class','button button_green_212_no_activ');
        }
    }
});

/**
 * 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_green_212');
			}else{
			$(id.Id).disabled = 'true';
			$(id.Id).set('class','button button_green_212_no_activ');	
			}
	}
});

/**
 *
 * Драйвер для карты Visicom'а
 *
 * @class Ria_Map_Main_Drivers_Visicom
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires    Ria_Map_Main_Common_GeoPoint
 */

 var Ria_Map_Main_Drivers_Visicom = new Class({

	Implements: Options,

 	options: {
		'mapContainerId' : ''
	},
	defaultMapZoom : 12,
	markers : new Hash(),
	layers : new Hash(),

	initialize: function(options) {

//console.log('Drivers_Visicom: initialize');

    	this.setOptions(options);
		this.mapContainer = $(this.options.mapContainerId);
		this.mapContainer.set('html','');
		//ставим ссылку копирайта
		this.mapContainer.grab(new Element('a',{
			'id':'visicom_copyright_link',
			'href':'http://maps.visicom.ua'
		}).set('text',Lang.ukraine_map));
		this.map = new VMap(this.mapContainer);
//alert('endof initialize');
	},
	setMapControl : function(controlName,controlParams) {
//        console.log('setMapControl');
            switch(controlName) {
                case 'mapTypes':
//                    this.addMaptypesControlPanel(controlParams);
                    break;
                case 'miniMap':
//                    this.map.addControl(new YMaps.MiniMap(), new YMaps.ControlPosition(this.getControlPositionByPositionId(controlParams['positioning']), new YMaps.Size(controlParams['offsetX'], controlParams['offsetY'])));
                    break;
                case 'scale':
//                    this.map.addControl(new YMaps.ScaleLine(), new YMaps.ControlPosition(this.getControlPositionByPositionId(controlParams['positioning']), new YMaps.Size(controlParams['offsetX'], controlParams['offsetY'])));
                    break;
                case 'mainPannel':
//                    switch(controlParams['type']) {
//                        case 2: this.setSmallMainPanel(controlParams); break;
//                        case 3: this.setSmallOnlyZoomMainPanel(controlParams); break;
//                        default: this.setLargeMainPanel(controlParams);
//                    }
                break;
            }
        },
	//инициализация карты
	initMap : function() {
//this.map.add(new VMarker([{lng: 30.5214, lat: 50.4650}]));
//            console.log('initMap');

//    	VMarker.prototype._init = function ()
//        {
//            if (VIs.D == null) {
//                return ;
//            }
//            if (this.O == null) {
//                this.Bh();
//            }
//            var AB = VIs.yu(this.h.K - VIs.AY(), VIs.getMaxY() - this.h.N, VIs.D._units_per_pixel);
//            this.G = Math.round(AB.getLeft() - (((this._offset_x)? this.offset_x : this.AT.getWidth() /2 )));
//            this.F = Math.round(AB.getTop() - ((this._offset_y)? this.offset_y : this.AT.getHeight()));
//            this._bounds = VIs.createBounds([this.h]);
//        }

//alert('initMap');
//        VMarker.prototype._init = function () {
//            alert (123321);

//            if (mapEngine._currentMap == null) {
//                return
//            }
//            if (this._div == null) {
//                this._createDOMElement()
//            }
//            var a = mapEngine.convertToScreenCoords(this._point._x - mapEngine.getMinX(), mapEngine.getMaxY() - this._point._y,
//            mapEngine._currentMap._units_per_pixel);
//            this._left = Math.round(a.getLeft() - (((this._offset_x)? this._offset_x : this._icon.getWidth() /2 )));
//            this._top = Math.round(a.getTop() - (((this._offset_y)? this._offset_y : this._icon.getHeight())));
//            this._bounds = mapEngine.createBounds([this._point]);
//        };

//        this.mapContainer.setStyle('position','relative');
//




        this.map.repaint();




//alert ('after resizeViewport');
//this.map.add(new VMarker([{lng: 30.5214, lat: 50.4650}]));

	},

	resizeMap : function(width,height) {

//        console.log('resizeMap');

		if($defined(this.map)) {
//			this.map.resizeViewport();
			this.map.repaint();
		}
	},

	repaintMap : function() {

//        console.log('repaintMap');

		this.map.repaint();
	},

	addMarkerToBase : function(marker) {

//        console.log('addMarkerToBase');
                var vpoint = marker.getGeoPoint().convertToMapPoint();
//console.log(JSON.encode(vpoint).toString());
		var vMarker = new VMarker(vpoint);
//                this.map.add(vMarker);
		var id = this.markers.getLength()+1;
		marker.setId(id);
		this.markers.set(id,vMarker);

//console.log('after addMarkerToBase');
	},


	addLayerToBase : function(layer) {

//        console.log('addLayerToBase');

//console.log('function addLayerToBase');

		var vlayer = new VLayer();
		var id = this.layers.getLength()+1;
		layer.setId(id);
		this.layers.set(id,vlayer);

//console.log('after addLayerToBase');


	},

	addMarkerToMap : function(marker) {
            	var vmarker = this.markers.get(marker.getId());
		this.map.add(vmarker);
		this.map.repaint();

//		var vmarker = this.markers.get(marker.getId());
//		this.map.add(vmarker);
//		this.map.repaint();

	},

	addMarkerToLayer : function(id,marker) {

//        console.log('addMarkerToLayer');

		var vmarker = this.markers.get(marker.getId());
		var vlayer = this.layers.get(id);
		vlayer.add(vmarker);
		this.map.repaint();
//this.map.add(vmarker);
//this.map.repaint();
	},

	addLayerToMap : function(layer) {
//console.log('function addLayerToMap');
		var vlayer = this.layers.get(layer.getId());
		this.map.add(vlayer);
//		this.map.repaint();

//console.log('!!!after addLayerToMap');
	},

	removeLayerFromMap : function(layer) {

//        console.log('removeLayerFromMap');

		var vlayer = this.layers.get(layer.getId());
		this.map.remove(vlayer);
		this.map.repaint();
	},

	convertToMapPoint : function(geoPoint) {

//        console.log('convertToMapPoint');

		return {lng: geoPoint.getLongitude(), lat: geoPoint.getLatitude()};
	},

	setNameToMarker : function(id,name) {

//        console.log('setNameToMarker');

		this.markers.get(id).hint(name);
//		this.markers.get(id).setHint(name);
	},

	setIconToMarker : function(id,width,height,src,offset_x,offset_y) {
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
		var vIcon = new VMarkerIcon(width,height,src);
		var vMarker = this.markers.get(id);
                vMarker.icon(vIcon);
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

//		if(offset_x) vmarker._offset_x = offset_x;
//		if(offset_y) vmarker._offset_y = offset_y;
//console.log(vIcon);
//		var icon = new VMarkerIcon(width,height,src,true);
//		var vmarker = this.markers.get(id);
//		if(offset_x) vmarker._offset_x = offset_x;
//		if(offset_y) vmarker._offset_y = offset_y;
//		vmarker.setIcon(icon);
	},

    setPointToMarker : function(id,point) {
//        console.log('setPointToMarker');
        var vMarker = this.markers.get(id);
        var vPoint = point.convertToMapPoint();

//        console.log(vPoint);

//        vmarker.setPoint();
        vMarker.coords(vPoint);
        this.map.repaint();
    },

    getPointFromMarker : function(id) {

//        console.log('getPointFromMarker');

        var vmarker = this.markers.get(id);
        var point = vmarker.coords()[0];

//console.log('point.lng:'+point.lng+',point.lat:'+point.lat);
        var GeoPoint = new Ria_Map_Main_Common_GeoPoint(point.lng,point.lat);
//alert('geoPoint');
//console.log(GeoPoint);

        return GeoPoint;
    },

	hideMarker : function(id) {
//
//        console.log('hideMarker');

		var vmarker = this.markers.get(id);
		vmarker.visible(false);
//		vmarker.hide();

		this.map.repaint();

	},

	showMarker : function(id) {

//        console.log('showMarker');

		var vmarker = this.markers.get(id);
                vmarker.visible(true);
//		vmarker.show();
		this.map.repaint();
	},

	hideLayer : function(id) {

//        console.log('hideLayer');
//
		var vlayer = this.layers.get(id);
		vlayer.visible(false);
//		vlayer.hide();
		this.map.repaint();

	},

	showLayer : function(id) {

//        console.log('showLayer');

		var vlayer = this.layers.get(id);
                vlayer.visible(true);
//		vlayer.show();
		this.map.repaint();
	},

	removeMarkerFromMap : function(marker) {

//        console.log('removeMarkerFromMap');

		var vmarker = this.markers.get(marker.getId());
		this.map.remove(vmarker);
		this.map.repaint();
	},

	removeMarkerFromLayer : function(id,marker) {

//        console.log('removeMarkerFromLayer');

		var vmarker = this.markers.get(marker.getId());
		var vlayer = this.layers.get(id);
		vlayer.remove(vmarker);
	},

	addInfoWindowToMarker : function(marker) {

//        console.log('addInfoWindowToMarker');

            var vmarker = this.markers.get(marker.getId());
            var title = new Element('div').set('html',marker.infoWindowName);
            var title_a = title.getElement('a');
            if(title_a) {
                var title_text = title.getElement('a').get('text').trim();
                if(title_text.length > 35) {
                    title_a.set('text',title_text.substr(0,35)+'...');
                } else {
                    title_a.set('text',title_text);
                }
            }
            var infoWindow = new VInfoWindow(title.get('html'),marker.infoWindowHtml);
//console.log(infoWindow.visible());
            vmarker.info(infoWindow);

//            vmarker.info().visible(true);
//            this.map.repaint();
//            vmarker.bindInfoWindow(infoWindow);
	},



	removeInfoWindowFromMarker : function(id) {

//        console.log('addInfoWindowToMarker');

		var vmarker = this.markers.get(id);
		vmarker.k = null;
	},

	openInfoWindowInMarker : function(id) {

//        console.log('openInfoWindowInMarker');
//        thfireMapEvent
		var vmarker = this.markers.get(id);

//		vmarker.info().visible(true);
//		vmarker.openInfoWindow();
	},

	closeInfoWindowInMarker : function(id) {

//        console.log('closeInfoWindowInMarker');

		var vmarker = this.markers.get(id);
		vmarker.closeInfoWindow();
	},

	setDraggableMarker : function(id,bool) {

//        console.log('setDraggableMarker');

		var vmarker = this.markers.get(id);
		vmarker.draggable(bool);
	},

	setMapCenter : function(geoPoint) {

//        console.log('setMapCenter');

            var defaultZoom = this.map.zoom();
            if (defaultZoom == undefined) defaultZoom = this.defaultMapZoom;

//            alert('zoom:'+this.getMapZoom());
//            alert('setMapCenter');
////		this.map.setCenter(geoPoint.convertToMapPoint());
            var point = geoPoint.convertToMapPoint();
            this.map.center(point, defaultZoom);

//alert('zoom:'+this.map.zoom());
//alert ( 'endof( setMapCenter )  ' );
//        getMapZoom

	},

	getMapCenter : function() {

//        console.log('getMapCenter');
                var mapPoint = this.map.center();
//                var vgeoPoint = this.map.�enter();
                return new Ria_Map_Main_Common_GeoPoint(mapPoint.lng,mapPoint.lat);
//		var vgeoPoint = this.map.getCenter().convertToGeoPoint();
//		return new Ria_Map_Main_Common_GeoPoint(vgeoPoint.getLongitude(),vgeoPoint.getLatitude());
	},

	setMapZoom : function(index) {

//        console.log('setMapZoom');

		var maxZoom = RMaps.Config.getConfig('maxZoom') - RMaps.Config.getConfig('minZoom');
		var zoom = (Math.round((index*maxZoom)/100))+RMaps.Config.getConfig('minZoom');
//alert('setZoom='+ zoom);
		this.map.zoom(zoom);
	},

	getMapZoom : function() {

//        console.log('getMapZoom');
        
//        this.map.add(new VMarker([{lng: 30.5214, lat: 50.4650}]));

//            alert('getMapZoom');
		var maxZoom = RMaps.Config.getConfig('maxZoom');
		var retZoom = this.map.zoom() - RMaps.Config.getConfig('minZoom');
                var retMapZoom = (Math.round((retZoom*100)/maxZoom));

//        alert('retMapZoom='+retMapZoom);

		return retMapZoom;
	},

	getClientRectangle : function() {
//this.map.add(new VMarker([{lng: 30.5214, lat: 50.4650}]));
//        console.log('getClientRectangle');
		var vrect = this.map.clientRect();
		var rect = new Hash();
//console.log(vrect.rightTop().lat);
		var vMaxPoint = vrect.rightTop();
		var vMinPoint = vrect.leftBottom();
		rect.set('min',new Ria_Map_Main_Common_GeoPoint(vMinPoint.lng,vMinPoint.lat));
		rect.set('max',new Ria_Map_Main_Common_GeoPoint(vMaxPoint.lng,vMaxPoint.lat));
//alert('carramba');
		return rect;
//
//
//
//		var vrect = this.map.getClientRect();
//		var rect = new Hash();
//		var vmaxPoint = vrect.getMaxPoint().convertToGeoPoint();
//		var vminPoint = vrect.getMinPoint().convertToGeoPoint();
//		rect.set('min',new Ria_Map_Main_Common_GeoPoint(vminPoint.getLongitude(),vminPoint.getLatitude()));
//		rect.set('max',new Ria_Map_Main_Common_GeoPoint(vmaxPoint.getLongitude(),vmaxPoint.getLatitude()));
//		return rect;
	},

	addEventListener : function(object,event,callback_func) {

//        console.log('addEventListener');
//
//            alert('event object.type='+object.type);
//            alert('event='+event);
//            this.latitude
		var vEvent = RMaps.Config.getConfig('events')[event];

//        console.log(vEvent);


		if(object.type == 'map') {

			var vObject = this.map;

                        switch(vEvent) {
                            case 'mouseclick':
                                vObject.mouseclick(callback_func);
                              break;
                            case 'mousedown':
                                vObject.mousedown(callback_func);
                              break;
                            case 'mouseup':
                                vObject.mouseup(callback_func);
                              break;
                            case 'mousedblclick':
                                vObject.mousedblclick(callback_func);
                            break;

                            case 'startdrag':
                                vObject.startdrag(callback_func);
                              break;
                            case 'dragging':
                                vObject.dragging(callback_func);
                              break;
                            case 'enddrag':
                                vObject.enddrag(callback_func);
                              break;

                            case 'beforezoomchange':
                                vObject.beforezoomchange(callback_func);
                              break;
                            case 'onzoomchange':
                                vObject.beforezoomchange(callback_func);
                              break;
                            default:
                        }

		} else if (object.type == 'marker') {
			var vObject = this.markers.get(object.getId());
                        switch(vEvent) {
                            case 'mouseclick':
                                vObject.mousedown(callback_func);
                            break;
                            case 'startdrag':
                                vObject.startdrag(callback_func);
                              break;
                            case 'dragging':
                                vObject.dragging(callback_func);
                              break;
                            case 'enddrag':
                                vObject.enddrag(callback_func);
                              break;
                            default:
                        }
		}



//		VEvents.addListener(vObject,vEvent,callback_func);
	},

	destructMap : function() {

//        console.log('destructMap');

//		this.layers.each(function(layer){
//			layer.getMarkers().each(function(marker){
//				var length = marker.BG.length;
//				for(var i = 0;i<length;i++) {
//					var event = marker.BG[0];
//					marker.removeEventListener(event.Af);
//				}
//				var length = marker.Ai.length;
//				for(var i = 0;i<length;i++) {
//					var event = marker.Ai[0];
//					marker.removeEventListener(event.Af);
//				}
//			}.bind(this));
//			this.map.removeLayer(layer);
//		}.bind(this));
//
//		var length = VIs.BO.length;
//		for(var i = 0;i<length;i++) {
//			var event = VIs.BO[0];
//			VIs.removeEventListener(event.Af);
//		}
//
//		VIs.removeAllMarkers();
//		var length = VIs.Ai.length;
//		for(var i = 0;i<length;i++) {
//			var event = VIs.Ai[0];
//			VIs.removeEventListener(event.Af);
//		}
//		VIs.D.hide();
//		VIs.D = null;
//		VIs.AS = new Array();
//		for(var x in VIs) {
//			delete VIs[x];
//		}
//		AG.AM = null;
		this.layers.each(function(layer){
                    layer.getMarkers().each(function(marker){
                        var length = marker._mouse_event_listeners.length;
                        for(var i = 0;i<length;i++) {
                                var event = marker._mouse_event_listeners[0];
                                marker.removeEventListener(event._handler);
                        }
                        var length = marker._event_listeners.length;
                        for(var i = 0;i<length;i++) {
                                var event = marker._event_listeners[0];
                                marker.removeEventListener(event._handler);
                        }
                    }.bind(this));
                    this.map.removeLayer(layer);
		}.bind(this));

		var length = mapEngine._map_event_listeners.length;
		for(var i = 0;i<length;i++) {
			var event = mapEngine._map_event_listeners[0];
			mapEngine.removeEventListener(event._handler);
		}

		mapEngine.removeAllMarkers();
		var length = mapEngine._mouse_event_listeners.length;
		for(var i = 0;i<length;i++) {
			var event = mapEngine._mouse_event_listeners[0];
			mapEngine.removeEventListener(event._handler);
		}
		mapEngine._currentMap.hide();
		mapEngine._currentMap = null;
		mapEngine._maps = new Array();
		for(var x in mapEngine) {
			delete mapEngine[x];
		}
//		AG.AM = null;
	},

	fireMapEvent : function(object,event,args) {

//        console.log('fireMapEvent');

//		this.map.fireMapEvent(event);
	},

    searchAddress : function ( address , callback ) {

//        console.log('searchAddress');

         if (address.length < 3) {
            alert(MSG_MORE_2);
            return
        }
        address = address.replace(/[,]/g,'');
        var words = address.split(" ");
        var settlement = undefined;
        var street = undefined;
        var building = undefined;
        var regexNumber = /^\d+\/?\d*[?|?|?|?|?|?|?|?|?|?|?|?]?$/i;
        if (words[1] == undefined) {
            street = words[0];
        } else if (words[2] == undefined)
        {
            if (regexNumber.exec(words[1]) == null) {
                settlement = words[0];
                street = words[1]
            }
            else {
                street = words[0];
                building = words[1];
            }
        }
        else
        {
            settlement = words[0];
            street = words[1];
            if (regexNumber.exec(words[2]) != null) {
                building = words[2];
            }
        }
        if ( !settlement && $defined ( $(riaMap.options.navigation.citySelectId) ) ) {
            settlement = $(riaMap.options.navigation.citySelectId).getProperty('value');
        }
        riaMap.ajaxManager.jsonRequest(Ria_Ajax.script, function ( json ) {
            if ( json.result == 1 ) {
//                $each(json.points, function ( value) {
//    //                riaMap.storage.map.setCenter( new Ria_Map_Main_Common_GeoPoint ( value.lng, value.lat ) );
//    //                riaMap.storage.map.setZoom ( 100 );
//                }.bind(this));
                if ( json.points.length > 0 ) {
                    callback ( json.points );
                } else {
                    alert ( Lang.service_unavailable );
                }
            } else {
                if ( json.error == "Object's not found" ) {
                    alert ( Lang.object_not_found );
                } else alert(json.error);
            }
        }, {
            'target' : 'map',
            'event' : 'visicomSearch',
            'city' : settlement,
            'street' : street,
            'building' : building
        });
    }


});
/**
 *
 * Драйвер для карты Yandex'а
 *
 * @class Ria_Map_Main_Drivers_Yandex
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires    Ria_Map_Main_Common_GeoPoint
 */
 var Ria_Map_Main_Drivers_Yandex = new Class({

	Implements: Options,

    options: {
		'mapContainerId' : ''
	},

	markers : new Hash(),
	layers : new Hash(),
	zoomEvents : new Array(),

	initialize: function(options) {
    	this.setOptions(options);
		this.mapContainer = $(this.options.mapContainerId);
		this.mapContainer.set('html','');
		this.map = new YMaps.Map(this.mapContainer);

//		this.map.addControl(new YMaps.Zoom());
//		var myMap = new YMaps.MapType(YMaps.MapType.MAP.getLayers(), ' map ', {minZoom:6, maxZoom:17});
//		var myHub = new YMaps.MapType(YMaps.MapType.HYBRID.getLayers(), 'Hybrid', {minZoom:6, maxZoom:17});
//		this.map.addControl(new YMaps.TypeControl([myMap, myHub]));
//		this.map.setType(myMap);
		this.map.enableScrollZoom();
	},
        //-- -- -- -- -- -- -- -- --
	setMapControl : function(controlName,controlParams) {
//            alert(controlName);
            switch(controlName) {
                case 'mapTypes':
                    this.addMaptypesControlPanel(controlParams);
                    break;
                case 'miniMap':
                    this.map.addControl(new YMaps.MiniMap(), new YMaps.ControlPosition(this.getControlPositionByPositionId(controlParams['positioning']), new YMaps.Size(controlParams['offsetX'], controlParams['offsetY'])));
                    break;
                case 'scale':
                    this.map.addControl(new YMaps.ScaleLine(), new YMaps.ControlPosition(this.getControlPositionByPositionId(controlParams['positioning']), new YMaps.Size(controlParams['offsetX'], controlParams['offsetY'])));
                    break;
                case 'mainPannel':
                    switch(controlParams['type']) {
                        case 2: this.setSmallMainPanel(controlParams); break;
                        case 3: this.setSmallOnlyZoomMainPanel(controlParams); break;
                        default: this.setLargeMainPanel(controlParams);
                    }
                break;
            }
        },
        addMaptypesControlPanel: function(controlParams) {
            var mapTypesArr = new Array();
            controlParams['mapTypes'].each(function(mapType, key) {
                switch(mapType) {
                    case 1:
                        if(!mapTypesArr.contains(YMaps.MapType.MAP)) {
                            mapTypesArr.push(YMaps.MapType.MAP);
                        }
                    break;

                    case 2:
                        if(!mapTypesArr.contains(YMaps.MapType.SATELLITE)) {
                            mapTypesArr.push(YMaps.MapType.SATELLITE);
                        }
                    break;

                    case 3:
                        if(!mapTypesArr.contains(YMaps.MapType.HYBRID)) {
                            mapTypesArr.push(YMaps.MapType.HYBRID);
                        }
                    break;
                    default:
                }
//
//                alert('alert '+mapTypeKey);

        }.bind(this));
            this.map.addControl(new YMaps.TypeControl(mapTypesArr), new YMaps.ControlPosition(this.getControlPositionByPositionId(controlParams['positioning']), new YMaps.Size(controlParams['offsetX'], controlParams['offsetY'])));
        },
        setSmallOnlyZoomMainPanel: function(controlParams) {
            var offsetY = controlParams['offsetY'];
            var offsetX = controlParams['offsetX'];
            var positioning = controlParams['positioning'];
            switch(positioning) {
                case 3:
                    offsetY+=50;
                break;
                default :
                    positioning = 0;
            }
            this.map.addControl(new YMaps.SmallZoom(), new YMaps.ControlPosition(this.getControlPositionByPositionId(positioning), new YMaps.Size(offsetX,offsetY)));
        },

        setLargeMainPanel : function(controlParams) {
            var ToolBarOffsetX = 0;
            var ToolBarOffsetY = 0;
            var SmallZoomOffsetX = 0;
            var SmallZoomOffsetY = 0;
            var positioning = controlParams['positioning'];
            if (positioning!=0 && positioning!=1 && positioning!=2 && positioning!=3) positioning = 0;
            ToolBarOffsetX = controlParams['offsetX'];
            ToolBarOffsetY = controlParams['offsetY'];
            SmallZoomOffsetX = controlParams['offsetX'];
            SmallZoomOffsetY = controlParams['offsetY']+30;
            this.map.addControl(new YMaps.ToolBar(), new YMaps.ControlPosition(this.getControlPositionByPositionId(positioning), new YMaps.Size(ToolBarOffsetX,ToolBarOffsetY)));
            this.map.addControl(new YMaps.Zoom(), new YMaps.ControlPosition(this.getControlPositionByPositionId(positioning), new YMaps.Size(SmallZoomOffsetX,SmallZoomOffsetY)));

        },
        setSmallMainPanel : function(controlParams) {
            var ToolBarOffsetX = 0;
            var ToolBarOffsetY = 0;
            var SmallZoomOffsetX = 0;
            var SmallZoomOffsetY = 0;
            var positioning = controlParams['positioning'];
            switch(positioning) {
                case 2:
                case 3:
                    positioning = 3;
                    ToolBarOffsetX = controlParams['offsetX'];
                    ToolBarOffsetY = controlParams['offsetY'];
                    SmallZoomOffsetX = controlParams['offsetX'];
                    SmallZoomOffsetY = controlParams['offsetY']+80;
                break;
                default:
                    positioning = 0;
                    ToolBarOffsetX = controlParams['offsetX'];
                    ToolBarOffsetY = controlParams['offsetY'];
                    SmallZoomOffsetX = controlParams['offsetX'];
                    SmallZoomOffsetY = controlParams['offsetY']+35;
//                        this.setLargeMainPanel(controlParams);
            }
            this.map.addControl(new YMaps.ToolBar(), new YMaps.ControlPosition(this.getControlPositionByPositionId(positioning), new YMaps.Size(ToolBarOffsetX,ToolBarOffsetY)));
            this.map.addControl(new YMaps.SmallZoom(), new YMaps.ControlPosition(this.getControlPositionByPositionId(positioning), new YMaps.Size(SmallZoomOffsetX,SmallZoomOffsetY)));
        },

        getControlPositionByPositionId : function(positioning) {
            var retVal  = YMaps.ControlPosition.TOP_LEFT;
            switch(positioning) {
            case 1:
                retVal  = YMaps.ControlPosition.TOP_RIGHT;
                break;
            case 2:
                retVal = YMaps.ControlPosition.BOTTOM_RIGHT;
                break;
            case 3:
                retVal = YMaps.ControlPosition.BOTTOM_LEFT;
                break;
            default:
                retVal  = YMaps.ControlPosition.TOP_LEFT;
//              code to be executed if n is different from case 1 and 2
            }
            return retVal;
        },


        //-- -- -- -- -- -- -- -- --
	//инициализация карты
	initMap : function() {
//		new YMaps.Events.observe(this.map, this.map.Events.MoveEnd,function() {
//    		this.map.closeBalloon();
//		}.bind(this));
		new YMaps.Events.observe(this.map, this.map.Events.Update,function() {
    		this.map.closeBalloon();
//    		alert('blabla');
		}.bind(this));
	},

	//изменения размеров карты
        resizeMap : function(width,height) {
		if($defined(this.map)) {
			this.map.redraw();
		}
	},

	repaintMap : function() {
//		this.map.update();
	},

	addMarkerToBase : function(marker) {
		var ymarker = new YMaps.Placemark(marker.getGeoPoint().convertToMapPoint());
		YMaps.Events.observe(ymarker,ymarker.Events.Click, function () {
			this.map.closeBalloon();
		}.bind(this));
		var id = this.markers.getLength()+1;
		marker.setId(id);
		this.markers.set(id,ymarker);
	},


	addLayerToBase : function(layer) {
		var ylayer = new YMaps.GeoObjectCollection();
		var id = this.layers.getLength()+1;
		layer.setId(id);
		this.layers.set(id,ylayer);
	},

	addMarkerToMap : function(marker) {
		var ymarker = this.markers.get(marker.getId());
		this.map.addOverlay(ymarker);
	},

	addMarkerToLayer : function(id,marker) {
		var ymarker = this.markers.get(marker.getId());
		var ylayer = this.layers.get(id);
		ylayer.add(ymarker);
	},

	addLayerToMap : function(layer) {
		var ylayer = this.layers.get(layer.getId());
		this.map.addOverlay(ylayer);
	},

	removeLayerFromMap : function(layer) {
		var ylayer = this.layers.get(layer.getId());
		this.map.removeOverlay(ylayer);
	},

	convertToMapPoint : function(geoPoint) {
		var point =  new YMaps.GeoPoint(geoPoint.getLongitude(),geoPoint.getLatitude());
		return point;
	},

	setNameToMarker : function(id,name) {

	},

	setIconToMarker : function(id,width,height,src,offset_x,offset_y) {
            var s = new YMaps.Style();
            s.iconStyle = new YMaps.IconStyle();
            s.iconStyle.offset = new YMaps.Point(0-((offset_x)? offset_x :Math.round(width/2)),0-((offset_y)? offset_y : height ));
            s.iconStyle.href = src;
            s.iconStyle.size = new YMaps.Point(width,height);
            this.markers.get(id).setOptions({style : s});
	},

    setPointToMarker : function(id,point) {
        var ymarker = this.markers.get(id);
        ymarker.setGeoPoint(point.convertToMapPoint());
    },

    getPointFromMarker : function(id) {
        var ymarker = this.markers.get(id);
        var point = ymarker.getGeoPoint();
        return new Ria_Map_Main_Common_GeoPoint(point.getLng(),point.getLat());
    },

	hideMarker : function(id) {
		this.map.removeOverlay(this.markers.get(id));
	},

	showMarker : function(id) {
		this.map.addOverlay(this.markers.get(id));
	},

	hideLayer : function(id) {
		this.map.removeOverlay(this.layers.get(id));
	},

	showLayer : function(id) {
		this.map.addOverlay(this.layers.get(id));
	},

	removeMarkerFromMap : function(marker) {
		this.map.removeOverlay(this.markers.get(marker.getId()));
	},

	removeMarkerFromLayer : function(id,marker) {
		var ymarker = this.markers.get(marker.getId());
		var ylayer = this.layers.get(id);
		ylayer.remove(ymarker);
	},

	addInfoWindowToMarker : function(marker) {
		var ymarker = this.markers.get(marker.getId());
		ymarker.clickEvent = new YMaps.Events.observe(ymarker, ymarker.Events.Click,function() {
            var text = '<div class="baloon_title">'+marker.infoWindowName+'</div>'+marker.infoWindowHtml;
    		this.map.openBalloon(ymarker.getGeoPoint(), text);
		}.bind(this));
	},

	removeInfoWindowFromMarker : function(id) {
		var ymarker = this.markers.get(id);
		ymarker.clickEvent.cleanup();
	},

	openInfoWindowInMarker : function(id) {
		var ymarker = this.markers.get(id);
		YMaps.Events.notify(ymarker,ymarker.Events.Click);
	},

	closeInfoWindowInMarker : function(id) {
		this.map.closeBalloon();
	},

	setDraggableMarker : function(id,bool) {
		var ymarker = this.markers.get(id);
		ymarker.setOptions({draggable : bool});
	},

	setMapCenter : function(geoPoint) {
		this.map.setCenter(geoPoint.convertToMapPoint());
	},

	getMapCenter : function() {
		var ygeoPoint = this.map.getCenter();
		return new Ria_Map_Main_Common_GeoPoint(ygeoPoint.getLng(),ygeoPoint.getLat());
	},

	setMapZoom : function(index) {
		var maxZoom = RMaps.Config.getConfig('maxZoom') - RMaps.Config.getConfig('minZoom');
		var zoom = (Math.round((index*maxZoom)/100))+RMaps.Config.getConfig('minZoom');
		this.map.setZoom(zoom);
	},

	getMapZoom : function() {
		var maxZoom = RMaps.Config.getConfig('maxZoom') - RMaps.Config.getConfig('minZoom');
		var zoom = this.map.getZoom()-RMaps.Config.getConfig('minZoom');
		return (Math.round((zoom*100)/maxZoom));
	},

	getClientRectangle : function() {
		var vrect = this.map.getBounds();
		var rect = new Hash();
		var vmaxPoint = vrect.getRightTop();
		var vminPoint = vrect.getLeftBottom();
		rect.set('min',new Ria_Map_Main_Common_GeoPoint(vminPoint.getLng(),vminPoint.getLat()));
		rect.set('max',new Ria_Map_Main_Common_GeoPoint(vmaxPoint.getLng(),vmaxPoint.getLat()));
		return rect;
	},

	addEventListener : function(object,event,callback_func) {
		if(object.type == 'map') {
			var yobject = this.map;
		} else if (object.type == 'marker') {
			var yobject = this.markers.get(object.getId());
		}
		event = object.type + "_" + event;
		eval('var yevent = yobject.' + RMaps.Config.getConfig('events')[event] + ';');
		if(event == 'map_zoomchange') {
			if(this.zoomEvents.length == 0) {
//				alert('adding event');
				this.zoom = this.map.getZoom();
				YMaps.Events.observe(yobject,yevent,function() {
					this.zoomEvent();
				}.bind(this));
			}
			this.zoomEvents.include(callback_func);
		} else {
			YMaps.Events.observe(yobject,yevent,function() {
				callback_func();
			}.bind(this));
		}
	},

	destructMap : function() {
		this.map.destructor();
	},

	zoomEvent : function() {

		if(this.map.getZoom() == this.zoom) {
//			alert('return');
			return;
		}
//		alert('ZoomChange');
		this.zoom = this.map.getZoom();
		this.zoomEvents.each(function(func){
			func();
		}.bind(this));
	},

    searchAddress : function ( address , callback ) {
        var geocoder = new YMaps.Geocoder(address);
        riaMap.ajaxManager.showSpinner();
        YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
            var result = new Array(),
                accuracy = ["exact", "near", "number","street"],
                prec;
            riaMap.ajaxManager.hideSpinner();
            for ( var i = 0; i < this.length(); i++ ) {
                prec = this.get(i).precision;
                if ( accuracy.contains(prec) ) {
                    var addr = this.get(i).AddressDetails;
                    if ( typeof addr.Country != "undefined" ) {
                        if ( addr.Country.CountryName != Lang.ukraine_map) continue;
                        if ( typeof addr.Country.Locality != "undefined" ) {
                            var city = addr.Country.Locality.LocalityName;
                            if ( typeof addr.Country.Locality.Thoroughfare != "undefined" ) {
                                var name = addr.Country.Locality.Thoroughfare.ThoroughfareName;
                                if ( typeof addr.Country.Locality.Thoroughfare.Premise != "undefined" ) {
                                    name += ", " + addr.Country.Locality.Thoroughfare.Premise.PremiseNumber;
                                }
                            }
                        }
                    }
                    var geoPoint = this.get(i).getGeoPoint();
                    result.include ( {
                        "name" : name,
                        "city" : city,
                        "lng" : geoPoint.getLng(),
                        "lat" : geoPoint.getLat()
                    } );
                }
            }
            if ( result.length > 0 ) {
               callback( result );
            } else {
               alert(Lang.object_not_found);
               return false;
            }
        });
        YMaps.Events.observe(geocoder, geocoder.Events.Fault, function () {
            alert(Lang.service_unavailable);
            return false;
        });
    }
});
/**
 * 
 * @class Ria_Map_Main_Drivers_Google_Layer
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires    Ria_Map_Main_Common_GeoPoint
 */
 var Ria_Map_Main_Drivers_Google_Layer = new Class({
    Implements: Options,

    options: {
            'minZoom' : '6',
            'maxZoom' : '19'
    },

    markers : new Hash(),
//    layers : new Hash(),

    initialize: function(driver,options){
        this.setOptions(options);
        this.driver = driver;
        this.minZoom = this.options['minZoom'];
        this.maxZoom = this.options['maxZoom'];

//this.show();

        this.onZoomEvent();
        //            alert('init');
    },
    setZoomLevels : function(minZoom,maxZoom) {
        this.minZoom = minZoom;
        this.maxZoom = maxZoom;
    },
    addMarker : function(id) {
//        alert('addMarkerToLayer '+id);
        this.markers.set(id,id);
    },
    
    removeMarker : function(id) {
        this.markers.erase(id);
    },

    show : function() {
//        alert('show');
        $each(this.markers, function(item, index) {

            this.driver.markers.get(item).show();
//            this.driver.map.addOverlay();
        }.bind(this));
    },
    hide : function() {
//         alert('hide');
        $each(this.markers, function(item, index){
            this.driver.markers.get(item).hide();
//            this.driver.map.removeOverlay(this.driver.markers.get((item)));
        }.bind(this));
       
    },
    onZoomEvent : function(id) {
        this.driver.addEventListener(this.driver.map, 'zoomchange', function() {
           var currentMapZoom = this.getCurrentMapZoom();
           if((currentMapZoom>this.maxZoom) || (currentMapZoom<this.minZoom)) {
               this.hide();
           } else {
               this.show();
           }
        }.bind(this));
    },
    getCurrentMapZoom : function() {
        var maxZoom = RMaps.Config.getConfig('maxZoom') - RMaps.Config.getConfig('minZoom');
        return (Math.round((this.driver.getMapZoom()*maxZoom)/100))+RMaps.Config.getConfig('minZoom');
    }
});

/**
 * 
 * @class Ria_Map_Main_Drivers_Google_Marker
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires    Ria_Map_Main_Common_GeoPoint
 */
 var Ria_Map_Main_Drivers_Google_Marker = new Class({
    Implements: Options,
    type : 'marker',
    isShow : false,
    latLngPoint : null,
    driver : null,
    draggable: false,
    gMarker : null,
    withIcon : false,
    iconChanged:false,
    iconHash: new Hash(),
    icon : null,
    events : new Array(),
    initialize: function(driver,latLngPoint,options) {
        this.icon = new GIcon(G_DEFAULT_ICON);
        this.driver = driver;
        this.setOptions(options);
        if(this.options['draggable']) this.draggable = this.options['draggable'];
        if(latLngPoint) this.latLngPoint = latLngPoint;
    },
    setPoint: function(latLngPoint) {
        this.latLngPoint = latLngPoint;
        if (this.isShow) this.redraw();
    },
    setMarkerOptions: function(options) {
        this.markerOptions = options;
    },
    redraw: function() {
            this.hide();
            this.show();
    },
    show: function() {
        if (!this.isShow) {
            this.isShow = true;
            if(this.iconChanged) {
                this.iconChanged = false;
                this.icon = this.getMarkerIconObject();
            }
            var markerOptions = {'draggable':true,'icon':this.icon};
            this.gMarker = new GMarker(this.latLngPoint, markerOptions);
            this.disableDragging();

            this.driver.map.addOverlay(this.gMarker);
            this.addListener(this,'dragend', function() {
                this.latLngPoint = this.gMarker.getLatLng();
            }.bind(this) );

            this.addListenersFromStack();
        } else this.redraw();
    },
    getPoint: function() {
        if (this.isShow) return this.gMarker.getPoint();
        else return this.latLngPoint;
    },
    hide: function() {
        if (this.isShow) {
            this.isShow = false;
            this.driver.map.removeOverlay(this.gMarker);
        }
    },
    enableDragging: function() {
        this.draggable = true;
        if (this.isShow) this.gMarker.enableDragging();
    },
    disableDragging: function() {
        this.draggable = false;
        this.gMarker.disableDragging();
    },
    addInfoWindowToMarker: function(marker) {
        this.infoWindowName = marker.infoWindowName;
        this.infoWindowHtml = marker.infoWindowHtml;
            this.addListener(this.gMarker, 'click', function() {
                var text = '<div class="baloon_titarle">'+this.infoWindowName+'</div>'+this.infoWindowHtml;
                this.gMarker.openInfoWindowHtml(text);
            }.bind(this));
        this.redraw();
    },
    openInfoWindowInMarker : function(id) {
        new GEvent.trigger(this.gMarker, 'click');
    },
    closeInfoWindowInMarker : function(id) {
         this.gMarker.closeInfoWindow();
    },

    removeInfoWindowFromMarker : function(id) {
//        var gMarker = this.driver.markers.get(id);
//        var gEvent = RMaps.Config.getConfig('events')['marker_ouseclick'];
//        new GEvent.clearListeners(this.gMarker,  gEvent);
    },
    getMarkerIconObject: function() {
        var gIcon = new GIcon(G_DEFAULT_ICON);
        if(this.iconHash.get('src')!='') gIcon.image = this.iconHash.get('src');
        if(this.iconHash.get('width')!=0 && this.iconHash.get('height')!=0) {
            var width = this.iconHash.get('width');// - offsetX*2;
            width = width +'px';
            var height = this.iconHash.get('height');// - offsetY*2;
            height = height +'px';
            gIcon.iconSize = new GSize(width,height);
            gIcon.shadowSize = gIcon.iconSize;
        }
        return gIcon;
    },
    setIconToMarker: function(src,width,height,offsetX,offsetY) {
        this.withIcon = true;
        this.iconHash.set('src',src);
        this.iconHash.set('width',width);
        this.iconHash.set('height',height);
        this.iconHash.set('offsetX',offsetX);
        this.iconHash.set('offsetY',offsetY);
        this.iconChanged = true;
        this.redraw();
    },
    addListener: function(gMarker,gEvent,callback_func) {
        this.events.push(new Hash({'event':gEvent,'callback_func':callback_func}));
//        alert(this.isShow.toString());
//        new GEvent.addListener(this.gMarker, gEvent, function() { callback_func(); });
    },
    addListenersFromStack: function() {
        window.addEvent('domready', function() {
        if (this.isShow) {
                $each(this.events, function(item, index) {
                    var tmpCallbackFunc = item.get('callback_func');
                    var tmpGEvent = item.get('event');
                    new GEvent.addListener(this.gMarker, tmpGEvent, function() { tmpCallbackFunc(); });
                }.bind(this));
        }
        }.bind(this));
    },
    fireMapEvent : function(event,args) {
//        console.log(event);
//        console.log(this.gMarker);
        new GEvent.trigger(this.gMarker,event,args);
//        console.log('message');

    },
    clearAllListenersFromStack: function() {
        this.events = new Array();
    }

});

/**
 * 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
    */
    var Ria_Hotel_DisplayHotelReviews = new Class({

        Extends: Ria_HtmlRequest,

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

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

/**
 * Description
 *
 *
 *
 * @class Ria_Rating_RatingRemindManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires    Ria_Rating_RatingBaseManager
*/
var Ria_Rating_RatingRemindManager = new Class({

    Extends: Ria_Rating_RatingBaseManager,

	initialize: function(options){
        this.parent(options);

        new Element('input',{
            'id':'rating_value_'+this.options['fieldName'],
            'type':'hidden',
            'name':this.options['fieldName'],
            'value':0
        }).inject($(this.options['parentId']));
	},

    eventClick:function(newValue){
        this.currentValue = newValue;
        $each(this.options['values'], function(title, value){
            if (value <= newValue) $('rating_img_'+this.options['fieldName']+'_'+value).setProperty('src', this.img_on);
            else $('rating_img_'+this.options['fieldName']+'_'+value).setProperty('src', this.img_off);
        }.bind(this));
        $('rating_value_'+this.options['fieldName']).setProperty('value', newValue);
    }

});
/**
 * 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);
		}
	}
	
});
/**
 * 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_FillFormUKR = 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);
			$(this.id.id5).set('value', jsonObj.result.guest_country);
			$(this.id.id6).set('value', jsonObj.result.guest_telephone);
		}
		
	}
});

/**
 * 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);
			$(this.id.id5).set('value', jsonObj.result.guest_country);
			$(this.id.id6).set('value', jsonObj.result.guest_telephone);
		}
		
	}
});

/**
 *
 * @class Ria_Hotel_Location_CitiesRequest
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_JsonRequest
 */
var Ria_Hotel_Location_CitiesRequest = new Class({
	
	Extends: Ria_JsonRequest, 
	
	options: {
		target: 	'addrNew',
		event: 		'getCities'
	},
	
	onGetResponse: function(jsonObj) {
		this.json = jsonObj;
		if (jsonObj.result>0){
			if ($defined(this.options.cities_element_id)) {
				this.processCities();
			}
			if ($defined(this.options.areas_element_id)) {
				this.processAreas();
			}
		} else if (this.options.state_id!=0) {
			alert(Lang.error);
		}
	},
		
	processCities: function() {
		var select = $(this.options.cities_element_id);
		select.empty();
		
		if (this.options.city_id == 0) {
			this.options.city_id = this.options.state_id;
		}
		new Element('option',{'value': 0, 'id':this.options.cities_element_id+'_0'}).inject(select).set('text', '- ' + this.json.any_city + ' -');
		
		$each(this.json.cities, function(item, index){
				var element = new Element('option', { 'value': index, 'id':this.options.cities_element_id+'_'+index });

				if ($defined(this.json.mapsCities)){
					element.riaMapZoom = 6;
					element.riaMapData = this.json.mapsCities[index];
				}
				
				if (index == this.options.city_id) {
					this.setSelected(element);
				}
				element.inject(select).set('text', item);
		}, this );
		
		select.set('disabled', false);
	},
	
	
	processAreas: function () {
		var select = $(this.options.areas_element_id);
		select.empty();
		new Element('option',{'value': 0, 'id':this.options.areas_element_id+'_0'}).inject(select).set('text', '- ' + this.json.not_set_male + ' -');
		
		$each(this.json.areas, function(item, index){
			var element = new Element('option', {'value': index, 'id':this.options.areas_element_id+'_'+index });
			
			if ($defined(this.json.mapsAreas)){
				element.riaMapZoom = 8;
				element.riaMapData = this.json.mapsAreas[index];
			}
			
			if (index == this.options.area_id) {
				this.setSelected(element);
			}
			element.inject(select).set('text', item);
		}, this);
		
		select.set('disabled', false);
	},
	
	setSelected:function(optionElement){
		optionElement.set('selected', true);
		
		if (optionElement.riaMapData){
			if (optionElement.riaMapData['geo_X']!=0){
				
				riaMapManagerObj.setCenter(new Ria_Map_GeoPoint({
					'geo_X':optionElement.riaMapData['geo_X'],
					'geo_Y':optionElement.riaMapData['geo_Y'],
					'zoom': optionElement.riaMapZoom,
					'engineId':1}
				));
				
				
			}
		}
	}
		
	
});
/**
 *
 * @class Ria_Hotel_Location_AreasRequest
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_JsonRequest
 */
var Ria_Hotel_Location_AreasRequest = new Class({
	
	Extends: Ria_JsonRequest, 
	
	options: {
		target: 	'addrNew',
		event: 		'getAreas'
	},
	
	onGetResponse: function(jsonObj) {
		this.json = jsonObj;
		if (jsonObj.result>0){
			if ($defined(this.options.areas_element_id)) {
				this.processAreas();
			}
		} else if (this.options.city_id!=0){
			alert(Lang.error);
		}
	},
		
	processAreas: function () {
		var select = $(this.options.areas_element_id);
		select.set('disabled', true);
		select.empty();
		new Element('option',{'value': 0, 'id':this.options.areas_element_id+'_0'}).inject(select).set('text', '- ' + this.json.not_set_male + ' -');
		
		$each(this.json.areas, function(item, index){
			var element = new Element('option', { 'value': index, 'id':this.options.areas_element_id+'_'+index });

			if ($defined(this.json.mapsAreas)){
				element.riaMapZoom = 8;
				element.riaMapData = this.json.mapsAreas[index];
			}
			
			if (index == this.options.area_id) { 
				this.setSelected(element);
			}
			element.inject(select).set('text', item);
		}, this);
		
		select.set('disabled', false);
	},
	
	setSelected:function(optionElement){
		optionElement.set('selected', true);
		
		if (optionElement.riaMapData){
			if (optionElement.riaMapData['geo_X']!=0){
				
				riaMapManagerObj.setCenter(new Ria_Map_GeoPoint({
					'geo_X':optionElement.riaMapData['geo_X'],
					'geo_Y':optionElement.riaMapData['geo_Y'],
					'zoom': optionElement.riaMapZoom,
					'engineId':1}
				));
				
			}
		}
	}
	
	
});
/**
 *
 * @class Ria_Hotel_Location_AddressRequest
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_JsonRequest
 */
var Ria_Hotel_Location_AddressRequest = new Class({
	
	Extends: Ria_JsonRequest, 
	
	options: {
		target: 	'addrNew',
		event: 		'searchMapAddress'
	},
	
	onGetResponse: function(jsonObj) {
		if (jsonObj.result>0){
			
			riaMapManagerObj.setCenter(new Ria_Map_GeoPoint({
				'geo_X':jsonObj.geo_X,
				'geo_Y':jsonObj.geo_Y,
				'zoom': 100,
				'engineId':1}
			));
			
		}
	}

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

        Extends: Ria_HtmlRequest,

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

   /**
    * @param {String} id id объекта, который будет обновлен по приходу ответа от сервера
    * @raram {Array} options параметры для построения запроса
    */
        initialize: function(ids, options){
            
            this.setOptions(options);
            element='div'+ ids.iter;
//            alert(element);
            new Element('div', {
                'id': 'div'+ ids.iter2
                }).inject(element, 'after');
            //$(element).inject(myDiv, 'after');

            $(ids.Id_div).set('load', {
                evalScripts: true
            });
            $(ids.Id_div).load(Ria_Ajax.script + '?' + Hash.toQueryString(this.options));
        }
    });

/**
 *
 * @class Ria_Map_Main_Drivers_Google
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires    Ria_Map_Main_Common_GeoPoint
 * @requires    Ria_Map_Main_Drivers_Google_Layer
 * @requires    Ria_Map_Main_Drivers_Google_Marker
 */
 var Ria_Map_Main_Drivers_Google = new Class({

	Implements: Options,

        options: {
		'mapContainerId' : ''
	},
//        type : 'map',
	markers : new Hash(),
	layers : new Hash(),
	zoomEvents : new Array(),

	initialize: function(options){
    	this.setOptions(options);
        this.setOptions(options);
            this.mapContainer = $(this.options.mapContainerId);
            this.mapContainer.set('html','');
            this.map = new GMap2(this.mapContainer);
            this.map.type = 'map';
	},
        setMapControl : function(controlName,controlParams) {
            var offsetX = controlParams['offsetX'];
            var offsetY = controlParams['offsetY'];
            var positioning = controlParams['positioning'];
            switch(controlName) {
                case 'mapTypes':
                    this.addMaptypesControlPanel(controlParams);
//                    this.map.addControl(new GMapTypeControl(), new GControlPosition(this.getControlPositionByPositionId(positioning), new GSize(offsetX,offsetY)));
                    break;
                case 'miniMap':
                    this.map.addControl(new GOverviewMapControl(), new GControlPosition(this.getControlPositionByPositionId(positioning), new GSize(offsetX,offsetY)));
                    break;
                case 'scale':
                    this.map.addControl(new GScaleControl(), new GControlPosition(this.getControlPositionByPositionId(positioning), new GSize(offsetX,offsetY)));
                    break;
                case 'mainPannel':
                    switch(controlParams['type']) {
                        case 2: this.map.addControl(new GSmallMapControl(), new GControlPosition(this.getControlPositionByPositionId(positioning), new GSize(offsetX,offsetY))); break;
                        case 3: this.map.addControl(new GSmallZoomControl(), new GControlPosition(this.getControlPositionByPositionId(positioning), new GSize(offsetX,offsetY))); break;
                        default: this.map.addControl(new GLargeMapControl(), new GControlPosition(this.getControlPositionByPositionId(positioning), new GSize(offsetX,offsetY)));
                    }
                break;
            }
        },
        addMaptypesControlPanel: function(controlParams) {
            var mapTypesArr = new Array();
            var offsetX = controlParams['offsetX'];
            var offsetY = controlParams['offsetY'];
            var positioning = controlParams['positioning'];

            
            this.map.removeMapType(G_SATELLITE_MAP);
            this.map.removeMapType(G_HYBRID_MAP);
            this.map.removeMapType(G_NORMAL_MAP);
            
            
            controlParams['mapTypes'].each(function(mapType, key) {
                switch(mapType) {
                    case 1:
                        if(!mapTypesArr.contains(G_NORMAL_MAP)) {
                            mapTypesArr.push(G_NORMAL_MAP);
                            this.map.addMapType(G_NORMAL_MAP);
                        }
                    break;
                    case 2:
                        if(!mapTypesArr.contains(G_SATELLITE_MAP)) {
                            mapTypesArr.push(G_SATELLITE_MAP);
                            this.map.addMapType(G_SATELLITE_MAP);
                        }
                    break;
                    case 3:
                        if(!mapTypesArr.contains(G_HYBRID_MAP)) {
                            mapTypesArr.push(G_HYBRID_MAP);
                            this.map.addMapType(G_HYBRID_MAP);
                        }
                    break;
                    case 4:
                        if(!mapTypesArr.contains(G_PHYSICAL_MAP)) {
                            mapTypesArr.push(G_PHYSICAL_MAP);
//                            this.map.addMapType(G_PHYSICAL_MAP);
                        }
                    break;
                    default:
                }
            }.bind(this));
            this.map.addControl(new GMapTypeControl(), new GControlPosition(this.getControlPositionByPositionId(positioning), new GSize(offsetX,offsetY)));
        },
        getControlPositionByPositionId : function(positioning) {
            var retVal  = G_ANCHOR_TOP_LEFT;
            switch(positioning) {
            case 1:
                retVal  = G_ANCHOR_TOP_RIGHT;
                break;
            case 2:
                retVal = G_ANCHOR_BOTTOM_RIGHT;
                break;
            case 3:
                retVal = G_ANCHOR_BOTTOM_LEFT;
                break;
            default:
                retVal  = G_ANCHOR_TOP_LEFT;
            }
            return retVal;
        },
	
	initMap : function() {
             this.addEventListener(this.map, 'enddrag', function() {
//                this.map.clearOverlays();
            }.bind(this));
            this.addEventListener(this.map, 'zoomchange', function() {
//                this.zoomEvent();
            }.bind(this));
	},

	resizeMap : function(width,height) {
//		if($defined(this.map)) {
//			this.map.redraw();
//		}
	},

	repaintMap : function() {
//		this.map.update();
	},

	addMarkerToBase : function(marker) {
            var gMarker = new Ria_Map_Main_Drivers_Google_Marker(this,marker.getGeoPoint().convertToMapPoint());
            var id = this.markers.getLength() + 1;
            marker.setId(id);
            this.markers.set(id,gMarker);
	},


	addLayerToBase : function(layer) {
            var gLayer = new Ria_Map_Main_Drivers_Google_Layer(this);
            gLayer.type = layer.type;
            var id = this.layers.getLength()+1;
            layer.setId(id);
            this.layers.set(id,gLayer);
	},

	addMarkerToMap : function(marker) {
            var gMarker = this.markers.get(marker.getId()).show();
	},

	addMarkerToLayer : function(id,marker) {
		var gMarker = this.markers.get(marker.getId());
                var gLayer = this.layers.get(id);
		gLayer.addMarker(marker.getId());
	},

	addLayerToMap : function(layer) {
            var gLayer = this.layers.get(layer.getId());
            gLayer.show();
	},

	removeLayerFromMap : function(layer) {
            var gLayer = this.layers.get(layer.getId()).hide();
	},

	convertToMapPoint : function(geoPoint) {
            return new GLatLng(geoPoint.getLatitude(),geoPoint.getLongitude());
	},

	setNameToMarker : function(id,name) {

	},

	setIconToMarker : function(id,width,height,src,offset_x,offset_y) {
            var gMarker = this.markers.get(id);
            gMarker.setIconToMarker(src,width,height,offset_x,offset_y);
//		var s = new YMaps.Style();
//		s.iconStyle.offset = new YMaps.Point(0-((offset_x)? offset_x :Math.round(width/2)),0-((offset_y)? offset_y : height ));
//		s.iconStyle.href = src;
//		s.iconStyle.size = new YMaps.Point(width,height);
//		this.markers.get(id).setOptions({style : s});
	},

    setPointToMarker : function(id,point) {
         var gMarker = this.markers.get(id);
         gMarker.setPoint(point.convertToMapPoint());
    },

    getPointFromMarker : function(id) {
        var gmarker = this.markers.get(id);
        var point = gmarker.getPoint();
        return new Ria_Map_Main_Common_GeoPoint(point.lng(),point.lat());
    },

	hideMarker : function(id) {
            this.markers.get(id).hide();
//		this.map.removeOverlay(this.markers.get(id));
	},

	showMarker : function(id) {
            this.markers.get(id).show();
//		this.map.addOverlay(this.markers.get(id));
	},

	hideLayer : function(id) {
            var gLayer = this.layers.get(id);
            gLayer.hide();
	},

	showLayer : function(id) {
            var gLayer = this.layers.get(id);
            gLayer.show();
	},

	removeMarkerFromMap : function(marker) {
		this.map.removeOverlay(this.markers.get(marker.getId()));
	},

	removeMarkerFromLayer : function(id,marker) {
            var gLayer = this.layers.get(id);
            gLayer.removeMarker(marker.getId());
	},

	addInfoWindowToMarker : function(marker) {
            var gMarker = this.markers.get(marker.getId());
            gMarker.addInfoWindowToMarker(marker);
	},

	removeInfoWindowFromMarker : function(id) {
            var gMarker = this.markers.get(id).removeInfoWindowFromMarker(id);
	},

	openInfoWindowInMarker : function(id) {
//            alert('openWnd');
            var gMarker = this.markers.get(id).openInfoWindowInMarker(id);
	},

	closeInfoWindowInMarker : function(id) {
            var gMarker = this.markers.get(id).closeInfoWindowInMarker(id);
	},

	setDraggableMarker : function(id,bool) {
            if (bool) this.markers.get(id).enableDragging();
            else this.markers.get(id).disableDragging();
	},

	setMapCenter : function(geoPoint) {
            this.map.setCenter(geoPoint.convertToMapPoint());
	},

	getMapCenter : function() {
            var gGeoPoint = this.map.getCenter();
            return new Ria_Map_Main_Common_GeoPoint(gGeoPoint.lng(),gGeoPoint.lat());
	},

	setMapZoom : function(index) {
            var maxZoom = RMaps.Config.getConfig('maxZoom') - RMaps.Config.getConfig('minZoom');
            var zoom = (Math.round((index*maxZoom)/100))+RMaps.Config.getConfig('minZoom');
            this.map.setZoom(zoom);
	},

	getMapZoom : function() {
            var maxZoom = RMaps.Config.getConfig('maxZoom') - RMaps.Config.getConfig('minZoom');
            var zoom = this.map.getZoom()-RMaps.Config.getConfig('minZoom');
            return  (Math.round((zoom*100)/maxZoom));
	},

	getClientRectangle : function() {
		var vrect = this.map.getBounds();
		var rect = new Hash();
		var vmaxPoint = vrect.getNorthEast();
		var vminPoint = vrect.getSouthWest();
		rect.set('min',new Ria_Map_Main_Common_GeoPoint(vminPoint.lng(),vminPoint.lat()));
		rect.set('max',new Ria_Map_Main_Common_GeoPoint(vmaxPoint.lng(),vmaxPoint.lat()));
		return rect;
	},

	addEventListener : function(object,event,callback_func) {
            event = object.type + "_" + event;
            var gEvent = RMaps.Config.getConfig('events')[event];

            if (object.type == 'marker') {
                var gObject = this.markers.get(object.getId());
//                this.zoomEvents.each(function(func){
////			func();
////		}.bind(this));
                gObject.addListener(object,gEvent, callback_func );
            } else if(object.type == 'map') {
                GEvent.addListener(this.map, gEvent, function() { callback_func(); }.bind(this));
            }
	},
        fireMapEvent : function(object,event,args) {
//console.log('fireMapEvent');
            event = object.type + "_" + event;
            var gEvent = RMaps.Config.getConfig('events')[event];

//        console.log(event);

//        console.log(gEvent);

            if (object.type == 'marker') {
                var gObject = this.markers.get(object.getId());
                gObject.fireMapEvent(gEvent, args );
            } else if(object.type == 'map') {
                new GEvent.trigger(this.map, gEvent,args);
            }
        },

	destructMap : function() {
//		this.map.destructor();
	},

	zoomEvent : function() {
	},

    searchAddress : function ( address , callback ) {
        riaMap.ajaxManager.showSpinner();

        var geocoder = new GClientGeocoder();
        geocoder.getLocations(address,function (response) {

//            var variable = JSON.encode(response).toString();
//            alert(variable);
//G_GEO_UNKNOWN_ADDRESS

            var result = new Array();
//            var accuracy = [ 5, 6, 7, 8 ,];
            if(parseInt(response.Status.code)==200) {
                $each(response.Placemark,function(placemarkItem, placemarkIndex) {
                    if (placemarkItem.AddressDetails.Accuracy >= 5) {
                        if (placemarkItem.address.contains(Lang.ukraine)) {
                            var addrArr = placemarkItem.address.split(',');
//                            alert (placemarkItem.address);
                            var city ='';
                            var name = '';
                            if (addrArr.length==3) {
                                 name = addrArr[0];
                                 city = addrArr[1];


                            } else if (addrArr.length==4) {
                                name = addrArr[1]+', '+addrArr[0];
                                city = addrArr[2];
                            }
//                            var variable = JSON.encode(placemarkItem).toString();
//                            alert(variable);

                            result.include ( {
                                "name" : name,
                                "city" : city,
                                "lng" : placemarkItem.Point.coordinates[0],
                                "lat" : placemarkItem.Point.coordinates[1]
                            } );
                        }
                    }
                });
            } else alert(Lang.service_unavailable);

            riaMap.ajaxManager.hideSpinner();
            
            if ( result.length > 0 ) {
               callback( result );
            } else {
               alert(Lang.object_not_found);
               return false;
            }

            
        });
        
//        var geocoder = new YMaps.Geocoder(address);

//        getLocations
//        var geocoder = new YMaps.Geocoder(address);
//        riaMap.ajaxManager.showSpinner();
//        YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
//            var result = new Array(),
//                accuracy = ["exact", "near", "number","street"],
//                prec;
//            riaMap.ajaxManager.hideSpinner();
//            for ( var i = 0; i < this.length(); i++ ) {
//                prec = this.get(i).precision;
//                if ( accuracy.contains(prec) ) {
//                    var addr = this.get(i).AddressDetails;
//                    if ( typeof addr.Country != "undefined" ) {
//                        if ( addr.Country.CountryName != "�������" ) continue;
//                        if ( typeof addr.Country.Locality != "undefined" ) {
//                            var city = addr.Country.Locality.LocalityName;
//                            if ( typeof addr.Country.Locality.Thoroughfare != "undefined" ) {
//                                var name = addr.Country.Locality.Thoroughfare.ThoroughfareName;
//                                if ( typeof addr.Country.Locality.Thoroughfare.Premise != "undefined" ) {
//                                    name += ", " + addr.Country.Locality.Thoroughfare.Premise.PremiseNumber;
//                                }
//                            }
//                        }
//                    }
//                    var geoPoint = this.get(i).getGeoPoint();
//                    result.include ( {
//                        "name" : name,
//                        "city" : city,
//                        "lng" : geoPoint.getLng(),
//                        "lat" : geoPoint.getLat()
//                    } );
//                }
//            }
//            if ( result.length > 0 ) {
//               callback( result );
//            } else {
//               return false;
//            }
//        });
//        YMaps.Events.observe(geocoder, geocoder.Events.Fault, function () {
//            return false;
//        });
    }
});
    /**
    * 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: {
            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
            });
            $(ids.Id_div).load(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: {
		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', 'icons_Statys_Notepad icons_Statys_added');
			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));		
	}
	

});
/**
 *
 * Класс доступен из любого инного класа,
 * у него устанавливаются все дефолтные настройки и
 * он хранит в себе объект драйвера
 *
 * @class Ria_Map_Main_Common_Config
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Map_Main_Drivers_Visicom
 * @requires   Ria_Map_Main_Drivers_Yandex
 * @requires   Ria_Map_Main_Drivers_Google
 */
 var Ria_Map_Main_Common_Config = new Class({

	Drivers: {
		'1' : {
				'name' : 'Visicom',
			   	'minZoom' : 0,
				'maxZoom' : 11,
//				'script' : 'http://maps.visicom.ua/api/getMap?map=ukraine',
				'events' : {
					'mouseclick' : 'mouseclick',
					'enddrag' : 'enddrag',
					'zoomchange' : 'zoomchange',

                                        //not exist in vizikom!!!
                                        'mouseover' : '',
					'mouseout' : ''
				}
			},
		'2' : {
				'name' : 'Yandex',
			   	'minZoom' : 6,
				'maxZoom' : 17,
//				'script': 'http://maps.visicom.ua/api/getMap?map=ukraine',
				'events' : {
					'marker_mouseclick' : 'Events.Click',

					'marker_mouseover' : 'Events.MouseOver',
					'marker_mouseout' : 'Events.MouseOut',

					'map_mouseclick' : 'Events.Click',
					'marker_enddrag' : 'Events.DragEnd',
					'map_enddrag' : 'Events.MoveEnd',
					'map_zoomchange' : 'Events.Update'
                                }
			}
                        ,
		'3' : {
				'name' : 'Google',
//                                'minZoom' : 0,
//				'maxZoom' : 19,
//			   	'minZoom' : 6,
//				'maxZoom' : 17,
			   	'minZoom' : 6,
				'maxZoom' : 19,
//				'script': 'http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAA9rPUKe9MiDCmtxJ8U3MF9BQ5GFsQBj65HhM_HQNIg6zZWXvhJhTYM8aDf81xEGomfphpgB8tmbbB_w',
				'events' : {
                                        'map_zoomchange' : 'zoomend',
                                        'map_dragstart' : 'dragstart',
					'map_mouseclick' : 'click',
					'map_enddrag' : 'moveend',

                                        'marker_dragstart' : 'dragstart',
                                        'marker_mouseclick' : 'click',
					'marker_enddrag' : 'dragend',

                                        'marker_mouseover' : 'mouseover',
                                        'marker_mouseout' : 'mouseout'
				}
			}
	},
        mapControls : {
            'mainPannel' : {
                'enabled' :1,
                //1 & default = LargeControl; 2 = SmallControl, 3 = smallZoomControl only
                'type' : 1,
                //0 - TOP_LEFT,1 - TOP_RIGHT,2 - BOTTOM_RIGHT,3 - BOTTOM_LEFT, enother = 0 - TOP_LEFT
                'positioning' :0,
                'offsetX' : 5,
                'offsetY' : 5
            },
            'scale' : {
                'enabled' : 1,
                'positioning' : 2,
                'offsetX' : 5,
                'offsetY' : 5
            },
            'miniMap' : {
                'enabled' : 0,
                'positioning' : 3,
                'offsetX' : 5,
                'offsetY' : 5
            },
            'mapTypes' : {
                'enabled' : 1,
                //1 - STANDART MAP; 2 = SATELITE PHOTOS, 3 = HIBRYD MAP, 4 (Only In Google) - PHYSICAL MAP
                'mapTypes' : new Array(1,3),
                'positioning' : 1,
                'offsetX' : 5,
                'offsetY' : 5
            }
        },

        setControlParam :  function(controlName,param,value) {
            this.mapControls[controlName][param] = value;
        },
        getControlParam :  function(controlName,param) {
            return this.mapControls[controlName][param];
        },
	hideControl :  function(controlName) {
            this.setControlParam(controlName,'enabled',0);
        },
        hideAllControl :  function() {
            var controlsConfig = this.getMapControlsParams();
            $each(controlsConfig,function(control, controlName) {
                this.setControlParam(controlName,'enabled',0);
            }.bind(this));
        },
	showControl :  function(controlName) {
            this.setControlParam(controlName,'enabled',1);
        },
        setControl :  function(controlName,control) {
            this.mapControls[controlName] = control;
        },
        //-- -- -- -- -- -- -- -- -- -- -- -- -- -- --

	initialize : function(mapContainerId,driverId) {
		eval('this.driver = new Ria_Map_Main_Drivers_' + this.Drivers[driverId].name + '({\'mapContainerId\' : \'' + mapContainerId + '\'})');
		this.driverId = driverId;
	},
	//������������� �������
	setDriver : function(mapContainerId,driverId) {
		if(this.driverId != driverId) {
			eval('this.driver = new Ria_Map_Main_Drivers_' + this.Drivers[driverId].name + '({\'mapContainerId\' : \'' + mapContainerId + '\'})');
			this.driverId = driverId;
		}
	},

	getDriver : function() {
		if($defined(this.driver)) {
			return this.driver;
		} else {
			return null;
		}
	},

	getConfig : function(key,driverId) {
        if(driverId == null) {
            driverId = this.driverId;
        }
		return this.Drivers[driverId][key];
	},
        getMapControlsParams : function(key) {
            if (key) return this.mapControls[key];
            else return this.mapControls;
        }
});

/**
 * 
 * Класс-адаптер для работы с маркерами
 * 
 * @class Ria_Map_Main_Adapters_Marker
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Map_Main_Common_Config
 * @requires   Ria_Map_Main_Common_GeoPoint
 */
 var Ria_Map_Main_Adapters_Marker = new Class({
    //Свойства маркера
    'longitude' : '',
    'latitude' : '',
    'name' : '',
    'icon' : {
            'width' : '',
            'height' : '',
            'src' : ''
    },
    'id' : '',
    'onmap' : false,
    'is_show' : true,
    'infoWindowName' : '',
    'infoWindowHtml' : '',
    'isOpenInfoWindow' : false,
    'isDraggable' : false,
    'type' : 'marker',

    initialize: function(point){
            //console.log('Ria_Map_Main_Adapters_Marker');
    this.longitude = point.getLongitude();
    this.latitude = point.getLatitude();
    RMaps.Config.getDriver().addMarkerToBase(this);
    RMaps.Config.getDriver().addEventListener(this,'enddrag',function() {
        var point = RMaps.Config.getDriver().getPointFromMarker(this.id);
        this.longitude = point.getLongitude();
        this.latitude = point.getLatitude();
    }.bind(this));
    },

    setName : function(name) {
            //console.log('Ria_Map_Main_Adapters_Marker->setName');
            this.name = name;
            RMaps.Config.getDriver().setNameToMarker(this.id,name);
    },

    setIcon : function(width,height,src,offset_x,offset_y) {
            //console.log('Ria_Map_Main_Adapters_Marker->setIcon');
            if(width != '' && height != '' && src != '') {
                    RMaps.Config.getDriver().setIconToMarker(this.id,width,height,src,offset_x,offset_y);
            }
    },

    setOnMap : function(bool) {
            //console.log('Ria_Map_Main_Adapters_Marker->setOnMap');
            this.onmap = bool;
    },

    show : function() {
            //console.log('Ria_Map_Main_Adapters_Marker->show');
            if(!this.is_show) {
                    this.is_show = true;
                    RMaps.Config.getDriver().showMarker(this.id);
            }
    },

    hide : function() {
            //console.log('Ria_Map_Main_Adapters_Marker->hide');
            if(this.is_show) {
                    this.is_show = false;
                    RMaps.Config.getDriver().hideMarker(this.id);
            }
    },

    getGeoPoint : function() {
            //console.log('Ria_Map_Main_Adapters_Marker->getGeoPoint');
            return new Ria_Map_Main_Common_GeoPoint(this.longitude,this.latitude);
    },

    setGeoPoint : function(point) {
            //console.log('Ria_Map_Main_Adapters_Marker->setGeoPoint');
            this.longitude = point.getLongitude();
        this.latitude = point.getLatitude();
        RMaps.Config.getDriver().setPointToMarker(this.id,point);
    },

    setId : function(id) {
            //console.log('Ria_Map_Main_Adapters_Marker->setId');
            this.id = id;
    },

    getId : function() {
            //console.log('Ria_Map_Main_Adapters_Marker->getId');
            return this.id;
    },

    destruct : function() {
            //console.log('Ria_Map_Main_Adapters_Marker->destruct');
            RMaps.Config.getDriver().removeMarkerFromMap(this);
            delete this;
    },

    addInfoWindow : function(name, htmlText) {
            //console.log('Ria_Map_Main_Adapters_Marker->addInfoWindow');
            this.infoWindowName = name;
            this.infoWindowHtml = htmlText;
            RMaps.Config.getDriver().addInfoWindowToMarker(this);
    },

    removeInfoWindow : function() {
            //console.log('Ria_Map_Main_Adapters_Marker->removeInfoWindow');
            this.infoWindowName = '';
            this.infoWindowHtml = '';
            RMaps.Config.getDriver().removeInfoWindowFromMarker(this.id);
    },

    openInfoWindow : function() {
            //console.log('Ria_Map_Main_Adapters_Marker->openInfoWindow');
            this.isOpenInfoWindow = true;
            RMaps.Config.getDriver().openInfoWindowInMarker(this.id);
    },

    closeInfoWindow : function() {
            //console.log('Ria_Map_Main_Adapters_Marker->closeInfoWindow');
            this.isOpenInfoWindow = false;
            RMaps.Config.getDriver().closeInfoWindowInMarker(this.id);
    },

    setDraggable : function(bool) {
            //console.log('Ria_Map_Main_Adapters_Marker->setDraggable');
            this.isDraggable = bool;
            RMaps.Config.getDriver().setDraggableMarker(this.id,bool);
    }
	
});
/**
 * 
 * Класс-адаптер для работы с слоями
 * 
 * @class Ria_Map_Main_Adapters_Layer
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Map_Main_Common_Config
 */
 var Ria_Map_Main_Adapters_Layer = new Class({
	//свойства класса
	'is_show' : true,
	'onmap' : false,
	innerMarkers : new Hash(),
	'id' : '',
	'type' : 'layer',
	
	initialize: function(){
		//console.log('Ria_Map_Main_Adapters_Layer');
		RMaps.Config.getDriver().addLayerToBase(this);
	},
	
	setId : function(id) {
		//console.log('Ria_Map_Main_Adapters_Layer->setId');
		this.id = id;
	},
	
	getId : function() {
		//console.log('Ria_Map_Main_Adapters_Layer->getId');
		//console.log(this.id);
		return this.id;
	},
	
	setOnMap : function(bool) {
		//console.log('Ria_Map_Main_Adapters_Layer->setOnMap');
		this.onmap = bool;
	},
	
	addMarker : function(marker) {
		//console.log('Ria_Map_Main_Adapters_Layer->addMarker');
		this.innerMarkers.set(marker.getId(),marker);
		RMaps.Config.getDriver().addMarkerToLayer(this.id,marker);
	},
	
	removeMarker : function(marker) {
		//console.log('Ria_Map_Main_Adapters_Layer->removeMarker');
		this.innerMarkers.erase(marker.getId());
		RMaps.Config.getDriver().removeMarkerFromLayer(this.id,marker);
	},
	
	getMarkers : function() {
		//console.log('Ria_Map_Main_Adapters_Layer->getMarkers');
		return this.innerMarkers;
	},
	
	show : function() {
		//console.log('Ria_Map_Main_Adapters_Layer->show');
		if(!this.is_show) {
			this.is_show = true;
			RMaps.Config.getDriver().showLayer(this.id);
		}
	},
	
	hide : function() {
		//console.log('Ria_Map_Main_Adapters_Layer->hide');
		if(this.is_show) {
			this.is_show = false;
			RMaps.Config.getDriver().hideLayer(this.id);
		}
	}
	
});
/**
 * 
 * Класс-адаптер для работы с событиями
 * 
 * @class Ria_Map_Main_Adapters_Events
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Map_Main_Common_Config
 */
 var Ria_Map_Main_Adapters_Events = new Class({
	
	addEventListener : function(object,event,callback_func) {
		//console.log('Ria_Map_Main_Adapters_Events->addEventListener');
		RMaps.Config.getDriver().addEventListener(object,event,callback_func);
	},
	
	fireEvent : function(object,event,args) {
		//console.log('Ria_Map_Main_Adapters_Events->fireEvent');
		RMaps.Config.getDriver().fireMapEvent(object,event,args);
	}
	
});
/**
 * Класс добавляющий 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: {
        '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({ 'rubricId':0, 'hotelId':this.hotelId});
		}.bind(this));		
	},
	
	createHint:function(){
		var hintDiv = new Element('div');
		
		var noRubricLink  = new Element('a', {'html': Lang.no_razdel,'href': 'javascript:void(0);', 'onclick':"new Ria_Hotel_Notepad_AddUserNoteRequest({'realtyId':"+this.realtyId+", 'rubricId':0})"});
		noRubricLink.inject(hintDiv);
		
		var brElement = new Element('br');
		brElement.inject(hintDiv);
		
		this.rubricArr.each(function(rubricName, rubricId){
			var rubricLink  = new Element('a', {'html': rubricName,'href': 'javascript:void(0);', 'onclick':"new Ria_Hotel_Notepad_AddUserNoteRequest({'realtyId':"+this.realtyId+", 'rubricId':"+rubricId+"})"});
			rubricLink.inject(hintDiv);
			
			var brElement = new Element('br');
			brElement.inject(hintDiv);
		}, this);
		
		Tip(hintDiv.get('html'), TITLE, Lang.add_to, STICKY, true, CLOSEBTN, true, CLICKCLOSE, true, PADDING, 5, CLOSEBTNCOLORS, ['#797979', '#ffffff', '#e30000', '#ffffff'], TITLEBGCOLOR, '#cacaca', BGCOLOR, '#ffffff', BORDERCOLOR, '#cacaca', TITLEFONTCOLOR, '#131313');
	}
	
	
});
/**
 * 
 * Класс-адаптер для работы с картой
 * 
 * @class Ria_Map_Main_Adapters_Map
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Map_Main_Common_Config
 * @requires   Ria_Map_Main_Common_GeoPoint
 */
 var Ria_Map_Main_Adapters_Map = new Class({
    //свойства карты
    markers : new Hash(),
    layers : new Hash(),
    centerPoint : new Ria_Map_Main_Common_GeoPoint(0,0),
    'zoom' : 0,
    'type' : 'map',
    //инициализация адаптера
    initialize: function(driverId, mapContainerId){
		//console.log('Ria_Map_Main_Adapters_Map');
        this.mapContainerId = mapContainerId;
        window.RMaps = {};
        window.RMaps.Config = new Ria_Map_Main_Common_Config(mapContainerId,driverId);
        this.driver = RMaps.Config.getDriver();
    },

    //изменения размеров контейнера карты
    resizeMap : function(width,height) {
		//console.log('Ria_Map_Main_Adapters_Map->resizeMap');
        if($defined(this.driver)) {
            this.driver.resizeMap(width,height);
        }
    },


    //метод отображения карты в контейнере
    paintMap : function() {
		//console.log('Ria_Map_Main_Adapters_Map->paintMap');
        if($defined(this.driver)) {
            this.setupControls();
            this.driver.initMap();
        }
    },

    setControlParam :  function(controlName,param,value) {
		//console.log('Ria_Map_Main_Adapters_Map->setControlParam');
        window.RMaps.Config.setControlParam(controlName,param,value);
    },
    getControlParam :  function(controlName,param) {
		//console.log('Ria_Map_Main_Adapters_Map->getControlParam');
        window.RMaps.Config.getControlParam(controlName,param);
    },
    setControl :  function(controlName,control) {
		//console.log('Ria_Map_Main_Adapters_Map->setControl');
        window.RMaps.Config.setControl(controlName,control);
    },

    hideAllControl :  function() {
		//console.log('Ria_Map_Main_Adapters_Map->hideAllControl');
        window.RMaps.Config.hideAllControl();
    },
    hideControl :  function(controlName) {
		//console.log('Ria_Map_Main_Adapters_Map->hideControl');
        window.RMaps.Config.hideControl(controlName);
    },
    showControl :  function(controlName) {
		//console.log('Ria_Map_Main_Adapters_Map->showControl');
        window.RMaps.Config.showControl(controlName);
    },
    setupControls : function() {
		//console.log('Ria_Map_Main_Adapters_Map->setupControls');
        var controlsConfig = window.RMaps.Config.getMapControlsParams();
        $each(controlsConfig,function(control, controlName) {
            if (control['enabled']==1) this.driver.setMapControl(controlName,control);
        }.bind(this));
    },


    repaintMap : function() {
		//console.log('Ria_Map_Main_Adapters_Map->repaintMap');
            this.driver.repaintMap();
    },
    //метод для добавления маркера на карту
    addMarker : function(marker) {
		//console.log('Ria_Map_Main_Adapters_Map->addMarker');
        if($defined(this.driver)) {
            this.markers.set(marker.getId(),marker);
            marker.setOnMap(true);
            this.driver.addMarkerToMap(marker);
        }
    },

    removeMarker : function(marker) {
		//console.log('Ria_Map_Main_Adapters_Map->removeMarker');
        if($defined(this.driver)) {
            this.markers.erase(marker.getId());
            marker.setOnMap(false);
            this.driver.removeMarkerFromMap(marker);
        }
    },

    addLayer : function(layer) {
		//console.log('Ria_Map_Main_Adapters_Map->addLayer');
        if($defined(this.driver)) {
            this.layers.set(layer.getId(),layer);
            layer.setOnMap(true);
            this.driver.addLayerToMap(layer);
        }
    },

    removeLayer : function(layer) {
		//console.log('Ria_Map_Main_Adapters_Map->removeLayer');
        if($defined(this.driver)) {
            this.layers.erase(layer.getId());
            layer.setOnMap(false);
            layer.getMarkers().each(function(marker){
                marker.setOnMap(false);
            });
            this.driver.removeLayerFromMap(layer);
        }
    },

    getCenter : function() {
		//console.log('Ria_Map_Main_Adapters_Map->getCenter');
        this.centerPoint = this.driver.getMapCenter();
        return this.centerPoint;
    },

    setCenter : function(geoPoint) {
		//console.log('Ria_Map_Main_Adapters_Map->setCenter');
        this.centerPoint = geoPoint;
        this.driver.setMapCenter(geoPoint);
    },

    getZoom : function() {
		//console.log('Ria_Map_Main_Adapters_Map->getZoom');
        this.zoom = this.driver.getMapZoom();
        return this.zoom;
    },

    setZoom : function(index) {
		//console.log('Ria_Map_Main_Adapters_Map->setZoom');
        if(index < 0) {index = 0;}
        if(index > 100) {index = 100;}
        this.driver.setMapZoom(index);
    },

    getClientRectangle : function() {
		//console.log('Ria_Map_Main_Adapters_Map->getClientRectangle');
        return this.driver.getClientRectangle();
    },

    convertToEngineZoom : function(old_zoom) {
		//console.log('Ria_Map_Main_Adapters_Map->convertToEngineZoom');
        var maxZoom = RMaps.Config.getConfig('maxZoom') - RMaps.Config.getConfig('minZoom');
		var zoom = (Math.round((old_zoom*maxZoom)/100))+RMaps.Config.getConfig('minZoom');
		return zoom;
    },

    convertFromEngineZoom : function(old_zoom) {
		//console.log('Ria_Map_Main_Adapters_Map->convertFromEngineZoom');
        var maxZoom = RMaps.Config.getConfig('maxZoom');
        var zoom = old_zoom - RMaps.Config.getConfig('minZoom');
        return (Math.round((zoom*100)/maxZoom));
    },
	
	getMarkers : function() {
		//console.log('Ria_Map_Main_Adapters_Map->getMarkers');
		return this.markers;
	},
	
	getLayers : function() {
		//console.log('Ria_Map_Main_Adapters_Map->getLayers');
		return this.layers;
	},
	
	destructMap : function() {
		//console.log('Ria_Map_Main_Adapters_Map->destructMap');
		this.driver.destructMap();
	}
	
});
/**
 * RIA Framework Map Mamager
 * Универсальный класс для управления картами
 * 
 * @class      Ria_Hotel_Map_Manager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Revision: 1.6 $
 * @author     <a href="mailto:Oleg.Cherniy@gmail.com">Oleg Cherniy</a>
 * @requires   Ria_Map_GeoPoint
 * @requires   Ria_Map_Main_Adapters_Map
 * @requires   Ria_Map_Main_Adapters_Events
 * @requires   Ria_Map_Main_Adapters_Marker
 * @requires   Ria_Map_Main_Common_GeoPoint
 */
var Ria_Hotel_Map_Manager = new Class({
    
	currentPoint: new Ria_Map_GeoPoint({
		'geo_X' 	: 30.516503952143655,
		'geo_Y' 	: 50.440802465948295,
		'zoom'  	: 70,
		'engineId'  : 1
	}),
	/**
	 * @param {Integer} engineId ID движка карт  
	 */
	initialize: function(engineId, mapContainerId, isInteractive){
		//console.log('Ria_Map_Manager');
		this.engineId = engineId;
		this.mapContainerId = mapContainerId;
		this.isInteractive = isInteractive;
		if(engineId>0) {
			//            var display = $(this.mapContainerId).getStyle('display');
			$(this.mapContainerId).setStyle('display','block');
			this.needQuestion = false;
			this.events = new Ria_Map_Main_Adapters_Events();

			this.map = new Ria_Map_Main_Adapters_Map(this.engineId,this.mapContainerId);
			this.map.setCenter(new Ria_Map_Main_Common_GeoPoint(this.currentPoint.geo_X,this.currentPoint.geo_Y));
			this.map.setZoom(this.currentPoint.zoom);
			this.map.paintMap();
			//            if(display == 'none') $(this.mapContainerId).setStyle('display','none');

//			this.point = new Ria_Map_Main_Adapters_Marker(
//				new Ria_Map_Main_Common_GeoPoint(this.currentPoint.geo_X,this.currentPoint.geo_Y)
//				);
			//this.point.setIcon(27,35,'http://maps.visicom.ua/images/markers/pointer-green.png',13,35);
//			this.point.setDraggable(true);
//			if($defined($('save_location'))) $('save_location').value = Lang.save_location;

			//this.map.addMarker(this.point);

			if (this.isInteractive){
				if ($defined($('mapControls'))) $('mapControls').setStyle('display', 'block');
				this.setDraggablePoint();

				this.events.addEventListener(this.map,'zoomchange', function(point) {
					if (!this.getSaveLocationStatus()) this.setNeedQuestionStatus(true);
				}.bind(this));

				this.events.addEventListener(this.map,'enddrag', function(point) {
					if (!this.getSaveLocationStatus()) this.setNeedQuestionStatus(true);
				}.bind(this));

				this.events.addEventListener(this.point, "enddrag", function(point) {
					this.setNeedQuestionStatus(true);
				}.bind(this));

				this.setNeedQuestionStatus(true);
			} else {
				this.setStaticPoint();
			}
		} else {
			this.map = new Ria_Map_Main_Adapters_Map(1,this.mapContainerId);
			this.map.setCenter(new Ria_Map_Main_Common_GeoPoint(this.currentPoint.geo_X,this.currentPoint.geo_Y));
			this.map.setZoom(this.currentPoint.zoom);
			this.map.paintMap();
			this.point = new Ria_Map_Main_Adapters_Marker(
				new Ria_Map_Main_Common_GeoPoint(this.currentPoint.geo_X,this.currentPoint.geo_Y)
				);
			this.point.setIcon(27,35,'http://maps.visicom.ua/images/markers/pointer-green.png',13,35);
			this.point.setDraggable(true);
		}
	},

	setMapEngine:function(engineId){
		//console.log('Ria_Map_Manager->setMapEngine');
		if(this.engineId != engineId) {
			//alert(JSON.encode(options));
			if(this.engineId !== 0) {
				this.currentPoint.geo_X = this.point.getGeoPoint().getLongitude();
				this.currentPoint.geo_Y = this.point.getGeoPoint().getLatitude();
				this.currentPoint.zoom = this.map.getZoom();
				this.map.destructMap();
				//			delete riaMap.storage;
				delete this['map'];
				delete this['point'];
			}
			this.initialize(engineId,this.mapContainerId,this.isInteractive);
		}
	},

	setDraggablePoint : function() {
		//console.log('Ria_Map_Manager->setDraggablePoint');
		//        this.point.setIcon(27,35,'http://maps.visicom.ua/images/markers/pointer-green.png',13,35);
		this.point.setIcon(27,35,'http://css.ria.ua/img/maps/down_green_arrow_pointer.png',13,35);
		this.point.setDraggable(true);
	},

	setStaticPoint : function() {
		//console.log('Ria_Map_Manager->setStaticPoint');
		//        this.point.setIcon(27,35,'http://maps.visicom.ua/api/images/markers/pointer-trans.png',13,35);
		//this.point.setIcon(27,35,'http://css.ria.ua/img/maps/down_red_arrow_pointer.png',13,35);
		//this.point.setDraggable(false);
	},
    
	showMap:function(){
		//console.log('Ria_Map_Manager->showMap');
		$(this.mapContainerId).setStyle('display','block');
		if (this.isInteractive){
			if ($defined($('mapControls'))) $('mapControls').setStyle('display', 'block');
		}
	},
	
	hideMap:function(){
		//console.log('Ria_Map_Manager->hideMap');
		this.changeSaveLocationStatus(false);
		this.setNeedQuestionStatus(false);
		$(this.mapContainerId).setStyle('display','none');
		if (this.isInteractive){
			if ($defined($('mapControls'))) $('mapControls').setStyle('display', 'none');
		}
	},
	
	changeSaveLocationStatus:function(status){
		//console.log('Ria_Map_Manager->changeSaveLocationStatus');
		if (status){
			var currentPoint = this.point.getGeoPoint();
			$('save_location').value = Lang.change_location;
			this.setStaticPoint();
			if($defined($('map_geo_x'))) $('map_geo_x').value = currentPoint.getLongitude();
			if($defined($('map_geo_y')))$('map_geo_y').value = currentPoint.getLatitude();
			//AGvin
			//			if($defined($('map_geo_zoom')))$('map_geo_zoom').value = this.map.convertToEngineZoom(this.map.getZoom());
			if($defined($('map_geo_zoom')))$('map_geo_zoom').value =  parseInt(this.map.getZoom());

			this.setNeedQuestionStatus(false);
		} else {
			$('save_location').value = Lang.save_location;
			this.setDraggablePoint();

			if($defined($('map_geo_x'))) $('map_geo_x').value = '';
			if($defined($('map_geo_y'))) $('map_geo_y').value = '';
			if($defined($('map_geo_zoom'))) $('map_geo_zoom').value = '';
			this.setNeedQuestionStatus(true);
		}
	},
	getZoom:function() {
		//console.log('Ria_Map_Manager->getZoom');
		return this.map.getZoom();
	},
	getCenter:function() {
		//console.log('Ria_Map_Manager->getCenter');
		return this.point.getGeoPoint();
	},
	getMapCenter:function() {
		//console.log('Ria_Map_Manager->getMapCenter');
		return this.map.getCenter();
	},
	setCenter:function(riaPoint) {
		//console.log('Ria_Map_Manager->setCenter');
		if(riaPoint.zoom) {
			//AGvin
			//            riaPoint.zoom = this.map.convertFromEngineZoom(riaPoint.zoom);
			//-- -- -- --

			this.map.setZoom(riaPoint.zoom);
		}
		this.currentPoint = riaPoint;
		this.map.setCenter(new Ria_Map_Main_Common_GeoPoint(this.currentPoint.geo_X,this.currentPoint.geo_Y));
		//this.point.setGeoPoint(new Ria_Map_Main_Common_GeoPoint(this.currentPoint.geo_X,this.currentPoint.geo_Y));
	},
	
	addListener:function(event, actionObject){
		//console.log('Ria_Map_Manager->addListener');
		this.events.addEventListener(this.map,event,actionObject);
	},

	setNeedQuestionStatus:function(status){
		//console.log('Ria_Map_Manager->setNeedQuestionStatus');
		this.needQuestion = status;
	},

	getNeedQuestionStatus:function(){
		//console.log('Ria_Map_Manager->getNeedQuestionStatus');
		return this.needQuestion;
	},

	getSaveLocationStatus:function(){
		//console.log('Ria_Map_Manager->getSaveLocationStatus');
		return ($('save_location').value == Lang.change_location);
	},

        addMarker:function(point)
        {
            this.map.addMarker(point);
        }
	
});
/**
 * RIA Framework Map Mamager
 * Универсальный класс для управления картами
 * 
 * @class      Ria_Map_Manager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Revision: 1.6 $
 * @author     <a href="mailto:Oleg.Cherniy@gmail.com">Oleg Cherniy</a>
 * @requires   Ria_Map_GeoPoint
 * @requires   Ria_Map_Main_Adapters_Map
 * @requires   Ria_Map_Main_Adapters_Events
 * @requires   Ria_Map_Main_Adapters_Marker
 * @requires   Ria_Map_Main_Common_GeoPoint
 */
var Ria_Map_Manager = new Class({
    
	currentPoint: new Ria_Map_GeoPoint({
		'geo_X' 	: 30.516503952143655,
		'geo_Y' 	: 50.440802465948295,
		'zoom'  	: 70,
		'engineId'  : 1
	}),
	/**
	 * @param {Integer} engineId ID движка карт  
	 */
	initialize: function(engineId, mapContainerId, isInteractive){
		//console.log('Ria_Map_Manager');
		this.engineId = engineId;
		this.mapContainerId = mapContainerId;
		this.isInteractive = isInteractive;
		if(engineId>0) {
			//            var display = $(this.mapContainerId).getStyle('display');
			$(this.mapContainerId).setStyle('display','block');
			this.needQuestion = false;
			this.events = new Ria_Map_Main_Adapters_Events();

			this.map = new Ria_Map_Main_Adapters_Map(this.engineId,this.mapContainerId);
			this.map.setCenter(new Ria_Map_Main_Common_GeoPoint(this.currentPoint.geo_X,this.currentPoint.geo_Y));
			this.map.setZoom(this.currentPoint.zoom);
			this.map.paintMap();
			//            if(display == 'none') $(this.mapContainerId).setStyle('display','none');

			this.point = new Ria_Map_Main_Adapters_Marker(
				new Ria_Map_Main_Common_GeoPoint(this.currentPoint.geo_X,this.currentPoint.geo_Y)
				);
			this.point.setIcon(27,35,'http://maps.visicom.ua/images/markers/pointer-green.png',13,35);
			this.point.setDraggable(true);
			if($defined($('save_location'))) $('save_location').value = Lang.save_location;

			this.map.addMarker(this.point);

			if (this.isInteractive){
				if ($defined($('mapControls'))) $('mapControls').setStyle('display', 'block');
				this.setDraggablePoint();

				this.events.addEventListener(this.map,'zoomchange', function(point) {
					if (!this.getSaveLocationStatus()) this.setNeedQuestionStatus(true);
				}.bind(this));

				this.events.addEventListener(this.map,'enddrag', function(point) {
					if (!this.getSaveLocationStatus()) this.setNeedQuestionStatus(true);
				}.bind(this));

				this.events.addEventListener(this.point, "enddrag", function(point) {
					this.setNeedQuestionStatus(true);
				}.bind(this));

				this.setNeedQuestionStatus(true);
			} else {
				this.setStaticPoint();
			}
		} else {
			this.map = new Ria_Map_Main_Adapters_Map(1,this.mapContainerId);
			this.map.setCenter(new Ria_Map_Main_Common_GeoPoint(this.currentPoint.geo_X,this.currentPoint.geo_Y));
			this.map.setZoom(this.currentPoint.zoom);
			this.map.paintMap();
			this.point = new Ria_Map_Main_Adapters_Marker(
				new Ria_Map_Main_Common_GeoPoint(this.currentPoint.geo_X,this.currentPoint.geo_Y)
				);
			this.point.setIcon(27,35,'http://maps.visicom.ua/images/markers/pointer-green.png',13,35);
			this.point.setDraggable(true);
		}
	},

	setMapEngine:function(engineId){
		//console.log('Ria_Map_Manager->setMapEngine');
		if(this.engineId != engineId) {
			//alert(JSON.encode(options));
			if(this.engineId !== 0) {
				this.currentPoint.geo_X = this.point.getGeoPoint().getLongitude();
				this.currentPoint.geo_Y = this.point.getGeoPoint().getLatitude();
				this.currentPoint.zoom = this.map.getZoom();
				this.map.destructMap();
				//			delete riaMap.storage;
				delete this['map'];
				delete this['point'];
			}
			this.initialize(engineId,this.mapContainerId,this.isInteractive);
		}
	},

	setDraggablePoint : function() {
		//console.log('Ria_Map_Manager->setDraggablePoint');
		//        this.point.setIcon(27,35,'http://maps.visicom.ua/images/markers/pointer-green.png',13,35);
		this.point.setIcon(27,35,'http://css.ria.ua/img/maps/down_green_arrow_pointer.png',13,35);
		this.point.setDraggable(true);
	},

	setStaticPoint : function() {
		//console.log('Ria_Map_Manager->setStaticPoint');
		//        this.point.setIcon(27,35,'http://maps.visicom.ua/api/images/markers/pointer-trans.png',13,35);
		this.point.setIcon(27,35,'http://css.ria.ua/img/maps/down_red_arrow_pointer.png',13,35);
		this.point.setDraggable(false);
	},
    
	showMap:function(){
		//console.log('Ria_Map_Manager->showMap');
		$(this.mapContainerId).setStyle('display','block');
		if (this.isInteractive){
			if ($defined($('mapControls'))) $('mapControls').setStyle('display', 'block');
		}
	},
	
	hideMap:function(){
		//console.log('Ria_Map_Manager->hideMap');
		this.changeSaveLocationStatus(false);
		this.setNeedQuestionStatus(false);
		$(this.mapContainerId).setStyle('display','none');
		if (this.isInteractive){
			if ($defined($('mapControls'))) $('mapControls').setStyle('display', 'none');
		}
	},
	
	changeSaveLocationStatus:function(status){
		//console.log('Ria_Map_Manager->changeSaveLocationStatus');
		if (status){
			var currentPoint = this.point.getGeoPoint();
			$('save_location').value = Lang.change_location;
			this.setStaticPoint();
			if($defined($('map_geo_x'))) $('map_geo_x').value = currentPoint.getLongitude();
			if($defined($('map_geo_y')))$('map_geo_y').value = currentPoint.getLatitude();
			//AGvin
			//			if($defined($('map_geo_zoom')))$('map_geo_zoom').value = this.map.convertToEngineZoom(this.map.getZoom());
			if($defined($('map_geo_zoom')))$('map_geo_zoom').value =  parseInt(this.map.getZoom());

			this.setNeedQuestionStatus(false);
		} else {
			$('save_location').value = Lang.save_location;
			this.setDraggablePoint();

			if($defined($('map_geo_x'))) $('map_geo_x').value = '';
			if($defined($('map_geo_y'))) $('map_geo_y').value = '';
			if($defined($('map_geo_zoom'))) $('map_geo_zoom').value = '';
			this.setNeedQuestionStatus(true);
		}
	},
	getZoom:function() {
		//console.log('Ria_Map_Manager->getZoom');
		return this.map.getZoom();
	},
	getCenter:function() {
		//console.log('Ria_Map_Manager->getCenter');
		return this.point.getGeoPoint();
	},
	getMapCenter:function() {
		//console.log('Ria_Map_Manager->getMapCenter');
		return this.map.getCenter();
	},
	setCenter:function(riaPoint) {
		//console.log('Ria_Map_Manager->setCenter');
		if(riaPoint.zoom) {
			//AGvin
			//            riaPoint.zoom = this.map.convertFromEngineZoom(riaPoint.zoom);
			//-- -- -- --

			this.map.setZoom(riaPoint.zoom);
		}
		this.currentPoint = riaPoint;
		this.map.setCenter(new Ria_Map_Main_Common_GeoPoint(this.currentPoint.geo_X,this.currentPoint.geo_Y));
		this.point.setGeoPoint(new Ria_Map_Main_Common_GeoPoint(this.currentPoint.geo_X,this.currentPoint.geo_Y));
	},
	
	addListener:function(event, actionObject){
		//console.log('Ria_Map_Manager->addListener');
		this.events.addEventListener(this.map,event,actionObject);
	},

	setNeedQuestionStatus:function(status){
		//console.log('Ria_Map_Manager->setNeedQuestionStatus');
		this.needQuestion = status;
	},

	getNeedQuestionStatus:function(){
		//console.log('Ria_Map_Manager->getNeedQuestionStatus');
		return this.needQuestion;
	},

	getSaveLocationStatus:function(){
		//console.log('Ria_Map_Manager->getSaveLocationStatus');
		return ($('save_location').value == Lang.change_location);
	}
	
});
/**
 * @class Ria_Hotel_Location
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Hotel_Location_CitiesRequest
 * @requires   Ria_Hotel_Location_AreasRequest
 * @requires   Ria_Hotel_Location_AddressRequest
 * @requires   Ria_Map_Manager
 */
var Ria_Hotel_Location = new Class({
	
	Implements: Options,
	
    options: {
		'city_id': 					0,
		'area_id': 					0,
		'states_element_id': 		null,
		'cities_element_id': 		null,
		'areas_element_id': 		null,
		'address_element_id': 		null,
		'with_map': 				0,
		'map_type': 				0,
		'mapContainerId': 			'',
		'current_zoom':				0,
		'mapsCities': 				null,
		'mapsAreas': 				null
	},
	
	initialize: function(options){
    	this.setOptions(options);
    	
    	if (this.options.with_map){
    		
    		riaMapManagerObj = new Ria_Map_Manager(this.options.map_type, this.options.mapContainerId, true);
    		
    		if ($defined(this.options.mapsCities) && $defined(this.options.cities_element_id)){
    			this.addMapsData(this.options.cities_element_id, this.options.mapsCities, 6);
    		}
    		
    		if ($defined(this.options.mapsAreas) && $defined(this.options.areas_element_id)){
    			this.addMapsData(this.options.areas_element_id, this.options.mapsAreas, 8);
    		}
    		
    		this.setupMapControlEvents();
    		
    	}
    	
    	this.setupLocationsEvents();
	},
	
	setupMapControlEvents:function(){
		if ($defined($('map_selector'))){
			$('map_selector').addEvent('change', function(){
				if($('map_selector').value==0) {
					riaMapManagerObj.hideMap(false);
				} else {
					
					riaMapManagerObj.setMapEngine($('map_selector').value);
					
					if ($('map_geo_x').value > 0 && $('map_geo_y').value > 0){
						geoPoint = new Ria_Map_GeoPoint({
							'geo_X':$('map_geo_x').value,
							'geo_Y':$('map_geo_y').value,
							'zoom': $('map_geo_zoom').value,
							'engineId':riaMapManagerObj.engineId
						});
						riaMapManagerObj.setCenter(geoPoint);
					}
					
					riaMapManagerObj.showMap();
				}
				
			}.bind(this));
		}
		
		if ($defined($('save_location'))){
			$('save_location').addEvent('click', function(){
				riaMapManagerObj.changeSaveLocationStatus($('save_location').value==Lang.save_location);
			}.bind(this));
		}
		
		if ($defined($('delete_location'))){
			$('delete_location').addEvent('click', function(){
			    $('map_selector').value = 0;
			    $('map_selector').fireEvent('change');
			}.bind(this));
		}
		
		if ($defined($('add_realty_form'))){
			$('add_realty_form').addEvent('submit', function(){
				if (riaMapManagerObj.getNeedQuestionStatus()){
					if (confirm (Lang.save_location_question)){
						riaMapManagerObj.changeSaveLocationStatus(true);
					} else {
						riaMapManagerObj.changeSaveLocationStatus(false);
					}
				}
			}.bind(this));
		}
		
	},
	
	addMapsData:function(selectId, mapData, zoom){
		$each(mapData, function(item, index){
			var element = $(selectId+'_'+index);
			
			element.riaMapZoom = zoom;
			element.riaMapData = item;
			
			if (index == this.options.city_id) {
				if (this.options.current_zoom > 0) {
					useZoom = this.options.current_zoom;
					this.options.current_zoom = 0;
				} else {
					useZoom = zoom;
				}
				riaMapManagerObj.currentPoint.initialize({
					'geo_X':item['geo_X'],
					'geo_Y':item['geo_Y'],
					'zoom': useZoom,
					'engineId':1
				});
				
			} else if (index == this.options.area_id) {
				if (this.options.current_zoom>0) {
					useZoom = this.options.current_zoom;
					this.options.current_zoom = 0;
				} else {
					useZoom = zoom;
				}
				riaMapManagerObj.currentPoint.initialize({
					'geo_X':item['geo_X'],
					'geo_Y':item['geo_Y'],
					'zoom': useZoom,
					'engineId':1
				});
				
			}
			
			
		}, this );
	},
	
	setupLocationsEvents:function(){
		//change State
    	if ($defined(this.options.states_element_id)){
            $(this.options.states_element_id).addEvent('change', function(){
            	
            	if ($defined(this.options.cities_element_id)){
            		this.loadCities();
            	}
            	
            }.bind(this));
    	}
    	
    	//change City
    	if ($defined(this.options.cities_element_id)){
    		
    		var citiesElement = $(this.options.cities_element_id);
    		
    		citiesElement.addEvent('change', function(){
    			var optionElement = $(this.options.cities_element_id+'_'+citiesElement.value);
    			
    			if (this.options.with_map && $defined(optionElement.riaMapData)){
    				if (optionElement.riaMapData['geo_X']!=0){
    					
    					riaMapManagerObj.setCenter(new Ria_Map_GeoPoint({
    						'geo_X':optionElement.riaMapData['geo_X'],
    						'geo_Y':optionElement.riaMapData['geo_Y'],
    						'zoom': optionElement.riaMapZoom,
    						'engineId':1}
    					));
    				}
    			}
    			
    			if ($defined(this.options.areas_element_id)){
    				this.loadAreas();
    			}
    		}.bind(this));
    	}
    	
    	//change Area
    	if ($defined(this.options.areas_element_id) && this.options.with_map){
    		var areasElement = $(this.options.areas_element_id); 
    		areasElement.addEvent('change', function(){
    			var optionElement = $(this.options.areas_element_id+'_'+areasElement.value);
    			
    			if ($defined(optionElement.riaMapData)){
    				if (optionElement.riaMapData['geo_X']!=0){
    					
    					riaMapManagerObj.setCenter(new Ria_Map_GeoPoint({
    						'geo_X':optionElement.riaMapData['geo_X'],
    						'geo_Y':optionElement.riaMapData['geo_Y'],
    						'zoom': optionElement.riaMapZoom,
    						'engineId':1}
    					));
    					
    				}
    			}
    			
    		}.bind(this));
    	}
    	
    	//change Address
    	if ($defined(this.options.address_element_id && this.options.with_map)){
    		$(this.options.address_element_id).addEvent('change', function(){
    			
    			if ($defined(this.options.cities_element_id) && $(this.options.cities_element_id).value>0)
    			
    			new Ria_Hotel_Location_AddressRequest({
    				'city_id':$(this.options.cities_element_id).value,
    				'address_str':$(this.options.address_element_id).value
    			});
    			
    		}.bind(this));
    	}
    	
	},
	
	loadCities:function(){
		var select = $(this.options.cities_element_id);
		select.empty();
		new Element('option',{value: 0}).inject(select).set('text',Lang.load);
		select.set('disabled', true);

    	if ($defined(this.options.areas_element_id)){
    		var select = $(this.options.areas_element_id);
    		select.empty();
    		new Element('option',{value: 0}).inject(select).set('text', Lang.load);
    		select.set('disabled', true);
    	}
    	
		new Ria_Hotel_Location_CitiesRequest({
			'state_id':$(this.options.states_element_id).value,
			'cities_element_id':this.options.cities_element_id,
			'areas_element_id':this.options.areas_element_id,
			'city_id':0,
			'area_id':0,
			'with_map':this.options.with_map
		});
	},
	
	loadAreas:function(){
		var select = $(this.options.areas_element_id);
		select.empty();
		new Element('option',{value: 0}).inject(select).set('text', Lang.load);
		select.set('disabled', true);
		
		new Ria_Hotel_Location_AreasRequest({
			'areas_element_id':this.options.areas_element_id,
			'city_id':$(this.options.cities_element_id).value,
			'area_id':this.options.area_id,
			'with_map':this.options.with_map
		});
	}
	
	
});
