// ******************************************************************************
// DHTML POPUP
// ******************************************************************************
// Also requires a reference to the global JS file (MILVER.js)
// 
// TODO: Destroy method? - FAP
// TODO: TabStop on radio buttons! - FAP
// TODO: Multi browser (ddlDHTML) - FAP
// 
// ******************************************************************************
ModalDialog = function()
{
	// Members
	this.url = null;
	this.ddEl = null;
	this.closeMode = null;
	this.posMode = null;
	this.waitMode = false;
	this.scriptRoot = "Scripts";
	this.loadingPage = "PLoading.aspx";
	this.width = 300;
	this.minHeight = -1;
	this.postArgsInHTMLInputID = null;
	this.height = 200;
	this.dragging = false;
	this.hideCovered = true;
	this.offsetX = 10;
	this.offsetY = 10;

	this.ddlTable = null;
	this.ddlTableDeferred = null;

	// HTML elements
	this.container = null;
	this.content = null;
}

// Detect IE browsers
ModalDialog.is_ie = (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent));
// Detect IE 6 browsers (no drop down lost problem with IE 7)
ModalDialog.is_ie6 = (ModalDialog.is_ie && /msie 6\.0/i.test(navigator.userAgent));
// Detect Opera browsers
ModalDialog.is_opera = /opera/i.test(navigator.userAgent);
// Ddetect KHTML-based browsers
ModalDialog.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);

// TODO: - FAP
if (!ModalDialog.is_ie)
	addEvent(document, "mousemove", getMouseXY);

var posX;
var posY;
// TODO: Inside modalDialog class - FAP
function getMouseXY(e)
{
	if (!e) var e = window.event||window.Event;
/*
	if (IE)
	{
*/
		var tmpX = e.clientX;
		var tmpY = e.clientY;
/*
	}
	else
	{
			var	tmpX = m.pageX;
			var	tmpY = m.pageY;
	}
*/
	if (!document.body.scrollTop)
	{
			var	iL = document.documentElement.scrollLeft;
			var	iV = document.documentElement.scrollTop;
	}
	else
	{
			var	iL = document.body.scrollLeft;
			var	iV = document.body.scrollTop;
	}
//		document.forms[0].MouseX.value = tmpX	+	iL;
//		document.forms[0].MouseY.value = tmpY	+	iV;
	posX = tmpX	+	iL;
	posY = tmpY	+	iV;
}

// BEGIN: UTILITY FUNCTIONS

ModalDialog.createElement = function(type, parent)
{
	var el = document.createElement(type);

	if (typeof parent != "undefined")
		parent.appendChild(el);

	return el;
};

ModalDialog.stopEvent = function(ev)
{
	ev || (ev = window.event);
	if (ModalDialog.is_ie)
	{
		ev.cancelBubble = true;
		ev.returnValue = false;
	} else
	{
		ev.preventDefault();
		ev.stopPropagation();
	}
	return false;
};

// END: UTILITY FUNCTIONS

// BEGIN: STATIC FUNCTIONS

ModalDialog.dragIt = function(ev)
{
	var md = window.modalDialog;
	if (!(md && md.dragging))
		return false;

	var pos;
	//if (ModalDialog.is_ie)
	//	pos = { x: window.event.clientX + document.body.scrollLeft, y: window.event.clientY + document.body.scrollTop };
	//else
	//	pos = { x: ev.pageX, y: ev.pageY };
	pos = { x: parseInt(md.container.style.left) + ev.clientX, y: parseInt(md.container.style.top) + ev.clientY };

	var st = md.container.style;
	st.left = (pos.x - md.xOffs) + "px";
	st.top = (pos.y - md.yOffs) + "px";

	return ModalDialog.stopEvent(ev);
};

ModalDialog.dragEnd = function(ev)
{
	var md = window.modalDialog;
	if (!md)
		return false;

	md.dragging = false;

	removeEvent(md.ddEl, "mousemove", ModalDialog.dragIt);
	removeEvent(md.ddEl, "mouseup", ModalDialog.dragEnd);
};

// END: STATIC FUNCTIONS

// BEGIN: OBJECT FUNCTIONS

ModalDialog._checkModalDialog = function(ev)
{
	var md = window.modalDialog;
	if (!md) return false;

	if (!md.ddlTableDeferred)
	// Using an iFrame expects any document mousedown event under the modal dialog - FAP
	//var el = ModalDialog.is_ie ? ModalDialog.getElement(ev) : ModalDialog.getTargetElement(ev);
	//for (; el != null && el != md.container; el = el.parentNode);
	//if (el == null)
	//{
		// Calls closeHandler which should hide the modal dialog.
		//window.modalDialog.callCloseHandler();
		md.hide();
		//return ModalDialog.stopEvent(ev);
	//}
};

