Type.registerNamespace('Mercell.Web.UI');

//
// Define the control properties.
//
Mercell.Web.UI.Popup = function(element)
{
	Mercell.Web.UI.Popup.initializeBase(this, [element]);
	var images = element.getElementsByTagName("IMG");

	this._closeImage = null;
	if(images.length > 0)
	{
		this._closeImage = images[0];
	}

	this._closeNow = null;
}

Mercell.Web.UI.Popup.prototype = {
	initialize: function()
	{
		Mercell.Web.UI.Popup.callBaseMethod(this, 'initialize');
		this._closeNow = Function.createDelegate(this, this._onCloseNow);
		if(this._closeImage != null)
		{
			$addHandler(this._closeImage, "click", this._closeNow);
		}
			
		if (this.get_show())
		{
			this.showPopup();
		}
		else
		{
			this.closePopup();
		}
	},

	dispose: function()
	{
		if (this._closeNow)
		{
			if(this._closeImage != null)
			{
				$removeHandler(this._closeImage, "click", this._closeNow);
			}
			
			this._closeNow = null;
		}

		Mercell.Web.UI.Popup.callBaseMethod(this, 'dispose');
	},

	get_show: function()
	{
		var hfShow = $get(this.get_element().id + "__show");
		return hfShow.value == "1";
	},

	set_show: function(value)
	{
		this.updateShow(value);
		if (value)
		{
			this.showPopup();
		}
		else
		{
			this.closePopup();
		}
	},

	updateShow: function(value)
	{
		var hfShow = $get(this.get_element().id + "__show");
		hfShow.value = value ? "1" : "0";
	},

	showPopup: function()
	{
		var status = Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack();
		if (status)
		{
			requestFade(true);
		}
		else
		{
			page.fade(true);
		}
		var popup = this.get_element();
		popup.style.display = "block";
		this.repositionPopup();
	},

	_onCloseNow: function()
	{
		var popup = this.get_element();
		popup.style.display = "none";
		this.updateShow(false);
		page.unFade();
	},

	closePopup: function()
	{
		var status = Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack();
		if (status)
		{
			requestUnfade();
		}
		else
		{
			page.unFade();
		}
		
		var popup = this.get_element();
		popup.style.display = "none";
		this.updateShow(false);
	},

	repositionPopup: function()
	{
		var popup = this.get_element();
		if (typeof (popup) !== 'undefined')
		{
			var top = page.scrollTop() + (page.offsetHeight() / 2) - (popup.clientHeight / 2);
			var left = page.scrollLeft() + (page.offsetWidth() / 2) - (popup.clientWidth / 2);

			if (popup.style.top != top)
			{
				popup.style.top = top + "px";
			}
			if (popup.style.left != left)
			{
				popup.style.left = left + "px";
			}

			var x = this;
			window.setTimeout(function() { x.repositionPopup(); }, 500);
		}
	}
}

Mercell.Web.UI.Popup.registerClass('Mercell.Web.UI.Popup', Sys.UI.Control);

if (typeof (Sys) !== 'undefined')
{
	Sys.Application.notifyScriptLoaded();
}
