/**
* Functions for dealing with css classes
* @package Utils
* 
* - vunger	080428	Added GetTop(), GetLeft()
* - msmaga	080507	Moved Comments drop-down from GenerateReport
* - msmaga	080509	jsEncoding for AjaxFormSubmit
* - thoare	080530	Implemented importNode() and node type constants for those browsers (IE!) which lack it.
* - msmaga 	080624	added pickComment()
* - vunger 	081208	added CheckForInteger()
* - shashagen 073109 After save, don't redirect until all responses when there are multiple forms on page
* - jmedellin	090819	added support for launching into Aqua
*/

var PendingSaveRequests = 0;    // counter incremented on AJAX form submit and decremented on response received
var SaveErrorOccured = false;   // track if any save errors occur when multiple forms are saved.

function hasClass (Element, ClassName)
{
	var Classes = (Element.className != '' ? Element.className.split (' ') : new Array ());
	
	for (var i = 0; i < Classes.length; i++)
		if (Classes [i] == ClassName)
			return true;
	
	return false;
}

function addClass (Element, ClassName)
{
	if (Element.className == '')
	{
		Element.className = ClassName;
	}
	else if (!hasClass (Element, ClassName))
	{
		Element.className += ' ' + ClassName;
	}
}

function removeClass (Element, ClassName)
{
	var Classes = (Element.className != '' ? Element.className.split (' ') : new Array ());
	var Spacer = '';
	
	Element.className = '';
	
	for (var i = 0; i < Classes.length; i++)
	{
		if (Classes [i] != ClassName)
		{
			Element.className += Spacer + Classes [i];
			Spacer = ' ';
		}
	}
}

function Cancel()
{
	history.go(-1);
}


//-----------------------------------------------------
// AJAX funxtions
//-----------------------------------------------------

function HTTPRequest (URL, Method, Parameters, Ready, FunctionName)
{
	var http_request = false;
	
	if (window.XMLHttpRequest) 
	{ // Mozilla, Safari, ...
	    http_request = new XMLHttpRequest();
	    if (http_request.overrideMimeType) 
	    {
	        http_request.overrideMimeType('text/xml');
	    }
	} 
	else if (window.ActiveXObject) 
	{ // IE
	    try 
	    {
	        http_request = new ActiveXObject("Msxml2.XMLHTTP");
	    } 
	    catch (e) 
	    {
	        try 
	        {
	            http_request = new ActiveXObject("Microsoft.XMLHTTP");
	        } 
	        catch (e) {}
	    }
	}
	
	if (!http_request)
	{
	    alert('Cannot create an XMLHTTP instance');
	    return false;
	}
	
	if (typeof Ready == 'function')
		http_request.onreadystatechange = function() { Ready (http_request); };
	else if (typeof Ready == 'object' && typeof FunctionName == 'undefined')
		http_request.onreadystatechange = function() { Ready.Receive (http_request); };
	else if (typeof Ready == 'object' && typeof FunctionName == 'string')
		http_request.onreadystatechange = function() { Ready [FunctionName] (http_request); };
	else
		alert ('Invalid AJAX callback parameters');
	
	Parameters += "&AJAX=1";

	http_request.open(Method, URL, true);
	http_request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	http_request.send(Parameters);
	return true;
}

function parseXML (XMLString)
{
	var xmlDoc = null;
	
	try
  	{
		xmlDoc = new ActiveXObject ("Microsoft.XMLDOM");
		xmlDoc.async = "false";
		xmlDoc.loadXML (XMLString);
	}
	catch (e)
	{
		try 
		{
			parser = new DOMParser ();
			xmlDoc = parser.parseFromString (XMLString,"text/xml");
		}
		catch (e)
		{
			alert (e.message);
		}
	}
	
	return xmlDoc;
}

//-----------------------------------------------------
//TIMER LOGIC
//-----------------------------------------------------
var timerID = 0;

// Global variable to be overridden
var BaseLocation = "";


function StartTimer ()
{
	timerID = setTimeout("HTTPRequest ('SessionActive.php', 'POST', '', CheckSession)", 5 * 60 * 1000); // check every 5 minutes
}

function StopTimer () 
{
	if (timerID) 
	{
		clearTimeout (timerID);
		timerID  = 0;
	}
}

function CheckSession (http_request)
{
	if (http_request.readyState == 4 && http_request.status == 200)
	{
		if (http_request.responseText.match ('true'))
		{
			StartTimer ();
		}
		else
		{
			var LogoffPage = BaseLocation + "LogOff.php?timeout=true";
			OverrideSaveCheck = true;
			window.location = LogoffPage;
		}
	}
}

//-->
//-----------------------------------------------------
//BULK TASK LOGIC
//-----------------------------------------------------

