// Global variables used in dynamic recaclulation
var changedAttrName = null;
// for inline references
var refPropId = null;  
var refAttrName = null;
var refKey = null;

// type checking functions

function checkValue(field, property, type, required) 
{
	var value = "";
	if (field.length && ! field.tagName)
	{
		// radio button
		for (ll = 0; ll < field.length; ++ll)
		{
			if (field [ll].checked && field [ll].value)
			{
				value = field [ll].value;
				break;
			}
		}
	}
	else
	{
		value = field.value;
	}
		
	if (value != "") 
	{
		if (type=="NUMBER" && !isNumber (value)) 
		{
			return false;
		}
		if (type=="FLOAT" && !isFloat (value)) 
		{
			return false;
		}
		if (type=="DATE" && !isDate (value)) 
		{
			return false;
		}
		if (type=="EMAIL" && !isEmail (value)) 
		{
			return false;
		}
	} 
	else 
	{	
		if (required) 
		{
			if (! field.disabled)
				return false;
		}
	}
	return true;
}

// Return true if value is an e-mail address
function isEmail(value) {
	invalidChars = " /:,;";
	if (value=="") return false;
	
	for (i=0; i<invalidChars.length;i++) {
	   badChar = invalidChars.charAt(i);
	   if (value.indexOf(badChar,0) != -1) return false;
	}
	
	atPos = value.indexOf("@", 1);
	if (atPos == -1) return false;
	if (value.indexOf("@", atPos + 1) != -1) return false;
	
	periodPos = value.indexOf(".", atPos);
	if (periodPos == -1) return false;
	
	if (periodPos+3 > value.length) return false;

	return true;
}



// Return true if value is a number
function isNumber(value) {
	if (value=="") return false;

	var d = parseInt(value);
	if (!isNaN(d)) 
		return true; 
	else 
		return false;		
}

// Return true if value is a number
function isFloat(value) 
{
	if (value=="") return false;

	var d = parseFloat(value);
	if (!isNaN(d)) 
		return true; 
	else 
		return false;		
}

// return true if value is a date
// ie in the format XX/YY/ZZ where XX YY and ZZ are numbers
function isDate(value) {
	if (value=="") return false;
	
	var pos = value.indexOf("/");
	if (pos == -1) return false;
	var d = parseInt(value.substring(0,pos));
	value = value.substring(pos+1, 999);
	pos = value.indexOf("/");
	if (pos==-1) return false;
	var m = parseInt(value.substring(0,pos));
	value = value.substring(pos+1, 999);
	var y = parseInt(value);	
	if (isNaN(d)) return false;	
	if (isNaN(m)) return false;	
	if (isNaN(y)) return false;	
	
	var type=navigator.appName;
	if (type=="Netscape") var lang = navigator.language;
	else var lang = navigator.userLanguage;
	lang = lang.substr(0,2);

	if (lang == "fr") var date = new Date(y, m-1, d);
	else var date = new Date(d, m-1, y);
	if (isNaN(date)) return false;	
	return true;
 }

// Set dirty flag of an object (but not references)
function setDirty (form)
{
	if (form.elements['isDirty'])
		form.elements['isDirty'].value = "true";
}

// Set dirty flag of an object's references
function setReferencesDirty (form)
{
	if (form.elements['isReferencesDirty'])
		form.elements['isReferencesDirty'].value = "true";
}

// check if object or its references have been changed and asks user a question if so
function confirmIfDirty (msg, elem)
{
	if (document.forms.length == 0)
		return true;  // proceed with whatever user is doing
	
	var form = null;
	if (elem == null)
	{
		form = document.forms [0];
	}
	else
	{
		form = findCompartmentForm (elem);
		if (form == null)
			return true;
	}
		
	// check if we are dealing with the entity form
	if (form.name != 'EntityFormBean')
		return true;  // proceed with whatever user is doing
		
	if (form.elements['isDirty'].value == "true" ||
		form.elements['isReferencesDirty'].value == "true")
	{
		return window.confirm (msg);
	}
	
	return true; // proceed with whatever user is doing
}

