/**
 * Window opener Class
 *
 * @class      Ria_Core_Common_Window
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Revision: 1.13 $
 * @author     <a href="mailto:sdobrovol@gmail.com">Sergey Dobrovolsky</a>
 */
var Ria_Core_Common_Window = new Class({

	Implements: Options,

	options: {
		'url':				'',
		'params':			{},
		'windowName': 		'',
		'width': 			screen.width,
		'height':  			screen.height,
		'offsetX': 			0,
		'offsetY': 			0,
		'paddingTop': 		-30,
		'paddingLeft':		0,

		'alwaysRaised': 	'yes',
		'toolbar':			'0',
		'directories':		'0',
		'menubar':			'0',
		'status':			'1',
		'location':			'0',
		'scrollbars':		'1',
		'copyhistory':		'0'
	},

	/**
	 * @raram {Array} options   
	 */
	initialize: function(options){
		this.setOptions(options);
		this.initParams();
		this.openWindow();
	},

	initParams: function(){
		this.str = '';

		var w = this.options['width'] - this.options['offsetX']*2;
		var h = this.options['height'] - this.options['offsetY']*2;
		this.str += "width="+w+",height="+h+",left=" + (this.options['offsetX'] + this.options['paddingLeft']);
		this.str += ",top=" + (this.options['offsetY']+this.options['paddingTop']);


		this.str += ",alwaysRaised=" + this.options['alwaysRaised'];
		this.str += ",toolbar=" + this.options['toolbar'];
		this.str += ",directories=" + this.options['directories'];
		this.str += ",menubar=" + this.options['menubar'];
		this.str += ",status=" + this.options['status'];
		this.str += ",location=" + this.options['location'];
		this.str += ",scrollbars=" + this.options['scrollbars'];
		this.str += ",copyhistory=" + this.options['copyhistory'];
	},

	openWindow:function(){
        var hash = new Hash(this.options['params']);
        var openString = this.options['url'];
        if (hash.getLength()>0){
            openString += '?' + Hash.toQueryString(this.options['params']);
        }
		window.open(openString, this.options['windowName'], this.str);
	}

});

/**
 * Description
 *
 * @class Ria_Common_SearchTabSwitcher
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
*/
var Ria_Common_SearchTabSwitcher = new Class({

    Implements: Options,

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

        this.setupTabEvents();

        this.switchTab(activeTab, false);
	},

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

    switchTab: function(activeTab, ext)
    {
        $each(this.options, function(value, key){

            if (activeTab == key){
                $(value.tabDiv).setStyle('display', 'block');
                $(key).setProperty('class', value.tabClass + ' active');
                if (!ext){
                    if ($chk($(value.extendedTab))){
                        $(value.extendedTab).fireEvent('click', true);
                    }
                }
            } else {
                $(value.tabDiv).setStyle('display', 'none');
                $(key).setProperty('class', value.tabClass);
            }
        });


    }



});
/**
 *     Ajax RIA Framework
 *
 * @copyright  2009 IT RIA
 * @license    GNU GPL v2
 * @version    $Id: Ajax.js,v 1.2 2009/03/09 13:17:34 Exp $
 */
var Ria_Core_Ajax = {
	'script': '/new_auto/ajax.php'
};

/**
 * Decription
 *
 * @class Ria_Core_Common_StatusImageManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
*/
var Ria_Core_Common_StatusImageManager = new Class({

    spinnerImg  : 'http://img.ria.ua/icons/gifs/spinner_grey.gif',
    checkImg    : 'http://img.ria.ua/icons/gifs/checkbullet.gif',
    errorImg    : 'http://img.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){
				var statusImgOpacity = new Fx.Style(element, 'opacity', {duration:3000});
				statusImgOpacity.start(1, 0);
			}
		}
		
	}
	
});
/**
* Description
*
* @class Ria_Core_Common_FormsOnEnterSubmit
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
*/
//## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
var Ria_Core_Common_FormsOnEnterSubmit = new Class({
    Implements: Options,
    //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    formId: '',
    options: { 'formId' : '' },
    //## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
    initialize: function(options) {
        this.setOptions(options);
        if(this.options.formId) {
            this.formId = this.options.formId;
            this.addSubmitToEnterButtonForFormElements(this.formId);
        }
    },
    //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    addSubmitToEnterButtonForFormElements: function() {
//        alert(this.formId);
        this.addSubmitToEnterButtonForFormInputs();
        this.addSubmitToEnterButtonForFormSelects();
    },
    addSubmitToEnterButtonForFormSelects: function() {
        $$('#'+this.formId+' input').each(function(inputElement, index) {
            inputElement.addEvent('keydown', function(event) {
                if (event.key=='enter') $(this.formId).submit();
            }.bind(this));
        }.bind(this));
    },
    addSubmitToEnterButtonForFormInputs: function() {
        $$('#'+this.formId+' select').each(function(selectElement, index) {
            selectElement.addEvent('keydown', function(event) {
                if (event.key=='enter') $(this.formId).submit();
            }.bind(this));
        }.bind(this));
    }
    //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
});















//    options: {
//        'formsIds' : {}
//    },
//    initialize: function(options) {
//        this.setOptions(options);
//        this.formsIds = this.options.formsIds;
//        alert(Hash.toQueryString(this.formsIds));
//        alert(this.formsIds.toString);


//        if ( $defined ( $( this.options.dom.sendButton ) ) ) {
//            $(this.options.dom.sendButton).addEvent('click', this.sendMessage.bind(this));
//        }

        //������������ ��� ����������� ������
//        if ( $defined ( $( this.options.dom.inputField ) ) ) {
//            $(this.options.dom.inputField).addEvent('keyup', function(ev) {
//                if ( ev.key == "enter") {
//                    $(this.options.dom.sendButton).fireEvent('click');
//                }
//            }.bind(this));
//        }


//    changeColorInChat : function () {
//        if ( $defined ( $(this.options.dom.outputField) ) ) {
//            $(this.options.dom.outputField).getElements('span').each(function(span) {
//                if ( span.getStyle('color') == this.options.general.hisOldColor )
//                    span.setStyle('color',this.options.general.hisColor);
//            }.bind(this));
//        }
//    }

/**
 * Description
 *
 * @class Ria_Core_Common_ScrollingManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
*/
var Ria_Core_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);
                }
            }
        }
	}

});
/**
 * @class Ria_Auto_Generic_CountersUpdate
 * @copyright  2010 IT RIA
 * @license    GNU GPL v2
 * @version    $Id: CountersUpdate.js,v 1.1 2010/10/10 12:21:11 sanka,avi,ai Exp $
 */
var Ria_Auto_Generic_CountersUpdate = new Class({

    initialize: function() {
        $('updateCounters').addEvent('click', function(){
            new Request.JSON({
                url : 'ajax.php?target=auto&event=topCounters',
//                data : {
//                    'target' : 'auto',
//                    'event'  : 'topCounters'
//                },

                onComplete : function(data) {
//                    data = {'lastVisit' : 100, 'day' : 109, 'hour' : 90};
                    $('counterPerHour').set("html",data.hour);
                    $('counterPerDay').set("html",data.day);
                    $('counterLastVisit').set("html",data.lastVisit);
                }
                
            }).get();

            
        });

    },

    updateCompareCount: function(){
        
    }

});




/*
 * JavaScript select velocycle
 *
 * PARAMS:
 * selector             - css selector needable super selects
 * optionsClass         - super options select class name
 * selectedClass        - selected element class name
 * selectedOptionClass  - selected option class name
 * hideClass            - css display:none class name
 * onClick              - onClick function
 *
 * USAGE:
 *
 * HTML:
 * <strong class="element-select">
 *   <a href="javascript:void(0)" class="selected">50</a>
 *   <span class="options hide">
 *     <a href="javascript:void(0)" value="10">10</a>
 *     <a href="javascript:void(0)" value="20">20</a>
 *     <a href="javascript:void(0)" value="50" class="select">50</a>
 *     <a href="javascript:void(0)" value="100">100</a>
 *   </span>
 * </strong>
 *
 * JS:
 * new Ria_Auto_Generic_SuperSelect({
 *       'selector'                  : '.element-select',
 *       'optionsClass'              : 'options',
 *       'selectedClass'             : 'selected',
 *       'selectedOptionClass'       : 'select',
 *       'hideClass'                 : 'hide',
 *       'onClick'                   : function(value) { alert(value+' clicked'); }
 * });
 *
 *
 * @class Ria_Auto_Generic_SuperSelect
 * @copyright  2010 RIA.ua
 * @license    GNU GPL v3
 */
var Ria_Auto_Generic_SuperSelect = new Class({
    Implements: Options,
    options : {
        'selector'                  : '#id',
        'optionsClass'              : 'options',
        'selectedClass'             : 'selected',
        'selectedOptionClass'       : 'select',
        'hideClass'                 : 'hide',
        'tag'                       : ' a',
        'onClick'                   : function(value){}
    },

    initialize : function(options) {
        this.setOptions(options);
        // Enumeration of all super select elements
        if (!window.iWasHere) {
            document.addEvent("click", function() {
                if(!window.over && window.opened) {
                    this.hideAll();
                }
            }.bind(this));
            window.iWasHere = true;
        }
        
        $$(this.options.selector).each(function(item){
            this.process(item);
        }.bind(this));        
        
    },

    hideAll : function() {
        if($defined($$('.'+this.options.optionsClass))) {
           $$('.'+this.options.optionsClass).each(function(iteml) {
                 iteml.addClass(this.options.hideClass);
           }.bind(this));
        }
        window.opened = false;
    },
    
    process : function(item) {
        

        var selectedOptionSelector = '#'+item.id+' .'+this.options.selectedClass;
        var optionsSelector = '#'+item.id+' .'+this.options.optionsClass;

        
        // Adding super select onclick function
        $$(selectedOptionSelector).addEvent('click', function() {
            // hide all
            
            if($defined($$('.'+this.options.optionsClass))) {
                $$('.'+this.options.optionsClass).each(function(iteml){
                    if (!iteml.hasClass(this.options.hideClass) && iteml.getParent().id && iteml.getParent().id != item.id) {
                        iteml.addClass(this.options.hideClass);
                    }
                }.bind(this));
            }
            
            // Showing super select options
            $$(optionsSelector).toggleClass(this.options.hideClass);
            //console.log('Opened');
            window.opened = true;
            window.over = true;
        }.bind(this));

        $$(optionsSelector, selectedOptionSelector).addEvent('mouseover', function() {
            window.over = true;
        }.bind(this));

        $$(optionsSelector, selectedOptionSelector).addEvent('mouseout', function() {
            window.over = false;
        }.bind(this));

        // Enumeration of all super select options
        $$(optionsSelector+this.options.tag).each(function(option) {
            option.addEvent('click', function() {
                // Setup main selected option
                if(!option.hasClass('close-alert')) {
                    $$(selectedOptionSelector).set('html', option.get('html'));
                }

                // Select option
                $$('#'+item.id+' .'+this.options.selectedOptionClass).removeClass(this.options.selectedOptionClass);
                option.addClass(this.options.selectedOptionClass);

                // Hide super select options
                $$(optionsSelector).toggleClass(this.options.hideClass);

                // Run callback function
                this.options.onClick(option.getAttribute('value'));
            }.bind(this));
        }.bind(this));       
    }

});
/* 
*
 * @class Ria_Auto_Generic_TopCounters
 * @copyright  2010 RIA.ua
 * @license    GNU GPL v3
 */
var Ria_Auto_Generic_TopCounters = new Class({

    bIsOpen: false, 

    hide : function() {
        if (!$('riaPeriodSelect').hasClass('hide')) {
            $('riaPeriodSelect').addClass('hide');
        }
    },
    
    toggle : function() {
    	$('userLocationEditDivId').setStyle('display', 'none');
        $('riaPeriodSelect').toggleClass('hide');
    },

    dontHide : true,

    setup : function() {
        $$('#addedCars', '#riaPeriodSelect').addEvent('mouseover',function() {
            this.dontHide = true;
        }.bind(this));
        
        $$('#addedCars', '#riaPeriodSelect').addEvent('mouseleave',function() {
            this.dontHide = false;
        }.bind(this));

        $('addedCars').addEvent('click',function() {
            this.dontHide = true;
            this.toggle();

            if ($('riaPeriodSelect').hasClass('hide')) {
                this.callBack();
            }

        }.bind(this));

        document.addEvent('click', function() {
            if (!this.dontHide) {
            	
                this.hide();
                this.callBack();
                this.dontHide = true;
            }
        }.bind(this));

        $$('#closePerDay', '#savePerDay').addEvent('click', function() {
            this.hide();
            this.callBack();
        }.bind(this));

    },

    callBack : function() {
        var items = $$('#riaPeriodSelect input[name=selected-top-count]');

        items.each(function(item) {
            if (item.getProperty('checked')) {
                stt = JSON.decode(item.getAttribute('val'));
                
                $('linkTopCount').set('href', stt.url);
                
                var settings = new Hash.Cookie('siteSettings',{path: '/', duration:'365'});
                settings.set('selectedTopCount', stt.id)
                
                $('linkTopCount').set('html', item.getParent('span').getElements('label')[0].get('html').trim());
                $$('#addedCars .icons-arrow').set('html', item.getParent('p').getElements('strong')[0].get('html').trim());
            }
        }.bind(this));
    }
	
});
/**
 * <b>Tab switcher</b>
 *
 * tabClass     - tab class name
 * panelClass   - panel class name
 * event        - javascript event (click, mouseover, etc)
 * invisibleCss - css display:none class name
 * selectCss    - css selected tab class name
 * autohide     - seconds to autoclose all tabs, 0 - don`t close
 * delay        - delay to open panel in seconds
 * attribute    - tag attribute with panel id
 *
 *
 * <h2>Using:</h2>
 *
 * <b>HTML:</b>
 * <a class="tabs select ria-topcars-tabs" tabid="ria-tab-used">tab1</a>
 * <a class="tabs ria-topcars-tabs" tabid="ria-tab-new">tab1</a>
 *
 * <div id="ria-tab-used" class="ria-topcars-panels">panel1</div>
 * <div id="ria-tab-new" class="ria-topcars-panels hide">panel2</div>
 *
 * <b>JS:</b>
 * new Ria_Auto_Generic_TabSwitcher({
 *      'tabClass'      : 'ria-topcars-tabs',
 *      'panelClass'    : 'ria-topcars-panels',
 *      'event'         : 'click',
 *      'invisibleCss'  : 'hide',
 *      'selectCss'     : 'select',
 *      'autohide'      : '1',
 *      'delay'         : '1',
 *      'attribute'     : 'tabid'
 * });
 *
 * @class Ria_Auto_Generic_TabSwitcher
 * @copyright  2010 RIA.ua
 * @license    GNU GPL v3
 */
var Ria_Auto_Generic_TabSwitcher = new Class({
    

    Implements: Options,
    
    over: false,
    
    closeMenuAllOver: null,
    
    options: {
        'attribute'       : 'tabid' ,
        'selectCss'       : 'select',
        'invisibleCss'    : 'hide'  ,
        'event'           : 'click' ,

        'css3RootElement' : '.',

        'tabClass'        : 'tabs'  ,
        'panelClass'      : 'panel' ,
        'autohide'        : '0'     ,
        'delay'           : '0',
        'jsAutoLoad'      : {}
    },

    initialize : function(options) {

        this.closeMenuAllOver = options['closeMenuAllOver'];
        delete options['closeMenuAllOver'];
        
        this.setOptions(options);
        this.oldDelay = this.options.delay;
        this.tabElements = $$(this.options.css3RootElement+this.options.tabClass);
        this.panelElements = $$(this.options.css3RootElement+this.options.panelClass);
        this.setupEvents();
    },

    setupEvents : function() {
        // Hide popup on unfocus click or escape key

        if (this.options.autohide > 0) {
            document.addEvent("click", function(event) {
                if (!this.over) {
                    this.hidePanel();
                }
            }.bind(this));

            document.addEvent('keydown', function(event) {
                if (event.key == "esc") {
                    this.hidePanel();
                }
            }.bind(this));
        }

        // Hide popup on unfocus click or escape key


        this.tabElements.each(function(item) {
            // Autohide
            if (this.options.autohide > 0) {
                item.addEvent('mouseover', function() {
                    this.over = true;
                    var attribute = item.getProperty(this.options.attribute);
                    if (this.options.jsAutoLoad[attribute] != undefined) {
                        this.options.jsAutoLoad[attribute]();
                    };
                    
                    
                }.bind(this));
                $(item.getProperty(this.options.attribute)).addEvent('mouseover', function() {
                    this.over = true;
                    
                }.bind(this));

                item.addEvent('mouseout', function() {
                    window.clearTimeout(this.timeoutDelayId);
                    this.over = false;
                    if(this.closeMenuAllOver != undefined){
                        this.over = this.closeMenuAllOver.getOver();
                    }
                    this.hideCheck();
                }.bind(this));
                $(item.getProperty(this.options.attribute)).addEvent('mouseout', function() {
                    window.clearTimeout(this.timeoutDelayId);
                    this.over = false;
                    if(this.closeMenuAllOver != undefined){
                        this.over = this.closeMenuAllOver.getOver();
                    }
                    this.hideCheck();
                }.bind(this));
            }
            // /Autohide

            // Remove delay on moving by elements panel
            if (this.options.delay > 0) {
                item.addEvent('mouseleave', function() {
                    this.options.delay = 0;

                    window.clearTimeout(this.timeoutAntiDelayId);
                    this.timeoutAntiDelayId = window.setTimeout(function() {
                        this.options.delay = this.oldDelay;
                    }.bind(this), 50);
                }.bind(this));
            }
            // /Remove delay on moving by elements panel

            // Process

            item.addEvent(this.options.event, function() {
                window.clearTimeout(this.timeoutDelayId);

                this.timeoutDelayId = window.setTimeout(function() {
                    //$$('#ria-tabs-panel div.'+this.options.tabClass).removeClass(this.options.selectCss);
                    this.tabElements.each( function(item2) { item2.removeClass(this.options.selectCss) }.bind(this));
                    item.addClass(this.options.selectCss);

                    this.panelElements.each( function(item2) { item2.addClass(this.options.invisibleCss) }.bind(this));
                    //$$('#ria-tabs-panel div.'+this.options.panelClass).addClass(this.options.invisibleCss);
                    $(item.getProperty(this.options.attribute)).removeClass(this.options.invisibleCss);

                }.bind(this), this.options.delay*1000);

                return false;
            }.bind(this));
            // /Process

        }.bind(this));
    },

    /**
     * Autohide popup on unfocus
     */
    hideCheck : function() {
        window.clearTimeout(this.timeoutHideId);

        this.timeoutHideId = window.setTimeout(function(){
            if (!this.over) {
                this.hidePanel();
            }
        }.bind(this), this.options.autohide*1000);
    },

    /**
     * Hide popup
     */
    hidePanel : function() {
        //$$('#ria-tabs-panel div.'+this.options.tabClass).removeClass(this.options.selectCss);
//      if (!($$('#ria-tabs-panel div.'+this.options.panelClass).hasClass(this.options.invisibleCss))) {
//      $$('#ria-tabs-panel div.'+this.options.panelClass).addClass(this.options.invisibleCss);
//  }
    	this.tabElements.each( function(item) { item.removeClass(this.options.selectCss) }.bind(this));
    	this.panelElements.each( function(item) {
    		if (! item.hasClass(this.options.invisibleCss)) {
    			item.addClass(this.options.invisibleCss)
    		}
    	}.bind(this) );
    },


    /**
     * Adds events to close links ([cancel], [x], ...)
     */
    addCloser :  function(id) {
        $(id).addEvent('click', function() {
            this.hidePanel();
        }.bind(this));
    }
});


//$(item.getProperty(this.options.attribute)).addEvent is not a function
//http://net-auto.ua/club/js/pack/jsClasses_1958715717_1304045338.js
//Line 3
/**
 *
 * @class Ria_Common_TopPanelSubMenu
 * @copyright  2009 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 */

var Ria_Common_TopPanelSubMenu = new Class({

    initialize: function(){
        this.setUpEvents();
    },

        setUpEvents: function(){
            $$('#MainNavigatorAnchorContainer a.icons-x24').each(function(item){
                if ($chk(item)){
                    item.addEvent('mouseover',function(){
                        this.bodyOfTopClassMenu(item.get('id'));
                    }.bind(this));
                }
            }.bind(this));
        },
//
//
        bodyOfTopClassMenu: function(activeAnchor){
            var leftMouseNow = '';
            if (activeAnchor){
                $(activeAnchor).removeEvents('mouseout');
                $(activeAnchor).addEvent('mouseout',function(){
                    leftMouseNow = activeAnchor;
                }.bind(this));

                var hideWithDelay = function(){
                   if (leftMouseNow!=activeAnchor){
                       $$('#MainNavigatorAnchorContainer a.icons-x24').each(function(item){
                        item.removeClass('select');
                        }.bind(this));
                        $$('#bottomContecstDd div.sub-menu').each(function(item){
                            item.setStyle('display','none');
                        }.bind(this));
                        $(activeAnchor).addClass('select');
                        if ($defined($(activeAnchor+'Child'))){
                            if ($('bottomContecstDd').getStyle('display')=='none')
                                $('bottomContecstDd').setStyle('display','block');
                            $(activeAnchor+'Child').setStyle('display','block');
                        }else{
                            $('bottomContecstDd').setStyle('display','none');
                        }
                   }
                };
                hideWithDelay.delay(200);
            }
        },

        setStylesNoneOther: function(){
            $$('#MainNavigatorAnchorContainer a.icons-x24').each(function(item){
                item.removeClass('select');
            });
            $$('#bottomContecstDd div.sub-menu').each(function(item){
                item.setStyle('display','none');
            });

        }

});

