/**
 *  Javascript Dialog And MessageBox
 * 
 * Intended for use with XHTML documents (IE uses document.documentElement instead
 * of document.body for some things).
 * 
 * @author Erick S <esatire@gmail.com>
 * @version 1.3.4 23/10/2007 - Fixed appearance on HTML pages where body doesn't take the full screen
 * @copyright Atarim Group LTD.
 */

function GetScreenCenterX()
{
	return document.documentElement.scrollLeft + document.documentElement.clientWidth/2;
}
function GetScreenCenterY()
{
// I need this hack because opera, firefox and IE all report sizes differently
	if (window.innerHeight)
		return document.documentElement.scrollTop + window.innerHeight/2;	
	else
		return document.documentElement.scrollTop + document.documentElement.clientHeight/2;
}

/** Because IE's select boxes ignore z-index, we disable them when showing a dialog modally
 * 
 * <p>
 * I'm keeping an array of the ones I disabled here, so if you had a select box that you
 * chose to disable from your own reasons, the dialog won't interfere with it.
 * </p>
 */
function ToggleSelects(disable)
{
	if (disable)
	{
		disabledSelects = new Array();
		var allSelects = document.getElementsByTagName('SELECT');
	
		for (var i=0;i<allSelects.length;i++)
		{
			if (disable && allSelects[i].disabled == false)
			{
				allSelects[i].disabled = true;
				disabledSelects.push(allSelects[i]);
			}
		}
	}
	else
	{
		for (var i=0;i<disabledSelects.length;i++)
		{
			disabledSelects[i].disabled = false;
			disabledSelects[i] = null;
		}
		disabledSelects = null;
	}
}
var disabledSelects;