// same as above but using iframe for the main page
function confirmIfMainFormDirty (msg)
{
	// check if we are dealing with the entity form
	var iframe = document.getElementById ('BAS_Main');
	if (iframe)
	{
		try
		{
			// check if we are in the process frame mode
			if (iframe.contentWindow.document.getElementById ("BAS_PROCESS_FRAME_ID") != null)
			{
				if (! window.confirm ("This will cancel current process. Are you sure you want to continue?"))
					return false;
			}
			
			if (iframe.contentWindow.document.forms.length == 0 || iframe.contentWindow.document.forms[0].name != 'EntityFormBean')
				return true;  // proceed with whatever user is doing
	
			if (iframe.contentWindow.document.forms [0].elements['isDirty'].value == "true" ||
			    iframe.contentWindow.document.forms [0].elements['isReferencesDirty'].value == "true")
			{
				return window.confirm (msg);
			}
		}
		catch (ee)
		{}
	}
	
	return true; // proceed with whatever user is doing
}

// check if references have been changed and asks user a question if so
function confirmIfReferencesDirty (msg, elem)
{
	var form = findCompartmentForm (elem);
	if (form == null)
		return true;
		
	if (form.elements['isReferencesDirty'] && form.elements['isReferencesDirty'].value == "true")
	{
		return window.confirm (msg);
	}
	
	return true; // proceed with whatever user is doing
}

/** This function is called from onFocus to invoke dynamic recalculation of the form after the specified
attribute has been changed **/
function callDynamicRecalc (form, fieldName, attrName)
{
	var s = null;
	if (refPropId)
	{
		s = '?actionMethod=inlineAttributeChanged&changedAttributeName=' + attrName +
			'&refPropId=' + refPropId +
		    '&refAttrName=' + refAttrName + 
			'&refKey=' + refKey;
	}
	else
	{
		s = '?actionMethod=attributeChanged&changedAttributeName=' + attrName;
	}
	
	callDynamicRecalc2 (form, s);
}

