var Lightbox = new Class({
	
	Implements: Options,
	
	options: {
		async: true,
		validator: null,
		message: '<p>Спасибо. Информация отправлена редакторам сайта.</p>'
	},
	
	cover: null,
	
	initialize: function(element, button, options){
		this.setOptions(options);
		this.element = $(element);
		this.button = $(button);
		
		if (this.element){
			this.closeButton = new Element('div', {'class': 'close-button'});
			
			new Element('span', {
				'class': 'js-cancel',
				'text': 'закрыть окно',
				'events': {
					'click': this.close.bindWithEvent(this)
				}
			}).inject(this.closeButton);
			
			this.element.getFirst().adopt(this.closeButton);
			
			this.button.addEvent('click', this.open.bindWithEvent(this));
			
			if (this.options.async){
				this.element.getElement('form').addEvent('submit', (function(e){
					e.stop();
					
					if (!this.options.validator || this.options.validator.validate()){
						this.element.setStyle('overflow', 'hidden');
						new Element('div', {
							'class': 'overlay',
							'html': this.options.message,
							styles: {
								top: this.element.getStyle('top'),
								height: this.element.getStyle('height')
							}
						}).injectTop(this.element);
						new Form.Request(e.target, {spinner: false}).send();
					}
				}).bindWithEvent(this));
			}
		}
	},
	
	updatePosition: function(){
		var docheight = document.documentElement.offsetHeight;
		var boxheight = this.element.offsetHeight;
		
		if (boxheight + 40 > docheight){
			boxheight = docheight - 40;
			this.element.setStyle('height', boxheight);
		}
		
		this.element.setStyle('top', (docheight - boxheight) / 2);
	},
	
	open: function(){
		this.cover = new Element('div', {id: 'lightbox-cover'}).set('opacity', 0.8).inject(this.element, 'before');
		this.cover.addEvent('click', this.close.bindWithEvent(this));
		this.element.set('opacity', 0).setStyle('display', 'block').fade('in');
		$$('body')[0].setStyle('overflow', 'hidden');
		this.updatePosition();
		setTimeout((function() {
			var frstInput = this.element.getElement('input,select,textarea');
			if (frstInput) frstInput.focus();
		}).bind(this), 500);
		$$('.banner').setStyle('visibility', 'hidden');
	},
	
	close: function(){
		this.element.fade('out').setStyle('display', 'none');
		this.cover.destroy();
		$$('body')[0].setStyle('overflow', 'auto');
		$$('.banner').setStyle('visibility', 'visible');
	}
	
});

