var popupWindow = function() {
	this._box = null;
	this._content = null;
};

popupWindow.prototype.setContent = function(value) {
	this.getContentBox().update(value);
	return this;
};

popupWindow.prototype.opened = function() {
	return (this._getBox().parentNode && this._getBox().parentNode.parentNode);
};

popupWindow.prototype.open = function() {
	document.body.appendChild(this._getBox());
	return this;
};

popupWindow.prototype.hide = function() {
	if (this._getBox().parentNode) {
		this._getBox().parentNode.removeChild(this._getBox());
	}
	return this;
};

popupWindow.prototype.setPreloader = function() {
	this._getBox().addClassName('preloader');
	return this;
};

popupWindow.prototype.removePreloader = function() {
	this._getBox().removeClassName('preloader');
	return this;
};

popupWindow.prototype._getBox = function() {
	if (this._box == null) {
		var box = document.createElement('div'), self = this;
		box.innerHTML = '<div class="l-window"><table><tbody><tr><td colspan="3" class="l-hdr"><img src="/images/tpl/window/header.png"/></td></tr><tr><td class="l-lft"><div></div></td><td class="l-cnt"><div class="l-cls"><img src="/images/tpl/window/close.png"/></div><div class="l-wrp"></div></td><td class="l-rht"><div></div></td></tr><tr><td colspan="3" class="l-ftr"><img src="/images/tpl/window/footer.png"/></td></tr></tbody></table></div>';
		this._box = $(box.firstChild);
		this._content = $(box.firstChild.firstChild.firstChild.firstChild.nextSibling.firstChild.nextSibling.firstChild.nextSibling);
		this._content.previousSibling.firstChild.onclick = function() {self.hide()};
	}
	return this._box;
};

popupWindow.prototype.getContentBox = function() {
	if (this._content == null) {
		this._getBox();
	}
	return this._content;
};


document.observe('dom:loaded', function () {

	var currentItem;

	var loadContent = function(transport) {
		if (currentItem) {
			currentItem.loadedPopupWindow = new popupWindow;
			currentItem.loadedPopupWindow.setContent(transport.responseText).open();

			$A(currentItem.loadedPopupWindow.getContentBox()
				.getElementsByTagName('form')).each(function(item) {
					item.windowOwn = currentItem.loadedPopupWindow;
					item.onsubmit = doSubmitForm;
				});

		}
		currentItem = null;
	};

	var doSubmitForm = function(e) {
		
		this.windowOwn.setPreloader();
		
		$(this).request({
			onComplete: function(transport) {
				this.windowOwn.removePreloader().setContent(transport.responseText);
			}.bind(this)
		});

		$(this).disable();

		return false;
	};

	var openPopup = function(e) {
		Event.stop(e);
		
		if (this.loadedPopupWindow) {
			if (this.loadedPopupWindow.opened()) {
				return;
			}
			this.loadedPopupWindow = null;
		}
		
		currentItem = this;
		new Ajax.Request(this.href, {method: 'get', onSuccess: loadContent});
	};

	$$('a.popupWindow').each(function(item) {
		item.observe('click', openPopup)
	});
});