/**
 * This class add default value to input text fiels
 * And remove this value then field on focus
 *
 * @class Ria_Common_DefaultValue
 * @copyright  2010 RIA Allegro
 * @license    GNU GPL v2
 * @version    ID:1.0
*/
 var Ria_Core_Common_DefaultValue = new Class({

    Implements: Options,

    options : {
            text            : 'Insert here...',
            id              : 'text',
            style_default   : {},
            style_value     : {},
            empty_values    : []
    },
    initialize: function(options){

        this.setOptions(options);

        $(this.options.id).addEvent('focus',function(){
            if ($(this.options.id).getProperty('value') == this.options.text){
                $(this.options.id).removeProperty('style');
                $(this.options.id).setStyles(this.options.style_value);
                $(this.options.id).setProperty('value', "");
            }
        }.bind(this));

        $(this.options.id).addEvent('blur',function(){
            if ($(this.options.id).getProperty('value') == "" || this.options.empty_values.contains($(this.options.id).getProperty('value'))){
                $(this.options.id).removeProperty('style');
                $(this.options.id).setStyles(this.options.style_default);
                $(this.options.id).setProperty('value', this.options.text);
            }
        }.bind(this));

        $(this.options.id).fireEvent('blur');
    }
});
/**
 * Loading Prototipes Versions In Select
*
* @class Ria_Spares_SparesRequest
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires    
*/
var Ria_Common_Autocompleter = new Class({
    initialize: function(options){
    new  Autocompleter.Request.JSON('str_search', '/new_auto/ajax.php?target=spares&event=autocompleter', {
        'postVar': 'str_search',
        'ajaxOptions' : {
            'method' : 'get',
            'user'   : 'vanya'
        }
    }
);


    }
});

/**
 * Loading Prototipes Versions In Select 
*
* @class Ria_Points_SearchPanelManagerNew
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
*/
var Ria_Points_SearchPanelManagerNew = new Class({
    
    Implements: Options,

	options: {},

    searchType : 'list',

    showAdvanced: false,
    
	initialize: function(searchType, typeId, showAdvanced, options)
    {
        if (!typeId) typeId = 1;

        if (searchType != '') this.searchType = searchType;
        this.typeId = typeId;

        this.showAdvanced = showAdvanced;

        this.setOptions(options);

        this.addEvents();

        this.repaintAll();

	},

    addEvents:function(){
       
        $('advancedSearchLink').addEvent('click', function() {
            this.typeId=$('typeId').value;
             if ($('advancedSearchPanel').hasClass('hide')) this.showAdvanced = true;
               else this.showAdvanced = false;
           
            this.repaintAll();
            return false;
        }.bind(this));

        $('categoriesSelector1').addEvent('click', function() {
            this.typeId=$('typeId').value;
               if ($('advancedSearchPanel').hasClass('hide')) {this.showAdvanced_old = false; }
               else this.showAdvanced_old = true;
            this.showAdvanced = false;
            this.repaintAll();
            this.showAdvanced = this.showAdvanced_old;
            this.repaintAll();
        }.bind(this));

        $('categoriesSelector2').addEvent('click', function() {
            this.typeId=$('typeId').value;
               if ($('advancedSearchPanel').hasClass('hide')) {this.showAdvanced_old = false; }
               else this.showAdvanced_old = true;
            this.showAdvanced = false;
            this.repaintAll();
            this.showAdvanced = this.showAdvanced_old;
            this.repaintAll();
        }.bind(this));

        $('categoriesSelector3').addEvent('click', function() {
            this.typeId=$('typeId').value;
               if ($('advancedSearchPanel').hasClass('hide')) {this.showAdvanced_old = false; }
               else this.showAdvanced_old = true;
            this.showAdvanced = false;
            this.repaintAll();
            this.showAdvanced = this.showAdvanced_old;
            this.repaintAll();
        }.bind(this));

//        $('hideAdvancedPointsPanel').addEvent('click', function() {
//            this.showAdvanced = false;
//            this.repaintAll();
//        }.bind(this));

        $('searchValues-1-9-0-0').addEvent('change', function() {
            var currValue = $('searchValues-1-9-0-0').value;
            if (currValue > 0){
                $('searchValues-1-9-0-0').setProperty('name', 'searchValues[1][9][' + currValue + '][0]');

                $('searchValues-1-9-0-1').setProperty('name', 'searchValues[1][9][' + currValue + '][1]');
                $('searchValues-1-9-0-1').removeProperty('disabled');
                $('searchValues-1-9-0-1-official').setProperty('value', currValue);
            } else {
                $('searchValues-1-9-0-0').removeProperty('name');

                $('searchValues-1-9-0-1').removeProperty('name');
                $('searchValues-1-9-0-1').setProperty('disabled', true);
                $('searchValues-1-9-0-1-all').setProperty('selected', true);
            }
        });

        $('searchValues-2-8-0-0').addEvent('change', function() {
            var currValue = $('searchValues-2-8-0-0').value;
            if (currValue > 0){
                $('searchValues-2-8-0-0').setProperty('name', 'searchValues[2][8][' + currValue + '][0]');
            } else {
                $('searchValues-2-8-0-0').removeProperty('name');
            }
        });

        if (this.searchType == 'map'){
            $('region-s').addEvent('change', function() {
                if ( $defined( $('region-s-option-' + this.value ) ) ){
                    window.riaMap.storage.map.setCenter(new Ria_Core_Map_Main_Common_GeoPoint($('region-s-option-' + this.value).getProperty('riaGeoX'), $('region-s-option-' + this.value).getProperty('riaGeoY')));
                    if (this.value >0) window.riaMap.storage.map.setZoom(50);
                    else window.riaMap.storage.map.setZoom(0);
                }
            });
        }

    },

    repaintAll:function(){
        this.showAdvancedPanel(this.showAdvanced);
        
        $each(this.options, function(value, key){
            if (key == this.typeId) {
                $(value).removeClass('hide');
                if (this.showAdvanced) {
                    this.setAllInputStatus(value, true);
                    $('searchValues-1-9-0-0').fireEvent('change');
                    $('searchValues-2-8-0-0').fireEvent('change');
                }
                else this.setAllInputStatus(value, false);
            } else {
                $(value).addClass('hide');
                this.setAllInputStatus(value, false);
            }
        }, this);

    },

    setAllInputStatus:function(blockId, enabled){
        $each($(blockId).getElements('input'), function(value){
            if (enabled) value.removeProperty('disabled');
            else value.setProperty('disabled', 'true');
        });
        
        $each($(blockId).getElements('select'), function(value){
            if (enabled) value.removeProperty('disabled');
            else value.setProperty('disabled', 'true');
        });
    },

    showAdvancedPanel:function(status){
                       var categor=this.typeId;
        if (status) {     
            $('advancedSearchPanel').removeClass('hide');
//            $('advancedSearchLink').removeClass('hide');
          
    
                                       $('advancedSearchPanel').removeClass('hide');
                            $('test_search').set('html', 'C  ');
//                            $('block_'+categor).removeClass('hide');
        } else {           
               $('advancedSearchPanel').addClass('hide');
//            $('advancedSearchLink').addClass('hide');

                         $('advancedSearchPanel').addClass('hide');
//                                    $('block_'+categor).addClass('hide');
                        $('test_search').set('html', ' ');
        }
    }
    
});
/**
 * Loading Prototipes Versions In Select 
*
* @class Ria_Points_SearchPanelManager
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
*/
var Ria_Points_SearchPanelManager = new Class({
    
    Implements: Options,

	options: {},

    searchType : 'list',

    showAdvanced: false,
    
	initialize: function(searchType, typeId, showAdvanced, options)
    {
        if (!typeId) typeId = 1;

        if (searchType != '') this.searchType = searchType;
        this.typeId = typeId;

        this.showAdvanced = showAdvanced;

        this.setOptions(options);

        this.addEvents();

        this.repaintAll();

	},

    addEvents:function(){
        $('advancedSearchLink').addEvent('click', function() {
            if ($('advancedSearchPanel').hasClass('noDisplay')) this.showAdvanced = true;
            else this.showAdvanced = false;
            this.repaintAll();
            return false;
        }.bind(this));

        $('hideAdvancedPointsPanel').addEvent('click', function() {
            this.showAdvanced = false;
            this.repaintAll();
        }.bind(this));

        $('searchValues-1-9-0-0').addEvent('change', function() {
            var currValue = $('searchValues-1-9-0-0').value;
            if (currValue > 0){
                $('searchValues-1-9-0-0').setProperty('name', 'searchValues[1][9][' + currValue + '][0]');

                $('searchValues-1-9-0-1').setProperty('name', 'searchValues[1][9][' + currValue + '][1]');
                $('searchValues-1-9-0-1').removeProperty('disabled');
                $('searchValues-1-9-0-1-official').setProperty('value', currValue);
            } else {
                $('searchValues-1-9-0-0').removeProperty('name');

                $('searchValues-1-9-0-1').removeProperty('name');
                $('searchValues-1-9-0-1').setProperty('disabled', true);
                $('searchValues-1-9-0-1-all').setProperty('selected', true);
            }
        });

        $('searchValues-2-8-0-0').addEvent('change', function() {
            var currValue = $('searchValues-2-8-0-0').value;
            if (currValue > 0){
                $('searchValues-2-8-0-0').setProperty('name', 'searchValues[2][8][' + currValue + '][0]');
            } else {
                $('searchValues-2-8-0-0').removeProperty('name');
            }
        });

        if (this.searchType == 'map'){
            $('region-s').addEvent('change', function() {
                if ( $defined( $('region-s-option-' + this.value ) ) ){
                    window.riaMap.storage.map.setCenter(new Ria_Core_Map_Main_Common_GeoPoint($('region-s-option-' + this.value).getProperty('riaGeoX'), $('region-s-option-' + this.value).getProperty('riaGeoY')));
                    if (this.value >0) window.riaMap.storage.map.setZoom(50);
                    else window.riaMap.storage.map.setZoom(0);
                }
            });
        }

    },

    repaintAll:function(){
        this.showAdvancedPanel(this.showAdvanced);
        
        $each(this.options, function(value, key){
            if (key == this.typeId) {
                $(value).removeClass('noDisplay');
                if (this.showAdvanced) {
                    this.setAllInputStatus(value, true);
                    $('searchValues-1-9-0-0').fireEvent('change');
                    $('searchValues-2-8-0-0').fireEvent('change');
                }
                else this.setAllInputStatus(value, false);
            } else {
                $(value).addClass('noDisplay');
                this.setAllInputStatus(value, false);
            }
        }, this);

    },

    setAllInputStatus:function(blockId, enabled){
        $each($(blockId).getElements('input'), function(value){
            if (enabled) value.removeProperty('disabled');
            else value.setProperty('disabled', 'true');
        });
        
        $each($(blockId).getElements('select'), function(value){
            if (enabled) value.removeProperty('disabled');
            else value.setProperty('disabled', 'true');
        });
    },

    showAdvancedPanel:function(status){
        if (status) {
            $('advancedSearchPanel').removeClass('noDisplay');
            $('advancedSearchLink').addClass('noDisplay');
        } else {
            $('advancedSearchPanel').addClass('noDisplay');
            $('advancedSearchLink').removeClass('noDisplay');
        }
    }
    
});
/**
* Loading request search string elements to drop list
*
* @class Ria_Points_SearchDropMove
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
*/
var Ria_Points_SearchDropMove = new Class({

	initialize: function(keyCode){
        this.items = new Array();
        this.startLine = '';
        this.selected = -1;
        this.keyListener(keyCode);
	},
    
    keyListener: function(keyCode){
        items = new Array();
        if (!((typeof(keyCode)=='undefined') || ((keyCode >= 65) && (keyCode <= 122)) || (keyCode == 8) || (keyCode == 0))){
            $each($('dropBox').getElementsByTagName('div'), function(dropItem){
                items.include(dropItem.id);
            });
        }
        if (keyCode == '40'){//down key
            if ($('dropBox').getStyle('display')=='none') $('dropBox').style.display='inline-block';
            if (this.selected<(items.length-1)) this.selected++;
            else this.selected=0;
            this.hover(items[this.selected]);
        }
        else if (keyCode=='38'){//up key
            if ($('dropBox').getStyle('display')=='none') $('dropBox').style.display='inline-block';
            if (this.selected > 0) this.selected--;
            else this.selected=items.length-1;
            this.hover(items[this.selected]);
        }
        else if (keyCode=='27'){//escape
            $('dropBox').setStyle('display', 'none');
            $('searchDropElement_'+this.selected).removeClass('DMHover');
            this.selected=-1;
        }
        else if (keyCode=='32'){//space
            //      
            this.startLine = $('searchStrField').value+'';
            //       
            Cookie.write('oldSearchStr', Cookie.read('searchStr'), {path: '/'});
            Cookie.write('searchStr', $('searchStrField').value+'', {path: '/'});
        }
        else if (keyCode=='8'){//backspace
            this.startLine = Cookie.read('oldSearchStr');
            Cookie.write('searchStr', Cookie.read('oldSearchStr'), {path: '/'});
        }
        else if (keyCode=='46'){//delete
            if (!$('searchStrField').value) $('dropBox').setStyle('display', 'none');
            this.startLine = '';
            Cookie.write('searchStr', '', {path: '/'});
            Cookie.write('oldSearchStr', '', {path: '/'});
        }
    },

    hover: function(element){
        $$('.DMHover').removeClass('DMHover');
        if ($(element)!=null) $(element).toggleClass('DMHover');
        if ($('searchStrField').value.indexOf(' ')<0) this.startLine='';
        if ($('dropId_'+this.selected)) $('searchStrField').value=this.startLine + $('dropId_'+this.selected).innerHTML;
    }
    
});
/**
* Hightlight search results
*
* @class Ria_Points_HightlightSearchResults
* @copyright  2009 IT RIA
* @license    GNU GPL v2
* @version    ID:
*/
var Ria_Points_HightlightSearchResults = new Class({

	initialize: function(searchText, searchElementClassName, wordsSeparator, highlightedDivClass){
        this.newValue = null;
        window.addEvent('domready', function(){
            if (searchText){
                //         
                $$('.'+searchElementClassName).each(function(item){
                    this.block = item.innerHTML;
                    //      
                    searchText.split(wordsSeparator).each(function(word){
                        //    2 ,    ,   
                        if (word.length>2) {
                            this.block = this.block.replace(eval('/([\\s-]{1})('+word+')/ig'), '$1<div class="'+highlightedDivClass+'">$2</div>');
                        }
                    },this);
                    // ,   
                    item.innerHTML = this.block;
                }.bind(this));
            }
        }.bind(this));
	}
});
/**
 * @class       Ria_Auto_Generic_CategorySelectSpares
 * 
 * @copyright   2010 RIA.ua
 * @license     GNU GPL v3
 */