function RequestBulkAction(sCommand, fForm)
{
	switch (sCommand)
	{
		case "BulkMoveImages":
			// go to a "browse page so that the usre can select a folder
			fForm.action = "MoveImages.php?action=Move"; 
			break;
		case "BulkCopyImages":
			// go to a "browse" page so that the user can select a folder
			fForm.action = "MoveImages.php?action=Copy"; 
			break;
		case "BulkDelete":
			// prompt the user to verify delete action
			if (!confirm("WARNING:  You are about to permanently delete the selected items from the system.  Are you sure you want to permanently delete the selected items?"))
				return;
			// tell user deletions have begun
			SpectrumMessageBox("Deleting...");	
			break;
		case "BulkEdit":
			fForm.action = "EditRecord.php";	
			fForm.BulkOpen.disabled=false;              // To prevent a bulk action from opening ImageScope
			break;
		case "BulkAnalyze":
			fForm.action = "AnalyzeSlides.php";	
			break;
		case "BulkExport":
			fForm.action = "BulkExport.php";	
			break;
		case "BulkAssign":
			fForm.action = "AssignParent.php"; 
			break;
		case "BulkAssignNew":
			fForm.NewRecord.disabled = false;
			fForm.action = "AssignParent.php";
			break;
		case "BulkAssignGrandparent":
			fForm.action = "AssignGrandparent.php";
			break;
		case "BulkAssignGrandparentNew":
			fForm.NewRecord.disabled = false;
			fForm.action = "AssignGrandparent.php";
			break;
	}
	
	// submit the bulk form
	fForm.action = 'BulkAction.php?Command=' +  sCommand;
	//fForm.Command.value=sCommand; 
	fForm.submit();
}

function isset(variable)
{
	var undefined;
	return ( variable == undefined ? false : true );
}

function GetFolderPath()
{
	var Folder;
	Folder = prompt("Specify a destination folder (e.g. \\\\servername\\sharename)","");
	if (Folder == "" || Folder == null)
	{
		return false;
	}
	else
	{
		document.BulkForm.DestinationFolder.value = Folder;
		return true;
	}

}


function SortList(sSortField, sSortOrder)
{
	document.ReSubmitSearchForm.SortField.value=sSortField; 
	document.ReSubmitSearchForm.SortOrder.value=sSortOrder; 
	document.ReSubmitSearchForm.PageNumber.value = 1;
	document.ReSubmitSearchForm.submit();
}

function IsImageScopeInstalled()
{
	// This function is used to determine if ImageScop is isntalled on the 
	// client machine.  There are two ways to do this... Under windows adn IE
	// we can try to create the viewport.  Under all other browsers, we have to
	// check the MIME types for "text/sis".
	if (IsWin() && IsIE())
	{
		// IE on windows... attempt to instantiate the viewport.
		try
		{
			var vp = new ActiveXObject("VIEWPORT.ViewportCtrl.1");
			return true;
		}
		catch(e)
		{
		}
	}
	else if(navigator.mimeTypes.length > 0 && navigator.mimeTypes["text/sis"])
	{
		// non-ie browsers can check the MIME types.
		return true;
	}
	return false;
	
}

function createAquaItem() 
{
	    var opt = document.createElement("option");
        // Add an Option object to Drop Down/List Box
        document.getElementById("MacroId").options.add(opt);
        // Assign text and value to Option object
        opt.text = unescape("HistoRX AQUA%AE Analysis");
        opt.value = "aqua";
}

function IsAquaInstalled() 
{
	// This function is used to determine if Aqua is isntalled on the 
	// client machine.  There are two ways to do this... Under windows and IE
	// we can <method TBD>.  Under all other browsers, we have to
	// check the MIME types for "text/hris".
	//Remove bypass when completel
	
	if(!isSupported)
		return;
		
	var aquaIsInstalled = false;
	if (IsWin() && IsIE())
	 {
		// IE on windows... attempt to instantiate the viewport.
		try
		{
			var hrx = new ActiveXObject("HistoRX.AperioPush.AperioResultData");
			aquaIsInstalled = true;
		}
		catch(e)
		{
		}
	}
	else if(navigator.mimeTypes.length > 0 && navigator.mimeTypes["text/hris"])
	{
		//non-ie browsers can check the MIME types.
		aquaIsInstalled = true;
	}
	if(aquaIsInstalled) 
	{
		createAquaItem();
		
	}	
}

function IsWin()
{
	var agt=navigator.userAgent.toLowerCase();
	return (agt.indexOf("win") != -1);	
}

function IsIE()
{
	return (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ;
}

function IsFF()
{
	return (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent));
}

