/** * Advanced.class.js* */
Advanced = Class.create();
Advanced.prototype = {
    form : null,
    container : null,
    advanced_container:null,
    request_text : 'Ваш запрос',
    initialize : function(form, container, request_text) {
        this.form = $(form);
        this.assignInputs(form);
        this.container = $(container);
        if (undefined != request_text) {
            this.request_text = request_text;
        }
    },

    onChangeState : function(e) {
        var options = {
            method : this.form.method,
            parameters : 'getlist=1&' + this.form.serialize(),
            onSuccess : this.buildList.bind(this)
        };
        new Ajax.Request(this.form.action, options);
    },

    assignInputs : function(target) {
        target = $(target);
        target.getElementsBySelector('input', 'select').each(
                function(element) {
                    element.observe('change', this.onChangeState
                            .bindAsEventListener(this));
                }.bind(this));
        this.onChangeState(target);
    },
    buildList : function(transport) {
        var json = transport.responseText.evalJSON(true);
        if (json.list.length > 0) {
            this.container.update(new Element('li').setStyle('color:#ff7701')
                    .update(this.request_text));
            json.list.each(function(item) {
                this.container.insert(new Element('li').update(item));
            }.bind(this));
            if (!this.container.visible()) {
                this.container.appear();
            }
        } else if (this.container.visible()) {
            this.container.fade( {
                afterFinish : function(effect) {
                    this.container.update(new Element('li'));
                }.bind(this)
            });
        }
    },
    advancedLink : function(link, container) {
        if (undefined == link || undefined == container) {
            throw "Advanced link not assigned";
        }
     this.advanced_container = $(container); 
     this.link = $(link);
     this.link.observe('click', function(e) {
         var span = this.link.next('span');
         if (Object.isUndefined(span.textContent)) {
             var modulate = span.innerText;    
         } else {
             var modulate = span.textContent;   
         }
        if (this.advanced_container.visible()) {
            this.advanced_container.blindUp({duration:0.5,afterFinish:function(effect){
                if (span && modulate) span.update(modulate.replace('-','+'));
            }.bind(this)});
        } else {
            this.advanced_container.blindDown({duration:0.5});
            if (span && modulate) span.update(modulate.replace('+','-'));
        }
    }.bindAsEventListener(this));
}
}
/** Advanced.class.js end**** */

/** AdvtImageManager.class.js* */
AdvtImageManager = Class.create();
var cacheBigImages = $H();
AdvtImageManager.prototype = {
	messages : null,
	activeImage : null,
	big_photo : null,
	initialize : function(container, messages) {
		if (undefined == messages) {
			throw "Messages not assigned";
		} else {
			this.messages = $H(messages);
		}
		this.photocounter = $('photo_counter'),
				this.nophoto = "/img/no-photo.png",
				new Image().src = this.nophoto;
		this.big_photo = $('big_photo');

		this.container = $(container);
		if (!this.container)
			return;
		this.createSortable();
		this.container.getElementsBySelector('form').each(
						function(form) {
							this.assignForm(form);
						}.bind(this));
		Event.observe(window, 'load', function() {// load big images
					    cacheBigImages.each(function(src) {
						imgManager.cacheImage(src.key,src.value);
					});
				});
	},
 
	assignForm:function(form) {
	var img =form.down('img');
        img.observe('mouseover', this.onImgMouseOver.bindAsEventListener(this));
        img.observe('mousedown', this.onImgClick.bindAsEventListener(this));
        this.cacheImage(form.down('input[name=image_id]').getValue(), form.down('input[name=image_src]').getValue());
		form.down('input[name=delete]').observe('click', this.onDeleteClick.bindAsEventListener(this));;
        form.down('input[name=turn_left]').observe('click', this.onRotateLeft.bindAsEventListener(this));;
        form.down('input[name=turn_right]').observe('click', this.onRotateRight.bindAsEventListener(this));;
	},
	
	
	cacheImage:function(id, src) {
		if (!cacheBigImages.get(id)) {
		    var img = new Image();
		    img.src=src;
		    cacheBigImages.set(id,img);
		    return src;
		} else {// update
			var img = cacheBigImages.get(id);
			img.src=img.src + '&rnd=' + Math.random();
			return img.src;
		}
	},
	
	
	createSortable:function(){
		var options = {
				overlap : 'horizontal',
				constraint : false,
				onUpdate : this.onSortUpdate.bind(this)
			};
			Sortable.create(this.container, options);
	},
	onSortUpdate : function(draggable) {
		var form = this.container.down('form');
		var options = {
			method : form.method,
			parameters : 'reorder=1&' + Sortable.serialize(draggable),
			onSuccess : function() {
				message_clear();
			}
		};
		if (undefined != this.messages.get('onSort'))
			message_write(this.messages.get('onSort'),'messages_notify');
		new Ajax.Request(form.action, options);
	},

	unsetActive : function() {
		if (this.activeImage != null) {
			var active_pict = $('photo_pict_' + this.activeImage);
			if (active_pict && active_pict.hasClassName('active_pict'))
				active_pict.removeClassName('active_pict');
		}
	},
	setActive : function(id) {
		if (this.activeImage == id)
			return;
		var pict = $('photo_pict_' + id);
		this.unsetActive();
		if (pict && !pict.hasClassName('active_pict')) {
			this.activeImage = id;
			pict.addClassName('active_pict');
			var src = pict.down('input[name=image_src]');
			if (src)
				this.big_photo.src = src.getValue();
		}
	},
	onImgClick : function(e) {
		var img = Event.element(e);
		if (img)
			var id = img.previous('input[name=image_id]');
		if (id) {
			this.unsetActive();
			this.setActive(id.getValue());
		}
	},

	onImgMouseOver : function(e) {
		var img = Event.element(e);
		if (null == this.activeImage) {
			var id = img.previous('input[name=image_src]');
			if (id)
				this.big_photo.src = id.getValue();
		}

	},

	onDeleteClick : function(e) {
		Event.stop(e);
		var element = Event.element(e);
		var form = element.up('form');
		if (!form)
			this.onDeleteFailure(e);
		var options = {
			method : form.method,
			parameters : form.down('input[name=image_id]').serialize() + '&'
					+ element.serialize(),
			onSuccess : this.onDeleteSuccsess.bind(this),
			onFailure : this.onDeleteFailure.bind(this)
		}
		this.setActive(form.down('input[name=image_id]').getValue());
		if (undefined != this.messages.get('ondelete')) {
			message_write(this.messages.get('ondelete'),'messages_notify');
		}
		new Ajax.Request(form.action, options);
	},

	onDeleteSuccsess : function(transport) {
		var json = transport.responseText.evalJSON(true);
		if (json.deleted) {
			if (undefined != this.messages.get('ondeletesuccess')) {
				message_write(this.messages.get('ondeletesuccess'),'messages_notify');
			}
			var image_id = json.image_id;
			var input = this.container.down('input[value=' + image_id + ']');
			if (json.photo_count > 0) {
				if (this.activeImage == null || this.activeImage == image_id) {
					var next_pict = input.up('li').next('li');
					if (next_pict) {
						var next_id = next_pict.down('input[name=image_id]')
								.getValue();
					} else if (json.photo_count > 1) {
						var next_pict = input.up('li').previous('li');
						if (next_pict)
							var next_id = next_pict.down('input[name=image_id]').getValue();
					}
				}

			}
			if (input) {
				var options = {
					duration : 0.3,
					afterFinish : function(effect) {
						message_clear();
						effect.element.remove();

					}
				}
				if (json.photo_count >= 0 && this.photocounter) {
					this.setImgCount(json.photo_count);
					if (json.photo_count == 0) {
						this.big_photo.src = this.nophoto;
					} else {
						if (next_id > 0) {
							this.setActive(next_id);
						}
					}
				}
				new Effect.Fade(input.up('li'), options);
				return;
			}
		}
	},

	setImgCount:function(count) {
		if (count>=0) {
			this.photocounter.update(count);
		}
	},
	onDeleteFailure : function(transport) {
		if (undefined != this.messages.get('ondeletefailure'))
			message_write(this.messages.get('ondeletefailure'));
	},

	onRotateLeft : function(e) {
		Event.stop(e);
		var element = Event.element(e);
		var form = element.up('form');
		if (!form)
			this.onRotateFailure(e);
		var options = {
			method : form.method,
			parameters : form.down('input[name=image_id]').serialize() + '&'
					+ element.serialize(),
			onSuccess : this.onRotateSuccess.bind(this),
			onFailure : this.onRotateFailure.bind(this)
		}
		this.setActive(form.down('input[name=image_id]').getValue());
		if (undefined != this.messages.get('onrotate')) {
			message_write(this.messages.get('onrotate'),'messages_notify');
		}
		new Ajax.Request(form.action, options);
	},

	onRotateRight : function(e) {
		Event.stop(e);
		var element = Event.element(e);
		var form = element.up('form');
		if (!form)
			this.onRotateFailure(e);
		var options = {
			method : form.method,
			parameters : form.down('input[name=image_id]').serialize() + '&'
					+ element.serialize(),
			onSuccess : this.onRotateSuccess.bind(this),
			onFailure : this.onRotateFailure.bind(this)
		}
		this.setActive(form.down('input[name=image_id]').getValue());
		if (undefined != this.messages.get('onrotate')) {
			message_write(this.messages.get('onrotate'),'messages_notify');
		}
		new Ajax.Request(form.action, options);
	},

	onRotateSuccess : function(transport) {
		var json = transport.responseText.evalJSON(true);
		if (json.rotated) {
			if (undefined != this.messages.get('onrotatesuccess')) {
				message_write(this.messages.get('onrotatesuccess'),'messages_notify');
			}
			var image_id = json.image_id;
			var input = this.container.down('input[value=' + image_id + ']');
			var src = input.next('input[name=image_src]');
			var img = input.next('img');
			if (img) {
				img.src = img.src + '&rnd=' + Math.random();
				this.big_photo.src = this.cacheImage(image_id,src.getValue());
			}
			message_clear();
		}
	},

	onRotateFailure : function(transport) {
		if (this.messages.get('onrotatefailue'))
			message_write(this.messages.get('onrotatefailure'));
	},

}