var Ria_Auto_Generic_CategorySelectSpares = new Class({
    Implements: Options,
    options: {
        'categorySelect'    : 'category',
        'categoriesSelect'  : 'categories',
        'markaSelectId'     : 'markaId',
        'modelSelectId'     : 'modelId',
        
        'categoryId'          : 'categoryId',
        'target'            : 'auto',
        'event'             : 'load_subcategory',
        'zone'   :   'mainPage',
        'countriesClass':''
    },

    initialize : function(options) {
        this.setOptions(options);
        this.setEvents();
    },

    setEvents : function() {
        if ($(this.options.categorySelect).tagName=='SELECT'){
            
            $(this.options.categorySelect).addEvent('change', function() {
                this.makeRequest($(this.options.categorySelect).value);
            }.bind(this));
            
        }else{
            $(this.options.categorySelect).addEvent('click', function() {
                $(this.options.categoriesSelect).toggleClass('hide');

                return false;
            }.bind(this));

            $$('#'+this.options.categoriesSelect+' div a').each(function(item) {
                item.addEvent('click', function() {
                    var categoryId = parseInt(item.getAttribute('value'));
                    $('typeId').value = categoryId;
                    $$('#'+this.options.categorySelect+' a').set('html', "<span>{%name}</span>".replace('{%name}', item.get('html')));
                    $(this.options.categorySelect).set('class', "select-bar corner-5 {%classname}".replace('{%classname}', item.get('class')));

                    $(this.options.categoriesSelect).toggleClass('hide');
                    this.makeRequest(categoryId);

                }.bind(this));
            }.bind(this));

            $$('body').addEvent('click', function(item) {
                if (!$(this.options.categoriesSelect).hasClass('hide')) {
                    $(this.options.categoriesSelect).addClass('hide');
                }
            }.bind(this));
        }
    },
    
    
    makeRequest: function(categoryId,countryEvent){
//          if ( !$('advancedSearchPanel').hasClass('hide')) {
//                     if ( !$('pointPanel_sto').hasClass('hide'))  $('pointPanel_sto').addClass('hide');
//                     if ( !$('pointPanel_zap').hasClass('hide'))  $('pointPanel_zap').addClass('hide');
//                     if ( !$('pointPanel_sto').hasClass('hide'))  $('pointPanel_sto').addClass('hide');
//
//
//if (categoryId==2) $('pointPanel_zap').removeClass('hide');
//else if (categoryId==3)   $('pointPanel_moi').removeClass('hide');
//else
//$('pointPanel_sto').removeClass('hide');
//          }

    
//        new Ria_Auto_Search_GetModelClassAjax({
//                    'sourceId'  : this.options.markaSelectId,
//                    'targetId'  : this.options.modelSelectId,
//
//                    'categoryId': categoryId.toInt(),
//                    'categoriesContainer'   :   '1',
//                    'zone'   :   this.options.zone,
//                    'countriesClass': this.options.countriesClass,
//                    'countryEvent':countryEvent
//                });
    },
    
    getCategoryId:function(){
        if ($(this.options.categorySelect).tagName=='SELECT'){
            return $(this.options.categorySelect).value;
        }else if($('CurrentCategoryHidden')){
            return $('CurrentCategoryHidden').value;
        }
        return 0;
    }

});
/*
*	Track  id of parent elenemt
*	Tracker  id of tracked element
*	OnUpdate  function whitch calls on each value change
*	OnComplete  function whitch calls on end of the drag
*	FingerOffset  distance between mouse pointer and corner tracker's edge
*	FormatNumbers  lead numders in hairlines with spaces
*	Min & Max  range of vaues
*	MinSpace  minimum difference between Min & Max
*	RoundTo  values will be rounded to this value
*	Margins  indent between Track & Tracker
*	AllowedValues  force Tracker to stick to the values
*
*	OnUpdate  function whitch called each time, when Tracker moved
*	OnComplete  function whitch called when user stop draging
*/
var Ria_Guru_DoubleTrackBar = new Class({

    initialize: function(Track, Tracker, Settings){
        this.Track = $(Track);
        this.Tracker = $(Tracker);

        this.OnUpdate = Settings.OnUpdate;
        this.OnComplete = Settings.OnComplete;
        this.FingerOffset = Settings.FingerOffset || 0;
        this.FormatNumbers = Settings.FormatNumbers || false;
        this.Min = Settings.Min || 0;
        this.Max = Settings.Max || 100;
        this.MinSpace = Settings.MinSpace || 0;
        this.RoundTo = Settings.RoundTo || 1;
        this.Margins = Settings.Margins || 0;
        this.AllowedValues = Settings.AllowedValues || false;
        this.Disabled = (typeof Settings.Disabled != 'undefined') ? Settings.Disabled : false;
        //           ---
        this.ToElement = $(Settings.ToElement);
        this.TrackerStart = Settings.Start || this.Min;
        this.TrackerEnd = Settings.End || this.Max;
        this.MinPosition = null;
        //          /---
        if (this.Min >= this.Max) this.Max = this.Min +1;

        this.MinPos = Settings.MinPos || this.Min;
        this.MaxPos = Settings.MaxPos || this.Max;

        if (this.Max - this.Min < this.MinSpace)
            this.MinSpace =  this.Max - this.Min;
        if (this.Max - this.Min < this.RoundTo)
            this.RoundTo =  this.Max - this.Min;
        this.MinSpace = Math.ceil(this.MinSpace/this.RoundTo)*this.RoundTo;

        this.Track.setStyle('width', (this.Track.clientWidth || this.Track.offsetWidth) + 'px');

        this.OnTrackMouseDown = this.bindAsEventListener(this.TrackMouseDown);
        this.OnDocumentMouseMove = this.bindAsEventListener(this.DocumentMouseMove);
        this.OnDocumentMouseUp = this.bindAsEventListener(this.DocumentMouseUp);

        //this.bindEvent(this.Track, 'mousedown', this.OnTrackMouseDown);
        this.bindEvent($('polzunok'), 'mousedown', this.OnTrackMouseDown);

        this.TrackerLeft = 0;
        this.UpdateTracker(this.Track.offsetWidth + this.FingerOffset);
        if (typeof this.OnUpdate == 'function') this.OnUpdate.call(this);
    },

    TrackMouseDown: function(event) {
        this.TrackerLeft = this.Tracker.offsetLeft - this.Margins;
        this.TrackerRight = this.TrackerLeft + this.Tracker.offsetWidth;

        this.TrackerOffsets = this.getOffsets(this.Track);

        var X = event.clientX + document.documentElement.scrollLeft;
        X -= this.TrackerOffsets[0];

        this.Left = Math.abs(this.TrackerLeft-X+this.Margins) <= Math.abs(this.TrackerRight-X+this.Margins);

        if (typeof this.Disabled == 'function') {
            if ( this.Disabled.call(this) )
                return true;
        } else if ( this.Disabled )
            return true;

        this.UpdateTracker(X);

        this.bindEvent(document, 'mousemove', this.OnDocumentMouseMove);
        this.bindEvent(document, 'mouseup', this.OnDocumentMouseUp);

        return this.stopEvent(event);
    },

    DocumentMouseMove: function(event) {
        this.UpdateTracker(event.clientX + document.documentElement.scrollLeft - this.TrackerOffsets[0]);
        return this.stopEvent(event);
    },

    DocumentMouseUp: function(event) {
        this.unbindEvent(document, 'mousemove', this.OnDocumentMouseMove);
        this.unbindEvent(document, 'mouseup', this.OnDocumentMouseUp);

        if (typeof this.OnComplete == 'function') {
            this.OnComplete.call(this);
        }
        return this.stopEvent(event);
    },

    UpdateTracker: function(X){
//        alert(this.MinPosition);
        var _LogicWidth = this.Track.offsetWidth - this.Margins*2 - 1;
        var _minSpace = Math.floor(_LogicWidth*this.MinSpace/(this.Max-this.Min));
        //  ---
        this.padding = _minSpace;
        // /---
        var _oldMin = this.MinPos;
        var _oldMax = this.MaxPos;

        X -= this.Margins;
        if (this.Left) {
            X += this.FingerOffset;
            this.TrackerLeft = Math.max(0, Math.min(this.TrackerRight - _minSpace - 1, X));
            this.MinPos = Math.round((this.Min + this.TrackerLeft*(this.Max-this.Min)/_LogicWidth) / this.RoundTo) * this.RoundTo;
            if (this.MinSpace >= this.MaxPos - this.MinPos) {
                this.MinPos = this.MaxPos - this.MinSpace;
            }
            if (this.AllowedValues) {
                this.TrackerLeft = Math.round(_LogicWidth*(this.MinPos - this.Min)/(this.Max - this.Min));
            }
        } else {
            X -= this.FingerOffset;
            this.TrackerRight = Math.max(this.TrackerLeft + _minSpace + 1 , Math.min(_LogicWidth + 1, X));
            this.MaxPos = Math.round((this.Min + (this.TrackerRight-1)*(this.Max-this.Min)/_LogicWidth) / this.RoundTo) * this.RoundTo;
            if (this.MinSpace >= this.MaxPos - this.MinPos) this.MaxPos = this.MinPos + this.MinSpace;
            if (this.AllowedValues) this.TrackerRight = Math.round(_LogicWidth*(this.MaxPos - this.Min)/(this.Max - this.Min))+1;
        }

        this.Tracker.setStyle('width', (this.TrackerRight - this.TrackerLeft) + 'px');
        this.Tracker.setStyle('left', (this.Margins + this.TrackerLeft) + 'px');

        //   ---
        if (this.TrackerStart || this.TrackerEnd){
            this.Tracker.setStyle('left', (this.TrackerStart-1)*_minSpace/this.MinSpace + 'px');
            this.ToElement.setStyle('left', (this.TrackerEnd-this.TrackerStart)*_minSpace/this.MinSpace + 'px');
            this.Tracker.setStyle('width', (this.TrackerEnd-this.TrackerStart)*_minSpace/this.MinSpace + 'px');
            this.TrackerStart = null;
            this.TrackerEnd = null;
        }
        if (this.MinPosition){
            this.MinPos = this.MinPosition;
            this.MinPosition = null;
        }
        //   /---
        if (typeof this.OnUpdate == 'function')
            if ( !this.AllowedValues || (this.AllowedValues && (_oldMax!=this.MaxPos || _oldMin!=this.MinPos)) )
                this.OnUpdate.call(this);
    },

    AddHairline: function (pos) {
        var _Touch = this.Track.appendChild( document.createElement('div') );
        var _LogicWidth = this.Track.offsetWidth - this.Margins*2 - 1;

        _Touch.style.left = this.Margins + _LogicWidth/(this.Max-this.Min)*(pos-this.Min) + 'px';
        _Touch.className = 'touch';
        _Touch.innerHTML = "<span>" + (this.FormatNumbers ? this.leadSpaces(pos) : pos) + "</span>";
    },

    AutoHairline: function(num) {
        if (num >= 1)
            this.AddHairline(this.Min);
        if (num >= 2)
            this.AddHairline(this.Max);
        if (num >= 3) {
            num--;
            var diff = this.Max - this.Min;
            var roundTo = [10, 20, 50, 100, 250, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 250000, 500000, 1000000];
            var DoRound = 1;
            for (var i=0; roundTo[i]; i++) {
                DoRound = roundTo[i]/10;
                if (roundTo[i]>diff)
                    break;
            }
            for (var i=1; i<num; i++) {
                var val = this.Min + diff/num*i;
                val = Math.round(val/DoRound)*DoRound;
                this.AddHairline(val);
            }
        }
    },

    getOffsets: function(element) {
        var valueT = 0, valueL = 0;
        do {
            valueT += element.offsetTop  || 0;
            valueL += element.offsetLeft || 0;
            element = element.offsetParent;
        } while (element);
        return [valueL, valueT];
    },

    leadSpaces: function(numb) {
        var res = '';
        numb = numb.toString();
        var l = numb.length;
        for (var i=l; i>0; i--)
            if ((l-i)%3==2)
                res = '&nbsp;'+numb.charAt(i-1)+res;
            else
                res = numb.charAt(i-1)+res;
        return res;
    },

    bindEvent: function(element, event, callBack){
        if (element.addEventListener) {
            element.addEventListener(event, callBack, false);
        } else {
            element.attachEvent('on' + event, callBack);
        }
    },

    unbindEvent: function(element, event, callBack){
        if (element.removeEventListener) {
            element.removeEventListener(event, callBack, false);
        } else if (element.detachEvent) {
            element.detachEvent('on' + event, callBack);
        }
    },

    bindAsEventListener: function (callBack) {
        var _object = this;
        return function(event) {
            return callBack.call(_object, event || window.event);
        }
    },
    
    stopEvent: function (event){
        if (event.preventDefault) {
            event.preventDefault();
            event.stopPropagation();
        } else {
            event.returnValue = false;
            event.cancelBubble = true;
        }
        return false;
    }
});
/**
 * Description
 *
 * @class Ria_Core_Rating_RatingBaseManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
*/
var Ria_Core_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 5px 0px 5px',
		'values'        : {1:'1 ball', 2:'2 ball',3:'3 ball', 4:'4 ball', 5:'5 ball'},
        'start'         : 0
	},
    
	initialize: function(options){
        this.setOptions(options);

        if ($defined(options.parentId) && $defined(options.fieldName) ){
            this.initializeRating();
        }
	},

    initializeRating: function(){
        var i = 0;
        $each(this.options['values'], function(title, value){
            var imgElement = new Element('img', {
                'src': (i<this.options['start'])?this.img_on: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']));
            i++;
        }.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));
    }

});
/**
 * Description
 *
 * @class Ria_Core_Rating_RatingViewManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
*/
var Ria_Core_Rating_RatingViewManager = 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',

	options: {
        'parentId'      : null,
        'padding'       : '0px 5px 0px 5px',
		'values'        : {1:'1 ball', 2:'2 ball',3:'3 ball', 4:'4 ball', 5:'5 ball'},
		'value'         : 0
	},
    
	initialize: function(options){
        this.setOptions(options);

        if ($defined(options.parentId)){
            this.initializeRating();
        }
	},

    initializeRating: function(){
        var viewTitle = this.options['values'][this.options['value']];
        $each(this.options['values'], function(title, value){
            var imgElement = new Element('img', {
                'src': (this.options['value']>=value) ? this.img_on : this.img_off,
                'styles': {
                    'padding': this.options['padding'],
                    'margin': '0px'
                },
                'title':viewTitle
            });
            imgElement.inject($(this.options['parentId']));

        }.bind(this));

    }

});
/**
 *
 * Общий класс для представления точки
 *
 * @class Ria_Core_Map_Main_Common_GeoPoint
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 */
 var Ria_Core_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);
	}

});
/**
 *
 * Абстрактный клас для событий. Имеет несколько базовых методов
 *
 * @class Ria_Core_Map_AbstractEvent
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 */


var Ria_Core_Map_AbstractEvent = new Class({

    /*
     * Устанавливает область карты, которая видна пользователю
     */
    setClientRectInObject : function(object,offset) {
    	var windowRect = riaMap.storage.map.getClientRectangle();
    	var zoom = riaMap.storage.map.getZoom();
    	offset = offset * (101-zoom);
    	object.zoom = zoom;
    	object.max_ltt = windowRect.max.getLatitude() + offset;
    	object.max_lngt = windowRect.max.getLongitude() + offset;
    	object.min_ltt = windowRect.min.getLatitude() - offset;
    	object.min_lngt = windowRect.min.getLongitude() - offset;
    	return object;
    },

	addMarkersFromResult : function(response) {
        $each(response, function(data, key){
            data.each(function(points){
                layerName = key + '_' + points.type_id;
                if(!$defined(riaMap.storage.layers)) {
                    riaMap.storage.layers = new Hash();
                }
                var layer = null;
                if(riaMap.storage.layers.has(layerName)) {
                    layer = riaMap.storage.layers.get(layerName);
                } else {
                    layer = new Ria_Core_Map_Main_Adapters_Layer();
                    riaMap.storage.layers.set(layerName, layer);
                    riaMap.storage.map.addLayer(layer);
                }
                points.points.each(function(point) {
                    if(key == 'local') {
                        this.placeLocalMarker(point, points, layer);
                    } else {
                        this.placeGlobalMarker(point, points, layer);
                    }
                }.bind(this));
                riaMap.storage.map.repaintMap();
            }.bind(this));
        }.bind(this));
	},

    placeLocalMarker : function(point,points,layer) {
        markerName = 'local_' + point.point_id + "_" + points.type_id;
        if(!$defined(riaMap.storage.markers)) {
            riaMap.storage.markers = new Hash();
        }
        if(!riaMap.storage.markers.has(markerName)) {
            var icon = points.icon;
            var marker = new Ria_Core_Map_Main_Adapters_Marker(
                new Ria_Core_Map_Main_Common_GeoPoint(point.longitude,point.latitude)
            );
            marker.setIcon(icon.width,icon.height,icon.src,icon.offset_x,icon.offset_y);
            marker.setName(point.name);
            marker.point_id = point.point_id;
            marker.type_id = points.type_id;
            marker.layers = new Array();
            marker.layers.include(points.type_id);

            riaMap.events.addEventListener(marker, "mouseclick",function() {
                if(marker.infoWindowHtml == '') {
                    this.onMarkerClick(marker);
                }
            }.bind(this));

            layer.addMarker(marker);
            riaMap.storage.markers.set(markerName,marker);
            if($defined(point.highlight)) {
                riaMap.storage.map.setCenter(marker.getGeoPoint());
                if(points.type_id == 0) {
                    riaMap.manager.showInGroup(point.point_id,point.highlightPointId,false);
                } else {
                    this.onMarkerClick(marker,true);
                }
            }
            if($defined(riaMap.storage.backToGroup)) {
//		    			alert(riaMap.storage.group_id);
                if(points.type_id == 0) {
                    if(point.point_id == riaMap.storage.group_id) {
                        riaMap.storage.log = "Found";
                        riaMap.storage.map.setCenter(marker.getGeoPoint());
                        this.onMarkerClick(marker,false);
                        delete riaMap.storage.backToGroup;
                    }
                }
            }
        } else {
            var temp_marker = riaMap.storage.markers.get(markerName);
            if(!temp_marker.layers.contains(points.layerName)) {
                layer.addMarker(temp_marker);
                temp_marker.layers.include(points.layerName);
            }
        }
    },

    placeGlobalMarker : function(point,points,layer) {
        markerName = 'global_' + point.point_id + "_" + points.type_id;
        if(!$defined(riaMap.storage.markers)) {
            riaMap.storage.markers = new Hash();
        }
        if(!riaMap.storage.markers.has(markerName)) {
            var icon = points.icon;
            var marker = new Ria_Core_Map_Main_Adapters_Marker(
                new Ria_Core_Map_Main_Common_GeoPoint(point.longitude,point.latitude)
            );
            marker.setIcon(icon.width,icon.height,icon.src,icon.offset_x,icon.offset_y);
            marker.setName(point.name);
            marker.point_id = point.point_id;
            marker.type_id = points.type_id;
            marker.layers = new Array();
            marker.layers.include(points.type_id);

            layer.addMarker(marker);
            riaMap.storage.markers.set(markerName,marker);
        } else {
            var temp_marker = riaMap.storage.markers.get(markerName);
            if(!temp_marker.layers.contains(points.layerName)) {
                layer.addMarker(temp_marker);
                temp_marker.layers.include(points.layerName);
            }
        }
    },

	onMarkerClick : function(marker,backward) {
        if ( riaMap.options.search.markerClickImpl ) {
            eval ( 'riaMap.manager.' + riaMap.options.search.markerClickImpl + '(' + marker.point_id + ');' );
        } else {
            var parametrs = riaMap.manager.makeGetParametrs('description');
            parametrs.id = marker.point_id;
            parametrs.is_group = ((marker.type_id == 0)? '1' : '0');
            if(backward) parametrs.backward = 1;
            riaMap.ajaxManager.htmlRequest(Ria_Core_Ajax.script,function(html) {
                if(marker.type_id == 0) {
                    var name = Lang.group_map_objects;
                } else {
                    var element = new Element('div').set('html',html);
                    var name = element.getElement('div').getElement('div').get('html');
                    element.getElement('div').getElement('div').destroy();
                    html = element.get('html');
                }
                marker.addInfoWindow(name,html);
                marker.openInfoWindow();
            }.bind(this),parametrs,true);
        }
	},

	clearMarkers : function() {
		if($defined(riaMap.storage.layers)) {
			riaMap.storage.layers.each(function(layer,key){
				layer.hide();
				layer.getMarkers().each(function(marker){
					layer.removeMarker(marker);
					marker.destruct();
				});
				riaMap.storage.map.removeLayer(layer);
			});
			riaMap.storage.layers = new Hash();
		}
    	riaMap.storage.markers = new Hash();
//    	riaMap.storage.map.repaintMap();
    }


});
 
/**
 * Class for ajax requests
 * 
 * @class      Ria_AjaxManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Revision: 1.7 $
 * @author     Sergiy Kukunin
 */
var Ria_AjaxManager = new Class({
	Implements: Options,
	
	options : {
		spinner : 'spinner'
	},
	
	initialize : function(options){
//		console.log('Ria_AjaxManager');
		this.setOptions(options);
		this.ajax;
	},
	
	jsonRequest : function(url,callback_func,getParametrs,is_cancel,extraOptions){
//		console.log('Ria_AjaxManager->jsonRequest');
		if(this.ajax && is_cancel) {
			this.ajax.cancel();
		}
		this.showSpinner(this.options.spinner);
		this.ajax = new Request.JSON({
			url: url, 
			onSuccess: function(data) {
				this.hideSpinner(this.options.spinner);
				callback_func(data,extraOptions);
			}.bind(this)
		}).get(getParametrs);
	},
	htmlRequest : function(url,callback_func,getParametrs,is_cancel,extraOptions){
//		console.log('Ria_AjaxManager->htmlRequest');
		if(this.ajax && is_cancel) {
			this.ajax.cancel();
		}
		this.showSpinner();
		this.ajax = new Request.HTML({
			url: url, 
			onSuccess: function(tree,list,html,js) {
				this.hideSpinner();
				callback_func(html,extraOptions);
			}.bind(this)
		}).get(getParametrs);
	},
	hideSpinner: function() {
//		console.log('Ria_AjaxManager->hideSpinner');
		if ($(this.options.spinner))	$(this.options.spinner).setStyle('display', 'none');
	},

	showSpinner: function(){
//		console.log('Ria_AjaxManager->showSpinner');
		if ($(this.options.spinner))	$(this.options.spinner).setStyle('display', 'block');
	}

});

/**
 * @class Ria_Points_AddPoint_BlockWorkTimeManager
*/

var Ria_Points_AddPoint_BlockWorkTimeManager = new Class({

    initialize: function(typeId, blockId)
    {
        this.typeId = typeId;
        this.blockId = blockId;

        this.addEvents();

        this.repaintAll();
    },

    addEvents:function(){
        $(this.typeId + ':' + this.blockId + ':0:0-0').addEvent('click', function() {
            this.repaintAll();
        }.bind(this));

        $(this.typeId + ':' + this.blockId + ':0:0-1').addEvent('click', function() {
            this.repaintAll();
        }.bind(this));

        $(this.typeId + ':' + this.blockId + ':1:0').addEvent('click', function() {
            this.checkEvent(1, $(this.typeId + ':' + this.blockId + ':1:0').checked);
        }.bind(this));

        $(this.typeId + ':' + this.blockId + ':2:0').addEvent('click', function() {
            this.checkEvent(2, $(this.typeId + ':' + this.blockId + ':2:0').checked);
        }.bind(this));

        $(this.typeId + ':' + this.blockId + ':3:0').addEvent('click', function() {
            this.checkEvent(3, $(this.typeId + ':' + this.blockId + ':3:0').checked);
        }.bind(this));
    },

    repaintAll:function(){
        if ($(this.typeId + ':' + this.blockId + ':0:0-0').checked){
            $(this.typeId + ':' + this.blockId + ':Monday').addClass('disabled');
            $(this.typeId + ':' + this.blockId + ':Saturday').addClass('disabled');
            $(this.typeId + ':' + this.blockId + ':Sunday').addClass('disabled');

            $(this.typeId + ':' + this.blockId + ':1:0').setProperty('disabled', 'true');
            $(this.typeId + ':' + this.blockId + ':2:0').setProperty('disabled', 'true');
            $(this.typeId + ':' + this.blockId + ':3:0').setProperty('disabled', 'true');
            
            this.checkEvent(1, false);
            this.checkEvent(2, false);
            this.checkEvent(3, false);
        } else {
            $(this.typeId + ':' + this.blockId + ':Monday').removeClass('disabled');
            $(this.typeId + ':' + this.blockId + ':Saturday').removeClass('disabled');
            $(this.typeId + ':' + this.blockId + ':Sunday').removeClass('disabled');

            $(this.typeId + ':' + this.blockId + ':1:0').removeProperty('disabled');
            $(this.typeId + ':' + this.blockId + ':2:0').removeProperty('disabled');
            $(this.typeId + ':' + this.blockId + ':3:0').removeProperty('disabled');

            this.checkEvent(1, $(this.typeId + ':' + this.blockId + ':1:0').checked);
            this.checkEvent(2, $(this.typeId + ':' + this.blockId + ':2:0').checked);
            this.checkEvent(3, $(this.typeId + ':' + this.blockId + ':3:0').checked);
        }
    },

    checkEvent:function(partId, status){
        if (status){
            $(this.typeId + ':' + this.blockId + ':' + partId + ':1').removeProperty('disabled');
            $(this.typeId + ':' + this.blockId + ':' + partId + ':2').removeProperty('disabled');
        } else {
            $(this.typeId + ':' + this.blockId + ':' + partId + ':1').setProperty('disabled', 'true');
            $(this.typeId + ':' + this.blockId + ':' + partId + ':2').setProperty('disabled', 'true');
        }
    }

});

/**
 * @class Ria_Points_AddPoint_BlockMarkaManager
*/

