/**
 * Класс для открывания/закрывания блоков
 * @version 3.0, 15.10.2008
 * @author Stepan Reznikov (stepan.reznikov@gmail.com)
 * @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
 * @param {Object} options Опции
 * @param {jQuery} options.container Контейнер с содержимым блока
 * @param {jQuery} options.link Элемент активирующий блок
 * @param {jQuery} [options.fader] Фейдер-засериватель
 * @param {jQuery} [options.close] Элемент закрывающий блок
 */

var PopupBlock = function (options) {
	if (options.container && options.link) {
		this.container = options.container;
		this.link = options.link;
		this.fader = options.fader;
		this.close = options.close;
		this.isOpen = !this.container.is(".hidden");
		this.attachEvents();
	}
	else {
		throw new Error("PopupBlock: required parameters 'options.container' and 'options.link' are missing or undefined.");
	}
};

PopupBlock.prototype = {

	ESCAPE_KEY_CODE: 27,

	attachEvents: function () {
		var that = this;
		this.link.click(function (event) {
			event.stopPropagation();
			event.preventDefault();
			that.toggle();
		});
		this.container.click(function (event) {
			event.stopPropagation();
		});
		if (this.close) {
			this.close.click(function () {
				that.hide();
			});
		}
	},

	toggle: function () {
		if (this.isOpen) {
			this.hide();
		}
		else {
			this.show();
		}
	},

	show: function () {
		this.isOpen = true;
		if (this.fader) {
			this.fader.removeClass("hidden");
		}
		this.container.removeClass("hidden");

		var that = this;

		this.documentClickHandler = function () {
			that.hide();
		};

		this.documentKeyDownHandler = function (event) {
			that.cancel(event);
		};

		$(document).click(this.documentClickHandler);
		$(document).keydown(this.documentKeyDownHandler);
	},

	hide: function () {
		this.isOpen = false;
		this.container.addClass("hidden");
		if (this.fader) {
			this.fader.addClass("hidden");
		}

		$(document).unbind("click", this.documentClickHandler);
		$(document).unbind("keydown", this.documentKeyDownHandler);
	},

	cancel: function (event) {
		var code = event.keyCode ? event.keyCode : event.which ? event.which : null;
		if (code === this.ESCAPE_KEY_CODE) {
			this.hide();
		}
	}

};