ModalDialog._checkModalDialogTabIdx = function(ev)
{
	if (ev.keyCode == 9) return false;
};

ModalDialog.prototype.chgHeight = function(h)
{
	this.content.style.height = h + 'px';
};

ModalDialog.prototype.chgWidth = function(w)
{
	this.content.style.width = (w > this.width ? this.width : w) + 'px';
};

ModalDialog.prototype.create = function() {
    var parent = document.getElementsByTagName("body")[0];

    var div = ModalDialog.createElement("div");
    this.container = div;
    div.className = "mdContainer";
    //	div.className = "mdContainer" + (this.waitMode ? "W" : "");

    var divt = ModalDialog.createElement("div");
    divt.className = "t";

    var divb = ModalDialog.createElement("div");
    divb.className = "b";

    var divl = ModalDialog.createElement("div");
    divl.className = "l";

    var divr = ModalDialog.createElement("div");
    divr.className = "r";

    var divbl = ModalDialog.createElement("div");
    divbl.className = "bl";

    var divbr = ModalDialog.createElement("div");
    divbr.className = "br";

    var divtl = ModalDialog.createElement("div");
    divtl.className = "tl";

    var divtr = ModalDialog.createElement("div");
    divtr.className = "tr";

    //<div class="t"><div class="b"><div class="l"><div class="r"><div class="bl"><div class="br"><div class="tl"><div class="tr">
    //Lorem ipsum dolor sit amet consectetur adipisicing elit
    //</div></div></div></div></div></div></div></div> 

    var iFrame = ModalDialog.createElement("iframe");
    this.content = iFrame;
    iFrame.className = "mdContent";
    iFrame.src = this.scriptRoot + "/" + this.loadingPage;
    iFrame.frameBorder = "0";
    iFrame.scrolling = "no";

    divtr.appendChild(iFrame);
    divtl.appendChild(divtr);
    divbr.appendChild(divtl);
    divbl.appendChild(divbr);
    divr.appendChild(divbl);
    divl.appendChild(divr);
    divb.appendChild(divl);
    divt.appendChild(divb);

    div.appendChild(divt);

    parent.appendChild(this.container);
}

ModalDialog.prototype.getCenter = function(w, h)
{
	var fullWidth  = getViewportWidth();
	var fullHeight = getViewportHeight();

	var scroll;
	if (ModalDialog.is_ie)
		scroll = { x: ieTrueBody().scrollLeft, y: ieTrueBody().scrollTop };
	else
		scroll = { x: window.scrollX, y: window.scrollY };

	//scroll.x = parseInt(scroll.x, 10);
	//scroll.y = parseInt(scroll.y, 10);

	return { x: (scroll.x + ((fullWidth - w) / 2)), y: (scroll.y + ((fullHeight - h) / 2)) }
}

ModalDialog.prototype.hide = function(args)
{
	removeEvent(document, "mousedown", ModalDialog._checkModalDialog);
	//if (!ModalDialog.is_ie) removeEvent(document, "keypress", ModalDialog._checkModalDialogTabIdx);

	this.container.style.display = "none";

	ModalDialog.OutItem();

	this.setTabIndexesState(true);
	if (this.waitMode)
		this.setButtonState(true);
	if (this.hideCovered)
		this.setCoveredVisibility(true);

	this.content.src = this.scriptRoot + "/" + this.loadingPage;

	if (args)
	{	
		if (this.closeMode == 'postBack')
		{
		    if (this.postArgsInHTMLInputID)
		        dialogPostBack(args, this.postArgsInHTMLInputID);
			else
			    dialogPostBack(args, null);
		}
		else
			dialogCallBack(args);
	}
};

ModalDialog.prototype.isShown = function()
{
	return (this.container.style.display == "block");
}

ModalDialog.prototype.mouseDown = function(ev)
{
	var md = window.modalDialog;
	if (!md) return false;

	md._dragStart(ev);
	//return ModalDialog.stopEvent(ev);
}

ModalDialog.prototype.moveAt = function(x, y)
{
	this.container.style.left = x + "px";
	this.container.style.top  = y + "px";
}

ModalDialog.prototype.redirect = function()
{
	this.chgHeight(this.height);
	this.chgWidth(this.width);

	var pos = this.getCenter(this.width, this.height);
	this.moveAt(pos.x, pos.y);
};