var Ria_Points_AddPoint_BlockMarkaManager = new Class({

    initialize: function(typeId, blockId)
    {
        this.typeId = typeId;
        this.blockId = blockId;

        this.addSelectAllEvent();

        this.repaintAll();
    },

    addSelectAllEvent:function(){
        $(this.typeId + ':' + this.blockId + ':all_vehicles').addEvent('click', function() {
            this.repaintAll();
        }.bind(this));

    },

    repaintAll:function(){
        if ( $(this.typeId + ':' + this.blockId + ':all_vehicles').checked ) {
            $(this.typeId + ':' + this.blockId + ':inputs_div').addClass('disabled');

            $(this.typeId + ':' + this.blockId + ':inputs_div').getElements('input').each(function(item, index){
                item.setProperty('disabled', 'true');
                if (item.getAttribute('class')=='make') item.setProperty('checked', 'checked');
                else item.removeProperty('checked');
            });

        } else {
            $(this.typeId + ':' + this.blockId + ':inputs_div').removeClass('disabled');

            $(this.typeId + ':' + this.blockId + ':inputs_div').getElements('input').each(function(item, index){
                item.removeProperty('disabled');
                item.removeProperty('checked');
            });

        }
    },

    officialEvent:function(markaId){
        if ( $(this.typeId + ':' + this.blockId + ':' + markaId + ':1').checked ) $(this.typeId + ':' + this.blockId + ':' + markaId + ':0').setProperty('checked', 'true');
    },

    noOfficialEvent:function(markaId){

        if ( !$(this.typeId + ':' + this.blockId + ':' + markaId + ':0').checked ) $(this.typeId + ':' + this.blockId + ':' + markaId + ':1').removeProperty('checked');
    }

});

/**
 * @class Ria_Points_AddPoint_BlockStoUslugiCost
 * @license    GNU GPL v2
 * @version    $Id: AddPoint_BlockStoUslugiCost.js,v 1.0 2009/10/14 11:15:11 avi Exp $
*/
var Ria_Points_AddPoint_BlockStoUslugiCost = new Class({

    'prefix'		: 'service_',
    'add_prefix'	: 'add_',
    'remove_prefix'	: 'remove_',
    'add_class'		: '.service-add',
    'remove_class'	: '.service-remove',
    'clone_div_class'	: '.services',
    'parent_id'		: 'services_list',
    'select_name_class' : '.select_serv',
    'text_name_class'	: '.text_serv',

    initialize: function(type_id, block_id)
    {
        this.type_id = type_id;
        this.block_id = block_id;

        this.max_size = $$(this.select_name_class)[0].length-1;
        this.elem = $(this.prefix+0).clone();
        this.addEvents();
    },
    
    renameIDs: function() {
        $$(this.add_class).each(function(item, index){
            item.id=this.add_prefix+index;
        }.bind(this));
        $$(this.remove_class).each(function(item, index){
            item.id=this.remove_prefix+index;
        }.bind(this));
        $$(this.clone_div_class).each(function(item, index){
            item.id=this.prefix+index;
        }.bind(this));
        $$(this.select_name_class).each(function(item, index){
            item.name='pointValues['+this.type_id+']['+this.block_id+']['+index+'][0]';
        }.bind(this));
        $$(this.text_name_class).each(function(item, index){
            item.name='pointValues['+this.type_id+']['+this.block_id+']['+index+'][1]';
        }.bind(this));
	},

    addSelect: function() {
        if (!this.stop){
            var newElement = this.elem.clone();
            newElement.inject(this.parent_id);
            this.renameIDs();
            this.addEvents();
        }
	},

    removeSelect: function(id) {
        var delElement = $(this.prefix+id);
        delElement.dispose();
        this.renameIDs();
        this.addEvents();
	},

    addEvents:function(){
        $$(this.add_class).removeEvents();
        $$(this.add_class).addEvent('click', function(){
            this.addSelect();
        }.bind(this));

        $$(this.remove_class).removeEvents();
        $$(this.remove_class).each(function(item, index){
            item.id=this.remove_prefix+index;
            item.addEvent('click', function(){
                if ($$(this.remove_class).length !=1)
                    this.removeSelect(index);
            }.bind(this));
        }.bind(this));
        if ($$(this.add_class).length >= this.max_size) this.stop = 1;
        else this.stop = 0;
    }
});

/**
 * @class Ria_Points_AddPoint_BlockStoUslugiCost
 * @license    GNU GPL v2
 * @version    $Id: AddPoint_BlockStoUslugiCost.js,v 1.0 2009/10/14 11:15:11 avi Exp $
*/
var Ria_Points_AddPoint_BlockPhones = new Class({

    initialize: function(type_id, block_id)
    {
        this.type_id = type_id;
        this.block_id = block_id;

        this.clone_div_class =      '.phone_li_' + type_id;
        this.prefix =               'phone_li_' + type_id + '_';
        this.parent_id =            'phone_list_' + type_id;
        this.phone_code_class =     '.phone_code_' + type_id;
        this.phone_number_class =   '.phone_number_' + type_id;

        this.add_prefix =           'phone_add_' + type_id + '_';
        this.remove_prefix =        'phone_remove_' + type_id + '_';
        this.add_class =            '.phone-add_' + type_id;
        this.remove_class =         '.phone-remove_' + type_id;


        this.max_size = 5;
        this.elem = $(this.prefix + 0).clone();
        this.addEvents();
    },
    
    renameIDs: function() {
        $$(this.add_class).each(function(item, index){
            item.id=this.add_prefix+index;
        }.bind(this));
        $$(this.remove_class).each(function(item, index){
            item.id=this.remove_prefix+index;
        }.bind(this));
        $$(this.clone_div_class).each(function(item, index){
            item.id=this.prefix+index;
        }.bind(this));
        $$(this.phone_code_class).each(function(item, index){
            item.name='pointValues['+this.type_id+']['+this.block_id+']['+index+'][0]';
        }.bind(this));
        $$(this.phone_number_class).each(function(item, index){
            item.name='pointValues['+this.type_id+']['+this.block_id+']['+index+'][1]';
        }.bind(this));
	},

    addPhone: function() {
        if (!this.stop){
            var newElement = this.elem.clone();
            newElement.inject(this.parent_id);
            this.renameIDs();
            this.addEvents();
        }
	},

    removePhone: function(id) {
        var delElement = $(this.prefix+id);
        delElement.dispose();
        this.renameIDs();
        this.addEvents();
	},

    addEvents:function(){
        $$(this.add_class).removeEvents();
        $$(this.add_class).addEvent('click', function(){
            this.addPhone();
        }.bind(this));

        $$(this.remove_class).removeEvents();
        $$(this.remove_class).each(function(item, index){
            item.id=this.remove_prefix+index;
            item.addEvent('click', function(){
                if ($$(this.remove_class).length !=1)
                    this.removePhone(index);
            }.bind(this));
        }.bind(this));
        if ($$(this.add_class).length >= this.max_size) this.stop = 1;
        else this.stop = 0;
    }
});

/**
 *  DOM-
 *
 * parentId - id   
 * dontReset - 1:  
 * selectZeroValue -     
 * injectBefore - id       
 * idRegexp -    id-  ( : id_0,  0  )
 * nameRegexp -    name-  ( : name[1][2][3][4],  3  )
 * renameNames - 1:  name-
 * maxEls -  - 
 * firstInvisible - -    (firstRemove - id , removeClass -   "")
 * 
 * @class       Ria_Common_Cloner
 * @copyright   2010 IT*RIA
 * @license     GNU GPL v2
 *
*/
var Ria_Common_Cloner = new Class ({
    Implements: Options,

    options: {
        parentId:'parent_0',
        dontReset:0,
        selectZeroValue:' ------- ',
        injectBefore:'end',
        idRegexp:/(\S+_)(\d+)/,
        nameRegexp:/(\S+\[)(\d+)(\][\[\d+\]]{3})/,
        renameNames:0,
        countEls:1,
        maxEls:5,
        firstInvisible:0,
        firstRemove:'remove_0',
        removeClass:'service-remove'
    },

    initialize: function(options){
        this.setOptions(options);
        this.regexpId = new RegExp(this.options.idRegexp);
        this.regexpName = new RegExp(this.options.nameRegexp);
        this.parentClassName = $(this.options.parentId).className;
        this.cloned = $(this.options.parentId).cloneNode(true);
    },

    cloneIt: function(){
        if (this.options.countEls < this.options.maxEls){
            this._cloneElement();
            this._renameElements();
            if(this.options.firstInvisible) $$('.'+this.options.removeClass).setStyle('display','inline-block');
        }
    },

    deleteIt: function(id){
        if (this.options.countEls > 1) {
            $(id).destroy();
            this._renameElements();
            this.options.countEls--;
        }
        if(this.options.firstInvisible && this.options.countEls==1){
            $(this.options.firstRemove).setStyle('display','none');
        }
    },

    _cloneElement: function(){
        var newElement = this.cloned.cloneNode(true);
        if (!this.options.dontReset) newElement = this._resetValues(newElement);
        newElement.injectBefore($(this.options.injectBefore));
        this.options.countEls++;
    },

    _renameElements: function(){
        $$('.'+this.parentClassName.split(' ')[0]).each(function(Elem, ind){
            //replace
            Elem.id=Elem.id.match(this.regexpId)[1]+ind;
            var elements = Elem.getElementsByTagName('*');
            for (var i=0; i<elements.length; i++){
                if (elements[i].id){
                    var matches = elements[i].id.match(this.regexpId);
                    elements[i].id=matches[1]+ind;
                    if (this.options.renameNames && elements[i].name){
                        var namesMatches = elements[i].name.match(this.regexpName);
                        if (namesMatches) elements[i].name = namesMatches[1]+ind+namesMatches[3];
                    }
                }
            }
        }.bind(this));
    },

    _resetValues: function(element){
        var elements = element.getElementsByTagName('*');
        for (var i=0; i<elements.length; i++){
            //  <SELECT>
            if (elements[i] == '[object HTMLSelectElement]'){
                // $$
                var optionsElements = elements[i].getElementsByTagName('option');
                var flag = false;
                for (var j=0; j<optionsElements.length; j++) if (optionsElements[j] && optionsElements[j].value == 0) flag = true;
                if (!flag) elements[i].innerHTML = '<option value="0">'+this.options.selectZeroValue+'</option>';
            }
            if (elements[i] == '[object HTMLOptionElement]'){
                if (elements[i].value==0) elements[i].selected = true;
                else elements[i].selected = false;
            }
            //  <INPUT>
            //tagName
            if (elements[i] == '[object HTMLInputElement]') elements[i].value = '';
        }
        return element;
    }
});
/**
 * Description
 *
 * @class Ria_Compare_CompareManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
*/
var Ria_Compare_CompareManager = new Class({

    Implements: Options,

	options: {
        'tableId'       : null,
        'fieldName'     : null,
        'padding'       : '0px 5px 0px 5px',
		'values'        : {1:'1 ball', 2:'2 ball',3:'3 ball', 4:'4 ball', 5:'5 ball'}
	},
    
	initialize: function(options){
//
//        if ($defined(options.parentId) && $defined(options.fieldName) ){
//            this.initializeRating();
//        }
        this.setOptions(options);
	},
    
    removeCar: function(auto_id){
        $(this.options['tableId']).getElements('tr').each(function(tr) {
            var tds = tr.getElements('td');
            tr.getElements('td').each(function(td, index) {
                if ( index > 0 ) {
                   td.setProperty('name','column_'+(index-1));
                }
            }.bind(this));
        }.bind(this));

        var column_index = parseInt($('compareDeleteForm_'+auto_id).getParent().getProperty('name').replace('column_',''));

        $(this.options['tableId']).getElements('tr').each(function(tr) {
           var tds = tr.getElements('td');
           if ( tds.length < 2 ) {
               tds[0].setProperty('colspan',tds[0].getProperty('colspan')-1);
           } else {
               tds.each(function(td, index) {
                   if ( index == column_index+1 ) {
                       td.destroy();
                   }
               }.bind(this));
               tr.getElements('td').each(function(td, index) {
                   if ( index > 0 ) {
                       td.setProperty('name','column_'+(index-1));
                   }
               }.bind(this));
           }
        }.bind(this));
    }
});
/**
 * Loading Prototipes Versions In Select
*
* @class Ria_Points_GetCommentsForm
* @copyright  2009 IT RIA
* @license    GNU GPL v2
* @version    ID:
*/
var Ria_Points_GetCommentsForm = new Class({
	initialize: function(parent, subscribe, target, action, parentId, reviewId, pointItemId, level, commentText){
        if ($$('.form-addComment')) $$('.form-addComment').destroy();
//        if ($('commentForm')) $('commentForm').destroy();
        var divE = new Element('div', {'class':'form-addComment'});
        var ddsE = new Element('dd', {'class':'text-r'});
        var ddE = new Element('dd');
        var dlE = new Element('dl');
        var formE = new Element('form', {'method':'post', 'id':'commentForm'});
        new Element('input', {
            'type':'hidden',
            'name':'target',
            'value':target
        }).inject(formE);
        new Element('input', {
            'type':'hidden',
            'name':'subscribe',
            'value':subscribe
        }).inject(formE);
        new Element('input', {
            'type':'hidden',
            'name':'action',
            'value':action
        }).inject(formE);
        new Element('input', {
            'type':'hidden',
            'name':'parentId',
            'value':parentId
        }).inject(formE);
        new Element('input', {
            'type':'hidden',
            'name':'reviewId',
            'value':reviewId
        }).inject(formE);
        new Element('input', {
            'type':'hidden',
            'name':'pointItemId',
            'value':pointItemId
        }).inject(formE);
        new Element('input', {
            'type':'hidden',
            'name':'level',
            'value':level
        }).inject(formE);
        new Element('textarea', {
            'name':'commentText',
            'html':commentText
        }).inject(ddE);
        ddE.inject(dlE);
        new Element('input', {
            'type':'submit',
            'class':'submit-x24 green-add-220 bold',
            'value':' ',
            'styles':{'float':'right'}
        }).inject(ddsE);
        ddsE.inject(dlE);
        dlE.inject(formE);
        formE.inject(divE);
        divE.inject($(parent));
	}
});
/* 
 *
 * @class Ria_Auto_Generic_SearchChooseTop
 * @copyright  2012 RIA.ua
 * @license    GNU GPL v3
 */

var Ria_Auto_Generic_SearchChooseTop = new Class({
            
    initialize : function(){
        
        
        this.cookieName = 'searchMode';    
        this.setupEvents();
                    
        if(Cookie.read('searchMode') == "old"){
            $('oldAutosSearchTop').fireEvent('change');
            $("item-1-top").setAttribute("checked", true);
        }
        if(Cookie.read('searchMode') == "new"){
            $('newAutosSearchTop').fireEvent('change');
            $("item-2-top").setAttribute("checked", true);
        }
                    
                
    },
            
    switchMyElements: function(idToHide, idToShow){
        if($(idToHide).hasClass('hide') || $(idToShow).hasClass('hide')){
                    
            $(idToHide).addClass('hide');
            $(idToHide).getElement('select').setAttribute('disabled', 'true');
                            
            $(idToShow).removeClass('hide');
            $(idToShow).getElement('select').removeProperty('disabled');
        }
    }.bind(this),
                
    setupEvents: function(){
                
                
        //elements to TOGGLE
        var switchItemsOld = ['oldHiddens'];
        var switchItemsNew = ['newHiddens'];
                
        //elemnts to HIDE
        var elementsChangable = ['yearsProductionsTop','photoTop']; 
                 
        $('oldAutosSearchTop').addEvent('change', function(){
            var myCookie = Cookie.write(this.cookieName, "old");    
                        
            elementsChangable.each(function(item) {
                $(item).removeClass('hide');
            });
                    
            this.switchMyElements('newMarkToggleTop',  'oldMarkToggleTop');
            this.switchMyElements('newModelToggleTop',  'oldModelToggleTop');
            this.switchMyElements('newRegionToggleTop',  'oldRegionToggleTop');
                    
                    
//            $('searchMaster').addClass('hide');
            
            $('advSearchTop').removeClass('hide');
            if( $('advSearchNewTop')) $('advSearchNew').addClass('hide');
                        
            $('hiddensParamsTop').getElement('input[name=target]').set('value', 'search');
            $('hiddensParamsTop').getElement('input[name=event]').set('value', 'little');
                    
            $('boxpanelZone0').set('action', '.');
                            
        }.bind(this));
                    
        $('newAutosSearchTop').addEvent('change', function(){
            var myCookie = Cookie.write(this.cookieName, "new");    
                        
            elementsChangable.each(function(item) {
                $(item).addClass('hide');
            });
                    
            this.switchMyElements('oldMarkToggleTop', 'newMarkToggleTop');
            this.switchMyElements('oldModelToggleTop', 'newModelToggleTop');
            this.switchMyElements('oldRegionToggleTop', 'newRegionToggleTop');
                    
                        
            $('hiddensParamsTop').getElement('input[name=target]').set('value', 'new');
            $('hiddensParamsTop').getElement('input[name=event]').set('value', 'view');
            
            $('boxpanelZone0').set('action', './newauto/search');
                    
            if($('advSearchNewTop')){
                $('advSearchNewTop').removeClass('hide');
            }
            $('advSearchTop').addClass('hide');
                    
        }.bind(this));
                    
                    
    }
                
            
                
});
/**
 *
 * @class      Ria_Auto_Generic_TabSwitcher_RequestSearchUrlParams
 * @copyright  2012 IT RIA.ua
 * @license    GNU GPL v2
 */



var Ria_Auto_Generic_TabSwitcher_RequestSearchUrlParams = new Class({
    
    Implements: Options,
    options: {
        paramNames: ['category', 'marka', 'model', 'state'],
        mainParams: ['category', 'marka']
    },

    params: {},
    mainParams: {},
        
    initialize: function(options){
        this.setOptions(options);
    },
    
    setParams: function(params){
        $each(params, function(item, index) {
            if(this.options.paramNames.indexOf(index) != -1){
                this.params[index] = item;
            }
            if(this.options.mainParams.indexOf(index) != -1){
                this.mainParams[index] = item;
            }
        }.bind(this))
    },
    
    getParams: function(){
        return this.params;
    },
    
    getMainParams: function(){
        return this.mainParams;
    }

});


/**
 *
 * @class      Ria_Auto_Generic_TabSwitcher_SetCheckedQuickSearch
 * @copyright  2012 IT RIA.ua
 * @license    GNU GPL v2
 */



var Ria_Auto_Generic_TabSwitcher_SetCheckedQuickSearch = new Class({
    
    Implements: Options,
    options: {
        params:     {'marka': '0', 'model': '0', 'state': '0'},
        elementsId: {'marka': 'marka_top_id', 'model': 'model_top_id', 'state': 'city_left_id'}
    },

    initialize: function(options){
        
        this.setOptions(options);
        
        Object.each(this.options.params.params, function(value, key){
            if($defined(this.options.elementsId[key])){
                $(this.options.elementsId[key]).set('value', value);
            }
        }.bind(this))
        
    }
    

});


/**
 *
 * @class      Ria_Auto_Generic_TabSwitcher_CloseMenuAllOver
 * @copyright  2012 IT RIA.ua
 * @license    GNU GPL v2
 */



var Ria_Auto_Generic_TabSwitcher_CloseMenuAllOver = new Class({

    over: false,
    
    setOver: function(over){
        this.over = over;
    },

    getOver: function(){
        return this.over;
    }

});


/**
 *
 * @class Ria_Auto_Generic_TabSwitcher_QuickSearch
 * @copyright  2012 IT RIA.ua
 * @license    GNU GPL v2
 */



var Ria_Auto_Generic_TabSwitcher_QuickSearch = new Class({
    
    Implements: Options,
    
    closeMenuAllOver: null,
    
    options: {
        requestSearchUrl          : '/static/target/common/event/throughSearch/',
        requestSearchUrlParamsObj : null,
        requestConteinerId        : 'through-search'
    },
        
    initialize: function(options){
        
            this.closeMenuAllOver = options['closeMenuAllOver'];
            delete options['closeMenuAllOver'];
        
            this.setOptions(options);
            this.SearchUrl = this.getSearchParams();
            this.mainSearchParams = this.getMainSearchParams();
            if (this.checkIsLoaded() == '' || this.checkIsLoaded() != this.mainSearchParams) {
                this.processRequest();
            } else if(this.checkLoadedParams() != this.SearchUrl && this.checkIsLoaded() == this.mainSearchParams){
                this.setloadedParams();
                new Ria_Auto_Generic_TabSwitcher_SetCheckedQuickSearch({params : this.options.requestSearchUrlParamsObj});
            }
    },
    
    
    checkIsLoaded : function() {
        return $(this.options.requestConteinerId).getElement('.wrapper').get('isLoaded');
    },
    checkLoadedParams : function() {
        return $(this.options.requestConteinerId).getElement('.wrapper').get('loadedParams');
    },
    
    getSearchParams: function(){
        return Hash.toQueryString(this.options.requestSearchUrlParamsObj.getParams());
    }, 
    
    getMainSearchParams: function(){
        return Hash.toQueryString(this.options.requestSearchUrlParamsObj.getMainParams());
    }, 
    
    processRequest : function() {
        var requestSearchUrl = this.options.requestSearchUrl + '&' + this.SearchUrl;
        var searchWrapper = $('through-search').getElement('.wrapper');
        var requestSearch = new Request.HTML({
                url: requestSearchUrl,
                method: 'get',
                evalScripts: false,
                onRequest: function(){
                        searchWrapper.set('html', '<div class="pop-up-loader hide" id="quick-search-loader" style="min-height: 150px;"></div>');
                    },
                onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
                    searchWrapper.set('html', responseHTML);
                    this.setupEvents(searchWrapper);
                    new Ria_Auto_Generic_SearchChooseTop();
                    this.setLoaded();
                    this.setloadedParams();
                }.bind(this),
                onFailure: function(){
                    searchWrapper.set('text', 'Sorry, your request failed :(');
                }
        })
        
        requestSearch.send();
        
    },
    
    setLoaded : function() {
        $(this.options.requestConteinerId).getElement('.wrapper').set('isLoaded', this.mainSearchParams);
    },
    
    setloadedParams: function(){
        $(this.options.requestConteinerId).getElement('.wrapper').set('loadedParams', this.SearchUrl);
    },
    
    setupEvents: function(searchWrapper){
        searchWrapper.getElements('select').each(function(item){
            item.addEvents({
                focus: function(){
                    this.closeMenuAllOver.setOver(true);
                }.bind(this),
                mouseover: function(){
                    this.closeMenuAllOver.setOver(true);
                }.bind(this),
                blur: function(){
                    this.closeMenuAllOver.setOver(false);
                }.bind(this),
                mouseout: function(event){
                    Event.stop(event);
                    this.closeMenuAllOver.setOver(false);
                }.bind(this)
            })
        }.bind(this));
    }

});