function BulkViewWithImageScopeOrBrowser (fForm)
{
	// view multiple slides in ImageScope.  If ImageScope
	// is not installed then view in browser.
	
	if (IsImageScopeInstalled() && !wPressed)
	{
		// request a SIS file
		NeedCheck = true;
		RequestBulkAction('BulkImageScopeView', fForm);
		NeedCheck = false;
	}
	else
	{
		// if there is more than one record Id
		var ImageIds = new Array ();
		
		// Can't just use the fForm['ImageIds[]'] notation because IE is too dumb to figure it out, even though MS came up with the idea
		var Inputs = fForm.getElementsByTagName ('INPUT');
		for (var i = 0; i < Inputs.length; i++)
			if (Inputs [i].name == 'ImageIds[]' && Inputs [i].value != '-1')
				window.open('ViewImage.php?ImageId=' + Inputs [i].value);
		
		wPressed = false;
	}
}

function viewImage(ImageId)
{
	var ImageScope = IsImageScopeInstalled() ? '&UseImageScope=1+' : '';
	window.open('ViewImage.php?' + ImageScope + '&ImageId=' + ImageId);
}

function MultiViewWithImageScopeOrBrowser(ImageServerURLs, ImageIds)
{
	// view multiple slides in ImageScope.  If ImageScope
	// is not installed then view in browser.

	if (IsImageScopeInstalled() && !wPressed)
	{
		NeedCheck = false;
		
		// ImageScope is installed so request a SIS file
		var ViewURL = 'BulkAction.php?Command=BulkImageScopeView';
		var Args = '';
		
		for (var i = 0; i < ImageIds.length; i++)
			if (ImageIds[i] != -1)
				Args += '&ImageIds[]=' + ImageIds [i];
		
		if (Args.length > 0)
			location.replace (ViewURL + Args);
		
		NeedCheck = true;
	}
	else
	{
		// ImageScope is not installed so view image in browser
		for (var i = 0; i < ImageIds.length; i++)
			if (ImageIds[i] != -1)
				window.open(ImageServerURLs [i] + '/@' + ImageIds [i] + "/view.apml",'Image' + ImageIds [i],'');	
		wPressed = false;
	}
}

function SingleViewWithImageScopeOrBrowser(ImageServerURL, ImageId)
{	

  	// this TableName logic is just temporary until we get the AIL change to
  	// have spots as ImageIds
  	/*
  	var TableName;
  	if (location.href.indexOf("EditCore.php") != -1)
  		TableName = "Spot";
  	else
  	*/
  	var TableName = "Image";
  	
  	
	// view a single slide in ImageScope.  If ImageScope is
	// not installed then view in browser
	if (IsImageScopeInstalled() && !wPressed)
	{
		NeedCheck = false;
		
		// ImageScope is installed so request a SIS file
		location.replace ('BulkAction.php?Command=BulkImageScopeView&ImageIds[]=' + ImageId + '&TableName=' + TableName);
		
		NeedCheck = true;
	}
	else
	{
		// ImageScope is not installed so view image in browser
		window.open(ImageServerURL + '/@' + ImageId + "/view.apml",'Image' + ImageId,"");
		wPressed = false;
	}
}


function trim(sString)
{
	while (sString.substring(0,1) == ' ')
		sString = sString.substring(1, sString.length);
	while (sString.substring(sString.length-1, sString.length) == ' ')
		sString = sString.substring(0,sString.length-1);
	return sString;
}

var MinimumFontSize = -4;
var MaximumFontSize = 4;
function SetFontSize()
{
	var cssRules = new Array ();
	var font_size;
	var BaseFontSize = 0;

	if (document.cookie !== undefined)
	{
		var matches = document.cookie.match(/BaseFontSize=(-?\d)/);
		if (matches !== null)
			BaseFontSize = parseInt(matches[1]);
	}
	
	if (!document.styleSheets || BaseFontSize == 0) return;
	
	for (var i = 0; i < document.styleSheets.length; i++)
	{
		if (document.styleSheets[i].cssRules)
			cssRules = document.styleSheets[i].cssRules;
		else if (document.styleSheets[i].rules)
			cssRules = document.styleSheets[i].rules;
		else continue;
		
		for (var j = 0; j < cssRules.length; j++)
		{			
			if (!isset(cssRules[j].style))
				continue;
			if (cssRules[j].style.getPropertyValue && cssRules[j].style.getPropertyValue("font-size"))
				font_size = cssRules[j].style.getPropertyValue("font-size");
			else if (cssRules[j].style.fontSize)
				font_size = cssRules[j].style.fontSize;
			else continue;
			
			font_size = (parseFloat(font_size) + BaseFontSize) + font_size.substring (parseFloat(font_size).toString().length);
			
			if (cssRules[j].style.getPropertyValue && cssRules[j].style.getPropertyValue("font-size"))
				cssRules[j].style.setProperty("font-size", font_size, null);
			else if (cssRules[j].style.fontSize)
				cssRules[j].style.fontSize = font_size;
		}
	}
}

