(function(){
var opened = false,
	inited = false,
	BODY, WINDOW,
	bg, win, target, options;

function escClose(e)
{
	if (e.keyCode == 27) voile.close();
	return true;
}

function updateVoile()
{
	bg.hide();
	if ($.browser.msie) {
		setTimeout(updateVoile2, 1);
	} else {
		updateVoile2();
	}
	//bg.css({height: BODY.outerHeight(true), width: BODY.width() + WINDOW.scrollLeft()});
}

function updateVoile2()
{
	var html = document.body.parentNode;
	var h = WINDOW.height();
	if (h < html.scrollHeight) h = html.scrollHeight;
	bg.css({height: h, width: html.scrollWidth});
	bg.show();
}

function updateWindow(notAnim)
{
	var p = getWindowPosition();
	win.stop();
	notAnim === true ? win.css(p) : win.animate(p, 200);
}

function getWindowPosition()
{
	var t = (WINDOW.height() - win.outerHeight(true)) / 3 + WINDOW.scrollTop();
	var l = (WINDOW.width() - win.outerWidth(true)) / 2 + WINDOW.scrollLeft();
	if (t < 0) t = 0;
	if (l < 0) l = 0;
	return {top: t, left: l};
}

var voile = this.voile = {
	open: function(_target, _options)
	{
		if (opened) voile.close();
		opened = true;

		options = $.extend({
			close: false,
			escClose: true
		}, _options);

		target = $(_target);
		if (!inited) {
			inited = true;
			BODY = $(document.body);
			WINDOW = $(window);

			bg = $('<div id="voile-bg">').css({opacity: 0.5, position: 'absolute', 'z-index': 9000, top: 0, left: 0, display: 'none'}).appendTo(BODY);
			if ($.browser.msie && $.browser.version <= 6) {
				$('<iframe style="width:100%;height:100%;border:none;"/>').css('opacity', 0).appendTo(bg);
			}
			win = $('<div id="voile-window">').css({position: 'absolute', 'z-index': 9001}).appendTo(BODY);
		}
		var w = BODY.width();
		$('html,body').addClass('voile');

		if (target[0].parentNode !== win[0])
			win.append(target);
		target.show();
		win.css({top:0,left:0}).show();
		updateVoile();
		updateWindow(true);
		WINDOW.resize(voile.update);
		WINDOW.scroll(updateWindow);
		if (options.escClose) WINDOW.keydown(escClose); // or BODY ???
	},
	close: function()
	{
		if (options.close) {
			if (false === options.close()) return;
		}
		if (!opened) return;
		WINDOW.unbind('resize', voile.update);
		WINDOW.unbind('scroll', updateWindow);
		if (options.escClose) WINDOW.unbind('keydown', escClose);
		bg.hide();
		win.hide();
		target.hide();
		$('html,body').removeClass('voile');
		opened = false;
	},
	update: function()
	{
		updateVoile();
		updateWindow();
	}
};

})();