/**
 * 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_Core_Ajax
 */

var Ria_Core_Ajax_JsonRequest = new Class({

	Implements: Options,
	
	options: {
		target: 'main',
		event: ''
	},

	/**
	 * @raram {Array} options параметры для построения запроса
	 */
	initialize: function(options){
		this.setOptions(options);
		new Request.JSON({url: Ria_Core_Ajax.script,
			onComplete: this.onGetResponse.bind(this)
		}).get(this.options);
	},
	
	/**
	 * Метод, который будет выполнен после получения
	 * ответа на Ajax-запрос.
	 * Вам  нужно его переопредплить.
	 * 
	 * @param {Object} jsonObj Объект с данными из JSON-ответа
	 */
	onGetResponse: function(jsonObj) {}
});

/**
 * Loading Prototipes Versions In Select 
*
* @class Ria_NewAutoSalon_ModelRequest
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax_JsonRequest
* @requires   Ria_Core_Common_StatusImageManager
*/
var Ria_NewAutoSalon_ModelRequest = new Class({

	Extends: Ria_Core_Ajax_JsonRequest,
    
	options: {
		target: 	'salonAuto',
		event:		'getSalonAutoModel'
	},
    
	initialize: function(options)
    {
		options.marka_id = $(options.marka_element).value;
		if (options.marka_id > 0){
			$(options.model_element).length = 1;
            $(options.model_element).setProperty('disabled', 'true');

            if (options.complete_element){
                $(options.complete_element).length = 1;
                $(options.complete_element).setProperty('disabled', 'true');
            }

			//new Ria_Core_Common_StatusImageManager('prototype_tr', 'spinner', false);
			this.parent(options);
		} else {
            $(options.model_element).length = 1;
            //$(options.model_element).setProperty('disabled', 'true');
            if (options.complete_element){
                $(options.complete_element).length = 1;
                //$(options.complete_element).setProperty('disabled', 'true');
            }
        }
	},
    
	onGetResponse: function(jsonObj)
    {
		this.json = jsonObj;
		//new Ria_Core_Common_StatusImageManager('prototype_tr', 'check', false);
		if (this.json.result){
            var model_element = $(this.options.model_element);
            model_element.empty();
            
			new Element('option', {'value': 0, 'text':this.json.any_model}).inject(model_element);
            
			$each(this.json.modelArr, function(item, index){
				new Element('option', {'value': index, 'text': item}).inject(model_element);
			}, this);
            model_element.removeProperty('disabled');
            
            if (this.options.complete_element) $(this.options.complete_element).removeProperty('disabled');
		}
	}

});
/**
 * Ajax запрос который вытягивает   
 *
 * @class Ria_Common_CitiesRequest
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Core_Ajax_JsonRequest
*/
var Ria_Common_CitiesRequest = new Class({
	
	Extends: Ria_Core_Ajax_JsonRequest, 
	
	options: {
		target: 	'location',
		event: 		'getCities'
	},

	initialize: function(options){
		if ($defined(options.city_element_id))
		{
			options.state_id=$(options.obl_element_id).value;
			
			var select = $(options.city_element_id);
			select.empty();
			new Element('option',{value: 0}).inject(select).set({'text':''});
			select.set('disabled', true);
			select.setProperty('class', 'select_during_loading');
			this.parent(options);
		} else {
			alert('Error: not set Cities Id');
		}
	},
    
	onGetResponse: function(jsonObj) {
        this.citiesArray = new Hash();
        
		this.json = jsonObj;
		if (jsonObj.result>0){
			if ($defined(this.options.city_element_id)) {
				
				var select = $(this.options.city_element_id);
				select.empty();
				if (!$defined(this.options.city_id)) {
					this.options.city_id = this.options.state_id;
				}
                new Element('option', {'value': 0, 'text':this.json.any_city}).inject(select);
                $each(this.json.cities, function(item, index){
					var element = new Element('option', { 'value': index});

					if (index == this.options.city_id) {
						element.set('selected', true);
                        if (this.options.with_map && this.options.map_name){
                            this.setMapPosition(this.json.mapsCities[index].geo_X, this.json.mapsCities[index].geo_Y);
                        }
					}
                    
					element.inject(select).set('text', item);

                    if (this.options.with_map && this.options.map_name){
                        if (this.json.mapsCities[index])
                            this.citiesArray.set(index, new Hash({'x':this.json.mapsCities[index].geo_X, 'y':this.json.mapsCities[index].geo_Y}));
                    }

				}, this );

                select.addEvent('change', function(){
                    if (this.citiesArray[select.value]) this.setMapPosition(this.citiesArray[select.value]['x'], this.citiesArray[select.value]['y']);
                }.bind(this));

                select.set('disabled', false);
                select.removeProperty('class');
			}
		} else if (this.options.city_id!=0){
			alert(Lang.error);
		}
	},

    setMapPosition:function(geo_x, geo_y){
        if (this.options.with_map && this.options.map_name) {
            eval('var mapObject = window.'+this.options.map_name+';');
            eval('var placemarkObject = window.'+this.options.placemark_name+';');

            centerPoint = new YMaps.GeoPoint(geo_x, geo_y);
            placemarkObject.setGeoPoint(centerPoint);
            mapObject.setCenter(centerPoint, 11);
        }
    }
	
});

/**
 * Loading Prototipes Versions In Select 
*
* @class Ria_Spares_SparesRequest
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax_JsonRequest
*/
var Ria_Spares_SparesRequest = new Class({

	Extends: Ria_Core_Ajax_JsonRequest,
    
	options: {
            target: 	'spares',
            event:	'getSpares'
	},

	initialize: function(options){
            options.group_id = $(options.group_element).value;
            if (options.group_id > 0) {
                $(options.spares_element).empty();
                $(options.spares_element).setProperty('disabled', 'true');
                $(options.spares_element).setProperty('class', 'select_during_loading');
                this.parent(options);
            } else {
                $(options.spares_element).length = 1;
            //$(options.model_element).setProperty('disabled', 'true');
            }
	},
    
	onGetResponse: function(jsonObj) {

            new Element('option', {'value': 0, 'text':jsonObj.any}).inject($(this.options.spares_element));
            $each(jsonObj.treeSpares, function(item, index){
                var element = new Element('option', { 'value': item.id});
                element.inject($(this.options.spares_element)).set('text', item.name);
            }, this );
            $(this.options.spares_element).removeProperty('disabled');
            $(this.options.spares_element).removeProperty('class');
	}
});
/**
* Loading search string like elements to drop list
*
* @class Ria_Points_SearchFieldRequest
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax_JsonRequest
*/
var Ria_Points_SearchFieldRequest = new Class({
	Extends: Ria_Core_Ajax_JsonRequest,

    options: {
		target: 	'autoservice',
		event:		'searchField',
                core_rewrite_off: 1
	},

	initialize: function(options){
        options.fieldVal = options.field.value;
        options.fieldId = options.field.id;

        if (options.fieldVal.length>=1) this.parent(options);
        else $('dropBox').setStyle('display','none');
	},
    
	onGetResponse: function(jsonObj){
        this.json=jsonObj;
        inc=0;
        if (this.json.result){
            $('dropBox').empty();
            $('dropBox').style.display='inline-block';
            var oldCount=0;
            var first=true;
            $each(this.json.answer,function(item,index){
                if (first) first=false
                else if (item.length && oldCount) new Element('hr').inject($('dropBox'));
                
                switch(index){
                    case "options": type=0; break
                    case "cities": type=''; break;
                    case "markas": type=''; break;
                }

                $each(item,function(dropItem){
                    if (!type) type=dropItem.Auto4Points_SpecTypeBlockDBO.Auto4Points_SpecTypeDBO[0].typeName;
                    new Element('div',{
                        'class':'searchDropElement',
                        'id':'searchDropElement_'+inc,
                        'html':'<span style="float:left; display:inline-block;" id="dropId_'+inc+'">'+dropItem.text+'</span>\
                                 <span style="color:#25AD00;float:right;">'+type+'</span><br/>',
                        'events':{
                            'click':function(){
                                var str='';
                                if (Cookie.read('searchStr')!='undefined' && $(this.json.fieldId).value.indexOf(' ')>0)
                                    str = Cookie.read('searchStr');
                                $(this.json.fieldId).value = str + dropItem.text;
                                $('dropBox').style.display='none';
                            }.bind(this)
                        }
                    }).inject($('dropBox'));
                    inc++;
                },this);
                oldCount=item.length;
            },this);
            if ($$('.searchDropElement').length<1) $('dropBox').style.display='none';
            //    ,    .
            if (first) $('dropBox').style.display='none';
        }
	}

});
/**
 * Loading Prototipes Versions In Select
*
* @class Ria_Points_ReviewVoteRequest
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax_JsonRequest
*/
var Ria_Points_ReviewVoteRequest = new Class({
	Extends: Ria_Core_Ajax_JsonRequest,
	options: {
		target: 	'autoservice',
		event:		'vote',
                core_rewrite_off: 1
	},
	initialize: function(options){
        options.believeCount = $('believe_'+options.id).innerHTML;
        options.unbelieveCount = $('unbelieve_'+options.id).innerHTML;
        this.parent(options);
	},
	onGetResponse: function(jsonObj) {
		this.json = jsonObj;
		if (this.json.result){
            $('ref1_'+jsonObj.id).addClass('disable');
            $('ref2_'+jsonObj.id).addClass('disable');
            if (jsonObj.vote==1) $('believe_'+jsonObj.id).innerHTML = jsonObj.believeCount;
            else $('unbelieve_'+jsonObj.id).innerHTML = jsonObj.unbelieveCount;
		}
	}
});
/**
* Subscribe for point reviews
*
* @class Ria_Points_SubscribeRequest
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax_JsonRequest
*/
var Ria_Points_SubscribeRequest = new Class({
	Extends: Ria_Core_Ajax_JsonRequest,
	options: {
		target: 	'autoservice',
		event:		'subscribe',
                core_rewrite_off: 1
	},
	initialize: function(options){
        this.parent(options);
	},
	onGetResponse: function(jsonObj) {
		this.json = jsonObj;
		if (this.json.result)
            $('reviews_subscribe').innerHTML = '    ';
	}
});
/**
 * @class Ria_NewAutoSalon_BuyFormManager
 * @requires Ria_Core_Ajax
 * @requires Ria_Core_Common_StatusImageManager
*/

var Ria_NewAutoSalon_BuyFormManager = new Class({

    validate: true,

    validate_options: [],

    initialize: function(completeId)
    {
        this.completeId = completeId;

        $('consult_link_' + this.completeId).addEvent('click', function(){
            this.change_div_visible(1);
            this.setupValidator(['buy_form_name_', 'buy_form_phone_', 'buy_form_message_']);
        }.bind(this));

        $('buy_link_' + this.completeId).addEvent('click', function(){
            this.change_div_visible(0);
            this.setupValidator(['buy_form_name_', 'buy_form_phone_', 'buy_form_message_']);
        }.bind(this));

    },

    change_div_visible: function(type){
        if ($defined($('drive_div_' + this.completeId))) $('drive_div_' + this.completeId).setStyle('display', 'none');
        var div = $('buy_div_' + this.completeId);
        if(div.getStyle('display') == 'none' || type != this.type) {
            var form = $('buy_form_' + this.completeId);
            this.formClear(form);
            if (type){
                $('formMessage_' + this.completeId).innerHTML = '<span style="color:#f00">*</span> :';
                if ($('formName_' + this.completeId))
                    $('formName_' + this.completeId).innerHTML = ' ';
                $('formTheme_' + this.completeId).value = 1;
                this.type = type;
            } else {
                $('formMessage_' + this.completeId).innerHTML = '<span style="color:#f00">*</span>:';
                if ($('formName_' + this.completeId))
                    $('formName_' + this.completeId).innerHTML = '';
                $('formTheme_' + this.completeId).value = '';
                this.type = type;
            }
            this.setFormSubmit();
            div.setStyle('display', 'block');
        } else {
            div.setStyle('display', 'none');
        }
    },

    setupValidator: function(options){
        this.validate = true;
        this.validate_options = options;
    },

    setFormSubmit: function (){

        var form = $('buy_form_' + this.completeId);

        form.removeEvents('submit');
        form.addEvent('submit', function(e) {
            e.stop();
            if (this.validate && !this.isformValid()) {
                alert('   !      .');
                return false;
            }
            
            form.set('send', {
                url: Ria_Core_Ajax.script,
                method: 'post',
                onComplete: function(response) {
                    var div = $('buy_div_' + this.completeId);
                    div.empty();
                    div.addClass('success');
                    div.set('html', '      .');
                }.bind(this)
            });
            form.send();
            new Ria_Core_Common_StatusImageManager('buy_div_' + this.completeId, 'spinner', false);
        }.bind(this));
    },

    isformValid: function (){
        var valid = true;
        
        this.validate_options.each(function(element){
            $(element + this.completeId).value = $(element + this.completeId).value.trim();
            if ( !$chk($(element + this.completeId).value.trim())){
                $(element + this.completeId + '_err').addClass('attention');
                valid = false;
            } else {
                $(element + this.completeId + '_err').removeClass('attention');
            }
        }.bind(this));
        return valid;
    },

    formClear: function (obj) {

        if(!$defined($('not_clear'))) {

            var elements = obj.getChildren();
            elements.each(function (element) {
                this.formClear(element);
                switch (element.get('tag')){
                    case 'input':
                        switch (element.getProperty('type')){
                            case 'checkbox':
                                element.setProperty('checked', false);
                            case 'text':
                                if (element.getProperty('name') != 'date')
                                    element.setProperty('value', '');
                        }
                        break;
                    case 'textarea':
                        element.setProperty('value','');
                        break;
                }
            }.bind(this));
        }
    }

});

/**
 * Loading Prototipes Versions In Select
*
* @class Ria_Spares_AutorazborkaByState
* @copyright  2010 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax_JsonRequest
*/
var Ria_Spares_AutorazborkaByState = new Class({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
            target: 	'spares',
            event:	'getAutorazborka'
	},
        initialize: function(options){
            
            options.state_id=$(options.obl_element_id).value;
                       
            options.marka_id=$(options.marka_element_id).value;
            options.category_id=$(options.category_element_id).value;
             this.parent(options);
	},

	onGetResponse: function(jsonObj) {
        if (jsonObj.result>0){
            $('autorazborka_all').setStyle('display','none');
            $('autorazborka_2').setStyle('display','block');
            $('autorazborka_2').empty();
            var text='';
            $each(jsonObj.autoRazborka_arr, function(item, index){

              if((index%2)==0){
                  
                  if (index == ((jsonObj.autoRazborka_arr.length)-1)){
                    text+='<div class="b-equal-height points-arr corner corner-4 boxed" style="margin-top: 10px;">';
                  } else  text+='<div class="b-equal-height points-arr corner corner-4" style="margin-top: 10px;">';

                  text += '<div class="b-first round-4px-grey">';
              }else {
                  text += '<div class="b-last round-4px-grey">';
              }

               text += '<em class="tl"></em><em class="tr"></em><em class="bl"></em><em class="br"></em>';
               text +=  '<dl class="avtorazborka"><dt><p>';
               text+='<a href="/autorazborka/razborka-'+item.autorazborka_id+'.html">'+item.title+'</a></p>';

                      if (item.address) text+= '<p><span>'+item.address+'</span></p>';
                      if(item.phones)  text+= '<p>.: <strong>'+item.phones+'</strong></p></dt><dd>';

                     if (item.logo)
                              text+='<img alt="" src="http://img.ria.ua/photos/'+item.logo.replace('.', 's.')+'">'+item.notice+'</dd>';
                    text+='<dd class="footer"><a title="'+RiaLang.Detailed+'" href="/autorazborka/razborka-'+item.autorazborka_id+'.html">'+RiaLang.Detailed+'</a>&raquo</dd></dl>';
                    text+='<div class="clr"></div></div>';

                    if((index%2)!=0){
                        text+='</div>';
                    }else if(index == ((jsonObj.autoRazborka_arr.length)-1)){
                        text+='</div>';
                    }
            }, this );
            $('autorazborka_2').set('html', text);
        }else {
            if($('autorazborka_all').getStyle('display')=='none'){
                $('autorazborka_all').setStyle('display','block');
                $('autorazborka_2').empty();
                $('autorazborka_2').setStyle('display','none');
            }
        }

	}
});



