/**
 * Popup block
 * (requires jQuery)
 *
 * @author Stepan Reznikov [stepan.reznikov@gmail.com]
 * @version 2.0 (2008-07-07)
 *
 * @param {Object} options Object with options
 */


var popup_block = function (options) {

	var that = {};

	var keep = false,
	    documentClickHandler,
	    documentKeyDownHandler;


	that.hide = function (event) {

		if (keep) {
			keep = false;
			return;
		}

		if (options.fader) {
			options.fader.addClass("hidden");
		}
		options.container.addClass("hidden");

		$(document).unbind("click", documentClickHandler);
		$(document).unbind("keydown", documentKeyDownHandler);
	};


	that.cancel = function (event) {
		var code = event.keyCode ? event.keyCode : event.which ? event.which : null;
		if (code === 27) {
			that.hide(event);
		}
	};


	that.show = function (event) {

		if (options.fader) {
			options.fader.removeClass("hidden");
		}
		options.container.removeClass("hidden");

		documentClickHandler = function (event) {
			that.hide(event);
		};

		documentKeyDownHandler = function (event) {
			that.cancel(event);
		};

		$(document).click(documentClickHandler);
		$(document).keydown(documentKeyDownHandler);
	};


	that.toggle = function (event) {

		event.preventDefault();
		event.stopPropagation();

		if (options.container.hasClass("hidden")) {
			that.show(event);
		} else {
			that.hide(event);
		}
	};


	options.container.click(function (event) {
		keep = true;
	});

	options.link.click(function (event) {
		that.toggle(event);
	});

	if (options.close) {
		options.close.click(function (event) {
			if (options.container.hasClass("hidden")) {
			} else {
				that.toggle(event);
			}
		});
	}

	return that;
};