/**
 * Popup block
 *
 * В версии 2.1 добавлены следующие улучшения:
 * <ul>
 *   <li>Флаг <code>keep</code> заменен на <code>event.stopPropagation().</code></li>
 *   <li>Форма появляется и исчезает плавно (под IE появляется/исчезает мгновенно в виду проблем с <code>filter</code>).</li>
 *   <li>Добавлен параметр <code>showFunction</code> - функция, выполняемая после показа popup'а.</li>
 * </ul>
 *
 * @author Stepan Reznikov [stepan.reznikov@gmail.com], Vladislav Yakovlev [scorpix@design.ru]
 * @version 2.1 (2008-09-23)
 * @requires jQuery
 *
 * @param {Object} options Object with options
 */
var PopupBlock = function (options) {

	var that = {};

	var documentClickHandler;

	var documentKeyDownHandler;


	that.hide = function (event) {

		if (options.fader) {
			options.fader.addClass('hidden');
		}

		if ($.browser.msie) {
			options.container.addClass('hidden');
		} else {
			options.container.animate({ opacity: 0 }, 300, function() {
				options.container.addClass('hidden').css('opacity', '');
			});
		}

		$(document).unbind('click', documentClickHandler);
		$(document).unbind('keydown', documentKeyDownHandler);
		
		if (options.hideFunction) {
			options.hideFunction();
		}
	};


	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');
		}

		if ($.browser.msie) {
			options.container.removeClass('hidden');
		} else {
			options.container.css('opacity', 0).removeClass('hidden').animate({ opacity: 1 }, 300, function() {
				options.container.css('opacity', '');
			});
		}

		documentClickHandler = function (event) {
			that.hide(event);
		};

		documentKeyDownHandler = function (event) {
			that.cancel(event);
		};

		$(document).click(documentClickHandler);
		$(document).keydown(documentKeyDownHandler);

		if (options.showFunction) {
			options.showFunction();
		}
	};


	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) {
		event.stopPropagation();
	});

	options.link.click(function (event) {
		that.toggle(event);
	});

	if (options.close) {
		options.close.click(function (event) {
			that.toggle(event);
		});
	}

	return that;
};