/**
 * Loading ... 
*
* @class Ria_Guru_VehicleRequestHTML
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax
* @requires   Ria_Core_Common_StatusImageManager
*/
var Ria_Guru_VehicleRequestHTML = new Class({

    Implements: Options,

    options: {
        target: 	'guru_Html',
        event:		'search',
        answerId:   null
    },

    initialize: function(options)
    {
        this.setOptions(options);
        
        $('loader_div').setStyle('display','inline');
        new Ria_Core_Common_StatusImageManager('loader', 'spinner', false);
        $('loader').setStyle('display', 'inline');

//        new Element('span', {'id':'loading', 'html': '...', 'styles': {'display':'inline'}}).inject($('loader'));

        new Request.HTML({
            url: Ria_Core_Ajax.script,
            onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
                $('result_block').set('html', responseHTML);
                $('polz').setStyle('visibility', 'visible');
                new Ria_Guru_CompletesRequestHTML({raiting:options.raiting});
            }
        }).get(this.options);
    }
});
/**
 * Loading ... 
*
* @class CompletesRequestHTML
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax
*/
var Ria_Guru_CompletesRequestHTML = new Class({

    Implements: Options,

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

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

        new Request.HTML({
            url: Ria_Core_Ajax.script,
            onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
                $('guru_search_completes').set('html', responseHTML);
                new Tips('.masterTip', {'text':'tip', 'title':''});
                if (!Cookie.read('Vote4MasterSearch') && $defined($('fiveStars')) ){//} && $('fiveStars')){
                    new Ria_Core_Rating_RatingRemindManager({
                        'parentId':'fiveStars',
                        'fieldName':'fiveStarsField',
                        'values': {1:'', 2:'', 3:'', 4:'', 5:''},
                        'padding': '0px 4px 0px 4px',
                        'start' : 0
                    });
                }else if($('fiveStars')){
                    new Ria_Core_Rating_RatingViewManager({
                        'parentId':'fiveStars',
                        'values': {1:'', 2:'', 3:'', 4:'', 5:''},
                        'padding': '0px 4px 0px 4px',
                        'value' : Math.round(options.raiting)
                    });
                }

                if ($('sendFriendForm')) {
                    $('sendFriendForm').addEvent('submit', function(e){
                        e.stop();
                    });
                }
                
                if ($('feedbackForm')) {
                    $('feedbackForm').addEvent('submit', function(e){
                        e.stop();
                    });
                }

                new Ria_Guru_PastQRequestHTML();
            }
        }).get(this.options);
    }
});
/**
 * Description
 *
 * @class Ria_Core_Rating_RatingRemindManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires    Ria_Core_Rating_RatingBaseManager
*/
var Ria_Core_Rating_RatingRemindManager = new Class({

    Extends: Ria_Core_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);
    }

});
/**
* Loading ... 
*
* @class Ria_Guru_RaitingRequestHTML
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax
*/
var Ria_Guru_RaitingRequestHTML = new Class({

    Extends: Ria_Core_Ajax_JsonRequest,

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

    Implements: Options,

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

    onGetResponse: function(jsonObj) {
        this.json = jsonObj;
        if (this.json.result){
            Cookie.write('Vote4MasterSearch','1',{path:'/',duration:14});
            $('fiveStarsDescr').innerHTML = "<p>    :</p>";
            $('fiveStars').innerHTML = "";

            new Ria_Core_Rating_RatingViewManager({
                'parentId':'fiveStars',
                'values': {
                    1:'',
                    2:'',
                    3:'',
                    4:'',
                    5:''
                },
                'padding': '0px 4px 0px 4px',
                'value' : Math.round(this.json.mark)
            });

            $('fiveStars').innerHTML = $('fiveStars').innerHTML+"(<strong>"+this.json.mark+"</strong>)";
        }
    }
});
/**
 * Loading ... 
*
* @class Ria_Guru_PastQRequestHTML
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax
*/
var Ria_Guru_PastQRequestHTML = new Class({

    Implements: Options,

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

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

        new Request.HTML({
            url: Ria_Core_Ajax.script,
            onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
                $('past_questions').set('html', responseHTML);
                $('loader').setStyle('display','none');
                $('loader_div').setStyle('display','none');
            }
        }).get(this.options);
    }
});
/**
 * Loading Prototipes Versions In Select
*
* @class Ria_Photo_FancyUpload_SetMainPhotoRequest
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax_JsonRequest
* @requires   Ria_Core_Common_StatusImageManager
*/
var Ria_Photo_FancyUpload_SetMainPhotoRequest = new Class({

    Extends: Ria_Core_Ajax_JsonRequest,

    options: {
        target              : 'photos',
        event               : 'set_main',
        photo_status_div    : 'photo_status',
        main_link_pref      : '',
        main_text_pref      : ''
    },

    initialize: function(options) {

        this.setOptions(options);

        if (this.options.photo_id > 0) {
            new Ria_Core_Common_StatusImageManager(this.options.photo_status_div, 'spinner', false);
            this.parent(this.options);
        } else {
            new Ria_Core_Common_StatusImageManager(this.options.photo_status_div, 'error', false);
        }
    },

    onGetResponse: function(jsonObj) {

        this.json = jsonObj;

        if (this.json.result) {
            $$('span.is_main').each(function(element){
               element.setStyle('display', 'none');
            });
            $$('a.file-main').each(function(element){
                element.setStyle('display', 'block');
            });
            $(this.options.main_link_pref + this.options.photo_id).setStyle('display', 'none');
            $(this.options.main_text_pref + this.options.photo_id).setStyle('display', 'inline');
            new Ria_Core_Common_StatusImageManager(this.options.photo_status_div, 'check', true);
        }
    }
});
/**
 * Loading Prototipes Versions In Select
*
* @class Ria_Photo_FancyUpload_DeletePhotoRequest
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax_JsonRequest
* @requires   Ria_Core_Common_StatusImageManager
*/
var Ria_Photo_FancyUpload_DeletePhotoRequest = new Class({

    Extends: Ria_Core_Ajax_JsonRequest,

    options: {
        target                  : 'photos',
        event                   : 'delete',
        photo_status_div        : 'photo_status',
        photo_container_pref    : ''
    },

    initialize: function(options) {

        this.setOptions(options);
        if (this.options.photo_id > 0) {
            new Ria_Core_Common_StatusImageManager(this.options.photo_status_div, 'spinner', false);
            this.parent(this.options);
        } else {
            new Ria_Core_Common_StatusImageManager(this.options.photo_status_div, 'error', false);
        }
    },

    onGetResponse: function(jsonObj) {

        this.json = jsonObj;
        if (this.json.result){
            $(this.options.photo_container_pref + this.options.photo_id).destroy();
        }
    }
});
/**
 *
 * ������� ��� ����� Visicom'�
 *
 * @class Ria_Core_Map_Main_Drivers_Visicom
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires    Ria_Core_Map_Main_Common_GeoPoint
 */

 var Ria_Core_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','����� �������'));
		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');

        //???? ?? ???????? ?????? ? Visicom
//    	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_Core_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_Core_Map_Main_Common_GeoPoint(mapPoint.lng,mapPoint.lat);
//		var vgeoPoint = this.map.getCenter().convertToGeoPoint();
//		return new Ria_Core_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_Core_Map_Main_Common_GeoPoint(vMinPoint.lng,vMinPoint.lat));
		rect.set('max',new Ria_Core_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_Core_Map_Main_Common_GeoPoint(vminPoint.getLongitude(),vminPoint.getLatitude()));
//		rect.set('max',new Ria_Core_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_Core_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_Core_Map_Main_Drivers_Yandex
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires    Ria_Core_Map_Main_Common_GeoPoint
 */
 var Ria_Core_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(), ' РљР°СЂС‚Р° ', {minZoom:6, maxZoom:17});
//		var myHub = new YMaps.MapType(YMaps.MapType.HYBRID.getLayers(), 'Р“РёР±СЂРёРґ', {minZoom:6, maxZoom:17});
//		this.map.addControl(new YMaps.TypeControl([myMap, myHub]));
//		this.map.setType(myMap);
//		this.map.enableScrollZoom();
		this.map.disableScrollZoom();
	},
        //-- -- -- -- -- -- -- -- --
	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_Core_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.layers.get(id).removeAll();
//		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_Core_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_Core_Map_Main_Common_GeoPoint(vminPoint.getLng(),vminPoint.getLat()));
		rect.set('max',new Ria_Core_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 != "Украина" ) 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_Core_Map_Main_Drivers_Google_Layer
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires    Ria_Core_Map_Main_Common_GeoPoint
 */
 var Ria_Core_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_Core_Map_Main_Drivers_Google_Marker
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires    Ria_Core_Map_Main_Common_GeoPoint
 */
 var Ria_Core_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();
    }

});

/**
 *
 * Класс, в котором храняться основные настройки карты
 *
 * @class Ria_Core_Map_MapOptions
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires Ria_Core_Ajax
 */
 var Ria_Core_Map_MapOptions = new Class({
	'mapContainer' : '',
    'ajaxDialog' : 'map',
	'driverId' : '1',
	'search' : {
        'enabled' : 0,
        'className' : '',
        'fieldsContainer' : '',
        'buttonId' : '',
        'searchOnLoad' : 0,
        'alreadySearched' : 0,
        'markerClickImpl' : ''
    },
    'navigation' : {
        'enabled' : 0,
        'stateSelectId' : '',
        'citySelectId' : ''
    },
    'mapChanger' : {
        'enabled' : 0,
        'maps' : {}
    },
    'globalPoints' : {
        'enabled' : 0,
        'openerInputField' : '',
        'openerDivContainer' : '',
        'checkboxesContainer' : '',
        'submitButton' : '',
        'drawFunc' : ''
    },
    'geoSearch' : {
        'enabled' : 0,
        'buttonId' : ''
    },
	'offset' : 0,
    'resizeMapEnabled' : 0,
    'ajaxSpinner' : '',
	'isFullscreen' : false
});

/**
 *
 * @class Ria_Points_AddPoint_AddressRequest
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Core_Ajax_JsonRequest
*/
var Ria_Points_AddPoint_AddressRequest = new Class({
	
	Extends: Ria_Core_Ajax_JsonRequest, 
	
	options: {
		target: 	'location',
		event: 		'address_search'
	},

	initialize: function(options){
        this.parent(options);
	},
    
	onGetResponse: function(jsonObj) {
		this.json = jsonObj;
		if (jsonObj.result>0){
            this.setMapPosition(this.json.geoX, this.json.geoY);
        }
	},

    setMapPosition:function(geo_x, geo_y){
        eval('var mapObject = window.'+this.options.map_name+';');
        eval('var placemarkObject = window.'+this.options.placemark_name+';');

        centerPoint = new YMaps.GeoPoint(geo_x, geo_y);
        placemarkObject.setGeoPoint(centerPoint);
        mapObject.setCenter(centerPoint);
    }
	
});
/**
 * Loading Prototipes Versions In Select 
*
* @class Ria_Points_PointPhotoDeleteRequest
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax_JsonRequest
* @requires   Ria_Core_Common_StatusImageManager
*/
var Ria_Points_PointPhotoDeleteRequest = new Class({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'autoservice',
		event:		'pointPhotoDelete',
                core_rewrite_off: 1
	},
    
	initialize: function(options)
    {
		if (options.photo_id > 0){
			new Ria_Core_Common_StatusImageManager('photoStatusDiv_' + options.photo_id, 'spinner', false);
			this.parent(options);
		} else {
            new Ria_Core_Common_StatusImageManager('photoStatusDiv_' + options.photo_id, 'error', false);
        }
	},

	onGetResponse: function(jsonObj)
    {
        this.json = jsonObj;
        if (this.json.result){
            $('partViewPhotoContainerDiv_' + this.options.photo_id).destroy();

            if (this.json.new_main_id){
                //var parent = $('partViewPhotoContainerDiv_' + this.json.new_main_id).getParent();
                //$('partViewPhotoContainerDiv_' + this.json.new_main_id).dispose().inject(parent,'top');
                
                $('mainPhotoTextId_' + this.json.new_main_id).setStyle('display', 'inline');
                $('setMainPhotoLinkDivId_' + this.json.new_main_id).setStyle('display', 'none');
                new Ria_Core_Common_StatusImageManager('photoStatusDiv_' + this.json.new_main_id, 'check', true);
            }
            
        }
	}
    
});
/**
 * Loading Prototipes Versions In Select
*
* @class Ria_Points_CommentVoteRequest
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax_JsonRequest
*/
var Ria_Points_CommentVoteRequest = new Class({
	Extends: Ria_Core_Ajax_JsonRequest,
	options: {
		target: 	'autoservice',
		event:		'comment_vote',
                core_rewrite_off: 1
	},
	initialize: function(options){
        options.raiting = $('raiting_'+options.id).innerHTML;
        this.parent(options);
	},
	onGetResponse: function(jsonObj) {
		this.json = jsonObj;
		if (this.json.result){
            $('plus_'+jsonObj.id).addClass('disable');
            $('minus_'+jsonObj.id).addClass('disable');
            $('raiting_'+jsonObj.id).innerHTML = jsonObj.raiting;
		}
	}
});
/**
 * Loading Prototipes Versions In Select
*
* @class Ria_Common_ModelRequest
* @copyright  2008 IT RIA
* @license    GNU GPL v2
* @version    ID:
* @requires   Ria_Core_Ajax_JsonRequest
* @requires   Ria_Core_Common_StatusImageManager
*/
var Ria_Common_ModelRequest = new Class({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'common',
		event:		'getAutoModel'
	},
	initialize: function(options){
		options.marka_id = $(options.marka_element).value;
		if (options.marka_id>0)
		{
			$(options.model_element).empty();
            $(options.model_element).setProperty('disabled', 'true');
            $(options.model_element).setProperty('class', 'select_during_loading');
			//new Ria_Core_Common_StatusImageManager('prototype_tr', 'spinner', false);
			this.parent(options);
		} else {
            $(options.model_element).length = 1;
            this.options = options;
            //$(options.model_element).setProperty('disabled', 'true');
        }
	},

//	onGetResponse: function(jsonObj) {
//		this.json = jsonObj;
//		//new Ria_Core_Common_StatusImageManager('prototype_tr', 'check', false);
//		if (this.json.result){
//			new Element('option', {'value': 0, 'text':this.json.any_model}).inject($(this.options.model_element));
//
//			$each(this.json.modelArr, function(item, index){
//				var element = new Element('option', { 'value': index});
//                                if (jsonObj.popular && item.count < 100) element.setStyle('color', '#7C7C7C');
//				element.inject($(this.options.model_element)).set('text', item);
//			}, this );
//            $(this.options.model_element).removeProperty('disabled');
//            $(this.options.model_element).removeProperty('class');
//		}
//
//	},

	onGetResponse: function(jsonObj) {
		this.json = jsonObj;
		//new Ria_Core_Common_StatusImageManager('prototype_tr', 'check', false);
		if (this.json.result){
			new Element('option', {'value': 0, 'text':this.json.any_model}).inject($(this.options.model_element));

			/*{assign var='model_parent_id' value=0}
                                    {foreach from=$model_arr item=item}
                                        {if $item.is_group}<optgroup label="{$item.name}">{assign var='model_parent_id' value=$item.model_id}
                                        {else}
                                        {if $model_parent_id>0 && $item.parent_id==0}
                                            </optgroup>
                                            {assign var='model_parent_id' value=0}
                                        {/if}
                                        <option value="{$item.model_id}" {if $item.ModelCountDBO.count<100 && $item.ModelCountDBO.count>0}style="color:#5C5C5C;"{elseif $item.ModelCountDBO.count==0}style="color:#9C9C9C;"{/if}{if $item.model_id==$model_id}selected{/if}>{$item.name}</option>
                                        {/if}
                                    {/foreach}*/
                        if(this.options.zone == 'search') {
                            var text = '';
                            $each(this.json.modelArr, function(item, index){
                                if($defined(item.model_id)) {
                                    var element = new Element('option', { 'value': item.model_id});
                                    if (item.ModelCountDBO.count < 20) element.setStyle('color', '#5C5C5C');
                                    if (item.is_group > 0) element.addClass('label');
                                    text = item.name;
                                    if(item.parent_id > 0) text = '&nbsp;&nbsp;&nbsp;&nbsp;'+text;
                                    element.inject($(this.options.model_element)).set('html', text);
                                }
                            }, this );
                        } else {
                            var parent_id = 0;
                            this.optgroup = '';
                            $each(this.json.modelArr, function(item, index){
                                if($defined(item.model_id)) {
                                    if (item.is_group>0){
                                        parent_id = item.model_id;
                                        this.optgroup = new Element('optgroup', {'label': item.name});
                                        this.optgroup.inject($(this.options.model_element));
                                    }else{
                                        var element = new Element('option', {'value': item.model_id}).set('text',item.name);
                                        if(item.count==0 && item.is_group==0)
                                            element.setStyle('color','#9C9C9C');
                                        else if (item.ModelCountDBO.count<20 && item.is_group==0)
                                            element.setStyle('color','#5C5C5C');
                                        if (parent_id == item.parent_id && this.optgroup!=''){
                                            this.optgroup.appendChild(element);
                                        }else element.inject($(this.options.model_element));
                                    }
                                }
                            }, this );
                        }
            $(this.options.model_element).removeProperty('disabled');
            //$(this.options.model_element).removeProperty('class');
            $(this.options.model_element).setProperty('class', 'catalog');
		}

	}
});
/**
 * @class Ria_NewAutoSalon_BuyFormManager
 * @requires Ria_Core_Ajax
 * @requires Ria_Core_Common_StatusImageManager
 * @requires Ria_NewAutoSalon_BuyFormManager
*/

var Ria_Points_SendFormManager = new Class({

    Extends: Ria_NewAutoSalon_BuyFormManager,

    validate: true,

    validate_options: [],

    initialize: function(){
        this.completeId = '';

        $('message_form_link').addEvent('click', function(){
            this.change_div_visible();
            this.setupValidator(['message_form_name', 'message_form_phone', 'message_form_message']);
        }.bind(this));


    },

    change_div_visible: function(){
        var div = $('message_div');
        if(div.getStyle('display') == 'none') {
            var form = $('message_form');
            this.formClear(form);
            this.setFormSubmit();
            div.setStyle('display', 'block');
        } else {
            div.setStyle('display', 'none');
        }
    },

    setFormSubmit: function (){

        var form = $('message_form');

        form.removeEvents('submit');
        form.addEvent('submit', function(e) {
            e.stop();

            if (this.validate && !this.isformValid()) {
                alert('   !      .');
                return false;
            }

            form.set('send', {
                url: Ria_Core_Ajax.script,
                method: 'post',
                onComplete: function(response) {
                    var div = $('message_div');
                    $('message_dl').empty();
                    div.empty();
                    div.addClass('success');
                    div.set('html', '      .');
                }.bind(this)
            });
            form.send();
            new Ria_Core_Common_StatusImageManager('message_div', 'spinner', false);
        }.bind(this));
    }

});

/**
 *
 * @class Ria_Core_Map_Main_Drivers_Google
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires    Ria_Core_Map_Main_Common_GeoPoint
 * @requires    Ria_Core_Map_Main_Drivers_Google_Layer
 * @requires    Ria_Core_Map_Main_Drivers_Google_Marker
 */
 var Ria_Core_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.enableDoubleClickZoom();
//            this.map.enableContinuousZoom();
//            this.map.enableScrollWheelZoom();
//            this.map.addControl(new GLargeMapControl());


//            this.map.setUIToDefault();

            this.map.type = 'map';
//		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(), ' ����� ', {minZoom:6, maxZoom:17});
//		var myHub = new YMaps.MapType(YMaps.MapType.HYBRID.getLayers(), ' ������� ', {minZoom:6, maxZoom:17});
//		this.map.addControl(new YMaps.TypeControl([myMap, myHub]));
//		this.map.setType(myMap);
//		this.map.enableScrollZoom();
	},
        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) {
//    *  G_NORMAL_MAP — обычная двумерная карта.
//    * G_SATELLITE_MAP — фотографическая карта.
//    * G_HYBRID_MAP — комбинация фотографий и слоя обычной карты с наиболее важными объектами (дорогами, названиями городов).
//    * G_PHYSICAL_MAP — физическая карта с информацией о рельефе местности.

                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:
                }
//
//                alert('alert '+mapTypeKey);

            }.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));
            

////		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();
//		}.bind(this));
	},

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

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

	addMarkerToBase : function(marker) {
//

//var gMarker = new GMarker(marker.getGeoPoint().convertToMapPoint(), {draggable: true});

//            var gMarker = new GMarker(marker.getGeoPoint().convertToMapPoint(), {draggable: true});

            var gMarker = new Ria_Core_Map_Main_Drivers_Google_Marker(this,marker.getGeoPoint().convertToMapPoint());
//            gMarker.disableDragging();

//            gMarker.type = marker.type;

//            this.addEventListener(this.map,'dragstart', function() {
////                gMarker.hide();
////                this.map.clearOverlays();
//                gMarker.closeInfoWindow();
//
//            }.bind(this));
            
            var id = this.markers.getLength() + 1;
            marker.setId(id);
            this.markers.set(id,gMarker);

//		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 gLayer = new Ria_Core_Map_Main_Drivers_Google_Layer(this);
            gLayer.type = layer.type;
            var id = this.layers.getLength()+1;
            layer.setId(id);
            this.layers.set(id,gLayer);
//		var ylayer = new YMaps.GeoObjectCollection();
//		var id = this.layers.getLength()+1;
//		layer.setId(id);
//		this.layers.set(id,ylayer);
	},

	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());
//gLayer.show();
/* ---- */