/** *AdvtLocation.class.js* */
AdvtLocation = Class.create();
AdvtLocation.getInstance=function() {
    if ( typeof AdvtLocation.instance == 'undefined' ) {
        // It has not... perform the initilization
        AdvtLocation.instance = new AdvtLocation();
    }
    return AdvtLocation.instance;
}
AdvtLocation.isNull = function() {
    return AdvtLocation.instance==null;
}
AdvtLocation.hide = function() {
    if (typeof AdvtLocation.instance == 'undefined')
        return;
    AdvtLocation.instance.hideMap();
}
AdvtLocation.prototype = {
    container : null,
    mapContainer : null,
    map : null,
    markers   : $A([]),
    markerTemplate : new Template('<div class="advt_teaser">#{desc}</div>'),
    initialize : function() {
    
    },
    isSetContainer:function() {
      return !this.container ==null;  
    },
    visible:function() {
      return this.mapContainer.visible();  
    },
    hideMap:function() {
      this.mapContainer.hide(); 
      this.description.hide();
    },
    show:function() {
      this.mapContainer.show(); 
      this.description.show();
    },
    setContainer:function(container) {
        this.container = $(container);
        if (!this.container) {
            return;
        }
        this.mapContainer = this.container.down('.map-container');
        if (!this.mapContainer.visible()) {
             this.mapContainer.show();
             this.loadMap();
        } else {  
          if (!document.loaded) { 
              Event.observe(window, 'load', this.loadMap.bind(this));
          } else {
              this.loadMap();   
          }
           
        }
        this.description = this.container.down('.photo_footer_description');
        if (this.description&&!this.description.visible())
             this.description.show();
        Event.observe(window, 'unload', function() {
            GUnload();
        });
    },
    loadMap : function() {
        if (!GBrowserIsCompatible())
            return;
        this.map = new GMap2(this.mapContainer);
        this.map.setCenter(new GLatLng(46.469328, 30.735562), 13);
        this.map.enableScrollWheelZoom();
        this.map.enableDoubleClickZoom();
        this.map.enableContinuousZoom();
        this.map.addControl(new CustomMapTypeControl());
        this.map.addControl(new CustomZoomControl());
        this.assignMarkers();  
    },
    assignMarkers:function() {
        if (this.markers.size()!=0) {
            this.map.closeExtInfoWindow();
            this.markers.each(function(marker){
                this.map.removeOverlay(marker);
                }.bind(this));
            this.markers.clear(); 
        }
        this.container.getElementsBySelector('.map-item').each(function(item) {
            var geo = item.down('.geo');
            coords = geo.title.split(';');
            advt =item.down('.advt_teaser');
            if (advt) {
                this.addMarkerToMap(
                     coords[0],
                     coords[1],
                     advt.innerHTML
                );
            } else {
                this.addMarkerToMap(
                        coords[0],
                        coords[1]
                   );
            }
        }.bind(this));
        this.zoomAndCenterMap();
        if (this.markers.size()==1)
        GEvent.trigger(this.markers.first(), 'click');
    },
    zoomAndCenterMap : function()
    {
        if (this.markers.size() == 0) {
            this.map.setCenter(new google.maps.LatLng(0, 0),1);
            return;
        } 
        var bounds = new google.maps.LatLngBounds();
        this.markers.each(function(marker) {
            bounds.extend(marker.getPoint());
        });
        var zoom = Math.max(1, this.map.getBoundsZoomLevel(bounds) - 1);
        if (this.markers.size()==1) {
            zoom = 13;   
        }
        this.map.setCenter(bounds.getCenter(), zoom);
    },
    addMarkerToMap : function(lat, lng, desc, teaser) {
        var myIcon = new GIcon(G_DEFAULT_ICON);
        myIcon.shadow = "";
        myIcon.image = "/img/house_marker2.png";
        myIcon.iconSize = new GSize(32, 32);
        myIcon.iconAnchor = new GPoint(9, 34);
        myIcon.infoWindowAnchor = new GPoint(16, 2);
        var marker = new GMarker(new GLatLng(lat, lng), {
            'icon' : myIcon,
            draggable : false
        });
        if (desc) {
            var html = this.markerTemplate.evaluate( {
                'lat' : lat,
                'lng' : lng,
                'desc' : desc
            });
            GEvent.addListener(marker, 'click', function() {
                marker.openExtInfoWindow(this.map, "advt_mapinfo_window", html, {paddingX:20,paddingY:20,
                    noCloseOnClick : false
                });
            }.bind(this));
        }
        this.map.addOverlay(marker);
        this.markers.push(marker);
    },
}
/** *Advt LocationManager.class.js** */
AdvtLocationsManager = Class.create();
AdvtLocationsManager.prototype = {

    url : null,
    method : null,
    advt_id : null,
    container : null, // DOM element in which map is shown
    map : null, // The instance of Google Maps
    geocoder : null, // Used to look up addresses
    messges : null,
    marker : null, // holds all markers added to map
    markerTemplate : null,

    initialize : function(container, form, advt_id, options) {
        form = $(form);
        this.url = form.action;
        this.method = form.method;
        this.advt_id = advt_id;
        this.container = $(container);
        this.messages = $H(options.messages);
        this.geocoder = new GClientGeocoder();
        this.markerTemplate = new Template(' #{desc}');
        Event.observe(window, 'load', this.loadMap.bind(this));
        Event.observe(window, 'unload', function() {
            GUnload();
        });
        form.observe('submit', this.onFormSubmit.bindAsEventListener(this));
    },

    loadMap : function() {
        if (!GBrowserIsCompatible())
            return;
        this.map = new GMap2(this.container);
        this.map.setCenter(new GLatLng(46.469328, 30.735562), 13);
        this.map.enableScrollWheelZoom();
        this.map.addControl(new CustomMapTypeControl());
        this.map.addControl(new CustomZoomControl());
        this.map.enableDoubleClickZoom();
        this.map.enableContinuousZoom();
        var options = {
            parameters : 'action=get&advt_id=' + this.advt_id,
            onSuccess : this.loadLocationsSuccess.bind(this)
        }

        new Ajax.Request(this.url, options);
    },
    removeMarker : function() {
        if (null != this.marker) {
            this.map.removeOverlay(this.marker);
            this.marker = null;
        }
    },

    zoomAndCenter : function() {
        this.map.setCenter(new GLatLng(this.marker.qa.y, this.marker.qa.x), 13);
    },
    addMarkerToMap : function(id, lat, lng, desc, teaser) {
        this.removeMarker();
        var myIcon = new GIcon(G_DEFAULT_ICON);
        myIcon.shadow = "";
        myIcon.image = "/img/house_marker2.png";
        myIcon.iconSize = new GSize(32, 32);
        myIcon.iconAnchor = new GPoint(9, 34);
        myIcon.infoWindowAnchor = new GPoint(16, 2);
        var marker = new GMarker(new GLatLng(lat, lng), {
            'icon' : myIcon,
            draggable : true
        });
        marker.location_id = id;
        var that = this;

        GEvent.addListener(marker, 'dragend', function() {
            that.dragComplete(this);
        });
        GEvent.addListener(marker, 'dragstart', function() {
            this.closeExtInfoWindow();
        });

        var html = this.markerTemplate.evaluate( {
            'location_id' : id,
            'lat' : lat,
            'lng' : lng,
            'desc' : desc
        });

        var node = Builder.build(desc);

        var button = node.down('input');
        button.setAttribute('location_id', id);
        button.observe('click', this.onRemoveMarker.bindAsEventListener(this));
        GEvent.addListener(marker, 'click', function() {
            marker.openExtInfoWindow(this.map, "advt_mapinfo_window", html, {paddingX:20,paddingY:20,
                noCloseOnClick : true
            });
        }.bind(this));
        this.map.addOverlay(marker);
        GEvent.trigger(marker, 'click');
        this.marker = marker;
        return marker;
    },

    loadLocationsSuccess : function(transport) {
        var json = transport.responseText.evalJSON(true);
        if (json.location == null && json.address != null) {
            $('location-input').setValue(json.address);
            this.geocoder.getLocations(json.address, this.createPoint
                    .bind(this));
        } else {
            this.addMarkerToMap(json.location.location_id,
                    json.location.latitude, json.location.longitude,
                    json.location.content);
            this.zoomAndCenter();
        }
    },

    onFormSubmit : function(e) {
        Event.stop(e);

        var form = Event.element(e);
        var address = $F(form.location).strip();

        if (address.length == 0)
            return;

        this.geocoder.getLocations(address, this.createPoint.bind(this));
    },

    createPoint : function(locations) {
        if (locations.Status.code != G_GEO_SUCCESS) {
            // something went wrong:
            var msg = '';
            switch (locations.Status.code) {
            case G_GEO_BAD_REQUEST:
                msg = this.messages.get('error_parse');// 'Unable to parse
                // request';
                break;
            case G_GEO_MISSING_QUERY:
                msg = this.messages.get('bad_query');// 'Query not
                // specified';
                break;
            case G_GEO_UNKNOWN_ADDRESS:
                msg = this.messages.get('unknown_address');// 'Unable to find
                // address';
                break;
            case G_GEO_UNAVAILABLE_ADDRESS:
                msg = this.messages.get('forbidden_addres');// 'Forbidden
                // address';
                break;
            case G_GEO_BAD_KEY:
                msg = this.messages.get('invalid_key');// 'Invalid API key';
                break;
            case G_GEO_TOO_MANY_QUERIES:
                msg = this.messages.get('many_queryes');// 'Too many geocoder
                // queries';
                break;
            case G_GEO_SERVER_ERROR:
            default:
                msg = this.messages.get('unknonw_error');// 'Unknown server
                // error occurred';
            }
            message_write(msg, 'error_message');
            return;
        }

        var placemark = locations.Placemark[0];

        var options = {
            method : this.method,
            parameters : 'action=add' + '&advt_id=' + this.advt_id
                    + '&latitude=' + placemark.Point.coordinates[1]
                    + '&longitude=' + placemark.Point.coordinates[0],
            onSuccess : this.createPointSuccess.bind(this)
        }

        new Ajax.Request(this.url, options);
    },

    createPointSuccess : function(transport) {
        var json = transport.responseText.evalJSON(true);

        if (json.location_id == 0) {
            message_write('Error adding location to blog post');
            return;
        }

        marker = this.addMarkerToMap(json.location_id, json.latitude,
                json.longitude, json.content);
        this.zoomAndCenter();
        GEvent.trigger(marker, 'click');
    },

    dragComplete : function(marker) {
        var point = marker.getPoint();
        var options = {
            parameters : 'action=move' + '&advt_id=' + this.advt_id
                    + '&location_id=' + marker.location_id + '&latitude='
                    + point.lat() + '&longitude=' + point.lng(),
            onSuccess : this.onDragCompleteSuccess.bind(this)
        }

        new Ajax.Request(this.url, options);
    },

    onDragCompleteSuccess : function(transport) {
        var json = transport.responseText.evalJSON(true);

        if (json.location_id) {
            var point = new GLatLng(parseInt(json.latitude),
                    parseInt(json.longitude));

            this.addMarkerToMap(json.location_id, json.latitude,
                    json.longitude, json.content);

        }
    },

    onRemoveMarker : function(e) {
        var button = Event.element(e);
        var location_id = button.getAttribute('location_id');

        var options = {
            parameters : 'action=delete' + '&advt_id=' + this.advt_id
                    + '&location_id=' + location_id,
            onSuccess : this.onRemoveMarkerSuccess.bind(this)
        };

        new Ajax.Request(this.url, options);
    },

    onRemoveMarkerSuccess : function(transport) {
        var json = transport.responseText.evalJSON(true);

        if (json.location_id)
            this.removeMarker();
    }
};
/** *Ajax_carusel.js** */
Ajax_Carusel = Class.create();
Ajax_Carusel.prototype = {
    count:10,
    items:null,
    carusel:null,
    carusel_id:null,
    about:null,
    initialize : function(params) {
	    var params = $H(params);
        if (undefined==params.get('action')) {
            throw "Action not assigned";
            exit();
        }
        if (undefined==params.get('carusel')) {
            throw "Carusel block not assigned";	
        } else {
           this.carusel_id = params.get('carusel');	
           this.carusel = $(params.get('carusel'));	
        }
        if (undefined!=params.get('about')) {
            this.about = $(params.get('about'));
        } else {
            throw "About block not assigned";
        }
        if (params.get('count')>0) {
            this.count=params.get('count');
        }
        
        var options = {
            method:'get',
            parameters:'count='+this.count,
            onSuccess:this.loadCarusel.bind(this)
        };
        new Ajax.Request(params.get('action'), options);
    },
    loadCarusel:function(transport) {
        var json = transport.responseText.evalJSON();
            this.items = $H(json);
            this.items.each(function(e,index){
                this.createSlide(e,index);
            	}.bind(this));
            new ImageSpinner(this.carusel_id,'/img/loadinfo.gif','img-notload',140,105);
           this.carousel_obj = new Carousel('carusel_wrapper',$$('#'+this.carusel_id+' .slide'),$$('.about_block a', 'a.carousel-jumper'),
              { 
                beforeMove:this.beforeMove.bind(this),
                afterMove:this.afterMove.bind(this),
                centering:true,
                duration: 1,
            	visibleSlides: 3,
            	currentLink:true,
            	circular: true,
            	auto:true});
    },
    
    createSlide:function(e,index) {
        id='slide-'+(index+1);
        jumper = 'slide-'+(index);
        var img = new Element('img',{src:e.value["image"].unescapeHTML(),alt:e.value["address"]});
        var a = new Element('a',{href:e.value["link"],'class':'carousel-jumper',rel:jumper}).update(img);
        var container = new Element('div',{'class':'slide',id:id}).update(a);
        this.carusel.insert(container); 
    },
    
    afterMove:function() {
       var cur_index=this.carousel_obj.current._index+2;
       this.about.update('');
       var item = this.items.get(cur_index);
       if (undefined!=item) {
          var link = new Element('a',{href:item['link'],title:item['title']}).update(item['address']);
       } else {
           return;
       }
       var address = new Element('div',{'class':'address'}).update(link);
       var advt_type = new Element('div',{'class':'advt_type'}).update(item['advt_type']);
       var price_block = new Element('div');
       if (item['price']!="0")
           var span_price = new Element('span',{'class':'price',}).update(item['price']);
       if (item['roomcount']!="")
           var span_roomcount = new Element('span',{'class':'roomcount',}).update("      "+item['roomcount']); 
       price_block.insert(span_price);
       price_block.insert(span_roomcount);
       
       var block_link = new Element('a',{href:item['link'],style:'font-size:100%;color:#604C3B;'});
       block_link.insert(address);
       block_link.insert(advt_type);
       block_link.insert(price_block);
       this.about.update(block_link);
       this.about.show();
    },
    beforeMove:function() {
        
        
        
        this.about.hide();
    }
    
};
/** *carusel.js* */
Carousel = Class.create(Abstract, {
	initialize: function (scroller, slides, controls, options) {
		this.scrolling	= false;
		this.scroller	= $(scroller);
		this.slides		= slides;
		this.controls	= controls;

		this.options    = Object.extend({
            duration:           1,
            auto:               false,
            frequency:          3,
            visibleSlides:      1,
            controlClassName:   'carousel-control',
            jumperClassName:    'carousel-jumper',
            disabledClassName:  'carousel-disabled',
            selectedClassName:  'carousel-selected',
            circular:           false,
            wheel:              true,
            effect:             'scroll',
            transition:         'sinoidal',
            centering:          'false',// centerin
            currentLink:        'false'
        }, options || {});
        
        if (this.options.effect == 'fade') {
            this.options.circular = true;
        }

		this.slides.each(function(slide, index) {
			slide._index = index;
        });

		if (this.controls) {
            this.controls.invoke('observe', 'click', this.click.bind(this));
        }
        
        if (this.options.wheel) {            
            this.scroller.observe('mousewheel', this.wheel.bindAsEventListener(this)).observe('DOMMouseScroll', this.wheel.bindAsEventListener(this));;
        }
        
        if (this.options.auto) {
            this.start();
        }

        if (this.slides.length<this.options.visibleSlides) {
            this.stop();
            this.deactivateControls();   
        }
		if (this.options.initial) {
			var initialIndex = this.slides.indexOf($(this.options.initial));
			if (initialIndex > (this.options.visibleSlides - 1) && this.options.visibleSlides > 1) {               
				if (initialIndex > this.slides.length - (this.options.visibleSlides + 1)) {
					initialIndex = this.slides.length - this.options.visibleSlides;
				}
			}
            this.moveTo(this.slides[initialIndex]);
		}
	},

	click: function (event) {
		this.stop();
		var element = event.findElement('a');
		if (element.hasClassName(this.options.selectedClassName)) {
		    window.location.href = element.readAttribute('href');
		}
		if (!element.hasClassName(this.options.disabledClassName)) {
			if (element.hasClassName(this.options.controlClassName)) {
				eval("this." + element.rel + "()");
            } else if (element.hasClassName(this.options.jumperClassName)) {
                
                this.moveTo(element.rel);
                if (this.options.selectedClassName) {
                    this.controls.invoke('removeClassName', this.options.selectedClassName);
                    element.addClassName(this.options.selectedClassName);
                }
            }
        }

		this.deactivateControls();

		event.stop();
    },
    
    
	moveTo: function (element) {
        if (this.options.beforeMove && (typeof this.options.beforeMove == 'function')) {
            this.options.beforeMove();
        }
		this.previous = this.current ? this.current : this.slides[0];
		this.current  = $(element);
		var scrollerOffset = this.scroller.cumulativeOffset();
		var elementOffset  = this.current.cumulativeOffset();

		if (this.scrolling) {
			this.scrolling.cancel();
		}

        switch (this.options.effect) {
            case 'fade':               
                this.scrolling = new Effect.Opacity(this.scroller, {
                    from:   1.0,
                    to:     0,
                    duration: this.options.duration,
                    afterFinish: (function () {
                        this.scroller.scrollLeft = elementOffset[0] - scrollerOffset[0];
                        this.scroller.scrollTop  = elementOffset[1] - scrollerOffset[1];

                        new Effect.Opacity(this.scroller, {
                            from: 0,
                            to: 1.0,
                            duration: this.options.duration,
                            afterFinish: (function () {
                                if (this.controls) {
                                    this.activateControls();
                                }
                                if (this.options.afterMove && (typeof this.options.afterMove == 'function')) {
                                    this.options.afterMove();
                                }
                            }).bind(this)
                        });
                    }
                ).bind(this)});
            break;
            case 'scroll':
            default:
                var transition;
                switch (this.options.transition) {
                    case 'spring':
                        transition = Effect.Transitions.spring;
                        break;
                    case 'sinoidal':
                    default:
                        transition = Effect.Transitions.sinoidal;
                        break;
                }

                this.scrolling = new Effect.SmoothScroll(this.scroller, {
                    duration: this.options.duration,
                    x: (elementOffset[0] - scrollerOffset[0]),
                    y: (elementOffset[1] - scrollerOffset[1]),
                    transition: transition,
                    afterFinish: (function () {
                        if (this.controls) {
                            this.activateControls();
                        }
                        if (this.options.afterMove && (typeof this.options.afterMove == 'function')) {
                            this.options.afterMove();
                        }                        
                        this.scrolling = false;
                    }).bind(this)});
            break;
        }

		return false;
	},

	prev: function () {
		if (this.current) {
			var currentIndex = this.current._index;
			var prevIndex = (currentIndex == 0) ? (this.options.circular ? this.slides.length - 1 : 0) : currentIndex - 1;
        } else {
            var prevIndex = (this.options.circular ? this.slides.length - 1 : 0);
        }

		if (prevIndex == (this.slides.length - 1) && this.options.circular && this.options.effect != 'fade') {
			this.scroller.scrollLeft =  (this.slides.length - 1) * this.slides.first().getWidth();
			this.scroller.scrollTop =  (this.slides.length - 1) * this.slides.first().getHeight();
			prevIndex = this.slides.length - 2;
        }

		this.moveTo(this.slides[prevIndex]);
	},

	next: function () {
		if (this.current) {
			var currentIndex = this.current._index;
			var nextIndex = (this.slides.length - 1 == currentIndex) ? (this.options.circular ? 0 : currentIndex) : currentIndex + 1;
        } else {
            var nextIndex = 1;
        }

		if (nextIndex == 0 && this.options.circular && this.options.effect != 'fade') {
			this.scroller.scrollLeft = 0;
			this.scroller.scrollTop  = 0;
			nextIndex = 1;
        }

		if (nextIndex > this.slides.length - (this.options.visibleSlides + 1)) {
		    if (this.options.centering==true) {
		      nextIndex = 1;  
		    } else {
		      nextIndex = this.slides.length - this.options.visibleSlides;
		    }
		}		

		this.moveTo(this.slides[nextIndex]);
	},

	first: function () {
		this.moveTo(this.slides[0]);
    },

	last: function () {
		this.moveTo(this.slides[this.slides.length - 1]);
    },

	toggle: function () {
		if (this.previous) {
			this.moveTo(this.slides[this.previous._index]);
        } else {
            return false;
        }
    },

	stop: function () {
		if (this.timer) {
			clearTimeout(this.timer);
		}
	},

	start: function () { 
        this.periodicallyUpdate();
    },

	pause: function () {
		this.stop();
		this.activateControls();
    },

	resume: function (event) {
		if (event) {
			var related = event.relatedTarget || event.toElement;
			if (!related || (!this.slides.include(related) && !this.slides.any(function (slide) { return related.descendantOf(slide); }))) {
				this.start();
            }
        } else {
            this.start();
        }
    },

	periodicallyUpdate: function () {
		if (this.timer != null) {
			clearTimeout(this.timer);
			this.next();
        }
		this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.options.frequency * 1000);
    },
    
    wheel: function (event) {
        event.cancelBubble = true;
        event.stop();
        
		var delta = 0;
		if (!event) {
            event = window.event;
        }
		if (event.wheelDelta) {
			delta = event.wheelDelta / 120; 
		} else if (event.detail) { 
            delta = -event.detail / 3;	
        }        
       
        if (!this.scrolling) {
            this.deactivateControls();
            if (delta > 0) {
                this.prev();
            } else {
                this.next();
            }            
        }
        
		return Math.round(delta); // Safari Round
    },

	deactivateControls: function () {
		this.controls.invoke('addClassName', this.options.disabledClassName);
    },

	activateControls: function () {
		this.controls.invoke('removeClassName', this.options.disabledClassName);
    }
});