ModalDialog.prototype.setCoveredVisibility = function(visible)
{
	if (!ModalDialog.is_ie6 && !ModalDialog.is_opera)
		return;

	function getVisib(obj)
	{
		var value = obj.style.visibility;
		if (!value)
		{
			// Gecko, W3C
			if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function")
			{
				if (!ModalDialog.is_khtml)
					value = document.defaultView.getComputedStyle(obj, "").getPropertyValue("visibility");
				else
					value = '';
			}
			// IE
			else if (obj.currentStyle)
				value = obj.currentStyle.visibility;
			else
				value = '';
		}
		return value;
	};

	//var tags = new Array("applet", "iframe", "select");
	var tags = new Array("applet", "select");
	for (var k = tags.length; k > 0;)
	{
		var cc = null;
		var ar = document.getElementsByTagName(tags[--k]);

		for (var i = ar.length; i > 0;)
		{
			cc = ar[--i];
			if (visible)
			{
				if (!cc.__old_visibility)
					cc.__old_visibility = getVisib(cc);
				cc.style.visibility = cc.__old_visibility;
			}
			else
			{
				if (!cc.__old_visibility)
					cc.__old_visibility = getVisib(cc);
				cc.style.visibility = "hidden";
			}
		}
	}
};

ModalDialog.prototype.setDocument = function(doc)
{
	this.ddEl = doc.getElementById("dragdrop");
	if (this.ddEl)
		addEvent(this.ddEl, "mousedown", this.mouseDown);
}

ModalDialog.prototype.setSize = function(w, mH, h)
{
	this.width = w;
	this.minHeight = mH;
	this.height = h;
};

ModalDialog.prototype.setTabIndexesState = function(enabled)
{
	//if (!ModalDialog.is_ie)
	//	return;

	var tags = new Array("a", "button", "input", "textarea", "select", "iframe");
	for (var k = tags.length; k > 0;)
	{
		var cc = null;
		var ar = document.getElementsByTagName(tags[--k]);

		for (var i = ar.length; i > 0;)
		{
			cc = ar[--i];
			if (enabled)
			{
				if (typeof cc.__old_index == "undefined")
					cc.__old_index = cc.tabIndex;
				cc.tabIndex = cc.__old_index;
			}
			else
			{
				if (typeof cc.__old_index == "undefined")
					cc.__old_index = cc.tabIndex;
				cc.tabIndex = "-1";
			}
		}
	}
}

ModalDialog.prototype.setButtonState = function(enabled)
{
	//if (!ModalDialog.is_ie)
	//	return;
	var tags = new Array("a", "input", "button");
	for (var k = tags.length; k > 0;)
	{
		var doIt;
		var cc = null;
		var ar = document.getElementsByTagName(tags[--k]);

		for (var i = ar.length; i > 0;)
		{
			cc = ar[--i];

			switch (tags[k])
			{
				case "a":
				case "input":
					doIt = cc.onclick != null;
					break;
				case "button":
					doIt = cc.id.indexOf("btnCancel") < 0;
					break;
				default:
					doIt = true;
					break;
			}
			if (!doIt) continue;

			if (enabled)
			{
				if (typeof cc.__old_state == "undefined")
					cc.__old_state = cc.disabled;
				cc.disabled = cc.__old_state;
			}
			else
			{
				if (typeof cc.__old_state == "undefined")
					cc.__old_state = cc.disabled;
				cc.disabled = true;
			}
		}
	}
}

ModalDialog.prototype.show = function()
{
	this.dragging = false;
	this.content.src = this.url;
	this.content.style.width = this.width + 'px';
	this.content.style.height = (this.minHeight > -1 ? this.minHeight : this.height) + 'px';

	this.setTabIndexesState(false);
	if (this.waitMode)
		this.setButtonState(false);
	if (this.hideCovered)
		this.setCoveredVisibility(false);
	this.container.style.display = "block";

	if (!this.waitMode)
		addEvent(document, "mousedown", ModalDialog._checkModalDialog);
	//if (!ModalDialog.is_ie) addEvent(document, "keypress", ModalDialog._checkModalDialogTabIdx);
};

ModalDialog.prototype.showAt = function(x, y)
{
	this.moveAt(x, y);
	this.show();
};

ModalDialog.prototype.showAtCenter = function()
{
	var pos = this.getCenter(this.width, this.height);
	this.showAt(pos.x, pos.y);
};