function JsDialog()
{
	// private vars
	var myself = this;
	var startX,startY,container;
	var tempX,tempY; // temporary position holders during mouse move
	// public vars / properties
	this.enterSubmits = false; // for prompt boxes with single line text fields
	// private method 'pointers'
 	var OkFunction = null;
 	var OkFunctionParam = null;
	var modal = false;

	// gui setup
	if (MessageBox.UseUnderlay)
	{
		var underlay = document.createElement("IFRAME");
		underlay.className = 'JsDialogUnderlay';
		underlay.src = 'about:blank';
		document.body.appendChild(underlay);
	}
	
	var container = document.createElement("DIV");
	container.className = "JsDialog";
	document.body.appendChild(container);
	container.innerHTML = "<table width='100%' cellspacing='0'>"+
  		"<tr><th class='JsDialogHeader' onselectstart='return false'></th></tr>"+
  		"<tr><td class='JsDialogContent' align='center' valign='top'></td></tr>" +
		"<tr><td align='center'><input class='JsDialogButton' type='button' value='Ok' /> &nbsp; "+
		"<input class='JsDialogButton' type='button' value='Cancel' /></td></tr></table>";
	this.header = container.getElementsByTagName('TH')[0];
	this.content = container.getElementsByTagName('TD')[0];
	var buttons = container.getElementsByTagName('INPUT');
	this.buttonOk = buttons[0];
	this.buttonOk.style.width = '100px';
	this.buttonOk.style.fontWeight = 'bold';
	this.buttonCancel = buttons[1];
	this.buttonCancel.style.width = '100px';	
	// attach functions to events
	this.buttonCancel.onclick = Hide;
	this.buttonOk.onclick = OnOkButton;
	this.header.onmousedown = OnMouseDown;
	function Hide()
	{
		if (modal)
		{
			MessageBox.overlay.style.visibility = 'hidden';
			if (MessageBox.UseUnderlay) ToggleSelects(false);
		}
		if (MessageBox.UseUnderlay) underlay.style.display = 'none';
		//container.style.display = "none";
		container.style.left = (-container.offsetWidth-50)+'px';
		container.style.top  = (-container.offsetHeight-50)+'px';
		document.onkeydown = null;
		//alert('hidden');
	}

	this.ShowCenter = function(w,h,showModal)
	{
		if (container.style.display != 'block') container.style.display = "block";
		// we gotta set width/height first, so x and y will be set correctly
		if (typeof (w) == 'undefined' || w == null)
		{
			w = this.content.offsetWidth;
		}
		if (typeof (h) == 'undefined' || h == null)
		{
			h = this.content.offsetHeight + this.header.offsetHeight + this.buttonOk.offsetHeight;
		}
		container.style.width = w +"px";
		this.content.style.height = h - this.header.offsetHeight - this.buttonOk.offsetHeight + 'px';

		var x = GetScreenCenterX() - (w/2);
		var y = GetScreenCenterY() - (h/2);
		//alert("w=" + w + " h=" + h + " x=" + x + " y="+y);
		this.Show(x,y,null,null,showModal);
	}
	
	this.Show = function(x,y,w,h,showModal)
	{
		if (typeof (x) != 'undefined') container.style.left = x + "px";
		if (typeof (y) != 'undefined') container.style.top = y + "px";
		if (typeof (w) != 'undefined' && w != null) container.style.width = w +"px";
		if (typeof (h) != 'undefined' && h != null) this.content.style.height = h + 'px';
		if (container.style.display != 'block') container.style.display = "block";
		if (MessageBox.UseUnderlay)
		{
			underlay.style.left = container.style.left;
			underlay.style.top = container.style.top;
			underlay.style.width = container.offsetWidth + 'px';
			underlay.style.height = container.offsetHeight + 'px';
			underlay.style.display = 'block';
			// alert(underlay.style.left + ' ' + underlay.style.top + ' / ' + underlay.style.width + ' ' + underlay.style.height);
		}
		document.onkeydown = WindowKeyPress;
		if (showModal)
		{
			if (MessageBox.overlay == null) MessageBox.CreateOverlay();
			MessageBox.overlay.style.width = document.documentElement.scrollWidth + 'px';
			if (document.documentElement.clientHeight > document.documentElement.scrollHeight)
				MessageBox.overlay.style.height = document.documentElement.clientHeight + 'px';
			else
				MessageBox.overlay.style.height = document.documentElement.scrollHeight + 'px';	
			 
			MessageBox.overlay.style.visibility = 'visible';
			if (MessageBox.UseUnderlay) ToggleSelects(true);
			modal = true; // our internal variable
		}		
	/* it looks a bit uglier, but if the dialog was called from a button in opera
	 * moving the focus to this button is the only way to make the click on enter
	 * work as expected
	 */
		if (this.buttonOk.style.display != 'none') this.buttonOk.focus();
	}
	
	this.SetContents = function(caption,message)
	{
		this.header.innerHTML = caption;
		this.content.innerHTML = message;
		// we reset his size here so show will calculate w/h correctly
		this.content.style.height='0px';
		this.content.style.width='0px';
	}

	this.SetOkFunction = function(funcName){OkFunction = funcName;}
	this.SetOkParam = function(someData){OkFunctionParam = someData;}
	this.GetOkParam = function(){return OkFunctionParam;}	

	function OnOkButton()
	{
		if (OkFunction != null)
		{
			var result = OkFunction(OkFunctionParam);
			// if okfunction specifically returns false don't hide the dialog yet			
			if (result == false) return;
		}
		Hide();
	}
	
	this.ClickOk = function()
	{
		OnOkButton();
	}

	function OnMouseDown(evt)
	{
		document.onmousemove = OnMouseMove;
		document.onmouseup = OnMouseUp;
		document.body.style.cursor = 'pointer';
		if (window.event)
		{
			startX = window.event.clientX - container.offsetLeft;
			startY = window.event.clientY - container.offsetTop;
		}
		else
		{
			startX = evt.clientX - container.offsetLeft;
			startY = evt.clientY - container.offsetTop;	  
  		}
		return false; // for disabling text-selection!
	}

	function OnMouseMove(evt)
	{
		if (window.event) evt = window.event;
		// NOTE: We decrease the scrolling values to simplify bounds checking calcs
		tempX = evt.clientX - startX - document.documentElement.scrollLeft;
		tempY  = evt.clientY - startY - document.documentElement.scrollTop;
		// bounds checking
		if (tempX < 0) tempX = 0;
		else if (tempX + container.offsetWidth >= document.documentElement.clientWidth)
			tempX = document.documentElement.clientWidth - container.offsetWidth;
		if (tempY < 0) tempY = 0;
		else if (tempY + container.offsetHeight >= document.documentElement.clientHeight)
			tempY = document.documentElement.clientHeight - container.offsetHeight;

		container.style.left = tempX + document.documentElement.scrollLeft + "px";
		container.style.top = tempY + document.documentElement.scrollTop + "px";
		if (MessageBox.UseUnderlay)
		{
			underlay.style.left = container.style.left;
			underlay.style.top = container.style.top;
		}
		window.status = container.style.left + '/' + container.style.top;		
		return false; // for disabling text-selection!
	}

	function OnMouseUp()
	{
		document.onmousemove = null;
		document.onmouseup = null;
		document.body.style.cursor = 'default';
	}
/** Gives the dialog box the following functionality:
 *  escape = close dialog
 *  alt + enter = simulate press on ok
 */
	function WindowKeyPress(evt)
	{
		var keynum,alt=false;

		if(window.event) // IE / Opera 9.0
		{
			keynum = window.event.keyCode
			if (window.event.altKey == 1) alt = true;
		}
		else if (evt.which) // Netscape/Firefox/Opera(8.0 maybe)
		{
			keynum = evt.which
			if (evt.altKey == 1) alt = true;
		}
		else return; // don't respond to enter/esc in unsupported browsers
		// alt + enter OR just enter for textfield prompts
		if (keynum == 13 && (alt == true || myself.enterSubmits))
		{
			myself.enterSubmits = false; // For future dialog boxes
			OnMouseUp(); // clear attached events, just in case
			OnOkButton();
			return false; // prevents it from popping up again in firefox
		}
		else if (keynum == 27)
		{
			OnMouseUp(); // clear attached events, just in case
			Hide();
		}
	}
}