Effect.SmoothScroll = Class.create();
Object.extend(Object.extend(Effect.SmoothScroll.prototype, Effect.Base.prototype), {
	initialize: function (element) {
		this.element = $(element);
		var options = Object.extend({ x: 0, y: 0, mode: 'absolute' } , arguments[1] || {});
		this.start(options);
    },

	setup: function () {
		if (this.options.continuous && !this.element._ext) {
			this.element.cleanWhitespace();
			this.element._ext = true;
			this.element.appendChild(this.element.firstChild);
        }

		this.originalLeft = this.element.scrollLeft;
		this.originalTop  = this.element.scrollTop;

		if (this.options.mode == 'absolute') {
			this.options.x -= this.originalLeft;
			this.options.y -= this.originalTop;
        }
    },

	update: function (position) {
		this.element.scrollLeft = this.options.x * position + this.originalLeft;
		this.element.scrollTop  = this.options.y * position + this.originalTop;
    }
});
/** **common.class.js** */
/**
 * Class with common method
 */
Common = Class.create();

Common.prototype = {
	getRowContainer : function(child) {
		var container = child;
		while (container = container.parentNode) {
			if (container.hasClassName('row') || container.hasClassName('search_row')) {
				return container;
			}
		}
	}

};
/** DynamicSelector.class.js* */
DynamicSelector = Class.create(Common, {
	selector : null,
	items : null,
	initialize : function(selector) {
		if (undefined == selector) {
			throw "Selector can't be null";
		}
		this.selector = $(selector);
		this.items = new Array();
		this.selector
				.observe('change', this.onChange.bindAsEventListener(this));
	},
	onChange : function(e) {
		this.allItemHide(e.target.value);
		this.allItemShow(e.target.value);
	},

	addItem : function(options) {
		this.items[this.items.length] = options;
		this.showItem(options,this.selector.value);
	},

	allItemShow : function(value) {
		this.items.each(function(item) {
			this.DynamicSelector.prototype.showItem(item,value);
		});

	},

	allItemHide : function(value) {
		this.items.each(function(item) {
			this.DynamicSelector.prototype.hideItem(item,value);
		});
	},

	showItem : function(item,value) {
		element = $(item.id);
		if (!element.visible()) {
			if (null == item.hide.find(function(val) {
				return val == value
			})) {
				element = $(item.id).show();
			}
		}
	},

	hideItem : function(item,value) {
		element = $(item.id);
		if (element.visible()) {
			if (null != item.hide.find(function(val) {
				return val == value
			})) {
				element.hide();
			}
		}
	}
});
/** *FromToAdapter.class.js** */
FromToAdapter = Class.create();
FromToAdapter.prototype = {
    from : null,
    to : null,
    defClass : 'default_value',
    initialize : function(from, to) {
        this.from = from;
        this.to = to;
    },
    setTarget : function(container) {
        var div = $(container);
        var from = div.down('input');
        var to = div.down('input', 1);
        if (from.getValue() == ''||from.getValue()=='0') {
            from.removeClassName(from.classNames());
            from.addClassName(this.defClass);
            from.setValue(this.from);
        }
        if (to.getValue() == ''||to.getValue()=='0') {
            to.removeClassName(from.classNames());
            to.addClassName(this.defClass);
            to.setValue(this.to);
        }
        from.observe('focus', this.onFromFocus.bindAsEventListener(this));
        from.observe('blur', this.onFromBlur.bindAsEventListener(this));
        to.observe('focus', this.onToFocus.bindAsEventListener(this));
        to.observe('blur', this.onToBlur.bindAsEventListener(this));
    },
    onFromFocus : function(e) {
        var element = Event.element(e);
        var value = element.getValue();
        if (value == this.from||value=='0') {
            element.clear();
            element.removeClassName(this.defClass);
        }
    },

    onFromBlur : function(e) {
        var element = Event.element(e);
        if (element.getValue() == ''||element.getValue()=='0') {
            element.addClassName(this.defClass);
            element.setValue(this.from);
        }
    },

    onToFocus : function(e) {
        var element = Event.element(e);
        var value = element.getValue();
        if (value == this.to||value=='0') {
            element.clear();
            element.removeClassName(this.defClass);
        }
    },

    onToBlur : function(e) {
        var element = Event.element(e);
        if (element.getValue() == ''||element.getValue()=='0') {
            element.addClassName(this.defClass);
            element.setValue(this.to);
        }
    }
};
/** GisAdapter.class.js* */
GisAdapter = Class.create();
GisAdapter.prototype = {
	gis1 : null,// region
	gis2 : null,// district
	gis3 : null,// settlement
	url : null,
	gis2Label : null,
	gis3Label : null,
	loadInfo1  : null,
	loadInfo2  : null,
	loadInfo3  : null,
	loadGis1Change:false,

	initialize : function(gis1, gis2, gis3, url) {
		this.gis1 = $(gis1);
		this.gis2 = $(gis2);
		this.gis3 = $(gis3);
		this.loadInfo1 = $('load_info1')||null;
		this.loadInfo2 = $('load_info2')||null;
		this.loadInfo3 = $('load_info3')||null;
		this.url = url;
		this.gis2Label = $(gis2 + 'Label');
		this.gis3Label = $(gis3 + 'Label');
		this.gis1
				.observe('change', this.onGis1Change.bindAsEventListener(this));
		this.gis2
				.observe('change', this.onGis2Change.bindAsEventListener(this));
	},

	onGis1Change : function() {
		var options = {
			parameters : {action:'gis1Change', gis1:this.gis1.getValue()},
			method : 'post',
			onSuccess : this.onSuccess.bind(this)
		};
		if (this.loadInfo2!=null) {
			this.loadInfo2.show();
		}
		if (this.loadInfo3!=null) {
			this.loadInfo3.show();
		}
		new Ajax.Request(this.url, options);
	},

	onGis2Change : function() {
		var options = {
			parameters : {action:'gis2Change', gis1:this.gis1.getValue(), gis2:this.gis2.getValue()},
			method : 'post',
			onSuccess : this.onSuccess.bind(this)
		};
		if (this.loadInfo1!=null && false==this.loadGis1Change) {
			this.loadInfo1.show();
		}
		if (this.loadInfo3!=null) {
			this.loadInfo3.show();
		}
		new Ajax.Request(this.url, options);
	},

	onSuccess : function(transport) {
		this.loadGis1Change=true;
		if (this.loadInfo1!=null) {
			this.loadInfo1.hide();
		}
		if (this.loadInfo2!=null) {
			this.loadInfo2.hide();
		}
		if (this.loadInfo3!=null) {
			this.loadInfo3.hide();
		}
		var json = transport.responseText.evalJSON(true);
		if (json.gis1Index!=null) {
			for(var i=0;i<(this.gis1.options.length);i++) {
			   if (this.gis1.options[i].value == json.gis1Index){
				   this.gis1.options[i].selected=true;
			   }
			}
		}
		if (json.gis2 != null) {
			this.gis2.update(json.gis2);
			this.gis2Label.update(json.gis2Label);
		}
		if (json.gis3 != null) {
			this.gis3.update(json.gis3);
			this.gis3Label.update(json.gis3Label);
		}
	}
};
/** *ImageSpinner.class.js* */
ImageSpinner = Class.create();
ImageSpinner.prototype = {
        images:null,
    initialize : function(container, infoload, className,defWidth,defHeight) {
        if (!container)
            throw "Image container not assigned!";
        if (!infoload)
            throw "Image container not assigned";
        this.images = new Array();
        $(container).getElementsBySelector('img').each(function(img) {
            var index = this.images.size();
            var src = img.src;
            img.src = '';
            var image=new Image().observe('load',
                    function(){
                       img.src = image.src;
                       img.removeClassName(className);
                       img.setStyle({width:'auto', height:'auto'});;
                     });
            var h = src.match(/h=([0-9]+)&/i);
            var w = src.match(/w=([0-9]+)&/i);
            img.addClassName(className);
            if ((w==null || w[1]==0)&&defWidth>0) {
                w = new Array();
                w[1]=defWidth;
            }
            if ((h==null||h[1]==0)&&defHeight>0) {
                h = new Array();
                h[1] =defHeight;
            }
                
            if (w!=null && w[1] && h!=null && h[1])
                img.setStyle({width:w[1]+'px', height:h[1]+'px'});
            
            
            image.src=src;
        }.bind(this));

    }
};
/** *InputRequire.class.js* */
InputRequire = Class.create();
InputRequire.prototype = {
	error_class : 'input_error',
	old_style : null,
	input : null,
	option : null,

	initialize : function(input, options) {
		this.input = $(input);
		this.option = $H(options);
		this.input.observe('focus', this.onFocus.bindAsEventListener(this));
		this.input.observe('blur', this.onBlur.bindAsEventListener(this));
		this.input.observe('change', this.onChange.bindAsEventListener(this));
		this.input.observe('keypress', this.onKeyPress
				.bindAsEventListener(this));
	},

	onFocus : function(e) {
		// alert(this.input.getValue());
	if (!this.validate() && !this.input.hasClassName()) {
		this.input.addClassName(this.error_class);
	}
},
onBlur : function(e) {
	if (this.validate()) {
		this.input.removeClassName(this.error_class);
	}
},
onChange : function(e) {
},
onKeyPress : function(e) {
	// alert(String.fromCharCode(e.charCode));
},
validate : function() {
	if (this.option.get('length') !== null) {
		return this.checkLength(this.option.get('length'));
	} else if (this.option.get('regex') !== null) {
		return this.checkReg(value, this.option.get('regex'));
	}
},
checkReg : function(value, regex) {

	return 0;
},
checkLength : function(length) {
	return this.input.textLength >= length;
}
};
/** LinkSubmitAgregator.class.js** */
LinkSubmitAgregator = Class.create();

