var MiniGallery = new Class({
	Implements: [Options, Events, Chain],

	options: {
		container: $('container'),
		modal_id: 'modal',
		previews: [],
		errors: {
			'load_error':'Ошибка загрузки! Пожалуйста, повторите запрос.'
		}
	},

	initialize: function(options, domain) {
		this.setOptions(options);
		this.browser = {};
		this.container = this.options.container;
		this.previews = this.options.previews;
		this.closeBound = this.modalClose.bind(this);
		this.injectModal(domain);
		if(Browser.Engine.trident && !!!document.querySelectorAll)  {
			this.browser.ie7lte = true;
			$(window).addEvent('scroll', this.onWindowResizeHandler.bind(this))
		}

		$(window).addEvent('resize', this.onWindowResizeHandler.bind(this));
	},

	cash:[],

	init: function(prev, main_src) {
		if(this.cash.length) return;
		this.cash.push(prev);
		this.previewClickHandler(prev, main_src);
	},

	injectModal: function(domain) {
		var modWidth, modHeight;
		this.modal = new Element('div').set('html', 
			'<div class="d-shadow">'+
			'<div class="head_mac">'+
				'<div class="first_line">'+
					'<div title="Закрыть" class="close_modal">'+
					'</div>'+
					'<span>Сайт по '+domain+'</span>'+
				'</div>'+
				'<div class="second_line">'+
					'<table cellpadding="0" cellspacing="0" border="0">'+
						'<tbody>'+
							'<tr>'+
								'<td class="first">'+
									'<div class="change_btns">'+
									'</div>'+
								'</td>'+
								'<td class="spacer"></td>'+
								'<td class="liquid">'+
									'<div class="address_line">'+
										'<div class="left">'+
											'<div class="right">'+
												'<span class="address">'+domain+'</span>'+
											'</div>'+
										'</div>'+
									'</div>'+
								'</td>'+
								'<td class="spacer"></td>'+
								'<td class="third">'+
									'<div class="search_inp">'+
									'</div>'+
								'</td>'+
							'</tr>'+
						'</tbody>'+
					'</table>'+
				'</div>'+
			'</div>'+
			'<div class="d-shadow-wrap">'+
				'<div class="img_holder wait"></div>'+
				'<div class="d-sh-cn d-sh-tl"></div>'+
				'<div class="d-sh-cn d-sh-tr"></div>'+
			'</div>'+
			'<div class="d-sh-cn d-sh-bl"></div>'+
			'<div class="d-sh-cn d-sh-br"></div>'+
		'</div>'
		).addClass('modal');
		this.modal.id = this.options.modal_id;
		this.modal.set('opacity', '0');
		document.body.appendChild(this.modal);
		modWidth = this.modal.getSize().x;
		modHeight = this.modal.getSize().y;
		this.modal.setStyles({
			'top':($(window).getSize().y-modHeight)/2 + (function() {return (this.browser.ie7lte)?$(window).getScroll().y:0}).delay(0, this),
			'left':($(window).getSize().x-modWidth)/2 + (function() {return (this.browser.ie7lte)?$(window).getScroll().x:0}).delay(0, this)
		});
	},

	showModal: function() {
		this.modal.store('opened', true);
		if(!this.modal.getElement('.img_holder').hasClass('wait')) this.modal.getElement('.img_holder').addClass('wait');
		this.modal.fade('in');
	},

	setHTML: function(elem) {
		var self = this;
		this.modal.getElement('.img_holder').removeClass('wait');
		elem.inject(this.modal.getElement('.img_holder'), 'top');
		elem.setStyles({
			'margin-top': - (elem.getSize().y + self.modal.getElement('.d-sh-bl').getSize().y)/2,
			'margin-left': - ((elem.getSize().x)/2 + this.modal.getElement('.img_holder').getElement('div').getStyle('padding-left').toInt())
		});
		return this;
	},

	errorHandle: function(prev) {
		var text = this.options.errors.load_error;
		this.modal.getElement('.img_holder').empty();
		var mes = new Element('div').addClass('load_error');
		mes.set('html', '<span></span>').getElement('span').set('html', text);
		this.setHTML(mes);
		prev.eliminate('img_load').eliminate('clicked');
		this.modal.eliminate('in_connect');
	},

	onWindowResizeHandler: function() {
		var modWidth = this.modal.getSize().x,
			modHeight = this.modal.getSize().y,
			winWidth = $(window).getSize().x,
			winHeight = $(window).getSize().y;
		(function() {
			this.modal.setStyles({
				'left':(winWidth - modWidth)/2 + (function() {return (this.browser.ie7lte)?$(window).getScroll().x:0}).delay(0, this),
				'top':(winHeight - modHeight)/2 + (function() {return (this.browser.ie7lte)?$(window).getScroll().y:0}).delay(0, this)
			});
		}).delay(0, this);
	},

	destroyer:function(obj) {
		this.modal.getElement('.img_holder').empty();
	},

	onShow: function() {
		this.fireEvent('show');
	},

	onStop: function() {
		this.fireEvent('stop');
	},

	animation: function() {
		return new Fx.Morph(this.modal, {duration:500, wait:false})
	},

	show: function(callback) {
		/*var delay;
		(this.modal.retrieve('opened'))?delay = 0:delay = 500;
		var fx = new Fx.Tween(this.modal, {
			duration:delay, 
			wait:false,
			onComplete:callback
		});
		var op = this.modal.get('opacity');
		fx.start('opacity', op, '1');
		this.onShow();
		this.modal.store('opened', true);
		return this;*/
		callback();
	},

	previewClickHandler: function(preview, main_src) {
		var self = this;
		if(preview.retrieve('clicked')) return;
		this.showModal();
		this.modal.getElement('.img_holder').addClass('wait');
		(!this.modal.getElement('.img_holder').getElement('img'))?this.destroyer():'';
		preview.store('clicked', true);
		var fx = this.animation();
		var img = new Image(),
			src = preview.getAttribute('rel') || main_src,
			paddings = this.modal.getStyle('padding');
		$(img).setStyle('visibility', 'hidden');
		var w, h,
			oldW = this.modal.getStyle('width'),
			oldH = this.modal.getStyle('height'),
			oldTop = this.modal.getStyle('top'),
			oldLeft = this.modal.getStyle('left');
		fx.cancel();
		if(!this.modal.getElement('.img_holder').getElement('img')) {
			try{
				img.onload = function() {
					img.onload = null;
					w = img.width;
					h = img.height;
					self.show(function() {
						var toLeft = ($(window).getSize().x - w)/2 + (function() {return (this.browser.ie7lte)?$(window).getScroll().x:0}).delay(0, this),
							toTop = ($(window).getSize().y - h)/2 + (function() {return (this.browser.ie7lte)?$(window).getScroll().y:0}).delay(0, this)
						fx.start({
							'height':[oldH, h],
							'width':[oldW, w],
							'top':[oldTop, toTop],
							'left':[oldLeft, toLeft]
						}).chain(
							function() {
								img.setStyle('visibility', 'visible');
								img.inject(this.modal.getElement('.img_holder'), 'top');
								this.modal.getElement('.img_holder').removeClass('wait');
								preview.eliminate('clicked');
								this.cash = [];
								this.closeHandlers();
							}.bind(this)
						);
					}.bind(this));
				}.bind(this);
				img.onerror = function() {preview.eliminate('img_load').eliminate('clicked'); self.fireEvent('previewClick', [null, self, preview]);}
				img.src = src + '?'+Math.random();
			}catch(e) {
				this.errorHandle(preview);
			}
		}else{
			img = this.modal.getElement('.img_holder').getElement('img');
			self.show(function() {
				var toLeft = ($(window).getSize().x - w)/2 + (function() {return (this.browser.ie7lte)?$(window).getScroll().x:0}).delay(0, this),
					toTop = ($(window).getSize().y - h)/2 + (function() {return (this.browser.ie7lte)?$(window).getScroll().y:0}).delay(0, this)
				fx.start({
					'height':[oldH, h],
					'width':[oldW, w],
					'top':[oldTop, toTop],
					'left':[oldLeft, toLeft]
				}).chain(
					function() {
						img.setStyle('visibility', 'visible');
						img.inject(this.modal.getElement('.img_holder'), 'top');
						this.modal.getElement('.img_holder').removeClass('wait');
						preview.eliminate('clicked');
						this.cash = [];
						this.closeHandlers();
					}.bind(this)
				);
			}.bind(this));
		}
	},

	closeHandlers: function() {
		document.addEvents({
			'keydown': this.closeBound,
			'click': this.closeBound
		});
		
		this.modal.getElement('.close_modal').addEvent('click', this.closeBound);
	},

	modalClose: function(e) {
		e = e || null;
		if(!this.modal.retrieve('opened')) { 
			document.removeEvent('keydown', this.closeBound);
			document.removeEvent('click', this.closeBound);
			this.modal.getElement('.close_modal').removeEvent('click', this.closeBound);
			return;
		}
		var none_clicked = this.modal.getElements('*').erase(this.modal.getElement('.close_modal')).extend([this.modal].extend(this.previews));
		var target = (e)?none_clicked.some(function(prev) {return e.target == prev}):null;
		//(e)?new Event(e).stop():'';
		this.onStop();
		if(!e || e.key == 'esc' || (!target && e.type != 'keydown')) {
			(e)?new Event(e).stop():'';
			this.modal.fade('out');
			if(this.modal.getElement('.img_holder').getElement('img')) this.modal.getElement('.img_holder').getElement('img').setStyle('visibility', 'hidden');
			else this.modal.getElement('.img_holder').empty();
			this.modal.eliminate('opened');
		}

		return this;
	}
});