function IncreaseFontSize()
{
	var cssRules = new Array ();
	var font_size;
	var BaseFontSize = 0;

	if (document.cookie !== undefined)
	{
		var matches = document.cookie.match(/BaseFontSize=(-?\d)/);
		if (matches !== null)
			BaseFontSize = parseInt(matches[1]);
	}
	
	if (!document.styleSheets || BaseFontSize >= MaximumFontSize) return;
	
	for (var i = 0; i < document.styleSheets.length; i++)
	{
		if (document.styleSheets[i].cssRules)
			cssRules = document.styleSheets[i].cssRules;
		else if (document.styleSheets[i].rules)
			cssRules = document.styleSheets[i].rules;
		else continue;
		
		for (var j = 0; j < cssRules.length; j++)
		{
			if (!isset(cssRules[j].style))
				continue;
			if (cssRules[j].style.getPropertyValue && cssRules[j].style.getPropertyValue("font-size"))
				font_size = cssRules[j].style.getPropertyValue("font-size");
			else if (cssRules[j].style.fontSize)
				font_size = cssRules[j].style.fontSize;
			else continue;
			
			font_size = (parseFloat(font_size) + 1) + font_size.substring (parseFloat(font_size).toString().length);
			
			if (cssRules[j].style.getPropertyValue && cssRules[j].style.getPropertyValue("font-size"))
				cssRules[j].style.setProperty("font-size", font_size, null);
			else if ((cssRules[j].style.fontSize) && (font_size !== 'undefined'))
				cssRules[j].style.fontSize = font_size;
		}
	}
	
	BaseFontSize++;
	document.cookie = '"BaseFontSize=' + BaseFontSize + '"';
	
	if (window.onresize)
		window.onresize ();
}

function DecreaseFontSize()
{
	var cssRules = new Array ();
	var font_size;
	var BaseFontSize = 0;

	if (document.cookie !== undefined)
	{
		var matches = document.cookie.match(/BaseFontSize=(-?\d)/);
		if (matches !== null)
			BaseFontSize = parseInt(matches[1]);
	}
	
	if (!document.styleSheets || BaseFontSize <= MinimumFontSize) return;
	
	for (var i = 0; i < document.styleSheets.length; i++)
	{
		if (document.styleSheets[i].cssRules)
			cssRules = document.styleSheets[i].cssRules;
		else if (document.styleSheets[i].rules)
			cssRules = document.styleSheets[i].rules;
		else continue;
		
		for (var j = 0; j < cssRules.length; j++)
		{			
			if (!isset(cssRules[j].style))
				continue;
			if (cssRules[j].style.getPropertyValue && cssRules[j].style.getPropertyValue("font-size"))
				font_size = cssRules[j].style.getPropertyValue("font-size");
			else if (cssRules[j].style.fontSize)
				font_size = cssRules[j].style.fontSize;
			else continue;
			
			font_size = (parseFloat(font_size) - 1) + font_size.substring (parseFloat(font_size).toString().length);
			
			if (cssRules[j].style.getPropertyValue && cssRules[j].style.getPropertyValue("font-size"))
				cssRules[j].style.setProperty("font-size", font_size, null);
			else if (cssRules[j].style.fontSize)
				cssRules[j].style.fontSize = font_size;
		}
	}
	
	BaseFontSize--;
	document.cookie = '"BaseFontSize=' + BaseFontSize + '"';
	
	if (window.onresize)
		window.onresize ();
}

function ResetFontSize()
{
	var cssRules = new Array ();
	var font_size;
	var BaseFontSize = 0;

	if (document.cookie !== undefined)
	{
		var matches = document.cookie.match(/BaseFontSize=(-?\d)/);
		if (matches !== null)
			BaseFontSize = parseInt(matches[1]);
	}
	
	for (var i = 0; i < document.styleSheets.length; i++)
	{
		if (document.styleSheets[i].cssRules)
			cssRules = document.styleSheets[i].cssRules;
		else if (document.styleSheets[i].rules)
			cssRules = document.styleSheets[i].rules;
		else continue;
		
		for (var j = 0; j < cssRules.length; j++)
		{			
			if (!isset(cssRules[j].style))
				continue;
			if (cssRules[j].style.getPropertyValue && cssRules[j].style.getPropertyValue("font-size"))
				font_size = cssRules[j].style.getPropertyValue("font-size");
			else if (cssRules[j].style.fontSize)
				font_size = cssRules[j].style.fontSize;
			else continue;
			
			font_size = (parseFloat(font_size) - BaseFontSize) + font_size.substring (parseFloat(font_size).toString().length);
			
			if (cssRules[j].style.getPropertyValue && cssRules[j].style.getPropertyValue("font-size"))
				cssRules[j].style.setProperty("font-size", font_size, null);
			else if (cssRules[j].style.fontSize)
				cssRules[j].style.fontSize = font_size;
		}
	}
	
	BaseFontSize = 0;
	document.cookie = '"BaseFontSize=0"';
	
	if (window.onresize)
		window.onresize ();
}