/** Internal function. Starts dragging the element. */
ModalDialog.prototype._dragStart = function(ev)
{
	if (this.dragging)
		return;
	this.dragging = true;

	var pos;
	//if (ModalDialog.is_ie)
	//	pos = { x: parseInt(this.container.style.left) + window.event.clientX, y: parseInt(this.container.style.top) + window.event.clientY };
	//else
		pos = { x: parseInt(this.container.style.left) + ev.clientX, y: parseInt(this.container.style.top) + ev.clientY };

	var st = this.container.style;
	this.xOffs = pos.x - parseInt(st.left);
	this.yOffs = pos.y - parseInt(st.top);

	addEvent(this.ddEl, "mousemove", ModalDialog.dragIt);
	addEvent(this.ddEl, "mouseup", ModalDialog.dragEnd);
};

// END: OBJECT FUNCTIONS

ModalDialog.OnItem = function(el)
{
	var md = window.modalDialog;
	if (!md) return false;

	if (md.isShown())
	{
		md.startDeferItem(el);
		return false;
	}

	if (md.ddlTable)
		ModalDialog.OutItem();

	md.ddlTable = el;
	md.ddlTable.onclick = ModalDialog.CreateMenu;
	md.ddlTable.onmouseout = ModalDialog.OutItem;
	md.ddlTable.className = "dhtmlddlsel";

	return false;
}

ModalDialog.OnLink = function(el)
{
	el.onblur = ModalDialog.OutItem;
	el.onkeydown = ModalDialog.PopMenu;

	var elTmp = FindElementByAttribute(el, "TABLE", "MD");
	if (elTmp)
		ModalDialog.OnItem(elTmp);

	return false;
}

ModalDialog.PopMenu = function(e)
{
	var md = window.modalDialog;
	if (!md) return false;

	if (e == null)
		e = window.event||window.Event;

	var nKeyCode = (e.keyCode) ? e.keyCode : e.which;
	if (!md.isShown() && ((e.shiftKey && nKeyCode==13) || (e.altKey && nKeyCode==40)))
	{
		ModalDialog.CreateMenu(e);
		return false;
	}
	else
		return true;
}

ModalDialog.CreateMenu = function(e)
{
	var md = window.modalDialog;
	if (!md) return false;

	if (e == null)
		e = window.event||window.Event;

	if (md.ddlTable == null)
		return;

	return md.createMenuEx(md.ddlTable, e);
}

ModalDialog.prototype.createMenuEx = function(container, e)
{
	if (container == null)
		return;

	container.onmouseout = null;

	if(!this.isShown())
		this.showDialog(container);
}

ModalDialog.prototype.showDialog = function(container)
{
	ModalDialog.HideDialog();
	this.showRoot(container);

	return false;
}
ModalDialog.prototype.showRoot = function(container)
{
	var y = 0;
	if (container)
		y += container.offsetHeight;

	this.menuHtcInternal_Show(container, y);
}

ModalDialog.prototype.menuHtcInternal_Show = function(container, y)
{
	var pos = this.setMenuPosition(container);
	var sFct = container.getAttribute('MD');

	if (sFct)
	{
		var fct = new String(sFct);
		fct = fct.replace("{0}", pos.x);
		fct = fct.replace("{1}", pos.y);
		fct = fct.replace(";", ""); // Remove end ; char (avoid DeferCall error...)
		DeferCall(fct);
	}
}

ModalDialog.prototype.setMenuPosition = function(container)
{
	// TODO: Move if outside the browser - FAP
	// TODO: Right of ddlDHTML - FAP

	var pos = GetElementPosition(container);

	var left = pos.x + 1;
	var top = (pos.y + pos.height);

	return { x: left, y: top}
}

ModalDialog.OutItem = function()
{
	var md = window.modalDialog;
	if (!md) return false;

	if (!md.isShown() && md.ddlTable != null)
	{
		md.ddlTable.onclick = null;
		md.ddlTable.onmouseout = null;
		md.ddlTable.className = "dhtmlddl";

		md.resetExecutionState();
	}
}

ModalDialog.prototype.resetExecutionState = function()
{
	this.ddlTable = null;
	ModalDialog.EndDeferItem();
}

ModalDialog.prototype.startDeferItem = function(el)
{
	if (el != this.ddlTable)
	{
		this.ddlTableDeferred = el;
		el.onmouseout = ModalDialog.EndDeferItem;
		el.onclick = ModalDialog.DeferredOnItem;
	}
}

ModalDialog.DeferredOnItem = function(e)
{
	var md = window.modalDialog;
	if (!md) return false;

	if (e == null)
		e = window.event||window.Event;

	var el = md.ddlTableDeferred;
	if (el)
	{
		ModalDialog.HideDialog();
		ModalDialog.OnItem(el);
		ModalDialog.CreateMenu(e);
		return false;
	}
}