LinkSubmitAgregator.prototype={
	form : null,
	link : null,
	
	initialize:function(form_id, link_id) 
	{
	  this.form = $(form_id);
	  this.link = $(link_id);
	  this.link.observe('click', this.onLinkClick.bindAsEventListener(this));
    },
	
    onLinkClick:function(e) {
    	this.form.submit();
    }	
};
/** *MenuHelper.class.js*** */
MenuHelper = Class.create();
MenuHelper.prototype = {
    main_container : null,
    load_info : null,
    successMessage : '',
    initialize : function(main_container, load_info) {
        this.main_container = $(main_container);
        if (null == this.main_container) {
            throw "Main container not assigned";
        }
        if (undefined != load_info) {
            this.load_info = $(load_info);
        }
    },
    selectAll : function(activator, container, checked) {
        if (Object.isArray(activator)) {
            activator.each(function(a) {
                this.__selectAll(a, container, checked)
            }.bind(this));
        } else {
            this.__selectAll(activator, container);
        }
    },
    __selectAll : function(activator, container, checked) {
        if (null == checked) {
            checked = false;
        }
        var container = $(container);
        if (null == container) {
            throw "Container not Found";
        }
        var activator = $(activator);
        if (null == activator) {
            throw "Activator not Found";
        }
        activator.observe('click', function(e) {
            container.getElementsBySelector('input[type=checkbox]').each(
                    function(element) {
                        element.checked = checked;
                    }.bind(this));

        }.bindAsEventListener(this));
    },

    removeAll : function(activator, container, action, message) {
        if (Object.isArray(activator)) {
            activator.each(function(a) {
                this.__removeAll(a, container, action, message);
            }.bind(this));
        } else {
            this.__removeAll(activator, container, action, message);
        }
    },
    __removeAll : function(activator, container, action, message) {
        if (null == action) {
            throw "Action not assigned";
        }
        var activator = $(activator);
        if (null == activator) {
            throw "Activator not Found";
        }
        var container = $(container);
        if (null == container) {
            throw "Container not assigned";
        }
        activator.observe('click', function(e) {
            var items = $H();
            container.getElementsBySelector('input[type=checkbox]').each(
                    function(element, index) {
                        if (element.checked == true) {
                            items.set('id[' + index + ']', element.getValue());
                        }
                    }.bind(this));
            if (items.size()==0) return;
            if (this.load_info) {
                this.load_info.show();
            }
            var options = {
                method : 'get',
                parameters : items.toQueryString(),
                onSuccess : this.updateMainContainer.bind(this)
            };
            if (undefined != message) {
                this.successMessage = message;
            }
            new Ajax.Request(action, options);
        }.bindAsEventListener(this));

    },
    ajaxSelector : function(activator) {
        var activator = $(activator);
        if (null == activator) {
            throw "Activator not Found";
        }
        activator.observe('change', function(e) {
            var element = Event.element(e);
            if (this.load_info) {
                this.load_info.show();
            }
            var form = element.up('form');
            var options = {
                method : form.method,
                parameters : form.serialize(),
                onSuccess : this.updateMainContainer.bind(this)
            };
            new Ajax.Request(form.action, options);
            if (null != this.requestForm) {
                var input_target = this.requestForm
                        .down('input[name=' + element.name + ']');
                if (null != input_target) {
                    input_target.setValue(element.getValue());
                }
            }
        }.bindAsEventListener(this));
    },
     ajaxLinkBlock : function() {
        document.observe('click',(function(event){
            element = event.findElement('a[rel^=ajax-link]');
            if (element) {
                event.stop();
            if (this.load_info) {
                this.load_info.show();
            }
            new Ajax.Request(element.readAttribute('href'), {
                method : 'get',
                onSuccess : this.updateMainContainer.bind(this),
                onFailure:function(transport){
                if (this.load_info && this.load_info.visible()) {
                    this.load_info.hide();
                }
                message_write('Error','error_message');
            }.bind(this)
            });}
        }).bind(this));
        
        
    },
    ajaxDeleteComment:function(){
      document.observe('click',(function(event){
          var element=event.findElement('a');
          if (element) {
          var rel =element.readAttribute('rel');
          if (rel=='ajax-del-com') {
             event.stop();   
             if (this.load_info) {
                 this.load_info.show();
             }
             new Ajax.Request(element.readAttribute('href'), {
                 method : 'get',
                 onSuccess : function(transport) {
                 var json = transport.responseText.evalJSON(true);
                 if (this.load_info && this.load_info.visible()) {
                     this.load_info.hide();
                 }
                 if (json.errors.size()==0) {
                     var comment = element.up(".comment");
                         Effect.Fade(comment,{afterFinish:function(effect){
                             comment.remove();
                             if (json.msg.length>0) {
                                 message_write(json.msg,'messages_notify');   
                             }
                         }.bind(this)});
                 } else {
                     if (json.msg.length>0) {
                         if (json.msgClass) {
                             message_write(json.msg,json.msgClass); 
                         } else {
                            message_write(json.msg,'messages_notify');
                         }
                     } 
                 }
                 }.bind(this),
                 onFailure:function(transport){
                 if (this.load_info && this.load_info.visible()) {
                     this.load_info.hide();
                 }
                 message_write('Error','error_message');
             }.bind(this)
             });
          } else if (rel=='ajax-comp-com') {
              event.stop();   
              if (this.load_info) {
                  this.load_info.show();
              }
              new Ajax.Request(element.readAttribute('href'), {
                  method : 'get',
                  onSuccess : function(transport) {
                      var json = transport.responseText.evalJSON(true);
                      if (this.load_info && this.load_info.visible()) {
                          this.load_info.hide();
                      }
                      if (json.errors.size()==0) {
                          Effect.Fade(element,{afterFinish:function(effect){
                              element.remove();
                              if (json.msg.length>0) {
                                  message_write(json.msg,'messages_notify');   
                              }
                          }.bind(this)})
                      } else {
                          if (json.msg.length>0) {
                              if (json.msgClass) {
                                  message_write(json.msg,json.msgClass); 
                              } else {
                                 message_write(json.msg,'messages_notify');
                              }
                          } 
                      }
              }.bind(this),
              onFailure:function(transport){
                  if (this.load_info && this.load_info.visible()) {
                      this.load_info.hide();
                  }
                  message_write('Error','error_message');
              }.bind(this)});
          }
      }}).bind(this));   
    },
    updateMainContainer : function(transport) {
        if (this.load_info && this.load_info.visible()) {
            this.load_info.hide();
        }
        if (this.successMessage.length > 0) {
            message_write(this.successMessage, 'messages_notify');
            this.successMessage = '';
        }
        this.main_container.update(transport.responseText);
    },
    ajaxFormHider : function(form, message) {
        var form = $(form);
        if (null == form) {
            throw "Form not assigned";
        }
        form.observe('submit', function(e) {
            Event.stop(e);
            var options = {
                method : form.method,
                parameters : form.serialize(),
                onSuccess : function(transport) {
                    form.hide();
                    this.updateMainContainer(transport);
                }.bind(this)
            }
            if (this.load_info) {
                this.load_info.show();
            }
            if (undefined != message) {
                this.successMessage = message;
            }
            new Ajax.Request(form.action, options);
        }.bindAsEventListener(this));
    },
    searchFormSlider : function(activator, form) {
        var form = $(form);
        if (null == form) {
            throw "Form not assigned";
        }
        var activator = $(activator);
        if (null != activator) {
            activator.observe('click', function() {
                if (!form.visible()) {
                    form.slideDown( {
                        afterFinish : function(e) {
                            this.main_container.hide();
                            activator.hide();
                        }.bind(this)
                    });
                }
            }.bindAsEventListener(this));
        }
    },
    ajaxForm : function(form, message, actionLinkClass) {
        var form = $(form);
        if (null == form) {
            throw "Form not assigned";
        }
        form.observe('submit', function(e) {
            Event.stop(e);
            var options = {
                method : form.method,
                parameters : form.serialize(),
                onSuccess : this.updateMainContainer.bind(this)
            }
            if (this.load_info) {
                this.load_info.show();
            }
            if (undefined != message) {
                this.successMessage = message;
            }
            new Ajax.Request(form.action, options);
        }.bindAsEventListener(this));
        if (undefined != actionLinkClass) {

            var actionLink = form.down('a.' + actionLinkClass);
            if (actionLink) {
                actionLink.observe('click', function(e) {
                    Event.stop(e);
                    if (this.load_info) {
                        this.load_info.show();
                    }
                    new Ajax.Request(actionLink.readAttribute('href'), {
                        method : 'get',
                        onSuccess : this.updateMainContainer.bind(this)
                    });
                }.bindAsEventListener(this));

            }
        }
    },

    note_menu : function(container) {
        this.note_menu = Prototype.emptyFunction;
        document.observe('click',(function(event){
            var element = event.findElement('a[rel^=ajax-note]');
            if (element) {
                event.stop();
                var options = {
                        method : "get",
                        onSuccess : function(transport) {
                            var json = transport.responseText.evalJSON(true);
                            if (null != json.msg) {
                                if (json.msgClass) {
                                   message_write(json.msg, json.msgClass); 
                                } else {
                                   message_write(json.msg, 'messages_notify');
                                }
                                message_clear();
                            }
                            if (null != json.href) {
                                element.writeAttribute('href', json.href);
                            }
                            if (null != json.title) {
                                element.writeAttribute('title', json.title);
                            }
                            if (null != json.className) {
                                var em = element.down('em');
                                if (em) {
                                  em.removeClassName(em.classNames());
                                  em.addClassName(json.className);
                                }
                            }
                            if (json.text && element.innerHTML.length>0 && !em) {
                                element.update(json.text);
                            }
                        }.bind(this)
                    };
                    new Ajax.Request(element.readAttribute('href'), options);
            }
        }).bind(this));
    },

    advancedLink : function(link, container) {
        if (undefined == link || undefined == container) {
            throw "Advanced link not assigned";
        }
        this.advanced_container = $(container);
        this.link = $(link);
        if (null==this.link) return;
        this.link.observe('click', function(e) {
            var span = this.link.next('span');
            if (Object.isUndefined(span.textContent)) {
                var modulate = span.innerText;
            } else {
                var modulate = span.textContent;
            }
            if (this.advanced_container.visible()) {
                this.advanced_container.blindUp( {
                    duration : 0.5,
                    afterFinish : function(effect) {
                        if (span && modulate)
                            span.update(modulate.replace('-', '+'));
                    }.bind(this)
                });
            } else {
                this.advanced_container.blindDown( {
                    duration : 0.5
                });
                if (span && modulate)
                    span.update(modulate.replace('+', '-'));
            }
        }.bindAsEventListener(this));
    },

    requestTrimmer : function(form) {
        var form = $(form);
        if (null == form) {
            throw "Form is null";
        }
        this.requestForm = form;
        form.getElementsBySelector('a').each(function(element) {
            element.observe('click', function(e) {
                var rel = element.readAttribute('rel');
                var inputs = rel.match(/([^%]+)/g);
                inputs.each(function(name) {
                    form.down('input[name="' + name + '"]').remove()
                }.bind(form));
                var options = {
                    method : 'get',
                    parameters : form.serialize(),
                    onSuccess : this.updateMainContainer.bind(this)
                };
                var li = element.up('li');
                li.fade( {
                    afterFinish : function(e) {
                        li.remove();
                    }.bind(li, form)
                });
                if (this.load_info) {
                    this.load_info.show();
                }
                new Ajax.Request(form.action, options);
            }.bindAsEventListener(this));
        }.bind(this));
        form.getElementsBySelector('select').each(function(element) {
            element.observe('change', function(element) {
                this.updateRequest();
            }.bindAsEventListener(this))
        }.bind(this));
    },

    updateRequest:function() {
        var options = {
                method : 'get',
                parameters : this.requestForm.serialize(),
                onSuccess : this.updateMainContainer.bind(this)
            };
            if (this.load_info) {
                this.load_info.show();
            }
            new Ajax.Request(this.requestForm.action, options);
    },
    requestGisUpdator : function(gis1, gis2, gis3) {
        var gis2 = $(gis2);
        if (null == gis2) {
            throw "Gis2 not assigned";
        }
        var gis2Label = gis2.previous('label');
        var gis3 = $(gis3);
        var gis3Label = gis3.previous('label');
        if (null == gis3) {
            throw "Gis3 not assigned";
        }

        gis3.observe('change',function(e){
                var gis3Hidden = this.requestForm
                        .down('input[name="gis3"]');
                if (undefined == gis3Hidden) {
                    gis3Hidden = new Element('input', {
                        type : 'hidden',
                        name : 'gis3',
                        value : gis3.getValue()
                    })
                    this.requestForm.insert(gis3Hidden);
                } else {
                      gis3Hidden.setValue(gis3.getValue());
                }
            this.updateRequest();
        }.bindAsEventListener(this));
        
        gis2.observe('change', function(e) {
            if (this.load_info) {
                this.load_info.show();
            }
            var options = {
                parameters : {
                    action : 'gis2Change',
                    'gis1' : gis1,
                    'gis2' : gis2.getValue()
                },
                method : 'post',
                onSuccess : function(transport) {
                    var json = transport.responseText.evalJSON(true);
                    if (json.gis2Label != null) {
                        gis2Label.update(json.gis2Label);
                    }
                    if (json.gis3 != null) {
                        gis3.update(json.gis3);
                        gis3Label.update(json.gis3Label);
                    }
                        var gis2Hidden = this.requestForm
                                .down('input[name="gis2"]');
                        if (undefined == gis2Hidden) {
                            gis2Hidden = new Element('input', {
                                type : 'hidden',
                                name : 'gis2',
                                value : gis2.getValue()
                            })
                            this.requestForm.insert(gis2Hidden);
                        } else {
                            gis2Hidden.setValue(gis2.getValue());
                        }
                        var gis3Hidden = this.requestForm
                                .down('input[name="gis3"]');
                        if (undefined == gis3Hidden) {
                            gis3Hidden = new Element('input', {
                                type : 'hidden',
                                name : 'gis3',
                                value : gis3.getValue()
                            })
                            this.requestForm.insert(gis3Hidden);
                        } else {
                              gis3Hidden.setValue(gis3.getValue());
                        }
                    this.updateRequest();
                }.bind(this)
            };
            new Ajax.Request('/utility/ongischange', options);
        }.bindAsEventListener(this));

    }
};
/** *MenuSelector.class.js* */
MenuSelector = Class.create();
MenuSelector.prototype = {
        container:null,
    initialize : function(container,selector) {
        this.container = $(container);
        var selector = $(selector);
        selector.observe('change',this.onSelectorChange.bindAsEventListener(this));
        
    },
    onSelectorChange:function(e) {
        var index = Event.element(e).getValue();
        var active = this.container.down('.active');
            active.removeClassName('active');
            active.down('.menu_text').hide();
            active.down('.menu_link').show();
        var activate = $('rtype-'+index);
            activate.down('.menu_link').hide(); 
            activate.down('.menu_text').show();
            activate.down('div').addClassName('active');
    }

};
/**
 * SelectorUpdater.class.js
 * 
 */