function ForceToNumber (Value, MinValue, MaxValue, Step)
{
	if (MinValue != null && Value < MinValue) Value = MinValue;
	else if (MaxValue != null && Value > MaxValue) Value = MaxValue;
	
	if (Step != null)
	{
		var Base = (MinValue != null) ? MinValue : ((MaxValue != null) ? MaxValue : 0);
		
		Value = Base + (Math.round ((Value - Base) / Step) * Step);
	}
	
	return Value;
}

function CheckModified (Element)
{
	if (Element.tagName == 'INPUT' || Element.tagName == 'SELECT' || Element.tagName == 'TEXTAREA')
	{
		Modified = CheckElement(Element);
	}
	else
	{
		var Inputs = GetInputs (Element);
		var Modified = false;

		for (var i = 0; i < Inputs.length; i++)
			Modified = CheckElement (Inputs [i]) || Modified;

		return Modified;
	}

	if (Modified == false)
		return false;

	var promptText = Element.getAttribute('getApproval');
	if ((promptText != null) && (promptText != ''))
	{
		var approved = confirm (promptText);
		if (approved)
		{
			// Once the user has OK'd a change for this field do not prompt again
			Element.setAttribute('getApproval', '');
			return true;
		}
	}
	else
	{
		return true;
	}

	if (Element.tagName == 'INPUT' || Element.tagName == 'SELECT' || Element.tagName == 'TEXTAREA')
	{
		RevertElement(Element);
	}
	else
	{
		var Inputs = GetInputs (Element);
		for (var i = 0; i < Inputs.length; i++)
			RevertElement (Inputs [i]) || Modified;
	}

	return false;
}

function CheckElement(Element)
{
	if (Element.getAttribute ('oldvalue') != undefined)
	{
		var OldValue = Element.getAttribute ('oldvalue');
		var NewValue = Element.value;

		removeClass (Element, 'Invalid');

		if (OldValue === NewValue)
		{
			removeClass (Element, 'Modified');

			var Label = document.getElementById (Element.id + '.Label');
			if (Label)
				Label.innerHTML = '';

			return false;
		}
		else
		{
			addClass (Element, 'Modified');
			return true;
		}
	}
	return true;
}

function RevertElement (Element)
{
	var oldValue = Element.getAttribute('oldvalue');
	if (oldValue != null)
	{
		if (Element.tagName == 'SELECT')
		{
			var options = Element.getElementsByTagName('OPTION');
			for (var i=0; i < options.length; i++)
			{
				if (options[i].selected)
				{
					if (options[i].value != oldValue)
						options[i].selected = false;
				}
				else 
				{
					if (options[i].value == oldValue)
						options[i].selected = true;
				}
			}
		}
		else
		{
			Element.value = oldValue;
		}
	}
}

function HideSpectrumMessageBox ()
{
	var divMsg = document.getElementById ('idDivMessage');
	
	if (divMsg)
		divMsg.style.display = 'none';
	
	return true;
}

function SpectrumMessageBox(sText)
{
	
	// figure aout where to display the message div
	
	var ClientHeight, ClientWidth, ScrollTop;

	// IE or mozilla?
	if (document.all)
	{
		ClientWidth 	= document.body.clientWidth;
		ClientHeight 	= document.body.clientHeight;
		ScrollTop 		= document.body.scrollTop;
	}
	else
	{
		ClientWidth 	= window.innerWidth;
		ClientHeight 	= window.innerHeight;
		ScrollTop 		= document.body.scrollTop;
	}
	
	var divMsg = document.getElementById ('idDivMessage');
	
	if (!divMsg)
	{
		divMsg = document.createElement('div');
	    divMsg.className    = "MessageBox";
	    divMsg.id           = 'idDivMessage';

	    var MsgWidth 	    = 200;
		var MsgHeight 	    = 10;

		divMsg.style.width	= MsgWidth;
		divMsg.style.height	= MsgHeight;
		divMsg.style.left	= (ClientWidth - MsgWidth) / 2;
		divMsg.style.top 	= (ClientHeight - MsgHeight) / 2 + ScrollTop;
		
		divMsg.appendChild(document.createElement('b'));
		document.body.appendChild(divMsg);
	}
	else
	{
		divMsg.style.display = '';
	}

	divMsg.firstChild.innerHTML = sText

	return true;
}

function EventTarget (e)
{
	var targ;
	if (!e) var e = window.event;
	
	if (e.target)
		targ = e.target;
	else if (e.srcElement)
		targ = e.srcElement;
	
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	
	return targ;
}