ModalDialog.EndDeferItem = function()
{
	var md = window.modalDialog;
	if (!md) return false;

	var el = md.ddlTableDeferred;
	if (el)
	{
		md.ddlTableDeferred = null;
		el.onmouseout = null;
		el.onclick = null;
	}
}

ModalDialog.HideDialog = function()
{
	var md = window.top.modalDialog;
	if (md && md.isShown())
		md.hide();
}

ModalDialog.showDialog = function(params)
{
	function param_default(name, def)
	{
		if (typeof params[name] == "undefined")
			params[name] = def;
	};

	param_default("url", null);
	param_default("width", 300);
	param_default("minHeight", -1);
	param_default("height", 200);
	param_default("postArgsInHTMLInputID", null);
	param_default("closeMode", null);
	param_default("posMode", 'center');
	param_default("waitMode", false);
	param_default("hideCovered", true);

	var md = window.modalDialog;
	if (!md)
	{
		window.modalDialog = md = new ModalDialog();
		md.create();
	}

	md.url = params.url;
	md.setSize(params.width, params.minHeight, params.height);
	md.postArgsInHTMLInputID = params.postArgsInHTMLInputID;
	md.closeMode = params.closeMode;
	md.posMode = params.posMode;
	md.waitMode = params.waitMode;
	md.hideCovered = params.hideCovered;
	md.container.className = "mdContainer" + (md.waitMode ? "W" : "");

	if (md.posMode == 'center')
		md.showAtCenter();
	else if (md.posMode == 'coordinates')
	{
		md.showAt(params.posX, params.posY);
	}
	else
	{
		// TODO: Test	multi	browser! - FAP
		// TODO: posx, posX, posy, posY -> pos.x, pos.X, etc. - FAP
		var	posx = 0;
		var	posy = 0;
		if (!e)	var	e = window.event||window.Event;
		posx = e.clientX;
		posy = e.clientY;
		if (!ModalDialog.is_ie)
		{
				posx = posX;
				posy = posY;
		}
		md.showAt(posx + md.offsetX, posy + md.offsetY);
	}
}

function dialogPostBack(args, postArgsInHTMLInputID)
{
    var argument = '';
    if (args.length > 2) // Backward compatibility otherwise '> 1' would be better but required a correct RegisterForEventValidation - FAP
    {
        for (var i = 1; i < args.length; i++)
        {
            if (argument == '')
                argument += args[i];
            else
                argument += ';' + args[i];
        }
    }

    if (postArgsInHTMLInputID)
    {
        var htmlInput = document.getElementById(postArgsInHTMLInputID);
        if (htmlInput)
            htmlInput.value = argument;

        __doPostBack(args[0], '');
    }
    else
	    __doPostBack(args[0], argument);
}

function dialogCallBack(args)
{
	//Anthem_InvokePageMethod("PopupCallBackResult", args, dialogPostCallBack, null);
}

function dialogPostCallBack(result, clientCallBackArg)
{
	// Empty function to make the Anthem_InvokeControlMethod call asynchronous !
}


// ******************************************************************************
// DHTML POPUP TIMER
// ******************************************************************************
// var t = window.timer;
// if (!t) window.timer = t = new Timer();
// [t.interval = 200;] // Optional, default 500
// t.onTimeout = ModalDialog.Hide;
// t.setAndStart(3); // Default interval = 500 -> 3 * 500 = 1500ms
// ******************************************************************************
Timer = function()
{
	// Members
	this.id = null;
	this.interval = 500; // 500 ms
	this.iterations = 0;
	this.onTimeout = null;
}

// BEGIN: OBJECT FUNCTIONS

Timer.prototype._run = function()
{
	if(this.iterations <= 0)
	{
		this.stop();
		// Delegate
		if (this.onTimeout)
		{
			try
			{
				this.onTimeout();
			}
			catch (err)
			{
				// e.g. delgate binding is declared in the popup
				// and the popup has been closed before the timer timeout occured
			}
		}
	}
	else
	{
		this.iterations -= 1;
		if (window.timer) // Should never occur... - FAP
			this.id = self.setTimeout('window.timer._run()', this.interval);
	}
}

Timer.prototype.setAndStart = function(iterations)
{
	if (!iterations)
		return false;

	this.iterations = iterations;

	this.stop();
	this._run();
}

Timer.prototype.stop = function()
{
	if(this.id)
	{
		clearTimeout(this.id);
		this.id = null;
	}
}

// END: OBJECT FUNCTIONS