//		var ymarker = this.markers.get(marker.getId());
//		var ylayer = this.layers.get(id);
//		ylayer.add(ymarker);
	},

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

	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_Core_Map_Main_Common_GeoPoint(point.lng(),point.lat());
    },

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

	showMarker : function(id) {
		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_Core_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_Core_Map_Main_Common_GeoPoint(vminPoint.lng(),vminPoint.lat()));
		rect.set('max',new Ria_Core_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 ) {
//        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_Points_AddPoint_MainManager
 * 
 * @requires   Ria_Points_AddPoint_AddressRequest
*/

var Ria_Points_AddPoint_MainManager = new Class({

    checkControlOptions : new Hash(),

    initialize: function()
    {
        this.citiesArray = new Hash();
    },

    addCheckControl:function(checkboxId, divId){
        $(checkboxId).addEvent('click', function() {
            if ( $(checkboxId).checked ) $(divId).setStyle('display', 'block');
            else $(divId).setStyle('display', 'none');

            this.checkForSubmit();

        }.bind(this));

        if ( $(checkboxId).checked ) {
            $(divId).setStyle('display', 'block');
            if ($defined($('submitButtonDiv'))) $('submitButtonDiv').setStyle('display', 'block');
        }
    },

    checkForSubmit:function(){
        var submitEnable = false;
        $('poi_types').getElements('input').each(function(item, index){
            if (item.checked) submitEnable = true;
        });

        if ($defined($('submitButtonDiv'))){
            if (submitEnable) $('submitButtonDiv').setStyle('display', 'block');
            else $('submitButtonDiv').setStyle('display', 'none');
        }
    },

    searchOnMap:function(){
        address = $('cityId').getSelected().get('html') + ', ' + $('postalAddress').value;
        new Ria_Points_AddPoint_AddressRequest({'address':address, 'map_name':'map', 'placemark_name':'placemark'});
    },

    updateCoordinates:function(str){
        $('geo_X').set('value', str.__lng);
        $('geo_Y').set('value', str.__lat);
    },

    addCityToArray:function(id, x, y){
        this.citiesArray.set(id, new Hash({'x':x,'y':y}));
    },

    getCitiesFromArray:function(id){
        if (this.citiesArray[id]) this.setMapPosition(this.citiesArray[id]['x'], this.citiesArray[id]['y']);
    },

    setMapPosition:function(geo_x, geo_y){
        centerPoint = new YMaps.GeoPoint(geo_x, geo_y);
        window.placemark.setGeoPoint(centerPoint);
        window.map.setCenter(centerPoint);
    }

});

/**
 *
 * Класс доступен из любого инного класа,
 * у него устанавливаются все дефолтные настройки и
 * он хранит в себе объект драйвера
 *
 * @class Ria_Core_Map_Main_Common_Config
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Core_Map_Main_Drivers_Visicom
 * @requires   Ria_Core_Map_Main_Drivers_Yandex
 * @requires   Ria_Core_Map_Main_Drivers_Google
 */
 var Ria_Core_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_Core_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_Core_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_Core_Map_Main_Adapters_Layer
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Core_Map_Main_Common_Config
 */
 var Ria_Core_Map_Main_Adapters_Layer = new Class({
	//�������� ������
	'is_show' : true,
	'onmap' : false,
	innerMarkers : new Hash(),
	'id' : '',
	'type' : 'layer',
	
	initialize: function(){
		//console.log('Ria_Core_Map_Main_Adapters_Layer');
		RMaps.Config.getDriver().addLayerToBase(this);
	},
	
	setId : function(id) {
		//console.log('Ria_Core_Map_Main_Adapters_Layer->setId');
		this.id = id;
	},
	
	getId : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Layer->getId');
		//console.log(this.id);
		return this.id;
	},
	
	setOnMap : function(bool) {
		//console.log('Ria_Core_Map_Main_Adapters_Layer->setOnMap');
		this.onmap = bool;
	},
	
	addMarker : function(marker) {
		//console.log('Ria_Core_Map_Main_Adapters_Layer->addMarker');
		this.innerMarkers.set(marker.getId(),marker);
		RMaps.Config.getDriver().addMarkerToLayer(this.id,marker);
	},
	
	removeMarker : function(marker) {
		//console.log('Ria_Core_Map_Main_Adapters_Layer->removeMarker');
		this.innerMarkers.erase(marker.getId());
		RMaps.Config.getDriver().removeMarkerFromLayer(this.id,marker);
	},
	
	getMarkers : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Layer->getMarkers');
		return this.innerMarkers;
	},
	
	show : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Layer->show');
		if(!this.is_show) {
			this.is_show = true;
			RMaps.Config.getDriver().showLayer(this.id);
		}
	},
	
	hide : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Layer->hide');
		if(this.is_show) {
			this.is_show = false;
			RMaps.Config.getDriver().hideLayer(this.id);
		}
	}
	
});
/**
 * 
 * �����-������� ��� ������ � ���������
 * 
 * @class Ria_Core_Map_Main_Adapters_Marker
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Core_Map_Main_Common_Config
 * @requires   Ria_Core_Map_Main_Common_GeoPoint
 */
 var Ria_Core_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_Core_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_Core_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_Core_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_Core_Map_Main_Adapters_Marker->setOnMap');
		this.onmap = bool;
	},
	
	show : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Marker->show');
		if(!this.is_show) {
			this.is_show = true;
			RMaps.Config.getDriver().showMarker(this.id);
		}
	},
	
	hide : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Marker->hide');
		if(this.is_show) {
			this.is_show = false;
			RMaps.Config.getDriver().hideMarker(this.id);
		}
	},
	
	getGeoPoint : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Marker->getGeoPoint');
		return new Ria_Core_Map_Main_Common_GeoPoint(this.longitude,this.latitude);
	},

    setGeoPoint : function(point) {
		//console.log('Ria_Core_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_Core_Map_Main_Adapters_Marker->setId');
		this.id = id;
	},
	
	getId : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Marker->getId');
		return this.id;
	},
	
	destruct : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Marker->destruct');
		RMaps.Config.getDriver().removeMarkerFromMap(this);
		delete this;
	},
	
	addInfoWindow : function(name, htmlText) {
		//console.log('Ria_Core_Map_Main_Adapters_Marker->addInfoWindow');
		this.infoWindowName = name;
		this.infoWindowHtml = htmlText;
		RMaps.Config.getDriver().addInfoWindowToMarker(this);
	},
	
	removeInfoWindow : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Marker->removeInfoWindow');
		this.infoWindowName = '';
		this.infoWindowHtml = '';
		RMaps.Config.getDriver().removeInfoWindowFromMarker(this.id);
	},
	
	openInfoWindow : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Marker->openInfoWindow');
		this.isOpenInfoWindow = true;
		RMaps.Config.getDriver().openInfoWindowInMarker(this.id);
	},
	
	closeInfoWindow : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Marker->closeInfoWindow');
		this.isOpenInfoWindow = false;
		RMaps.Config.getDriver().closeInfoWindowInMarker(this.id);
	},
	
	setDraggable : function(bool) {
		//console.log('Ria_Core_Map_Main_Adapters_Marker->setDraggable');
		this.isDraggable = bool;
		RMaps.Config.getDriver().setDraggableMarker(this.id,bool);
	}
	
});
/**
 *
 * Класс, который вызывается по клике на геопоиске
 *
 * @class Ria_Core_Map_GeoSearchEvent
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Core_Ajax
 * @requires   Ria_Core_Map_Main_Common_GeoPoint
 * @requires   Ria_Core_Map_Main_Adapters_Marker

 */
 var Ria_Core_Map_GeoSearchEvent = new Class({
	initialize: function(){

	},

    geoSearchEvent : function() {
//        riaMap.ajaxManager.jsonRequest(Ria_Core_Ajax.script,this.ajaxCallBack,{
//            'target' : 'map',
//            'event' : 'geoSearch',
//            'word' : $(riaMap.options.geoSearch.textFieldId).getProperty('value'),
//            'driverId' : riaMap.options.driverId,
//            'centerPoint' : JSON.encode(riaMap.storage.map.getCenter())
//        },true);

        var searchText = $(riaMap.options.geoSearch.textFieldId).getProperty('value');
//        alert ( searchText );
        RMaps.Config.getDriver().searchAddress(searchText, this.printAddresses.bind(this));
//        if ( riaMap.options.driverId == 1 ) this.visicomFinder($(riaMap.options.geoSearch.textFieldId).getProperty('value'), $(riaMap.options.geoSearch.resultBlock));
//        else if ( riaMap.options.driverId == 2 ) this.yandexFinder($(riaMap.options.geoSearch.textFieldId).getProperty('value'), $(riaMap.options.geoSearch.resultBlock));
    },

    printAddresses : function ( addresses ) {
        this.clearResultBlock();
        this.printResultBlock(addresses);
    },

    clearResultBlock : function() {
        if ($defined ( $(riaMap.options.geoSearch.resultBlock) ) ) {
            $(riaMap.options.geoSearch.resultBlock).set('html','').removeProperty('class');
        }
        window.fireEvent('resize');
    },

    printResultBlock : function( address ) {
        if ( address.length ) {
            var block = $(riaMap.options.geoSearch.resultBlock);
            block.setProperty('class','cont_round3px');
            block.grab(
                new Element('div',{'class':'round'}).grab(
                    new Element('div',{'class':'lt'})
                ).grab(
                    new Element('div',{'class':'rt'})
                ).grab(
                    new Element('a',{'class':'closeBloce'}).addEvent('click',this.clearResultBlock.bind(this))
                )
            );
    //
            var centerDiv = new Element('div',{'class':'lr_borde result_search'}).inject(block);
            centerDiv.grab(new Element('p',{'class':'t_panel'}).set('html',"Найдено <span>" + address.length + "</span> объекта"));
            var ul = new Element('ul').inject(centerDiv);
            $each(address,function(value) {
                var li = new Element('li').inject(ul);
                var a = new Element('a',{'href':'javascript:void(0)'}).set('text',value.name);
                a.addEvent('click',this.showAddressOnMap.bind(this,[value.lng, value.lat, value.city, value.name]));
                li.grab(new Element('div').grab(a));
                li.appendText(value.city);
            }.bind(this));

            centerDiv.grab( new Element( 'p', {
                'style' : 'text-align:center; border-bottom:none; border-top:1px dotted #D9D9D9; margin-top:10px; padding:10px 0px 0px;'
            }).grab( new Element( 'a', {
                'href' : 'javascript:void(0)',
                'text'  : Lang.close_geosearch_result
            }).addEvent( 'click', this.clearResultBlock.bind( this ) ) ) );
    //
            block.grab(
                new Element('div',{'class':'round'}).grab(
                    new Element('div',{'class':'lb'})
                ).grab(
                    new Element('div',{'class':'rb'})
                )
            );
            var duration = 500;
            var color = '#fff096';
            block.set('tween', {
                fps: duration,
                onComplete : function() {
                    block.set('tween',{fps : duration, onComplete : null}),
                    block.tween('background-color',color,'#fff')
                }
            });
            block.tween('background-color','#fff',color);
            window.fireEvent('resize');
        }
    },

    showAddressOnMap : function ( lng, lat, city, name ) {
        var commas = 0;
        for ( var i = 0; i < name.length;i++ ) {
            if ( name.charAt ( i ) == ',') commas++;
        }
        if ( commas > 1 ) {
            var zoom = 100;
        } else {
            var zoom = 80;
        }
        if ( typeof riaMap.storage.geoSearcPoints == "undefined" ) riaMap.storage.geoSearcPoints = [];
        this.clearGeoSearchPoints();
        marker = new Ria_Core_Map_Main_Adapters_Marker( new Ria_Core_Map_Main_Common_GeoPoint ( lng, lat ) );
        riaMap.storage.geoSearcPoints.include(marker);
        riaMap.storage.map.setCenter( new Ria_Core_Map_Main_Common_GeoPoint ( lng, lat ) );
        riaMap.storage.map.setZoom(zoom);
        marker.setIcon(27,35,'http://css.ria.ua/img/maps/down_red_arrow_pointer.png',13,35);
//        marker.setIcon(27,35,'http://maps.visicom.ua/api/images/markers/pointer-trans.png',13,35);
        riaMap.storage.map.addMarker(marker);
        marker.addInfoWindow('', "<div style=\"font-size:14px;color:#B54C00;font-weight:bold\">"+ name + "</div>" + "<span style=\"font-size:12px;\">" + city + "</span>");
        marker.openInfoWindow();
    },

    clearGeoSearchPoints : function() {
        $each( riaMap.storage.geoSearcPoints, function ( value ) {
            value.getId();
            riaMap.storage.map.removeMarker ( value );
        } );
        riaMap.storage.geoSearcPoints = [];
    }

});
/**
 *
 * Класс, который вызывается по змене зума или перетаскивании карты
 *
 * @class Ria_Core_Map_MapEvent
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Core_Ajax
 * @requires   Ria_Core_Map_Main_Adapters_Layer
 * @requires   Ria_Core_Map_Main_Adapters_Marker
 * @requires   Ria_Core_Map_AbstractEvent
 */
 var Ria_Core_Map_MapEvent = new Class({
	Extends: Ria_Core_Map_AbstractEvent,
	initialize: function(){
		this.screen = this.setClientRectInObject(new Object(),riaMap.options.offset);
	},

	mapEvent : function(event) {
		//alert(event);
        if(riaMap.options.search.alreadySearched) {
            if((((this.isNeedNewPoints()) && (event == 'enddrag')) || (event == 'zoomchange'))) {
                var parametrs = riaMap.manager.makeGetParametrs('search');
                parametrs = this.setClientRectInObject(parametrs,riaMap.options.offset);
//				console.log(parametrs);
                this.screen = parametrs;
                if(event == 'zoomchange') {
                    this.clearMarkers();
                }
                riaMap.ajaxManager.jsonRequest(Ria_Core_Ajax.script,function(data) {
                    this.addMarkersFromResult(data);
                }.bind(this),parametrs,true);
            }
        }
	},

	isNeedNewPoints : function() {
    	if(this.screen) {
	    	var new_screen = this.setClientRectInObject(new Object, 0);
	    	if(	(this.screen.min_lngt > new_screen.min_lngt) ||
	    		(this.screen.min_ltt > new_screen.min_ltt) ||
	    		(this.screen.max_lngt < new_screen.max_lngt) ||
	    		(this.screen.max_ltt < new_screen.max_ltt)) {
	    		return true;
	    	} else {
	    		return false;
	    	}
    	} else {
    		return false;
    	}
    }

});

/**
 * 
 * �����-������� ��� ������ � ���������
 * 
 * @class Ria_Core_Map_Main_Adapters_Events
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Core_Map_Main_Common_Config
 */
 var Ria_Core_Map_Main_Adapters_Events = new Class({
	
	addEventListener : function(object,event,callback_func) {
		//console.log('Ria_Core_Map_Main_Adapters_Events->addEventListener');
		RMaps.Config.getDriver().addEventListener(object,event,callback_func);
	},
	
	fireEvent : function(object,event,args) {
		//console.log('Ria_Core_Map_Main_Adapters_Events->fireEvent');
		RMaps.Config.getDriver().fireMapEvent(object,event,args);
	}
	
});
/**
 * 
 * �����-������� ��� ������ � ������
 * 
 * @class Ria_Core_Map_Main_Adapters_Map
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Core_Map_Main_Common_Config
 * @requires   Ria_Core_Map_Main_Common_GeoPoint
 */
 var Ria_Core_Map_Main_Adapters_Map = new Class({
//�������� �����
    markers : new Hash(),
    layers : new Hash(),
    centerPoint : new Ria_Core_Map_Main_Common_GeoPoint(0,0),
    'zoom' : 0,
    'type' : 'map',
    //������������� ��������
    initialize: function(driverId, mapContainerId){
		//console.log('Ria_Core_Map_Main_Adapters_Map');
        this.mapContainerId = mapContainerId;
        window.RMaps = {};
        window.RMaps.Config = new Ria_Core_Map_Main_Common_Config(mapContainerId,driverId);
        this.driver = RMaps.Config.getDriver();
    },

    //��������� �������� ���������� �����
    resizeMap : function(width,height) {
		//console.log('Ria_Core_Map_Main_Adapters_Map->resizeMap');
        if($defined(this.driver)) {
            this.driver.resizeMap(width,height);
        }
    },


    //����� ����������� ����� � ����������
    paintMap : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Map->paintMap');
        if($defined(this.driver)) {
            this.setupControls();
            this.driver.initMap();
        }
    },

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

    hideAllControl :  function() {
		//console.log('Ria_Core_Map_Main_Adapters_Map->hideAllControl');
        window.RMaps.Config.hideAllControl();
    },
    hideControl :  function(controlName) {
		//console.log('Ria_Core_Map_Main_Adapters_Map->hideControl');
        window.RMaps.Config.hideControl(controlName);
    },
    showControl :  function(controlName) {
		//console.log('Ria_Core_Map_Main_Adapters_Map->showControl');
        window.RMaps.Config.showControl(controlName);
    },
    setupControls : function() {
		//console.log('Ria_Core_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_Core_Map_Main_Adapters_Map->repaintMap');
            this.driver.repaintMap();
    },
    //����� ��� ���������� ������� �� �����
    addMarker : function(marker) {
		//console.log('Ria_Core_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_Core_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_Core_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_Core_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_Core_Map_Main_Adapters_Map->getCenter');
        this.centerPoint = this.driver.getMapCenter();
        return this.centerPoint;
    },

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

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

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

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

    convertToEngineZoom : function(old_zoom) {
		//console.log('Ria_Core_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_Core_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_Core_Map_Main_Adapters_Map->getMarkers');
		return this.markers;
	},
	
	getLayers : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Map->getLayers');
		return this.layers;
	},
	
	destructMap : function() {
		//console.log('Ria_Core_Map_Main_Adapters_Map->destructMap');
		this.driver.destructMap();
	}
	
});
/**
 *
 * Класс, который вызывается по клику на поисковую форму
 *
 * @class Ria_Core_Map_SearchEvent
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Core_Ajax
 * @requires   Ria_Core_Map_Main_Adapters_Layer
 * @requires   Ria_Core_Map_Main_Adapters_Marker
 * @requires   Ria_Core_Map_AbstractEvent
 */
 var Ria_Core_Map_SearchEvent = new Class({
	Extends: Ria_Core_Map_AbstractEvent,
	initialize: function(){

	},

	searchEvent : function() {
		this.clearMarkers();
		riaMap.options.search.alreadySearched = 1;
		var parametrs = riaMap.manager.makeGetParametrs('search');
		this.setClientRectInObject(parametrs,riaMap.options.offset);
		riaMap.ajaxManager.jsonRequest(Ria_Core_Ajax.script,this.addMarkersFromResult.bind(this),parametrs,true);
	}

});

/**
 *
 * Класс, который назначает события на элементы карты
 *
 * @class Ria_Core_Map_EventsManager
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires Ria_Core_Map_SearchEvent
 * @requires Ria_Core_Map_GeoSearchEvent
 * @requires Ria_Core_Map_MapEvent
 */
 var Ria_Core_Map_EventsManager = new Class({

	initialize: function(){
		this.searchEvent = new Ria_Core_Map_SearchEvent();
		this.geoSearchEvent = new Ria_Core_Map_GeoSearchEvent();
		this.mapEvent = new Ria_Core_Map_MapEvent();
	},

	addEventToSearchForm : function() {
		$(riaMap.options.search.buttonId).addEvent('click',function() {
			this.searchEvent.searchEvent();
			return false;
		}.bind(this));
	},
    
	execEventToSearch : function() {
            this.searchEvent.searchEvent();
            return false;
    },
    
	addEventToMap : function(event) {
		riaMap.events.addEventListener(riaMap.storage.map,event,function() {
			this.mapEvent.mapEvent(event);
		}.bind(this));
	},

    addEventToGeoSearchForm : function() {
        if ( $defined ( $( riaMap.options.geoSearch.buttonId ) ) ) {
            $(riaMap.options.geoSearch.buttonId).addEvent('click',function() {
                this.geoSearchEvent.geoSearchEvent();
                return false;
            }.bind(this));
            $(riaMap.options.geoSearch.textFieldId).addEvent('keyup', function(ev) {
                if ( ev.key == "enter") {
                    $(riaMap.options.geoSearch.buttonId).fireEvent('click');
                }
            }.bind(this));
        }
    }
});