function AJAXFormSubmit (Element)
{
	var Inputs = GetInputs (Element.form);
	var Params = '';
	var Modified = Element.name == 'Event';
	var EsigUserName = '';
	var EsigPassword = '';

	if (isset (document.getElementById('SigUserName')))
		EsigUserName = document.getElementById('SigUserName').value;
	if (isset (document.getElementById('SigPassword')))
		EsigPassword = document.getElementById('SigPassword').value;

	var Table = Element;
	while (Table && Table.tagName != 'TABLE')
		Table = Table.parentNode;

	for (var i = 0; i < Inputs.length; i++)
	{
		if (Inputs [i].tagName == 'INPUT' && Inputs [i].type == 'button' && Inputs [i] != Element)
			continue;
		else if (hasClass (Inputs [i], 'Modified') || hasClass (Inputs [i], 'Required') || Inputs [i] == Element || hasClass (Inputs[i], 'Invalid'))
		{
			if (!Modified && (hasClass (Inputs [i], 'Modified') || (hasClass (Inputs [i], 'Invalid'))))
				Modified = true;
			
			if (Params != '')
				Params = Params + '&';
			
			Params = Params + Inputs [i].name + '=' + encodeURIComponent (Inputs [i].value);
		}
	}

	if ((Params != '') && (EsigUserName != ''))
		Params = Params + '&SigUserName=' + EsigUserName + '&SigPassword=' + EsigPassword;

	var Receive = new function ()
	{
		this.Form = Element.form;
		this.Table = Table;

		this.Receive = function (http_request)
		{
			if (http_request.readyState == 4 && http_request.status == 200) 
			{
                PendingSaveRequests--;
				try
				{
					var Data = eval ('(' + http_request.responseText + ')');
				}
				catch (e)
				{
					OverrideSaveCheck = true;
					document.write (http_request.responseText);
					return;
				}

				var CellMap = new function () {};
				for (var i = 0; i < this.Table.rows.length; i++)
				{
					var Cell = this.Table.rows [i].firstChild ? this.Table.rows [i].firstChild.nextSibling : null;
					
					if (Cell && Cell.getAttribute ('TableName') && Cell.getAttribute ('ColumnName'))
						CellMap [Cell.getAttribute ('ColumnName')] = Cell;
				}

				for (var i in Data.Cells)
				{
					if (CellMap [i])
					{
						CellMap [i].innerHTML = Data.Cells [i].Contents;
						
						var Label = document.getElementById (Data.Cells [i].TableName + '.' + Data.Cells [i].ColumnName + '.Label');
						
						if (Data.Cells [i].Error && Label)
                        {
                            SaveErrorOccured = true;
							Label.innerHTML = Data.Cells [i].Error;
                        }
						else if (Label)
							Label.innerHTML = '';
					}
				}

				if (Data.ErrorCode == '-7029')
					getEsig();

                // only redirect to a new page if this is the last form save response
                // and if there were no errors.
                if (Data.GoToPage && PendingSaveRequests == 0 && !SaveErrorOccured)
                    document.location.href = Data.GoToPage;
			}
		}
	}

    PendingSaveRequests++
	HTTPRequest (Element.form.action, Element.form.method, Params, Receive);

	return false;
}

function GetInputs (Element)
{
	var i = 0;
	
	var Inputs = Element.getElementsByTagName ('INPUT');
	var TextAreas = Element.getElementsByTagName ('TEXTAREA');
	var Selects = Element.getElementsByTagName ('SELECT');
	
	var RetArray = new Array ();
	
	for (i = 0; i < Inputs.length; i++)
		RetArray.push (Inputs [i]);
	for (i = 0; i < TextAreas.length; i++)
		RetArray.push (TextAreas [i]);
	for (i = 0; i < Selects.length; i++)
		RetArray.push (Selects [i]);
	
	return RetArray;
}

function AJAXFormReset (Element)
{
	var Inputs = GetInputs (Element.form);
	var TableName = '';
	
	for (var i = 0; i < Inputs.length; i++)
		if (Inputs [i].name == 'TableName')
			TableName = Inputs [i].value;
	
	for (var i = 0; i < Inputs.length; i++)
	{
		if (hasClass (Inputs [i], 'Modified'))
		{
			switch (Inputs [i].tagName)
			{
			case 'SELECT':
				for (var j = 0; j < Inputs [i].options.length; j++)
					if (Inputs [i].options [j].value == Inputs [i].getAttribute ('oldvalue'))
						Inputs [i].selectedIndex = j;
				
				break;
			case 'INPUT':
				Inputs [i].value = Inputs [i].getAttribute ('oldvalue');
				
				switch (Inputs [i].type.toUpperCase ())
				{
				case 'CHECKBOX':
					Inputs [i].checked = (Inputs [i].value == '1');
					break;
				}
				break;
			case 'TEXTAREA':
				Inputs [i].value = Inputs [i].getAttribute ('oldvalue');
				break;
			}
			
			removeClass (Inputs [i], 'Modified');
			
			var Label = document.getElementById (TableName + '.' + Inputs [i].name + '.Label');
			if (Label)
				Label.innerHTML = '';
		}
	}
	
	return false;
}

