/*
Copyright (c) ScanFrame 2007.
All Rights Reserved.

$Source: /export/cvs/primo/com/jscripts/dialog.js,v $
$Author: arjan $
$Revision: 1.24 $

Identification:
  LIB

Initial Author:
  AVO 20070527

Purpose:
	Common library for dialog javascript functions.

*/
//---------------------------------------------------------------------------
/**
* Object tracks the current modal dialog opened from this window.
* @type TDialogWindow
*/
var DialogWin = new TDialogWindow();
/**
* Object used to handle events when this page is the dialog.
* @type TDialogHandler
*/
var Dialog = new TDialogHandler();
//---------------------------------------------------------------------------
/**
* Returns object for controlling the modal dialog itself.
* @constructor
*/
function TDialogHandler()
{
	/**
	* Set to true when this browser is a modal dialog.
	* @type boolean
	*/
	this.IsModal = null;
	/**
	* Holds the opener window.
	* @type window
	*/
	this.Opener = opener ? opener : parent;
	//-----------------------------------------
	/**
	* Add needed window events are linked here.
	*/
	SfLib.AddEvent(window, 'load', new Closure(this, 'EvLoad').Call);
	SfLib.AddEvent(window, 'unload', new Closure(this, 'EvUnLoad').Call);
	//-----------------------------------------
	/**
	* Called from a window dialog to set openers ModalResult value.
	* The location of this fnction should be Dialog but its needed because
	* it does not work otherwise.
	* @param mixed
	* @returns void
	*/
	this.SetModalResult = function(result)
	{
		// Assign the result only when modal.
		if (this.Opener && this.IsModal)
			this.Opener.DialogWin.ModalResult = result;
		// Pass the result to an overloadable handler in this window.
		this.HandleModalResult(result, window.name);
	};
	//-----------------------------------------
	/**
	* Handler to show overlay in Firefox when it is hidden by the next handler
	* during a reload of the browser.
	* @private
	* @param event Built-In event class.
	*/
	this.EvLoad = function(ev)
	{
		//
		if (BrowserDetect.browser == 'Explorer' && this.Opener && this.IsModal)
			this.Opener.DialogWin.Window = window;
		//
		this.EvInit(window.name);
		//
		if (BrowserDetect.browser != 'Explorer' && this.Opener && this.IsModal)
		{
			// Only move the inpage dialog to the back when one exists.
			var cur = this.Opener.DialogWin.InPageCurrent();
			// cur.frameElement should indicate that this frame is attached within an inpage modal dialog.
			if (cur && cur.frameElement)
				this.Opener.DialogWin.InPageCurrent().MoveToBack(true);
			else
				this.Opener.DialogWin.PageOverlayDisplay(true);
		}
		//
		return true;
	};
	//-----------------------------------------
	/**
	* Handler to hide overlay.
	* @private
	* @param event Built-In event class.
	*/
	this.EvUnLoad = function(ev)
	{
		if (BrowserDetect.browser != 'Explorer' && this.Opener && this.IsModal)
		{
			// Only move the inpage dialog to the front when one exists.
			if (this.Opener.DialogWin && this.Opener.DialogWin.InPageCurrent())
				this.Opener.DialogWin.InPageCurrent().MoveToBack(false);
			else
				this.Opener.DialogWin.PageOverlayDisplay(false);
		}
		//
		if (this.Opener && this.IsModal && this.Opener.DialogWin && this.Opener.DialogWin.ModalResult != null)
			// Make the opener call the Modal result.
			this.Opener.DialogWin.EvModalResult(this.Opener.DialogWin.ModalResult, window.name);
		// Close any open dialog when thish window is unloading.
		if (DialogWin && DialogWin.Window && !DialogWin.Window.closed)
		{
			// Call the event handler on the window if possible.
			if (DialogWin.Window.Dialog && typeof DialogWin.Window.Dialog.EvUnLoad == 'function')
				DialogWin.Window.Dialog.EvUnLoad();
			// Close the dialog.
			DialogWin.Window.close();
			// Assign null as a flag and signal.
			DialogWin.Window = null;
		}
		//
		if (BrowserDetect.browser == 'Explorer' && this.Opener && this.IsModal)
		{
			//this.Opener.focus();
			//this.Opener.DialogWin.Window = null;
		}
		//
		return true;
	};
	//-----------------------------------------
	/**
	* Event handler for dialog initialization.
	*/
	this.EvInit = function()
	{
		// Only set this once.
		if (this.IsModal == null)
			// Check if this window is the one that was modal created.
			this.IsModal = this.Opener && this.Opener.DialogWin && this.Opener.DialogWin.Window == window;
		// When modal let the caller initialize the dialog.
		if (this.IsModal == true)
			return this.Opener.DialogWin.EvInit();
		//
		return true;
	};
	//-----------------------------------------
	/**
	* Event handler for dialog buttons.
	* May be overloaded when needed.
	* @param string Holds the name of the button.
	*/
	this.EvButtonClick = function(name)
	{
		// Look for a handler for the button clicked.
		var func = 'this.ButtonHandler_' + name;
		if (eval('typeof(' + func + ')') == 'function')
			if (eval(func + '(this, name)'))
				return true;
		// Default handling of modeless dialog buttons.
		switch (name)
		{
			case 'cancel':
			case 'close':
				window.close();
				break;
		}
		return true;
	};
	//-----------------------------------------
	/**
	* Handler which must be implemented or overloaded to handle a modal dialogs result.
	* @param mixed Value returned by the dialog.
	* @param string Name of the browser window with which it was opened.
	* @return void
	*/
	this.HandleModalResult = function(result, name)
	{
		SfLib.DebugOut("TDialogHandler::HandleModalResult(" + result + ", " + name + ")");
	};
	//-----------------------------------------
}
//===========================================================================
/**
* Returns object for controlling a modal dialog spawn from this page.
* @constructor
*/
function TDialogWindow()
{
	//-----------------------------------------
	/**
	* Trick to access this objects members from Call().
	* @type TDialogWindow
	*/
	var self = this;
	/**
	* Set by a closing modal window to allow the this window to refresh
	* for example its content or other.
	* Is reset by OpenModal() member function.
	* @type mixed
	*/
	this.ModalResult = null;
	/**
	* Window of the modal dialog.
	* @type window
	*/
	this.Window = null;
	/**
	* Holds the name of the overlay element.
	* @type string
	*/
	this.OverlayName = 'page_overlay';
	/**
	* Name of the modal window.
	* @type string
	*/
	this.Name = '';
	/**
	* Array to keep track of the in page dialog handlers.
	* @type Array
	*/
	this.InPageHandlers = new Array();
	/**
	* Stack to keep track of the in page dialog names.
	* @type Array
	*/
	this.InPageStack = new Array();
	/**
	* Holds the input element last focussed.
	* @type HTMLElement
	*/
	this.Focussed = null;
	/**
	* Holds the direction of the Tab key where Forward = 1, Backwards -1 and  None = 0.
	* @type boolean
	*/
	this.TabDirection = 1;
	//-----------------------------------------
	/**
	* Relays the resize event to all the existing dialogs.
	* @private
	* @param event Build-in class event.
	*/
	this.ResizeHandler = function (ev)
	{
		// Iterate through all the dialogs using the stack.
		for (var i = 0; i < self.InPageStack.length; i++)
		{
			var ip = self.InPage(self.InPageStack[self.InPageStack.length - 1]);
			// Call when the function is implemented
			if (ip && typeof ip.EvResize == 'function')
				ip.EvResize(ev);
		}
	};
	// Handler for resizing the in page dialogs.
	SfLib.AddEvent(window, 'resize', new TEventReducer(this.ResizeHandler, 300).Call);
	//-----------------------------------------
	/**
	* Relays the key event to current dialog.
	* @private
	* @param event Build-in class event.
	* @returns boolean
	*/
	this.KeyDownHandler = function (ev)
	{
		// Flag to make the even propagate or not.
		var propagate = true;
		var keyname = SfLib.GetKeyName(ev);
		// Get current in page dialog.
		var ip = self.InPageCurrent();
		// Check if in page modal dialog is active.
		if (ip)
		{
			if (typeof ip.EvKey == 'function')
				propagate = ip.EvKey(ev, keyname, SfLib.IsKeyEventToIgnore(ev));
		}
		else if (typeof self.EvKey == 'function')
			propagate = self.EvKey(ev, keyname, SfLib.IsKeyEventToIgnore(ev));
		// Check if the event should be propagated or not.
		if (!propagate)
			SfLib.StopPropagation(ev);
		// Return true for IE browsers to make the event continue.
		return propagate;
	};
	// Handler for key events of dialogs and in page modal dialogs.
	SfLib.AddEvent(document, 'keydown', this.KeyDownHandler);
	//-----------------------------------------
	/**
	* Handles
	* @private
	* @param event Build-in class event.
	* @returns boolean
	*/
	this.InputEventHandler = function (ev)
	{
		// Assign the new focussed element.
		if (ev.type == 'focus')
		{
			// Assign the focus element.
			this.Focussed = ev.srcElement;
			// Get current in page dialog.
			var ip = self.InPageCurrent();
			if (ip)
			{
				// When the focussed element does not belong to allowed in page set
				// focus a different one.
				if (ev.srcElement.getAttribute('__inpageref') != ip.Name)
				{
					// Get all input elements.
					var elems = ip.Elem.getElementsByTagName('INPUT');
					if (elems.length == 0)
						elems = ip.Elem.getElementsByTagName('A');
					// When forward direction is enabled.
					for (var i = 0; i < elems.length; i++)
					{
						// Filter only elements that can have focus.
						if (elems[i].type == 'hidden' || elems[i].name == '' || elems[i].disabled)
							continue;
						// Focus the element and break the loop.
						elems[i].focus();
						break;
					}
				}
			}
		}
		//
		if (ev.type == 'blur')
		{
			// Reset the focus element member.
			this.Focussed = null;
		}
	};
	//-----------------------------------------
	/**
	* Handles
	* @private
	* @param event Build-in class event.
	* @returns boolean
	*/
	this.HookFocusHandler = function (element, name)
	{
		var elems = SfLib.GetElementsByTagNames(element, Array('INPUT', 'A'));
		for (var i = 0; i < elems.length; i++)
		{
			// Skip elements which ref has been set already.
			if (elems[i].getAttribute('__inpageref'))
				continue;
			// Set the reference to which the unput belongs.
			elems[i].setAttribute('__inpageref', name);
			// Attach an event for blurring to prevent focus stealing.
			SfLib.AddEvent(elems[i], 'blur', this.InputEventHandler);
			SfLib.AddEvent(elems[i], 'focus', this.InputEventHandler);
		}
	};
	//-----------------------------------------
	/**
	* Key event handler which must be overloaded.
	* @see SfLib.GetKeyName()
	* @param event Build-in class event.
	* @param string Name of the key pressed
	* @param boolean
	* @returns boolean
	*/
	this.EvKeyEvent = function(ev, keyname, ignorable)
	{
		SfLib.DebugOut("TDialogHandler::EvKeyEvent(" + ev + ", " + keyname + ", " + ignorable + ")");
		// Do not stop propagation.
		return false;
	};
	//-----------------------------------------
	/**
	* @class Place holder for in page dialogs.
	* @constructor
	*/
	this.TInPage = function(owner, name)
	{
		/**
		* Name of the in page dialog.
		* @type string
		*/
		this.Name = name;
		/**
		* HTMLElement when active.
		* @type HTMLElement
		*/
		this.Elem = null;
		/**
		* Callback handler for a modal result.
		* @type function
		*/
		this.Callback = null;
		/**
		* Calls the handler Initialize function when it exists.
		* @private
		* @returns void
		*/
		this.DoInitialize = function()
		{
			if (typeof this.Initialize == 'function')
				this.Initialize(this);
		};
		/**
		* Change the z-index of the element.
		* @private
		* @param boolean
		*/
		this.MoveToBack = function (back)
		{
			if (this.Elem)
				this.Elem.style.zIndex = back ? 4000 : 4002;
		};
		// Assign functions from the owner class.
		this.SetModalInPage = new Closure(owner, 'SetModalInPage').Call;
		this.OpenModalInPage = new Closure(owner, 'OpenModalInPage').Call;
		this.CloseModalInPage = new Closure(owner, 'CloseModalInPage').Call;
	};
	//-----------------------------------------
	/**
	* Returns the current dialog and top of the stack.
	* When empty is there return null.
	* @returns TInPage
	*/
	this.InPageCurrent = function()
	{
		if (this.InPageStack.length)
			return this.InPage(this.InPageStack[this.InPageStack.length - 1]);
		return null;
	};
	//-----------------------------------------
	/**
	* Function returning the in page handler object using the passed name.
	* @param string Name of the in page dialog.
	* @return TInPage
	*/
	this.InPage = function (name)
	{
		// Check if in page name has already an assigned object.
		if (!this.InPageHandlers[name])
			this.InPageHandlers[name] =	new this.TInPage(this, name);
		// Return the existing object for the passed name.
		return this.InPageHandlers[name];
	};
	//-----------------------------------------
	/**
	* Called from the modal dialog window and must be overloaded.
	* Can be overloaded.
	* @param string Name of the dialog window which was opened.
	*/
	this.EvInit = function(name)
	{
		//SfLib.DebugOut("TDialogWindow::EvInit(" + name + ")");
	};
	//-----------------------------------------
	/**
	* Event handler when modal dialog window closes/unloads.
	*/
	this.EvModalResult = function(result, name)
	{
		SfLib.DebugOut("TDialogWindow::EvModalResult(" + result + ", " + name + ")");
	};
	//-----------------------------------------
	/**
	* Called from an in page dialog to handle a result.
	* @returns mixed
	* @returns void
	*/
	this.SetModalResult = function(result, name)
	{
		var ip = this.InPageCurrent();
		// Check if a callback function is present.
		if (ip && ip.Callback)
			ip.Callback(result, ip.Name);
		else
		{
			// If an In page is active use its name.
			if (ip && !name)
				this.Name = ip.Name;
			else
				this.Name = name;
			// Assign the value.
			this.ModalResult = result;
			// Call the overloaded handler.
			this.EvModalResult(this.ModalResult, this.Name);
		}
	};
	//-----------------------------------------
	/**
	* Displays or not the overlay element.
	* @param boolean Represents On or Off.
	* @returns void
	*/
	this.PageOverlayDisplay = function(on)
	{
		SfLib.Display(this.AddPageOverlay(this.OverlayName), on);
	};
	//-----------------------------------------
	/**
	* Returns the HTML element from overlay.
	* @param string Name of the ovelay element.
	* @returns THMLElement
	*/
	this.AddPageOverlay = function(overlay_name)
	{
		var page_overlay = null;
		// Check if it alreadfy exists.
		if (page_overlay = document.getElementById(overlay_name))
			// Return the created overlay.
			return page_overlay;
		// Assemble the rules for IE and FF.
		var rules =
			"\n\tposition:absolute;" +
			"\n\ttop:0;" +
			"\n\tleft:0;" +
			"\n\twidth:100%;" +
			"\n\theight:100%;" +
			"\n\tz-index:4001;";
		// For not tiring X-terminals so much.
		if (true)//BrowserDetect.OS != "Linux")
		{
			rules += "\n\tbackground-color:#000;" +
			"\n\t-moz-opacity: 0.4;" +
			"\n\topacity:.40;" +
			"";
		}
		//
		var style = null;
		var head = document.getElementsByTagName('head')[0];
		// Detect Explorer as the browser.
		if (BrowserDetect.browser == 'Explorer')
		{
			style = document.createStyleSheet();
			// Add rule for explorer because generates an warning in Firefox
			rules += "\n\tfilter: alpha(opacity=40);";
			style.addRule("DIV#" + overlay_name, rules);
		}
		else if (BrowserDetect.browser == 'Chromium' || BrowserDetect.browser == 'Safari')
		{
			var style = document.createElement('style');
			style.setAttribute('type', 'text/css');
			head.appendChild(style);
			document.styleSheets[document.styleSheets.length - 1].addRule("DIV#" + overlay_name, rules);
		}
		else
		{
			var style = document.createElement('style');
			style.setAttribute('type', 'text/css');
			style.innerHTML = "DIV#" + overlay_name + "\n{\n" + rules + "\n}";
			head.appendChild(style);
		}
		// Get the body element.
		var the_body = document.getElementsByTagName('body')[0];
		// Create element that is used as the overlay.
		page_overlay = document.createElement('div');
		// The Firefox browser lets us hide the overlay already.
		if (BrowserDetect.browser == 'Firefox')
			page_overlay.setAttribute('style', 'display:none');
		//
		page_overlay.id = overlay_name;
		// Assign some events to clear the overlay.
		page_overlay.onclick = new Closure(this, 'CheckModal').Call;
		//
		the_body.appendChild(page_overlay);
		// Return the created overlay.
		return page_overlay;
	};
	//-----------------------------------------
	/**
	* Returns true when a modal dialog is active.
	* @returns boolean
	*/
	this.CheckModal = function()
	{
		if (typeof this.Window == 'object')
		{
			//
			if (this.Window && !this.Window.closed && this.Window.Dialog != null)
			{
				if (typeof this.Window.focus == 'function')
				{
					// Seems firefox does not let go of the focus in Windows.
					if (BrowserDetect.browser == 'Firefox')
						// So we put it in a timed function.
						setTimeout(function (ev){self.Window.focus();}, 0);
					else
						this.Window.focus();
				}
			}
			else if (typeof this == 'object')
			{
				// When no stack remove the overlay.
				if (this.InPageCurrent())
					this.InPageCurrent().MoveToBack(false);
				else
					this.PageOverlayDisplay(false);
			}
		}
		//
		return true;
	};
	//-----------------------------------------
	/**
	* In page dialog event handler for buttons.
	* Is called by the button onclick event.
	* Looks for member functions like 'ButtonHandler_<btnname>' to handle a click.
	* Returns true when handled.
	* @param string Name of the button.
	* @return boolean
	*/
	this.EvButtonClick = function(name)
	{
		// Check if a dialog is still open.
		if (this.InPageStack.length)
		{
			// Look for a handler for the button clicked.
			var func = 'this.InPageCurrent().ButtonHandler_' + name;
			if (eval('typeof(' + func + ')') == 'function')
				if (eval(func + '(this, name)'))
					return true;
			// Do some default handling when not handled by the other handler.
			switch (name)
			{
				default:
					return false;

				case 'cancel':
				case 'close':
					this.CloseModalInPage();
					break;
			}
		}
		return true;
	};
	//-----------------------------------------
	/**
	* Closes an open in page dialog.
	* @returns boolean
	*/
	this.CloseModalInPage = function ()
	{
		var retval = true;
		// Check if a dialog is still open.
		if (this.InPageStack.length)
		{
			// Get the last injstance from the stack.
			var ip = this.InPage(this.InPageStack.pop());
			// Remove the element from thye document.
			if (ip.Elem && ip.Elem.parentNode)
				ip.Elem.parentNode.removeChild(ip.Elem);
			// Clear the member which is also used as a flag.
			ip.Elem = null;
			// Make the the one below this one visible.
			if (this.InPageStack.length)
				this.InPageCurrent().MoveToBack(false);
		}
		else
			retval = false;
		// When the stack is reduced to zero.
		if (!this.InPageStack.length)
			// Remove the overlay.
			this.PageOverlayDisplay(false);
		// Signal success.
		return retval;
	};
	//-----------------------------------------
	/**
	* Opens a in page modal dialog.
	* @param string URL to the page section containing the in page HTML.
	* @param string name of the in page dialog.
	* @param number Width
	* @param number	Height
	* @returns HTMLElement Element containing the in page dialog content.
	*/
	this.OpenModalInPage = function (url, name, w_width, w_height, callback)
	{
		this.SetModalInPage(new Array(url), name, w_width, w_height, callback);
	};
	//-----------------------------------------
	/**
	* Called to go to a next page in the in page wizard or dialog.
	* @param string HTML tagged content of the dialog.
	* @param string name of the in page dialog.
	* @param number Width
	* @param number	Height
	* @returns HTMLElement Element containing the in page dialog content.
	*/
	this.SetModalInPage = function (html, name, w_width, w_height, callback)
	{
		// Check if the name was passed.
		if (typeof name == 'undefined' || name == null)
		{
			// Check if a dialog name is on stack. If so use that one.
			if (this.InPageCurrent())
				name = this.InPageCurrent().Name;
			else
				SfLib.DebugOut("TDialogWin::SetModalInPage()\nDesign error a name was not passed!", 1);
		}
		else
		{
			if (this.InPageCurrent())
				this.InPageCurrent().MoveToBack(true);
		}
		// Create easy to access local reference.
		var ip = this.InPage(name);
		// When a callback has been passed.
		if (typeof callback == 'function')
			ip.Callback = callback;
		// Check if this dialog is opened if so push the name it to stack.
		if (!ip.Elem)
			this.InPageStack.push(name);
		// Convert the width and height into a TValueUnit instance.
		w_width = SfLib.GetValueUnit(w_width, ip.Elem ? ip.Elem.style.width : 400);
		w_height = SfLib.GetValueUnit(w_height, ip.Elem ? ip.Elem.style.height : 300);
		// Remove the element from the document to recreate it.
		if (ip.Elem)
			ip.Elem.parentNode.removeChild(ip.Elem);
		// Enable the overlay.
		this.PageOverlayDisplay(true);
		// Check if an url was posted.
		var url = '<unknown>';
		if (typeof html == 'object')
			html = SfLib.GetByHttpPost(url = html[0]);
		//
		var elem = document.createElement('div');
		//
		elem.style.position = 'absolute';
		elem.style.overflow = 'auto';
		elem.style.zIndex = 4002;
		elem.style.backgroundColor = 'white';
		elem.className = 'inpage_dlg';
		// Test if the width is relative.
		if (w_width.Unit == '%')
		{
			// Loose the border when 100%.
			if (w_width.Value >= 100)
			{
				SfLib.DebugOut("Loosing borders....");
				elem.style.borderRightWidth = elem.style.borderLeftWidth = '0px';
			}
			elem.style.width = w_width.String();
			w_width.Value = (100 - w_width.Value) / 2;
			elem.style.left = w_width.String();
			elem.style.marginLeft = 'auto';
		}
		else
		{
			elem.style.marginLeft = w_width.String(-0.5);
			elem.style.width = w_width.String();
			elem.style.left = '50%';
		}
		// Test if the height is relative.
		if (w_height.Unit == '%')
		{
			// Loose the border when 100%.
			if (w_height.Value >= 100)
				elem.style.borderTopWidth = elem.style.borderBottomWidth = '0px';
			elem.style.height = w_height.String();
			w_height.Value = (100 - w_height.Value) / 2;
			elem.style.top = w_height.String();
			elem.style.marginTop = 'auto';
		}
		else
		{
			elem.style.marginTop = w_height.String(-0.5);
			elem.style.height = w_height.String();
			elem.style.top = '50%';
		}
		// Assign the element.
		ip.Elem = elem;
		// If the in page HTML content contains an DOCTYPE start tag bail out.
		if (SfLib.ContainsHtmlDocType(html, true, url))
		{
			this.CloseModalInPage();
			return null;
		}
		// Fill the element with dialog stuf.
		SfLib.SetInnerHtml(ip.Elem, html, false);
		// Hook event handlers to focusable elements in the element first.
		this.HookFocusHandler(ip.Elem, name);
		// Hook event handlers to focusable elements in the whole page.
		this.HookFocusHandler(document.body, '');
		// This will execute the scripts in Firefox.
		document.body.appendChild(ip.Elem);
		// Execute the javascript in the dialog.
		SfLib.EvaluateHtml(html);
		// Call the initializer for this dialog.
		ip.DoInitialize();
		// Return the element containg the dialog.
		return ip.Elem;
	};
	//-----------------------------------------
	/**
	* Opens a new window a modal dialog and returns the new window.
	* @param string URL to the page.
	* @param string Name of the browser window.
	* @param number Width
	* @param number Height
	* @returns window Build-in type.
	*/
	this.OpenModal = function(url, name, w_width, w_height)
	{
		if (!this.Window || (this.Window && this.Window.closed))
		{
			// Initialize properties of the modal dialog object.
			this.Name = name;
			// Reset the modal result value.
			this.ModalResult = null;
			// Install handlers.
			SfLib.AddEvent(window, 'focus', new Closure(this, 'CheckModal').Call);
			SfLib.AddEvent(window, 'click', new Closure(this, 'CheckModal').Call);
			// Generate the dialog and make sure it has focus.
			this.Window = window.open(url, name, this.GetOpts(w_width, w_height));
			if (!this.Window)
			{
				SfLib.DebugOut('TDialogWindow::OpenModal(' + name + ') \n' +
					'Failed to open a window to \'' + url + '\'\nTry to unblock popups for this domain.', 1);
				return null;
			}
			// Create partial transparent overlay over parent window.
			this.PageOverlayDisplay(true);
			// When inpage dialog exist move it behind the overlay.
			if (this.InPageCurrent())
				this.InPageCurrent().MoveToBack(true);
		}
		else
		{
			// Focus the created window.
			this.Window.focus();
		}
		return this.Window;
	};
	//-----------------------------------------
	/**
	* Opens a new window a modal dialog and returns the new window.
	* @param string URL to the page.
	* @param string Name of the browser window.
	* @param number Width
	* @param number Height
	* @returns window Build-in type.
	*/
	this.AttachModalInPageIFrame = function(iframe)
	{
		if (!this.Window || (this.Window && this.Window.closed))
		{
			// Initialize properties of the modal dialog object.
			this.Name = iframe.name;
			// Reset the modal result value.
			this.ModalResult = null;
			// Install handlers.
			//SfLib.AddEvent(window, 'focus', new Closure(this, 'CheckModal').Call);
			//SfLib.AddEvent(window, 'click', new Closure(this, 'CheckModal').Call);
			// Generate the dialog and make sure it has focus.
			this.Window = iframe;
		}
		else
		{
			// Focus the created window.
			this.Window.focus();
		}
		return this.Window;
	};
	//-----------------------------------------
	/**
	* Returns the options to open a browser window as a dialog.
	* @param number Width
	* @param number	Height
	* @returns string
	*/
	this.GetOpts = function(w_width, w_height)
	{
		// When negative use the screen width.
		if (w_width < 0)
			w_width = screen.width * 0.8;
		if (w_height < 0)
			w_height = screen.height * 0.8;
		//
		var w_left, w_top;
		if (BrowserDetect.browser == 'Firefox')
		{
			// Center on the main window.
			w_left = window.screenX + ((window.outerWidth - w_width) / 2);
			w_top = window.screenY + ((window.outerHeight - w_height) / 2);
		}
		else
		{
			w_left = (screen.width - w_width) / 2;
			w_top = (screen.height - w_height) / 2;
		}
		// Assemble the options,
		var opts = "";
		opts += "width=" + w_width;
		opts += ",height=" + w_height;
		opts += ",left=" + w_left;
		opts += ",top=" + w_top;
		opts += ",alwaysRaised";
		opts += ",scrollbars=no";
		if (1)
		{
			opts += ",status=no";
			opts += ",location=no";
			opts += ",menubar=no";
			opts += ",toolbar=no";
		}
		else
		{
			opts += ",status=yes";
			opts += ",location=yes";
			opts += ",menubar=yes";
			opts += ",toolbar=yes";
		}
		opts += ",copyhistory=no";
		opts += ",directories=no";
		opts += ",resizable=yes";
		opts += ",modal=yes";
		opts += ",dependent=yes";
		//
		return opts;
	};
	//-----------------------------------------
}
//---------------------------------------------------------------------------
/**
* Global function to open a modal dialog.
* @param string URL to the page to be opned as dialog.
* @param string Name of the browser window to open.
* @param number width
* @param number	height
* @param boolean inpage
* @returns window Build-in class window.
*/
SfLib.OpenDialogModal = function (url, name, w_width, w_height, in_page)
{
	if (in_page)
		return DialogWin.OpenModalInPage(url, name, w_width, w_height);
	else
		return DialogWin.OpenModal(url, name, w_width, w_height);
};
//---------------------------------------------------------------------------
/**
* Global function to open a modal in page or embbedded dialog.
* @param string URL to the page section containing the in page HTML.
* @param string name of the in page dialog.
* @param number Width
* @param number	Height
* @returns HTMLElement Element containing the in page dialog content.
*/
SfLib.OpenDialogModalInPage = function (url, name, w_width, w_height, callback)
{
	return DialogWin.OpenModalInPage(url, name, w_width, w_height, callback);
};
//---------------------------------------------------------------------------
/**
* Loads the calculator script on demand when executed.
* @param HTMLElement input
* @param string lang Language code like 'en'.
* @return void
*/
SfLib.CalculatorDialog = function (input, lang)
{
	var url = 'jscripts/calculator.js';
	this.CalculatorDialog = (function () {alert('Calculater script \'' + url + '\' failed to load.');});
	this.JavascriptImport(url, 'calculator', function(){SfLib.CalculatorDialog(input, lang);});
};
//---------------------------------------------------------------------------
/**
* Loads the calendar script on demand when executed.
* @param HTMLElement input
* @param string lang Language code like 'en'.
* @param boolean show_time Enables editing of time.
* @return void
*/
SfLib.CalendarDialog = function (input, lang, show_time)
{
	var url = 'jscripts/calendar.js';
	this.CalendarDialog = (function () {alert('Calendar script \'' + url + '\' failed to load.');});
	this.JavascriptImport(url, 'calculator', function(){SfLib.CalendarDialog(input, lang, show_time);});
};
//---------------------------------------------------------------------------
//Iterate through all functions and make them global.
if (!window['__common_lib_no_compat__'])
	for (var item in SfLib)
		if (typeof SfLib[item] == 'function' && typeof window[item] == 'undefined')
			window[item] = new Closure(SfLib, item).Call;
//---------------------------------------------------------------------------