/**
 *
 * Основной класс для отображения карты
 *
 * @class Ria_Core_Map_Main
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Core_Map_Main_Adapters_Map
 * @requires   Ria_Core_Map_Main_Common_GeoPoint
 * @requires   Ria_Core_Map_EventsManager
 * @requires   Ria_Core_Map_MapOptions
 * @requires   Ria_AjaxManager
 * @requires   Ria_Core_Map_Main_Adapters_Events
 */
 var Ria_Core_Map_Main = new Class({
	queryOptions : new Hash(),
	initialize: function(driverId,options){
		//console.log('Ria_Core_Map_Main');
    	//глобальные переменные
        if(!$defined(window.riaMap)) window.riaMap = {};
        if(!$defined(window.riaMap.manager)) window.riaMap.manager = this;
    	window.riaMap.options = new Ria_Core_Map_MapOptions(); //эта переменная хранит настройки карты (id'шки элементов и т.п.)
    	riaMap.options = $merge(riaMap.options,options);

        window.riaMap.storage = new Object(); //эта переменная хранит ссылку на карту, на маркеры и слои
        window.riaMap.ajaxManager = new Ria_AjaxManager({spinner : riaMap.options.ajaxSpinner}); //эта переменная хранит менеджер аякс запросов
    	window.riaMap.events = new Ria_Core_Map_Main_Adapters_Events(); //эта переменная хранит менеджер событий карты
		if(riaMap.options.resizeMapEnabled) {
            this.calculateSize(false);
        }
		/* определяем стандартные переменные */
		if(driverId) {
   			riaMap.options.driverId = driverId;
   		}
   		if(riaMap.options.zoom != '') {
   			var zoom = riaMap.options.zoom;
   		} else {
   			var zoom = 60;
   		}

   		if(riaMap.options.lngt && riaMap.options.ltt) {
   			var lngt = riaMap.options.lngt;
   			var ltt = riaMap.options.ltt;
   		} else {
   			var lngt = 30.511413;
   			var ltt = 50.455203;
   		}
   		/* обьявляем карту */
   		riaMap.storage.map = new Ria_Core_Map_Main_Adapters_Map(riaMap.options.driverId,riaMap.options.mapContainer);
    	riaMap.storage.map.setCenter(new Ria_Core_Map_Main_Common_GeoPoint(lngt, ltt));
    	riaMap.storage.map.setZoom(zoom);
    	this.addElementsToMap(); //добавляем элементы к карте
 		riaMap.storage.map.paintMap();
 		this.eventManager = new Ria_Core_Map_EventsManager();
 		/* цепляем события */
 		if(!$defined(riaMap.options.noEvents)) {
 			this.addEvents();
 		}
		if(riaMap.options.autosearch.enabled){
			this.eventManager.execEventToSearch();
		}
 		this.addMapEvents();
 		if(riaMap.options.search.searchOnLoad && riaMap.options.search.enabled) {
 			$(riaMap.options.search.buttonId).fireEvent('click');
 		}
        if(riaMap.options.navigation.enabled) {
            if($defined(window.riaCityGeoPoints)) {
                var city_points = new Hash(window.riaCityGeoPoints);
                var array = $(riaMap.options.navigation.citySelectId).getElements('option');
                for(var i = 0;i<array.length;i++){
                    var key = array[i].getProperty('value');
                    if(city_points.has(key)) {
                        array[i].riaPointData = {};
                        array[i].riaPointData.longitude = city_points[key].geo_X;
                        array[i].riaPointData.latitude = city_points[key].geo_Y;
                    }
                }
            }
        }
        this.userInitialize();
        window.fireEvent('resize');
	},
	/**
	 * @param bool показывает, нужно ли изменять размер карты, или только контейнера
	 */
	calculateSize : function(is_resizeMap) {
		//console.log('Ria_Core_Map_Main->calculateSize');
	},

    userInitialize : function() {
		//console.log('Ria_Core_Map_Main->userInitialize');
    },

	addEvents : function() {
		//console.log('Ria_Core_Map_Main->addEvents');
		/* добавляем событие на изменения размера экрана */
        if(riaMap.options.resizeMapEnabled) {
            window.addEvent('resize',function() {
                this.calculateSize(true);
                this.calculateSize(true);
            }.bind(this));
        }
		/* добавляем событие на изменение локации */
        if(riaMap.options.navigation.enabled) {
            this.addNavigationEvents();
        }
		/* добавляем события на кнопки переключения карт */
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//        if(riaMap.options.mapChanger.enabled) {
//            $each(riaMap.options.mapChanger.maps,function(name,key){
//                if($defined($(riaMap.options.mapChanger['on' + name + 'Link']))) {
//                    $(riaMap.options.mapChanger['on' + name + 'Link']).addEvent('click',function(){
//                        this.changeMap(key);
//                    }.bind(this));
//                }
//            }.bind(this));
//        }
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

        if(riaMap.options.mapChanger.enabled) {
            $each(riaMap.options.mapChanger.maps,function(name,key){
                if($defined($(riaMap.options.mapChanger['on' + name + 'Link']))) {
                    $(riaMap.options.mapChanger['on' + name + 'Link']).addEvent('click',function(){
                        var maptypeChangParametr = 'changeMapTypeTo';
                        var mapNewLatitude = 'mapNewLtt';
                        var mapNewLongitude = 'mapNewLngt';
                        var mapNewZoom = 'mapNewZoom';
                        var url = window.location.toString();
                        var urlAdd = '';
                        var newUrl ='';
                        var uri = '';
                        var queryString = '';

                        if(url.indexOf("?")>=0) {
                            var strArr = url.split('?');
                            uri = strArr[0];
                            queryString = strArr[1];
                            var queryStringParamsArr = queryString.split('&');
                            var newQueryStringParamsArr = new Array();
                            $each(queryStringParamsArr,function(qsItem,qsIndex) {
                                if (!((qsItem.indexOf(maptypeChangParametr)>=0) || (qsItem.indexOf(mapNewLatitude)>=0) ||(qsItem.indexOf(mapNewLongitude)>=0) || (qsItem.indexOf(mapNewZoom)>=0)))
                                    newQueryStringParamsArr.push(qsItem);
                            }.bind(this));
                            var newQueryString = newQueryStringParamsArr.join('&');
                            urlAdd += '?';
                            urlAdd += newQueryString;
                            if (newQueryString.length) urlAdd += '&';
                        } else {
                            uri = url;
                            urlAdd += '?';
                        }
                        urlAdd += maptypeChangParametr + '=' + key;
                        urlAdd += '&' + mapNewLatitude + '=' + riaMap.storage.map.getCenter().getLatitude();
                        urlAdd += '&' + mapNewLongitude + '=' + riaMap.storage.map.getCenter().getLongitude();
                        urlAdd += '&' + mapNewZoom + '=' + riaMap.storage.map.getZoom();

                        newUrl = uri + urlAdd;

                        window.location = newUrl;
                    }.bind(this));
                }
            }.bind(this));
        }


// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
        if(riaMap.options.search.enabled) {
            this.eventManager.addEventToSearchForm(); //добавляем события на кнопку поиска
        }

        if(riaMap.options.geoSearch.enabled) {
            this.eventManager.addEventToGeoSearchForm(); //добавляем события на кнопку поиска
        }
	},

    addNavigationEvents : function() {
		//console.log('Ria_Core_Map_Main->addNavigationEvents');
        // добавляем событие на изменения города
        if($defined($(riaMap.options.navigation.citySelectId))) {
            $(riaMap.options.navigation.citySelectId).addEvent('change',function(){
                var value = $(riaMap.options.navigation.citySelectId).getProperty('value');
                if(value != 0) {
                    var option = $(riaMap.options.citySelectId + "_" + $(riaMap.options.navigation.citySelectId).getProperty('value'));
                    if($defined(option.riaPointData)) {
                        riaMap.storage.map.setCenter(
                            new Ria_Core_Map_Main_Common_GeoPoint(option.riaPointData.longitude,option.riaPointData.latitude)
                        );
                    }
                    if(riaMap.options.isSearch == '1') {
                        $(riaMap.options.search.buttonId).fireEvent('click');
                    }
                }
            });
        }


        /* добавляем событие на изменения области */
        if($defined($(riaMap.options.navigation.stateSelectId))) {
            $(riaMap.options.navigation.stateSelectId).addEvent('change',function(city_id){
                var citySelect = $(riaMap.options.navigation.citySelectId);
                citySelect.empty();
                if(typeof city_id == 'object') {
                    city_id = $(riaMap.options.navigation.stateSelectId).getProperty('value');
                }
                new Element('option',{value: 0}).inject(citySelect).set('text', Lang.load);
                citySelect.set('disabled', true);
                riaMap.ajaxManager.jsonRequest(Ria_Core_Ajax.script,function(response){
                    citySelect.empty();
                    citySelect.removeProperty('disabled');
                    if(response.result == 1) {
                        new Element('option',{'value': 0, 'id':riaMap.options.citySelectId+'_0'}).inject(citySelect).set('text', '- ' + response.any_city + ' -');
                        $each(response.cities, function(value,key){
                            var element = new Element('option', {'value': key, 'id':riaMap.options.citySelectId + '_' + key});
                            if ($defined(response.mapsCities)){
                                //alert(JSON.encode(response.mapsCities[key]));
                                if($defined(response.mapsCities[key])) {
                                    element.riaPointData = {};
                                    element.riaPointData.longitude = response.mapsCities[key].geo_X;
                                    element.riaPointData.latitude = response.mapsCities[key].geo_Y;
                                }
                            }

                            if (key == city_id) {
                                element.setProperty('selected','selected');
                                citySelect.fireEvent('change',{},100);
                            }
                            element.inject(citySelect).set('text', value);
                        }, this);
                    }
                }.bind(this),{
                    'target' : 'addrNew',
                    'event' : 'getCities',
                    'state_id' : $(riaMap.options.navigation.stateSelectId).getProperty('value'),
                    'with_map' : '1'
                },true);
            });
        }
    },
	addMapEvents : function() {
		//console.log('Ria_Core_Map_Main->addMapEvents');
		this.eventManager.addEventToMap('zoomchange');
		this.eventManager.addEventToMap('enddrag');
	},

	changeMap : function(driverId) {
		//console.log('Ria_Core_Map_Main->changeMap');
		if(riaMap.options.driverId != driverId) {
			var options = {
				'alreadySearched' : riaMap.options.search.alreadySearched,
				'zoom' : riaMap.storage.map.getZoom() + '',
				'lngt' : riaMap.storage.map.getCenter().getLongitude() + '',
				'ltt' : riaMap.storage.map.getCenter().getLatitude() + '',
				'noEvents' : 'true'
			}
//			//console.log();
			//alert(JSON.encode(options));
			riaMap.storage.map.destructMap();
//			delete riaMap.storage;
			for(var x in riaMap.storage) {
				delete riaMap.storage[x];
			}
			this.initialize(driverId,options);
		}
	},

    showInGroup : function(group_id,point_id,zoomchange) {
		//console.log('Ria_Core_Map_Main->showInGroup');
		if(zoomchange) {
			var zoom = riaMap.storage.map.getZoom();
			riaMap.storage.groupZoom = zoom;
			riaMap.storage.pointInGroupId = point_id;
			riaMap.storage.group_id = group_id;
			riaMap.storage.map.setCenter(riaMap.storage.markers.get('local_' + group_id + "_0").getGeoPoint());
			riaMap.storage.map.setZoom(100);
		} else {
	    	var marker = riaMap.storage.layers.get('local_0').getMarkers().filter(function(point){
	    		return (point.point_id == group_id);
	    	}).getValues()[0];
			riaMap.ajaxManager.htmlRequest(Ria_Core_Ajax.script,function(html) {
					var div = new Element('div').set('html',html);
					var name_div = div.getElement('div').getElement('div');
					var title = name_div.get('text');
					if(riaMap.options.driverId == 1){
						name_div.destroy();
					}
					marker.addInfoWindow(title,div.get('html'));
					marker.openInfoWindow();
					//marker.infoWindowHtml = '';
			}.bind(this),{
				'target' : 'map',
				'event' : 'description',
				'id' : point_id,
				'is_group' : 0,
				'backward' : 1
			});
		}
    },
    backToGroup : function() {
		//console.log('Ria_Core_Map_Main->backToGroup');
    	riaMap.storage.backToGroup = 1;
    	riaMap.storage.map.setZoom(riaMap.storage.groupZoom);
//		setTimeout('this.backToGroupTimer()',200);
//		this.backToGroupTimer();
    },
    showGroup : function(longitude,latitude) {
		//console.log('Ria_Core_Map_Main->showGroup');
    	var zoom = riaMap.storage.map.getZoom();
    	if(zoom >= 85) {
    		var i = 100-zoom;
    	} else {
    		var i = 15;
    	}
    	riaMap.storage.map.setCenter(new Ria_Core_Map_Main_Common_GeoPoint(longitude,latitude));
    	riaMap.storage.map.setZoom(zoom+i);
    	//riaMap.events.fireEvent(riaMap.storage.map,'zoomchange');
    },

    makeGetParametrs : function(event) {
		//console.log('Ria_Core_Map_Main->makeGetParametrs');
    	var getParametrs = {
			'target'	:	riaMap.options.ajaxDialog,
			'searchOptions'	:	this.queryOptions.toQueryString(),
			'event'		:	event,
            'core_rewrite_off' : 1
        };
        var elements = $$('#' + riaMap.options.search.fieldsContainer + ' .' + riaMap.options.search.className);
        $each(elements,function(value){
            if(value.getProperty('type') != 'radio') {
                getParametrs[value.getProperty('id')] = value.getProperty('value');
            }else if(value.getProperty('type') == 'radio') {
                if(value.getProperty('checked')) {
                    getParametrs[value.getProperty('name')] = value.getProperty('value');
                }
            }
        }.bind(this));
//			'ob_type' : ($(riaMap.options.realtySaleRadioId).getProperty('checked'))? 1 : 2,
//			'realty_type' : $(riaMap.options.realtyTypeSelectId).getProperty('value').toInt(),
//			'kom_s' : $(riaMap.options.komSFieldId).getProperty('value'),
//			'kom_po' : $(riaMap.options.komPoFieldId).getProperty('value'),
//			'price_s' : $(riaMap.options.priceSFieldId).getProperty('value'),
//			'price_po' : $(riaMap.options.pricePoFieldId).getProperty('value'),
//			'currency_id' : $(riaMap.options.currencyFieldId).getProperty('value')
////            'extra_types' : $(riaMap.options.extra_types_input).getProperty('value')
//		};
		if($defined(riaMap.storage.pointInGroupId)) {
			getParametrs.highlightPointId = riaMap.storage.pointInGroupId;
			delete riaMap.storage.pointInGroupId;
		}
		return getParametrs;
    },

	addElementsToMap : function() {
		//console.log('Ria_Core_Map_Main->addElementsToMap');
        if(riaMap.options.resizeMapEnabled) {
            this.paintFullscreenToggleButton();
        }
        if(riaMap.options.ajaxSpinner) {
            this.paintAjaxSpinner();
        }
	},

    toggleMapSize : function() {
		//console.log('Ria_Core_Map_Main->toggleMapSize');
    },

    paintAjaxSpinner : function() {
		//console.log('Ria_Core_Map_Main->paintAjaxSpinner');
    },

    paintFullscreenToggleButton : function() {
		//console.log('Ria_Core_Map_Main->paintFullscreenToggleButton');
    }
});
/**
 *
 * Класс-конфигуратор карты, который наследует основной
 *
 * @class Ria_Map_Init
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    ID:
 * @requires   Ria_Core_Map_Main
 */
var Ria_Map_Init = new Class({
    Extends : Ria_Core_Map_Main,
	
    initialize : function(driverId, options){
        options = $merge(options,{
            'mapContainer'  : 'bigMapContainer',
            'ajaxDialog'    : 'autoservice',
            'search' : {
                'enabled'           : 0,
                'className'         : 'search',
                'fieldsContainer'   : 'container-serch-f',
                'buttonId'          : 'submit_search',
                'searchOnLoad'      : 1
            },

            'navigation' : {
                'enabled'       : 0,
                'stateSelectId' : 'left_state_panel',
                'citySelectId'  : 'left_city_panel'
            },

            'mapChanger' : {
                'enabled' : 0,
                'maps' : {
                    '1':'Visicom',
                    '2':'Yandex',
                    '3':'Google'
                },
                'onVisicomLink' : 'visicom_change_link',
                'onYandexLink'  : 'yandex_change_link',
                'onGoogleLink'  : 'google_change_link'
            },

            'geoSearch' : {
                'enabled'       : 0,
                'buttonId'      : 'geosearch_submit_id',
                'textFieldId'   : 'geosearch_input_field',
                'resultBlock'   : 'geosearch_result_block'
            },

            'globalPoints' : {
                'enabled'               : 0,
                'openerInputField'      : 'extra_types',
                'openerDivContainer'    : 'extraObjectsDivContainer',
                'checkboxesContainer'   : 'checkbox_container',
                'submitButton'          : 'types_window_button',
                'drawFunc'              : 'paintCheckboxResult'
            },

            'autosearch'    : {
                'enabled'   : 0
            },

            'offset'            : 0.007,
            'resizeMapEnabled'  : 1,
            'ajaxSpinner'       : 'ajax_loader'
        });

        this.parent(driverId, options);

        if ($defined($('maximizeMap'))){
            $('maximizeMap').addEvent('click',function(){
                $('ajax_loader').setStyles({
                    'top':window.getSize().y - 40,
                    'height':40,
                    'width':window.getSize().x-2,
                    'left':0,
                    'right':0,
                    'bottom':0
                });
                $('maps').setStyles({
                    'position':'absolute',
                    'padding':'0',
                    'left':'0px',
                    'top':'0px',
                    'z-index':10001
                });
                $('bigMapContainer').setStyles({
                    'padding':'0',
                    'width':window.getSize().x-2,
                    'height':window.getSize().y-2
                });
                $('maximizeC').setStyle('display','none');
                $('minimizeC').setStyles({
                    'display':'block',
                    'left':window.getSize().x-141,
                    'top':30
                });
                //			$('ajax_loader').setStyle('position','relative');
                new Fx.Scroll(window,{
                    duration:1
                }).toElement('maps');
                riaMap.storage.map.resizeMap();
            });
        }

        if ($defined($('maximizeMap'))){
            $('minimizeMap').addEvent('click',function(){
                $('ajax_loader').setStyles({
                    'top':'',
                    'height':'',
                    'width':'',
                    'left':0,
                    'right':0,
                    'bottom':0
                });
                $('maps').setStyles({
                    'position':'relative',
                    'padding':0,
                    'left':'0px',
                    'top':'0px',
                    'z-index':10001
                });
                $('bigMapContainer').setStyles({
                    'width': '585px',
                    'height': '350px'
                });
                $('maximizeC').setStyle('display','block');
                $('minimizeC').setStyle('display','none');
                new Fx.Scroll(window,{
                    duration:500
                }).toElement('maps');
                riaMap.storage.map.resizeMap();
            });
        }
    },

    addSubmitEvent : function(id){
        $('searchPointsForm').addEvent('submit', function(e) {
            e.stop();
            this.queryOptions = this.getFormSendValues();
            
            var sV = this.parse_str(this.queryOptions);
            var sS = this.queryOptions.searchStr;

            if ($defined($('sPanMapSeach'))) $('sPanMapSeach').setProperty('href', './autoservice/search_map/'+sV+'searchStr='+sS);
            if ($defined($('swType_1'))) $('swType_1').setProperty('href', './autoservice/search_map/sto/?searchStr='+sS);
            if ($defined($('swType_2'))) $('swType_2').setProperty('href', './autoservice/search_map/autozapchasti/?searchStr='+sS);
            if ($defined($('swType_3'))) $('swType_3').setProperty('href', './autoservice/search_map/automoyki/?searchStr='+sS);
            if ($defined($('swList'))) $('swList').setProperty('href', './autoservice/search_list/'+sV+'searchStr='+sS);
//            console.log(sV);
//            console.log(sS);

            this.eventManager.execEventToSearch();
        }.bind(this));
    },

    parse_str: function(s) {
        var str = '?';
        s.each(function(item, index){
            if (index.match(/searchValues\S*/)) str += index+'='+item+'&';
        });
        return str;
    },


    getFormSendValues:function(){
        var ret = new Hash();
        $('searchPointsForm').getElements('input').each(function(element){
            if (!element.getProperty('disabled')){
                switch (element.getProperty('type')){
                    case 'checkbox':
                        if (element.getProperty('checked')) ret.set(element.getProperty('name'), element.value);
                        break;
                    case 'text':
                        ret.set(element.getProperty('name'), element.value);
                        break;
                    case 'hidden':
                        ret.set(element.getProperty('name'), element.value);
                        break;
                    case 'radio':
                        if (element.getProperty('checked')) ret.set(element.getProperty('name'), element.value);
                        break;
                }
            }
        });

        $('searchPointsForm').getElements('select').each(function(element){
            if (!element.getProperty('disabled')) {
                if (element.value > 0 && element.getProperty('id') != 'region-s') {
                    ret.set(element.getProperty('name'), element.value);
                }
            }
        });
        
        return ret;
    },

    calculateSize : function(is_resizeMap) {
        if(riaMap.options.isFullscreen) {
            var width = window.getSize().x-2;
            var height = window.getSize().y-2;
        } else {
            var width = window.getSize().x/2;
            var height = window.getSize().y/2;
        }
        if(is_resizeMap) {
            riaMap.storage.map.resizeMap(width,height);
        }
    },

    toggleMapSize : function() {
        var left_panel = $('main').getElements('div').filter(function(item){
            return item.hasClass('left_panel');
        })[0];
        if(!riaMap.options.isFullscreen) {
            left_panel.setStyle('display','none');
            $('top_panel').setStyle('display','none');
            $('submenu_full').setStyle('display','none');
            $('main').setStyles({
                'padding-top' : '0px',
                'padding-left' : '0px'
            });
            $(riaMap.options.mapContainer).setStyle('margin-left','0px');
            riaMap.options.isFullscreen = true;
            riaMap.storage.fullscreenToggleLink.setProperty('class','min_size_maps');
            riaMap.storage.fullscreenToggleLink.set('text','свернуть');
        } else {
            riaMap.options.isFullscreen = false;
            $(riaMap.options.mapContainer).setStyle('width','640px');
            riaMap.storage.fullscreenToggleLink.set('text','развернуть');
            riaMap.storage.fullscreenToggleLink.setProperty('class','max_size_maps');
        }
        window.fireEvent('resize');
    },

    paintAjaxSpinner : function() {
        new Element('div',{
            'id':riaMap.options.ajaxSpinner,
            'class':'LoaderMaps'
        }).grab(
            new Element('div',{
                'class':'LevelTwo'
            }).grab(
                new Element('div').grab(
                    new Element('img',{
                        'src' : 'http://img.dom.ria.ua/img/map_icons/loader/loader.gif',
                        'width' : '220px',
                        'height' : '19px',
                        'alt' : 'Ajax Loader'
                    })
                    )
                )
            ).inject($(riaMap.options.mapContainer));
        this.calculateSize(false);
    },

    paintFullscreenToggleButton : function() {
        riaMap.storage.fullscreenToggleLink = new Element('a',{
            'href' : 'javascript:void(0)',
            'class' : 'max_size_maps'
        }).set('text','развернуть');
        new Element('div',{
            'class':'FlyPanel_ResizeMaps'
        }).grab(
            new Element('div',{
                'class':'LevelTwo'
            }).grab(
                new Element('div').grab(riaMap.storage.fullscreenToggleLink)
                )
            ).inject($(riaMap.options.mapContainer));
        riaMap.storage.fullscreenToggleLink.addEvent('click',this.toggleMapSize.bind(this));
    },

    paintCheckboxResult : function(active) {
        var container = $(riaMap.options.globalPoints.openerDivContainer);
        var ul = new Element('ul');
        active.each(function(value){
            ul.grab(new Element('li').set('text',value));
        });
        container.set('html','');
        container.grab(ul);
    }
});