var OverrideSaveCheck = false;
function CheckDataUnsaved ()
{
	if (!OverrideSaveCheck)
	{
		var Inputs = GetInputs (document);
		
		for (var i = 0; i < Inputs.length; i++)
			if (hasClass (Inputs [i], 'Modified'))
{
				return true;
}
	}

	OverrideSaveCheck = false;
	return false;
}

function getEsig()
{
	var esigWindow = document.getElementById('esigDiv');
	esigWindow.className = 'esigDiv';
	esigWindow.style.display = '';
	esigWindow.innerHTML = "<TABLE><TR><TH colspan='6'>SIGNATURE&nbsp;VALIDATION&nbsp;REQUIRED</TH></TR><TR><TD>User Name:</TD><TD><INPUT type='text' id='SigUserName' name='SigUserName'  /></TD><TD>Password:</TD><TD><INPUT type='password' id='SigPassword' name='SigPassword' /><TD><INPUT type='button' class='esigButton' value='Sign' onclick='submitEsig()'></TD><TD><INPUT type='button' class='esigButton' value='Cancel' onclick='CancelEsig()'></TD></TR></TABLE>";
	document.getElementById('SigUserName').focus();
	return true;
}

function hideEsig()
{
	if (!isset (document.getElementById('SigUserName')))
		return true;
		
	var esigWindow = document.getElementById('esigDiv');
	esigWindow.className = '';
	esigWindow.style.display = 'none';
	
	document.getElementById('SigUserName').value = '';
	document.getElementById('SigPassword').value = '';
	return true;
}
	
function submitEsig()
{
	SaveAll();
}

var startY = 200;
var sy;
function floatEsig()
{
	if(document.documentElement.scrollTop)
		sy = document.documentElement.scrollTop;
	else
		sy = document.body.scrollTop;

	var temp = sy + startY;
	var newY = temp.toString() + "px";
	
	var esigWindow = document.getElementById("esigDiv");
	esigWindow.style.top = newY;
}

function getElementsByClass(getClass)
{
	var elementsArray = [];
	var matchedArray = [];
	var expression = new RegExp("(^| )" + getClass + "(|$)");
	
	if (document.all)
		elementsArray = document.all;
	else
		elementsArray = document.getElementsByTagName("*");
	
	for (var i = 0; i < elementsArray.length; i++)
	{		
		if (expression.test(elementsArray[i].className))
		{
			var includedElement = elementsArray[i];
			matchedArray[matchedArray.length] = elementsArray[i];
		}
	}
	return matchedArray;
}

function GetFormOf (Element)
{
	alert (Element.tagName);
	while (Element && Element.tagName != 'FORM')
		Element = Element.parentNode;
	
	return Element;
}

function GetTop (inputObj)
{
	var returnValue = inputObj.offsetTop;
	
	while((inputObj = inputObj.offsetParent) != null)
	{
		returnValue += inputObj.offsetTop;
	}
	
	return returnValue;
}

function GetLeft (inputObj)
{
	var returnValue = inputObj.offsetLeft;
	
	while((inputObj = inputObj.offsetParent) != null)
	{
		returnValue += inputObj.offsetLeft;
	}
	
	return returnValue;
}

/* for comment drop-down/add-ins: */

function CloseCommentMenu ()
{
	if (PreventClose == 1) // catch an override to the close menu event
		PreventClose = 0;
	else // otherwise close the menu
		document.getElementById ('CannedMenu').style.display = 'none';
}

function Select (TextArea, sType)
{
	PreventClose = 1; // set an override to prevent the menu from being closed
	SelectedTextArea = TextArea;
	
	var xy = findPos (TextArea);
	var CannedMenu = document.getElementById ('CannedMenu');
	
	CannedMenu.style.display = ''; // show the menu
	
	CannedMenu.style.left =	xy [0]; // move the menu to the selected element
	CannedMenu.style.top = xy [1] - document.getElementById ('CannedMenu').offsetHeight;
	
	if (sType)
	{
		MenuItems = CannedMenu.firstChild.rows [0].cells[1].firstChild.childNodes;
		
		for (var i = 0; i < MenuItems.length; i++)
		{
			if (MenuItems [i].id == sType)
				MenuItems [i].style.display = '';
			else
				MenuItems [i].style.display = 'none';
		}
	}
}

function DeSelect (TextArea)
{
	PreventClose = 0; // Unless over-ridden, the comment menu should be closed
	setTimeout ('CloseCommentMenu ()', 250); // Set a timer to make sure that the onclick event (InsertComment) occurs before the menu gets closed.
}