SelectorUpdater = Class.create();
SelectorUpdater.prototype = {
	target : null,
	uri : null,
	infoloader : null,
	trigger : null,
	dir   : '',
	lastvalue:null,
	initialize : function(options) {
		if (undefined != options.target) {
			this.target = $(options.target);
		} else {
			throw "target not assigned";
		}
		if (undefined != options.uri) {
			this.uri = options.uri;
		} else {
			throw "Update uri no assigned";
		}
		if (undefined != options.infoloader) {
			this.infoloader = $(options.infoloader);
		}
		if (undefined != options.trigger) {
			this.trigger = $H(options.trigger);
		} else {
			throw "Query not assigned";
		}
		if (undefined != options.dir) {
		    this.dir = options.dir;
		}
		if (undefined != options.selector) {
			selector = $(options.selector);
			selector.observe('change',
					this.onChange.bindAsEventListener(this));
			this.lastvalue = selector.value; 
		} else {
			throw "Selector not assigned";
		}
	},

	onChange : function(e) {
		if (this.trigger.get(this.lastvalue)!=this.trigger.get(e.target.value)) {
		    this.request(e.target.value);
		}
		this.lastvalue = e.target.value;
	},

	request : function(value) {
		var options = {
			parameters :'query='+this.dir+this.trigger.get(value),
			method : 'post',
			onSuccess : this.onSuccess.bind(this)
		};
		if (null != this.infoloader) {
			this.infoloader.show();
		}
		new Ajax.Request(this.uri, options);
	},

	onSuccess : function(transport) {
		if (null != this.infoloader) {
			this.infoloader.hide();
		}
		var json = transport.responseText.evalJSON(true);
		if (null != json.result) {
		    this.target.update(json.result.stripScripts());
		    json.result.evalScripts();
		}
	}

};
/** *UserFormValidator.class.js** */
UserFormValidator = Class.create(Common,{
	submit : null,
	form : null,
	error_msg : null,
	load_info : null,
	defClass : 'default_value',
	initialize : function(form, link_submit, error_msg) {
        this.error_msg = error_msg;
		this.load_info = $('load_info') || null;
		this.form = $(form);
		if (link_submit != null) {
			this.submit = $(link_submit);
			this.submit.observe('click', this.onLinkClick
					.bindAsEventListener(this));
		}
		this.form.observe('submit', this.onSubmit.bindAsEventListener(this));
		this.resetErrors();

	},

	resetErrors : function() {
		this.form.getElementsBySelector('.error').invoke('hide');
		this.form.getElementsBySelector('.input_error').each(function(e) {
			e.removeClassName('input_error');
		});
	},

	showError : function(key, val) {
		var formElement = this.form[key];
		formElement.addClassName('input_error');
		var container = this.getRowContainer(formElement);
		container = container.getElementsBySelector('.error');
		if (container[0]) {
			container[0].update(val);
			container[0].show();
		}
	},

	onLinkClick : function(e) {
		this.onSubmit(e);
	},

	onSubmit : function(e) {
		if (null == this.submit) {
		    Event.stop(e);
		}
		var options = {
			parameters : this.form.serialize(),
			method : this.form.method,
			onSuccess : this.onFormSuccess.bind(this)
		};
		this.resetErrors();
		if (this.load_info != null) {
			this.load_info.show();
		}
		new Ajax.Request(this.form.action, options);
	},

	onFormSuccess : function(transport) {
		if (null != this.load_info) {
			this.load_info.hide();
		}
		var json = transport.responseText.evalJSON(true);
		if (Object.values(json) != '') {
			var errors = $H(json.errors);
			if (errors.size() > 0) {
				message_write(this.error_msg, 'error_message')
				errors.each(function(pair) {
					this.showError(pair.key, pair.value);
				}.bind(this));
			}
		} else {
			this.form.submit();
		}
	},

	serializeWithoutDef : function() {
		var elements = this.form.getElements();
		var data = new Array(elements.size());
		for ( var i = 0; i < elements.size(); i++) {
			if (elements[i].hasClassName(this.defClass)) {
				data[i] = elements[i].name + '=';
			} else {
				data[i] = elements[i].serialize();
			}
		}
		return data.join('&');
	},

	clearDefault : function() {
		var inputs = this.form.getInputs();
		inputs.each(function(input) {
			if (input.hasClassName(this.UserFormValidator.prototype.defClass)) {
				input.clear();
			}
		});

	}
});
/** *AbstractValidate.class.js** */
AbstractValidate = Class.create(Common,{
	oldClass      : null,
	defClass      : 'default_value',
	errormsg      : 'Значение должно быть числом',
	requiremsg    : 'Ожидается ввод значения',
	descriptShow  :  true,
	defValue      :  "",
    initialize:function(input, errormsg, defclass) {
       if (null!=errormsg) {
    	   this.errormsg = errormsg;   
       }
       if (null!=defclass) {
    	   this.defClass = defclass;
       }
       if (null!=input) {
          this.setValidator(input);
       }
       
    },
    getDefaultClassName:function() {
    	return this.defClass;
    },
    setDefaultClassName:function(classname) {
    	this.defClass= classname;
    },
    setErrorMsg:function(msg) {
    	this.errormsg = msg;
    },
    setRequireMsg:function(msg) {
    	this.requiremsg = msg;
    },
    getErrorMsg:function() {
    	return this.errormsg;
    },
    getRequireMsg:function(){
    	return this.requiremsg;
    },
    
    setDescriptShow:function(flag) {
    	this.descriptShow = flag;
    },        
	setValidator:function(input){
       var target=$(input)||null;
       if (this.getDefault()!='' && target.getValue()=='') {
    	   this.oldClass = target.classNames();
    	   target.addClassName(this.defClass);
    	   target.setValue(this.getDefault());
       }
       target.observe('focus', this.onFocus.bindAsEventListener(this));
       target.observe('blur', this.onBlur.bindAsEventListener(this));
    },
    
    setValidators:function(inputs) {
       for(i=0; i<inputs.length;i++) {
           this.setValidator(inputs[i]);
       }
    },
	
    onFocus:function(e) {
    	if (e.target.getValue()==this.getDefault()) {
    		e.target.setValue('');
    		e.target.removeClassName(this.defClass);
    		
    	}
    	if (true == this.descriptShow) {
    	    this.showDescription(e.target);	
    	}
    },
    
    onBlur:function(e) {
    	var value = e.target.getValue();
    	if ((value!=='') && (false==this.validate(value))) {
    		this.showError(e.target, this.errormsg);
    	    e.target.select();
    	    return;
    	} else if (value=='' || value==this.getDefault()) {
    		if (this.isRequirement(e.target)) {
    		    this.showError(e.target, this.requiremsg);
    		}
    		e.target.addClassName(this.defClass);
    		e.target.setValue(this.getDefault());
    	} else {
    	   this.hideError(e.target);
    	}
    	this.hideDescription(e.target);
    },
    
    
    validate:function(sText) {
     return true;    
    },
    
    showError:function(element, msg) {
    	var container = this.getRowContainer(element); 
    	    container =container.getElementsBySelector('.error'); 
        if (container[0]) {
            container[0].update(msg);
            container[0].show();
        }
    }, 
    
    hideError:function(element) {
    	var container = this.getRowContainer(element); 
            container =container.getElementsBySelector('.error'); 
        if (container[0]) {
    	   container[0].update('');
    	   container[0].hide();
      }
    },
    
    showDescription:function(element)  {
    	var container = this.getRowContainer(element);  
            container =container.getElementsBySelector('.input_description'); 
        if (container[0]) {
     	    container[0].show();
        // new Effect.Appear(container[0].id);
       }
    },
    
    hideDescription:function(element) {
    	var container = this.getRowContainer(element);
    	    container =container.getElementsBySelector('.input_description'); 
         if (container[0]) {
      	    container[0].hide();
        	// new Effect.Fade(container[0].id);
        }
    },
                  
    isRequirement:function(element) {
    	 var required =  element.next();
    		 if (null!=required) {
    			 return required.innerHTML=="*";
    		 }
    	 return false;
    },
    
    getDefault:function() {
    	return this.defValue;
    },
    
    setDefault:function(value) {
    	this.defValue=value;
    }
	
});
/** AlnumValidate.class.js* */
AlnumValidate = Class.create(AbstractValidate,{
	validate:function(sText) {
	   var reg = /^[\w\s\d\а-я"\(\)]+$/i;
	   return reg.test(sText);
 }
});
/** EmailValidate.class.js* */
EmailValidate = Class.create(AbstractValidate,{
	validate:function(sText) {
	   var reg =  /^([a-z0-9_.]+)@([a-z0-9]+).([a-z]{2,3})$/i;
	   return reg.test(sText);
 }
});
/** IntegerValidate.class.js* */
IntegerValidate = Class.create(AbstractValidate, {
	validate : function(sText) {
		var validChar = "0123456789";
		var isNumber = true;
		var c;
		for ( var i = 0; i < sText.length && isNumber == true; i++) {
			c = sText.charAt(i);
			if (validChar.indexOf(c) == -1) {
				isNumber = false;
			}
		}
		return isNumber;
	}
});
/** PhoneValidate.class.js* */
PhoneValidate = Class.create(AbstractValidate, {
	validate : function(sText) {
        var phonepat =/^[\d- +()]+$/ ;
        return phonepat.test(sText);
	}
});
/** TimeValidate.class.js* */
TimeValidate = Class.create(AbstractValidate, {
	validate : function(sText) {
        var timepat = /^([\d]{0,2})([:-]?)([\d]{0,2})$/;
        	return timepat.test(sText);
	}
});
/** WebAddressValidate.class.js* */
WebAddressValidate = Class.create(AbstractValidate, {
	validate : function(sText) {
		var webpat = /^http:\/\/[\w\d=?&%.]+$/i;
		return webpat.test(sText);
	}
});
/* maphighlight.js* */
MapHighlight = Class.create();
MapHighlight.prototype = {
    has_VML : null,
    has_canvas : null,
    initialize : function(img,options) {
        this.has_canvas = new Element('canvas');
        this.has_canvas = this.has_canvas && this.has_canvas.getContext;
        if (!this.has_canvas) {
            return this;
        }
        
        this.canvas_style = {
                position: 'absolute',
                left: 0,
                top: 0,
                padding: 0,
                border: 0
            };
        this.options = Object.extend( {
            fill : true,
            fillColor : '000000',
            fillOpacity : 0.2,
            stroke : true,
            strokeColor : 'ff0000',
            strokeOpacity : 1,
            strokeWidth : 1,
            fade : true,
            alwaysOn : false
        }, options || {});
        
        this.img = $(img);
        this.img.observe('load',function(e){this.highligth(Event.element(e));}.bind(this));
    },
    highligth:function(img) {
        this.map =img.next('map[name="'+img.readAttribute('usemap').substr(1)+'"]');
        if (!(img.hasAttribute('usemap')&& this.map.areas.length>0 && !img.hasClassName('maphighlighted'))){return;}
        wrap= new Element('div').setStyle({background:'url('+img.src+')',position:'relative',padding:0,width:img.width+'px',height:img.height+'px'});
        img.setStyle({opacity:'0'}).setStyle(this.canvas_style);
        this.canvas = this.create_canvas_for(img);
        this.canvas.setStyle(this.canvas_style);
        this.canvas.height=img.height;
        this.canvas.width=img.width;
        wrap.insert(this.canvas);
        img.wrap(wrap);
        $A(this.map.areas).each(function(element){
            element.observe('mouseover',function(e){
                var shape = this.shape_from_area(Event.element(e));
                  this.add_shape_to(this.canvas, shape[0], shape[1], this.options);
            }.bindAsEventListener(this));
            if (!this.options.olwaysOn) {
                element.observe('mouseout',function(e){
                       this.clear_canvas(this.canvas);
                }.bindAsEventListener(this));
            }
        }.bind(this));
        img.addClassName('maphighlighted');
    },
    
    hex_to_decimal : function(hex) {
        return Math.max(0, Math.min(parseInt(hex, 16), 255));
    },
    css3color : function(color, opacity) {
        return 'rgba(' + this.hex_to_decimal(color.substr(0, 2)) + ','
                + this.hex_to_decimal(color.substr(2, 2)) + ','
                + this.hex_to_decimal(color.substr(4, 2)) + ',' + opacity + ')';
    },

    create_canvas_for : function(img) {
        var c = new Element('canvas');
        c.setStyle( {
            width : img.width + 'px',
            height : img.height + 'px'
        });
        c.getContext("2d").clearRect(0, 0, c.width, c.height);
        return c;
    },
    clear_canvas : function(canvas) {
        canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
    },

    add_shape_to : function(canvas, shape, coords, options) {
        var i, context = canvas.getContext('2d');
        this.clear_canvas(canvas);
        context.beginPath();
        if (shape == 'rect') {
            context.rect(coords[0], coords[1], coords[2] - coords[0], coords[3]
                    - coords[1]);
        } else if (shape == 'poly') {
            context.moveTo(coords[0], coords[1]);
            for (i = 2; i < coords.length; i += 2) {
                context.lineTo(coords[i], coords[i + 1]);
            }
        } else if (shape == 'circ') {
            context.arc(coords[0], coords[1], coords[2], 0, Math.PI * 2, false);
        }
        context.closePath();
        if (options.fill) {
            context.fillStyle = this.css3color(options.fillColor,
                    options.fillOpacity);
            context.fill();
        }
        if (options.stroke||shape=='circ') {
            context.strokeStyle = this.css3color(options.strokeColor,
                    options.strokeOpacity);
            context.lineWidth = options.strokeWidth;
            context.stroke();
        }
        if (options.fade) {
            canvas.setStyle({opacity:0});
            new Effect.Opacity(canvas, {
                from : 0,
                to : 1.0,
                duration:0.5
            });
        }

    },
    fader : function(element,opacity,duration) {
            if (opacity<=1) {
                element.setStyle({opacity:0});
                window.setTimeout(this.fader, 10, element, opacity + 0.1, 10);
                
            }
    },
    shape_from_area:function(area) {
        var i, coords = area.coords.split(',');
        for (i=0; i < coords.length; i++) { coords[i] = parseFloat(coords[i]); }
        return [area.readAttribute('shape').toLowerCase().substr(0,4), coords];
    },
    
    is_image_loaded:function(img) {
        if(!img.complete) { return false; } // IE
        if(typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) { return false; } // Others
        return true;
        
    }
};
/**text area char counter**/
var TextCounter = Class.create();
TextCounter.prototype = {
    initialize: function(textareaid, counter, maxLength) {
        this.maxLength = maxLength;
        this.textarea = $(textareaid);
        this.counter = $(counter);
        this.counter.update(maxLength);
        Event.observe(this.textarea, 'keyup', this.checkChars.bindAsEventListener(this));
        Event.observe(this.textarea, 'keydown', this.checkChars.bindAsEventListener(this));
        this.checkChars();
    }, 
    checkChars: function(e) {
        var includeBreaksInCount = false; // false = don't count a return (\r or \n) in the count.
        var charCount = this.textarea.value.length;
        var breaks = 0;
        if (!includeBreaksInCount) {
            var lines = this.textarea.value.split('\n');
            breaks = lines.length;
            // check for /r at the end of the lines (IE)
            for (var i=0; i<lines.length; i++) {
                var line = lines[ i ];                
                if (line.charCodeAt(line.length-1) == 13)
                    breaks++;
            }
            
        }
        
        // check if over limit
        if ((charCount-breaks) > this.maxLength) {            
            this.textarea.value = this.textarea.value.substring(0, (this.maxLength + breaks) );
        }
        
        // update counter
        if (this.counter) {
            if ((charCount-breaks) > this.maxLength) {
                this.counter.update("0");
            } else {
                this.counter.update((this.maxLength + breaks) - charCount);
            }        
        }
    }
}
/** Script.js** */
var script_settings = {
	    messages : 'messages_content_block',
	    messages_hide_delay : 3.0,
	    ajax_preloader:'ajax_load_info'
	}

	function init(e) {
	    // highlight messages
      var messages = $(script_settings.messages);
	    if (messages && messages.visible()) {
	        new Effect.Highlight(messages, {
	            startcolor : '#00FF00',
	            endcolor : '#90ee90',
	            afterFinish : function(effect) {
	                message_clear();
	            }
	        });
	    }
	  // target blank links
	    assign_target();
	    ajaxLinkListener();
	}

    function assign_target(target) {
        if (target) {
            var elements = $A($(target).getElementsByClassName('target_blank')); 
        } else {
            var elements = $A(document.getElementsByClassName('target_blank'));            
        }
        elements.each(function(a){
            a.observe('click',function(e){
                Event.stop(e);
                var new_window = window.open(a.readAttribute('href'),'_blank');
                new_window.focus();
          }.bindAsEventListener(a));      
       }.bind(this));  
    }

    
    function ajaxLinkListener() {
        document.observe('click', (function(event) {
            var link = event.findElement('a');
            if (link) {
                var rel = link.readAttribute('rel');
                if (!rel)
                    return;
                var pat = /(confirm-)?(scroll-up-)?(ajax-link-)([a-z0-9-_]*)/i;
                var match = rel.match(pat);
                if (match && match.size() == 5 && (update_block = $(match[4]))) {
                    event.stop();
                    if (match[1]) {
                       if (!confirm(link.readAttribute('title') + "?"))
                           
                            return;
                    } 
                    options = {
                        method : 'get',
                        onSuccess : (function(transport) {
                            if (preloader)
                                preloader.hide();
                            update_block.update(transport.responseText);
                            if (match[2]) {
                                window.scrollTo(0,0);
                            }
                        }).bind(this)
                    }
                    var preloader = $(script_settings.ajax_preloader);
                    if (preloader)
                        preloader.show();
                    new Ajax.Request(link.readAttribute('href'), options);
                } else {
                   var pat = /(confirm)/gi;
                   var match = rel.match(pat);
                   if (match) {
                      if (!confirm(link.readAttribute('title') + "?"))
                           event.stop();
                   }
                }
            }
        }).bind(this));
    }
    
	function message_write(message, className, hide) {
	    var messages = $(script_settings.messages);
	    if (!messages)
	        return;
	    if (message.length == 0) {
	        messages.hide();
	        return;
	    }

	    if (undefined != className && className!=messages.classNames()) {
	        messages.removeClassName(messages.classNames());
	        messages.addClassName(className);
	    } 
	    messages.update(message);
	    messages.show();
	    if (hide) {
	        new Effect.Highlight(messages, {
	            startcolor : '#00FF00',
	            endcolor : messages.getStyle('background-color')// '#90ee90'
	        });
	    } else {
	        new Effect.Highlight(messages, {
	            startcolor : '#00FF00',
	            endcolor : messages.getStyle('background-color'),// '#90ee90',
	            afterFinish : function(effect) {
	                message_clear();
	            }
	        });
	    }
	}
	function message_clear() {
	    setTimeout("message_write('')", script_settings.messages_hide_delay * 1000);
	}
	document.observe('dom:loaded',init);