/** Static class for showing messageboxes just like everyone is used to */
function MessageBox(){}

// unfortunately, I have to do a browser check for IE6/6b/5.5, to deal with select
// boxes. Using the underlay on firefox messes up with the caret in input elements
if (navigator.appVersion.search(/MSIE (6|5)/) != -1)
	MessageBox.UseUnderlay = true;
else
	MessageBox.UseUnderlay = false;

MessageBox.overlay		= null;
MessageBox.dialog			= null;
MessageBox.CancelFunc	= function(){MessageBox.result = 0;}
MessageBox.OkFunc			= function(){MessageBox.result = 1;}

MessageBox.CreateOverlay = function()
{
	MessageBox.overlay = document.createElement('DIV');
	MessageBox.overlay.className = 'PageOverlay';
	document.body.appendChild(MessageBox.overlay);
}
/** Basic prompt box with a text input
 * @param {any}data Optional
 * @param {int}maxLength Optional - Defaults to 255
 */
MessageBox.Prompt = function(message,resultFunc,data,maxLength)
{
	if (typeof maxLength == 'undefined') maxLength = 255;
	if (MessageBox.dialog == null) MessageBox.dialog = new JsDialog();
	var promptContent =
	"<input id='MessageBox_Prompt_Field' type='text' size='55' maxlength='"+
	maxLength + "' />";
	MessageBox.dialog.enterSubmits = true;
	MessageBox.SetPrompt(message,promptContent,resultFunc,data);
}
/** Prompt with more options
 * @param {string}value Default value. Can be null.
 * @param {bool}multiline Use textarea or text input
 * @param {int}maxLength Required in this version
 * @param {any}data Optional
 */
MessageBox.PromptAdv = function(title,value,multiline,maxLength,resultFunc,data)
{
	if (MessageBox.dialog == null) MessageBox.dialog = new JsDialog();
	if (multiline)
	{
		var promptContent =
		"<textarea id='MessageBox_Prompt_Field' rows='4' " +
		"onkeypress='return checkMaxLength(event,this," + maxLength + ")'>" +
		value + "</textarea>";
	}
	else
	{
		value = value.replace(/"/,"&quot;");
		var promptContent =
		"<input id='MessageBox_Prompt_Field' type='text' maxlength='"+
		maxLength + "' value=\""+value+'" />';
		MessageBox.dialog.enterSubmits = true;
	}
	MessageBox.SetPrompt(title,promptContent,resultFunc,data);
}
/** Shortcut to actually set the content.
 * Note: CAN'T USE A VARIABLE 'content' AS IT COLIDES WITH INTERNAL JSDIALOG PROPERTY 
 */
MessageBox.SetPrompt = function(title,_content,resultFunc,data)
{
	with (MessageBox.dialog)
	{
		buttonCancel.style.display = 'inline';
		buttonCancel.value = 'Cancel';
		buttonOk.value = 'Ok';
		var dataObj = new Object();
		dataObj.resultFunc = resultFunc;
		dataObj.data = data;
		SetOkFunction(MessageBox.PromptOk);
		SetOkParam(dataObj);
		SetContents(title,_content);
		ShowCenter(350,80,true);
	}
	$('MessageBox_Prompt_Field').focus();
}
MessageBox.PromptOk = function()
{
	with (MessageBox.dialog)
	{
		var value = trim(document.getElementById('MessageBox_Prompt_Field').value);
		if (value)
		{
			var dataObj = GetOkParam();
			dataObj.resultFunc(value,dataObj.data);
		}
	}
	return true;
}
MessageBox.Confirm = function(message,resultFunc,data)
{
	if (MessageBox.dialog == null) MessageBox.dialog = new JsDialog();
	with (MessageBox.dialog)
	{
		buttonCancel.style.display = 'inline';
		buttonCancel.value = 'No';
		buttonOk.value = 'Yes';
		SetOkFunction(resultFunc);
		SetOkParam(data);
		SetContents('Confirm',message);
		ShowCenter(null,null,true);
	}
}
MessageBox.Alert = function(message)
{
	if (MessageBox.dialog == null) MessageBox.dialog = new JsDialog();	
	with (MessageBox.dialog)
	{
		buttonCancel.style.display = 'none';
		SetOkFunction(null);
		SetContents('Alert',message);
		ShowCenter(null,null,true);
	}
}