function InsertComment (Comment)
{
	if (SelectedTextArea == 0) return;
	
	for (var i = 0; i < Comment.length && Comment [i] != -1; i++)
	{
		SelectedTextArea.value += String.fromCharCode (Comment [i]); // append the canned comment
	}
	
	PreventClose = 0; // disable any overrides
	
	CloseCommentMenu (); // close the menu
}

function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

// To avoid complications due to undefined constants... (IE!)
if (!document.ELEMENT_NODE)
{
	document.ELEMENT_NODE = 1;
	document.ATTRIBUTE_NODE = 2;
	document.TEXT_NODE = 3;
	document.CDATA_SECTION_NODE = 4;
	document.ENTITY_REFERENCE_NODE = 5;
	document.ENTITY_NODE = 6;
	document.PROCESSING_INSTRUCTION_NODE	= 7;
	document.COMMENT_NODE = 8;
	document.DOCUMENT_NODE = 9;
	document.DOCUMENT_TYPE_NODE = 10;
	document.DOCUMENT_FRAGMENT_NODE = 11;
	document.NOTATION_NODE = 12;
}

// Because not all browsers (IE!) implement the importNode function for DOM objects
if (!document.importNode)
{
	document.importNode = function (node, allChildren)
	{
		var newNode;
		
		switch (node.nodeType)
		{
		case document.ELEMENT_NODE:
			newNode = document.createElement (node.nodeName);
			if (node.attributes)
			{
				for (var i = 0; i < node.attributes.length; i++)
				{
					newNode.setAttribute (node.attributes [i].nodeName, node.getAttribute (node.attributes [i].nodeName));
				}
				
				if (allChildren && node.childNodes)
				{
					var childNode = node.firstChild;
					while (childNode)
					{
						var newChild = document.importNode (childNode, true)
						newNode.appendChild (newChild);
						childNode = childNode.nextSibling;
					}
				}
			}
			break;
		
		case document.CDATA_SECTION_NODE:
			newNode = document.createCDATASection (node.nodeValue);
			break;
		
		case document.COMMENT_NODE:
			newNode = document.createComment (node.nodeValue);
			break;
		
		default:
			newNode = document.createTextNode (node.nodeValue);
			break;
		}
		
		return newNode;
	}
}

function EnableRecordButtons ()
{
	var elm = document.getElementById ('SaveAllTop');
	if (elm != undefined)
	{
		document.getElementById ('SaveAllTop').disabled = false;
		document.getElementById ('ResetAllTop').disabled = false;
		document.getElementById ('SaveAllBottom').disabled = false;
		document.getElementById ('ResetAllBottom').disabled = false;
	}
}

function SaveAll ()
{
    SaveErrorOccured = false;
    
	var Inputs = GetInputs (document);
	
	for (var i = 0; i < Inputs.length; i++)
	{
		if (Inputs [i].type == 'button' && hasClass (Inputs [i], 'Save'))
		{
			Inputs [i].onclick ();
		}
	}

	hideEsig();
}

function ResetAll ()
{
	var Inputs = GetInputs (document);
	for (var i = 0; i < Inputs.length; i++)
	{
		if (Inputs [i].type == 'button' && hasClass (Inputs [i], 'Reset'))
		{
			Inputs [i].onclick ();
		}
	}

	hideEsig();
}

function CancelEsig ()
{
	hideEsig();
}

function escapeXML (str)
{
	var div = document.createElement('div');
	var text = document.createTextNode(str);
	div.appendChild(text);
	return div.innerHTML;
}

function strpbrk(haystack, char_list)
{
	var retVal = -1;
	for (var i = 0; i < char_list.length; i++)
	{
		var pos = haystack.indexOf(char_list.charAt(i));
		if (pos > -1)
			if (retVal == -1 || pos < retVal)
				retVal = pos;
	}
	return retVal;
}

// Ensure user has entered an integer number
function CheckForInteger(e)
{
	// ie or firefox?
	key = (document.all)?window.event.keyCode : e.which; 

	// BackSpace or 0 - 9
	if ((key >= 0x30 && key <= 0x39) || (key == 8))
		return true;

	if (key == 13)
	{
		// Return
		this.blur ();  // loose focus on this widget (force an onchange())
	}
	return false;
}

function CheckValue2(elm)
{
	var field = elm.nextSibling;
	while (field)
	{
		if (field.name == 'FieldValue2[]')
		{
			if (elm.value == "Range")
				field.style.display = '';
			else
				field.style.display = 'none';
			break;
		}
		field = field.nextSibling;
	}
}

function ShowMessage(val)
{
	var sub = document.getElementById(val);

	sub.style.display="block";
	sub.style.color="#ff4444"
}
function HideMessage(val)
{
	var sub = document.getElementById(val);
	sub.style.display="none";
}