// Another variation of the above
function callDynamicRecalc2 (form, url)
{
	// form.submit();
	// use AJAX to submit the form
	// remember old focus field
    var ua = navigator.userAgent.toLowerCase();
    isIE = ua.indexOf("msie") > -1;
    
	var oldFocusName = null;
	if (form.elements['focusFieldName'].value && form.elements['focusFieldName'].value != "") 
	{ 
		var oldFocus = document.getElementsByName (form.elements['focusFieldName'].value); 
 		if (oldFocus && oldFocus.length > 0 && ! oldFocus[0].disabled)
 		{
			oldFocusName = form.elements['focusFieldName'].value; 
 		}
	}
	
	var parameters = new Object ();
	// this indicates to a server that this is a special AJAX request
	parameters ["BAS_AJAX_REQUEST"] = "true";
	
	getFormInputValues (form, parameters);
	
	var queryString = "";
	for (var i in parameters) 
	{
		if (queryString.length>0) 
			queryString += "&";
		
		queryString += encodeURIComponent(i) + "=" + encodeURIComponent(parameters[i]);
	}
	
	if (form.action.indexOf ("?") > 0)
	{
		if (url.indexOf ("?") == 0)
			url = "&" + url.substring (1);
		else if (url.indexOf ("&") != 0)
			url = "&" + url;
	}
	else if (url.indexOf ("?") != 0)
	{
		url = "?" + url;
	}

	AjaxRequest.post(
  	{
    		'url': form.action + url
    		,'onSuccess':function(req)
    			{ 
    				// reset globals
					changedAttrName = null;
					refPropId = null;  
					refAttrName = null;
					refKey = null;
				
    				var body = findTagContents (req.responseText, "form");
    				if (body != null)
    				{
    					form.innerHTML = body;
    					
 						// initialize any ext elements present in the form
 						try
 						{
							doHandleExtElements (form, false);
						}
						catch (e)
						{
							// EXT may be undefined
						}
						
    					if (oldFocusName)
    					{
							var oldFocus = document.getElementsByName (oldFocusName); 
							if (oldFocus && oldFocus.length > 0 && ! oldFocus[0].disabled)
							{
								if (isIE)
								{
									// there is a bug in IE that forces us to set the focus
									// to some other field and then set our focus
									setFocusToOtherField (form, oldFocus [0]);
								}
								oldFocus [0].focus (); 
							}
						}
    				}
    			}
    		,'onError':function (req)
    			{ 
    				alert ('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);
    			}
	    	,'async': (isIE ? false : true)
    		,'parameters': parameters
    		,'queryString': queryString
  	}
	);
	
}

function setFocusToOtherField (form, oldFocus)
{
	for (i = 0; i < form.elements.length; ++ i)
	{
		if (form.elements [i] != oldFocus &&
		    form.elements [i].type && ! form.elements [i].disabled &&
		     (form.elements [i].type == 'radio' ||
	    	  form.elements [i].type == 'checkbox' ||
		      form.elements [i].type == 'text' || 
		      form.elements [i].type == 'textarea')
		   )
		 {
		 	form.elements [i].focus ();
		 	return;
		 }

	}
}

// Return true if the application menu should be enabled
function isMenuEnabled ()
{
	// some iframes can have URL to external sites. Such iframes will give access denied acception
	// so catch it and absorb
	try
	{
		// If menu is disabled there should be a special DIV in the main frame
		if (! top.frames ['main'] || ! top.frames ['main'].document)
			return true;
		
		return top.frames ['main'].document.getElementById ('BAS_MENU_DISABLED_ID') == null;
	}
	catch (ex)
	{
		return true;
	}
}

function disableMenu ()
{
	// some iframes can have URL to external sites. Such iframes will give access denied acception
	// so catch it and absorb
	try
	{
		if (! top.frames ['main'] || ! top.frames ['main'].document)
			return;
			
		var div = top.frames ['main'].document.getElementById ('BAS_MENU_DISABLED_ID');
		if (div == null)
		{
			var div = top.frames ['main'].document.createElement('div');
			div.setAttribute ('id', 'BAS_MENU_DISABLED_ID');
			div.style.visibility = 'hidden';
			
			top.frames ['main'].document.body.appendChild (div);
		}
	}
	catch (ex)
	{
	}
}	

function enableMenu ()
{
	// some iframes can have URL to external sites. Such iframes will give access denied acception
	// so catch it and absorb
	try
	{
		if (! top.frames ['main'] || ! top.frames ['main'].document)
			return;
			
		var div = top.frames ['main'].document.getElementById ('BAS_MENU_DISABLED_ID');
		if (div != null)
		{
			top.frames ['main'].document.body.removeChild (div);
		}
	}
	catch (ex)
	{
	}
}	

// Set target for links by finding out IFRAME that the link belongs to (if any) and looking
// for its target attribitue

var elemToFindForTarget = null;
var oldFormTarget = null;

function setTargetForLink (linkElem)
{
	// find IFrame where the element belongs
	if (! top.frames ['main'] || ! top.frames ['main'].document)
		return;

	var iframes = top.frames ['main'].document.getElementsByTagName ('iframe');
	if (! iframes)
		return;
	
	elemToFindForTarget = linkElem;
	if (! linkElem.tagName || linkElem.tagName.toLowerCase () != "a")
	{
		// search for enclosing form
		while (elemToFindForTarget.parentNode)
		{
			if (elemToFindForTarget.tagName && elemToFindForTarget.tagName.toLowerCase () == "form")
				break;
				
			elemToFindForTarget = elemToFindForTarget.parentNode;
		}
		
		if (! elemToFindForTarget.parentNode)
			return;  // unknown element
	}
	
	for (kk = 0; kk < iframes.length; ++ kk)
	{
		// some iframes can have URL to external sites. Such iframes will give access denied acception
		// so catch it and absorb
		try
		{
			var elems = iframes [kk].contentWindow.document.getElementsByTagName (elemToFindForTarget.tagName);
			if (elems)
			{
				for (jj = 0; jj < elems.length; ++ jj)
				{
					if (elems [jj] == elemToFindForTarget)
					{
						// found it
						for (attrNmb = 0; attrNmb < iframes [kk].attributes.length; ++ attrNmb)
						{
							if (iframes [kk].attributes [attrNmb].name == 'target' && iframes [kk].attributes [attrNmb].value)
							{
								oldFormTarget = elemToFindForTarget.target;
								elemToFindForTarget.target = iframes [kk].attributes [attrNmb].value;
								
								// add special request parameter to indicate to the server that
								// the call is from IFRAME parent
								if (elemToFindForTarget.target != "main")
								{
									if (elemToFindForTarget.tagName.toLowerCase () == 'a')
									{
										elemToFindForTarget.href += "&iframeParent=true";
									}
									else if (elemToFindForTarget.tagName.toLowerCase () == 'form')
									{
										// we need to restore the target of the form. Otherwise ALL links
										// of the form will have new target
										setTimeout ("elemToFindForTarget.target = oldFormTarget;", 1000);
										
										var input = document.getElementById ("iframeParent");
										if (input == null) 
										{
											input = document.createElement('INPUT');
											input.type = 'hidden';
											input.name = "iframeParent";
											
											elemToFindForTarget.appendChild (input);
										}
										
										input.value = "true";
									}
								}
								
								return true;
							}
						}
					}
				}
			}
		}
		catch (e)
		{}
	}
	
	return true;
}
