/****************************************************************
FILE: FormValidation.js

DESCRIPTION: 	This file contains a library of validation functions for Risk Rating App
  				using javascript regular expressions.  Library also contains functions 
  				that reformat fields for display or for storage.


  RISK RATING VALIDATION FUNCTIONS:

  isValidEmail 		- checks format of email address
  isValidUSPhone 	- checks format of US phone number
  isValidNumeric 	- checks for valid numeric value
  isValidInteger 	- checks for valid integer value
  isValidNotEmpty 	- checks for blank form field
  isEmpty
  isValidUSZip 		- checks for valid US zip code
  isValidUSDate 	- checks for valid date in US format
  isValidValue 		- checks a string against supplied pattern
  isValidSSN		- checks a string against supplied pattern
  inYrRangeUSDate	- checks for valid date in US format and for year range
 
  Additional FUNCTIONS:

  rightTrim 		- removes trailing spaces from a string
  leftTrim 			- removes leading spaces from a string
  trimAll 			- removes leading and trailing spaces from a string
  removeCurrency 	- removes currency formatting characters (), $
  addCurrency 		- inserts currency formatting characters
  removePercent 	- removes percent formatting characters (), %
  addPercent 		- inserts percent formatting characters
  removeCommas 		- removes comma separators from a number
  addCommas 		- adds comma separators to a number
  startsWith		- checks if the string starts with the supplied string (ignoring case)
  removeCharacters 	- removes characters from a string that match 
  passed pattern
*******************************************************************/


/****************************************************************/

function slasher(path){
	path = path.replace(new RegExp(/\\/g),"/");
	var pos = path.lastIndexOf("/");  
	return path.substring(0, pos+1);
}
function slasher2(path){
	path = path.replace(new RegExp(/\\/g),"/");
	return path;
}
function parseField(inField){
	var fArray = inField.split('_');
	if(fArray.length < 3)
		return new Array[3];
	else
		return fArray;
}
//Right trims the string...  Useful for SQL datatypes of CHAR
function RTrim(strTrim){
	var str = new String(strTrim);
	var i = 0;
	var c = "";
	var endpos = 0
	for (i = str.length; i >= 0 && endpos == 0; i = i - 1) {
		c = str.charAt(i);
		if (whitespace.indexOf(c) == -1)
			endpos = i;
	}
	return str.substring(0,endpos+1);
}
/************************************************
DESCRIPTION: Validates that a string contains a
  valid email pattern.

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS: Accounts for email with country appended
  does not validate that email contains valid URL
  type (.com, .gov, etc.) or valid country suffix.
*************************************************/
function isValidEmail( strValue) {
	var objRegExp  = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;

  	//check for valid email
  	return objRegExp.test(strValue);
  	
}
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern.
  Ex. (999) 999-9999 or (999)999-9999

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
function isValidUSPhone( strValue ) {
  var objRegExp  = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;
  //check for valid us phone with or without space between
  //area code
  return objRegExp.test(strValue);
}
/*****************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
******************************************************************/
function  isValidNumeric( strValue ) {
	var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
	//check for numeric characters
	return objRegExp.test(strValue);
}
function isValidSSN( strValue ){
    var objRegExp = /^\d{3}\-?\d{2}\-?\d{4}$/;
    return objRegExp.test(strValue);
}

/************************************************
DESCRIPTION: Validates that a string contains only
    valid integer number.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
**************************************************/
function isValidInteger( strValue ) {
	var objRegExp  = /(^-?\d\d*$)/;
	//check for integer characters
	return objRegExp.test(strValue);
}
/************************************************
DESCRIPTION: Validates that a string is not all
  blank (whitespace) characters.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
function isValidNotEmpty( strValue ) {
	var strTemp = strValue;
	strTemp = trimAll(strTemp);
	if(strTemp.length > 0){
	  return true;
	}
	return false;
}
function isEmpty( strValue ) {
	var strTemp = strValue;
	strTemp = trimAll(strTemp);
	if(strTemp.length > 0){
	  return false;
	}
	return true;
}
/************************************************
DESCRIPTION: Validates that a string a United
  States zip code in 5 digit format or zip+4
  format. 99999 or 99999-9999

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

*************************************************/
function isValidUSZip( strValue ) {
	var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;

  	//check for valid US Zipcode
  	return objRegExp.test(strValue);
}
/************************************************
DESCRIPTION: Validates that a string contains only
    valid dates with 2 digit month, 2 digit day,
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
function isValidUSDate( strValue ) {
	var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
	 //check to see if in correct format
	if(!objRegExp.test(strValue)){
	  return false; //doesn't match pattern, bad date
	}else{
	  var strSeparator = strValue.substring(2,3) 
	  var arrayDate = strValue.split(strSeparator); 
	  //create a lookup for months not equal to Feb.
	  var arrayLookup = { '01' : 31,'03' : 31, 
	                      '04' : 30,'05' : 31,
	                      '06' : 30,'07' : 31,
	                      '08' : 31,'09' : 30,
	                      '10' : 31,'11' : 30,'12' : 31}
	  //Pick Day from MM/DD/YYYY
	  //var intDay = parseInt(arrayDate[0],10); 
	  var intDay = parseInt(arrayDate[1],10); 
	
	  //check if month value and day value agree
	  if(arrayLookup[arrayDate[0]] != null) {
	    if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
	      return true; //found in lookup table, good date
	  }
	  
	  //check for February
	  //Pick Day from MM/DD/YYYY
	  //var intMonth = parseInt(arrayDate[1],10);
	  var intMonth = parseInt(arrayDate[0],10);
	  
	  if (intMonth == 2) { 
	     var intYear = parseInt(arrayDate[2]);
	     if (intDay > 0 && intDay < 29) {
	         return true;
	     }
	     else if (intDay == 29) {
	       if ((intYear % 4 == 0) && (intYear % 100 != 0) || 
	           (intYear % 400 == 0)) {
	            // year div by 4 and ((not div by 100) or div by 400) ->ok
	           return true;
	       }   
	     }
	  }
	}  
	return false; //any other values, bad date
}
/************************************************
DESCRIPTION: Validates that a string matches
  a valid regular expression value.

PARAMETERS:
   strValue - String to be tested for validity
   strMatchPattern - String containing a valid
      regular expression match pattern.

RETURNS:
   True if valid, otherwise false.
*************************************************/
function isValidValue( strValue, strMatchPattern ) {
	var objRegExp = new RegExp( strMatchPattern);
	return objRegExp.test(strValue);
}
function startsWith(strValue, strStr){
   var objRegExp = new RegExp("^"+strStr,"i");
   return objRegExp.test(strValue);
}
function endsWith(strValue, strStr){
   var objRegExp = new RegExp(strStr+"$","i");
   return objRegExp.test(strValue);
}
/************************************************
DESCRIPTION: Trims trailing whitespace chars.

PARAMETERS:
   strValue - String to be trimmed.

RETURNS:
   Source string with right whitespaces removed.
*************************************************/
function rightTrim( strValue ) {
	var objRegExp = /^([\w\W]*)(\b\s*)$/;
	if(objRegExp.test(strValue)) {
		 //remove trailing a whitespace characters
		 strValue = strValue.replace(objRegExp, '$1');
	}
	return strValue;
}
/************************************************
DESCRIPTION: Trims leading whitespace chars.

PARAMETERS:
   strValue - String to be trimmed

RETURNS:
   Source string with left whitespaces removed.
*************************************************/
function leftTrim( strValue ) {
	var objRegExp = /^(\s*)(\b[\w\W]*)$/;

	if(objRegExp.test(strValue)) {
	 	//remove leading a whitespace characters
		strValue = strValue.replace(objRegExp, '$2');
	}
  return strValue;
}
/************************************************
DESCRIPTION: Removes leading and trailing spaces.

PARAMETERS: Source string from which spaces will
  be removed;

RETURNS: Source string with whitespaces removed.
*************************************************/
function trimAll( strValue ) {
 	var objRegExp = /^(\s*)$/;
    //check for all spaces
	if(objRegExp.test(strValue)) {
	   strValue = strValue.replace(objRegExp, '');
	   if( strValue.length == 0)
	      return strValue;
	}

	//check for leading & trailing spaces
	objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
	try{
	if(objRegExp.test(strValue)) {
	    //remove leading and trailing whitespace characters
	    strValue = strValue.replace(objRegExp, '$2');
	}
	}catch(err){
	
	}
  	return strValue;
}
/************************************************
DESCRIPTION: Removes currency formatting from
  source string.

PARAMETERS:
  strValue - Source string from which currency formatting
     will be removed;

RETURNS: Source string with commas removed.
*************************************************/
function removeCurrency( strValue ) {
	var objRegExp = /\(/;
	var strMinus = '';
	
	//check if negative
	if(objRegExp.test(strValue)){
		strMinus = '-';
	}
	
	objRegExp = /\)|\(|[,]/g;
	strValue = strValue.replace(objRegExp,'');
	if(strValue.indexOf('$') >= 0){
		strValue = strValue.substring(1, strValue.length);
	}
	return strMinus + strValue;
}
/************************************************
DESCRIPTION: Formats a number as currency.

PARAMETERS:
  strValue - Source string to be formatted

REMARKS: Assumes number passed is a valid
  numeric value in the rounded to 2 decimal
  places.  If not, returns original value.
*************************************************/
function addCurrency2( strValue ) {
    strValue = ''+parseFloat(strValue).toFixed(2);
  	var objRegExp = /-?[0-9]+\.[0-9]{2}$/;
	if( objRegExp.test(strValue)) {
		//objRegExp.compile('^-');
		strValue = addCommas(strValue);
		if (objRegExp.test(strValue)){
			strValue = '(' + strValue.replace(objRegExp,'') + ')';
		}
		return '$' + strValue;
	}else{
		return false;
	}
}
function addCurrency(num) {
	num = num.toString().replace(/\$|\,/g, '');
	if (isNaN(num))
		return false;
	var sign = (num == (num = Math.abs(num)));
	num = Math.floor(num * 100 + 0.50000000001);
	var cents = num % 100;
	num = Math.floor(num / 100).toString();
	if (cents < 10)
		cents = "0" + cents;
	for ( var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
		num = num.substring(0, num.length - (4 * i + 3)) + ','
				+ num.substring(num.length - (4 * i + 3));
	return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

function addPercent( strValue ) {
    strValue = ''+(parseFloat(strValue).toFixed(2));
    var sections = strValue.split('.');
    if(sections.length > 1){
       if(sections[0].length == 0)
          sections[0] = '0';
       else
          sections[0] = parseInt(sections[0]);
          
       if(sections[1].length == 0)
          sections[1] = '0';
       else
          sections[1] = sections[1]; //parseInt(sections[1]) - leads to triming of leading zero in decimal side
          
       if(parseFloat(strValue) < 0.0){
       	  sections[0] = parseInt(removeCharacters('' + sections[0], '-'));
       	  strValue = '-'+sections[0]+"."+sections[1];
       }else {
          strValue = ''+sections[0]+"."+sections[1];
       }
    }else{
       strValue = ''+parseInt(sections[0]);+".0";
    }
    return strValue+'%';    
}
function add100Percent( strValue ) {
    strValue = ''+(parseFloat(strValue).toFixed(2));
    var sections = strValue.split('.');
    if(sections.length > 1){
       if(sections[0].length == 0)
          sections[0] = '0';
       else{
          if(parseInt(sections[0])>100)
             sections[0]='100';
          else if(parseInt(sections[0]) < 0)
          	 sections[0]='0';
          else
             sections[0] = parseInt(sections[0]);
       }   
       if(sections[1].length == 0)
          sections[1] = '0';
       else
          sections[1] = sections[1]; //parseInt(sections[1]) - leads to triming of leading zero in decimal side
          
       strValue = ''+sections[0]+"."+sections[1];
    }else{
       if(parseInt(sections[0])>100)
          sections[0]='100';
       strValue = ''+parseInt(sections[0]);+".0";
    }
    return strValue+'%';    
}
function removePercent(strValue){
    return strValue.replace('%','');
}
function removeOddChars(strValue){
	strValue = strValue.replaceAll(/^[\s(&nbsp;)]+/g ,' ');
	strValue = strValue.replaceAll(/^[\s(&gt;)]+/g,'>');
	strValue = strValue.replaceAll(/^[\s(&lt;)]+/g,'<');
	strValue = strValue.replaceAll(/^[\s(&amp;)]+/g,'&');
    return strValue;
}
function addInterest( strValue ) {
	strValue = ''+ parseFloat(strValue).toFixed(4);
    /*var sections = strValue.split('.');
    if(sections.length > 1){
       if(sections[0].length == 0)
          sections[0] = '0';
       else
          sections[0] = parseInt(sections[0]);
          
       if(sections[1].length == 0)
          sections[1] = '0';
       else
          sections[1] = sections[1]; //parseInt(sections[1]) - leads to triming of leading zero in decimal side
          
       strValue = ''+sections[0]+"."+sections[1];
    }else{
       strValue = ''+parseInt(sections[0]);+".0";
    }*/
    return strValue+'%';
}
function removeInterest(strValue){
    return strValue.replace('%','');
}
function makeInteger( strValue ) {
	var objRegExp = /[^0-9]/;
    return objRegExp.exec(strValue);
	
}
/************************************************
DESCRIPTION: Removes commas from source string.

PARAMETERS:
  strValue - Source string from which commas will
    be removed;

RETURNS: Source string with commas removed.
*************************************************/
function removeCommas( strValue ) {
	var objRegExp = /,/g; //search for commas globally
	return strValue.replace(objRegExp,'');
}
function removeDecimal( strValue ) {
	var objRegExp = /./g; //search for commas globally
	return strValue.replace(objRegExp,'');
}
/************************************************
DESCRIPTION: Inserts commas into numeric string.

PARAMETERS:
  strValue - source string containing commas.

RETURNS: String modified with comma grouping if
  source was all numeric, otherwise source is
  returned.

REMARKS: Used with integers or numbers with
  2 or less decimal places.
UPDATED: Works for any number of decimal places.
*************************************************/
function addCommas( strValue ) {
    try{
  	var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})');
  	var decValue = '';
	//check for match to search criteria
	if(strValue.indexOf(".") != -1) {
		decValue = strValue.substr(strValue.indexOf(".")+1);
		strValue = strValue.substring(0, strValue.indexOf("."));
	}
	while(objRegExp.test(strValue)) {
	   strValue = strValue.replace(objRegExp, '$1,$2');
	}}catch(err){}
	if(decValue != '')
		strValue = strValue + "." + decValue;
  	return strValue;
}
function customRegExp(strValue, regEx){
    //alert(strValue+"<:>"+regEx);
  	var objRegExp  = new RegExp(regEx);
	//check for match to search criteria
	return objRegExp.test(strValue);

}
/************************************************
DESCRIPTION: Removes characters from a source string
  based upon matches of the supplied pattern.

PARAMETERS:
  strValue - source string containing number.

RETURNS: String modified with characters
  matching search pattern removed

USAGE:  strNoSpaces = removeCharacters( ' sfdf  dfd', '\s*')
*************************************************/
function removeCharacters( strValue, strMatchPattern ) {
	var objRegExp =  new RegExp( strMatchPattern, 'gi' );
	//replace passed pattern matches with blanks
	return strValue.replace(objRegExp,'');
}

/************************************************
DESCRIPTION: Validates that a string contains only
    valid dates with 2 digit month, 2 digit day,
    4 digit year. Also checks for year range.
    Date separator can be ., -, or /.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy

PARAMETERS:
   strValue - String to be tested for validity
   frmYear	- starting year of the range (inclusive)
   toYear	- ending year of the range (inclusive)

RETURNS:
   True if valid, otherwise false.
*************************************************/
function inYrRangeUSDate(strValue, frmYear, toYear) {
	//check date for validity and US format
	if(!isValidUSDate(strValue))
		return false;
		
	var strSeparator = strValue.substring(2,3) 
	var arrayDate = strValue.split(strSeparator); 
	var intYear = parseInt(arrayDate[2],10);
	//check date for range validity
	if(intYear < parseInt(frmYear,10) || intYear > parseInt(toYear,10))
		return false;
	
	return true;
}

function changeDateFrmt(val) {
	//var obj = eval(object);
	//var val = obj.value;
	//Replacing / & . with -
	val = val.replace(/\//g,'-');
	val = val.replace(/\./g,'-');
	//obj.value = val;
	
	//Converting to proper mm/dd/yyyy format
	var currentDate = val;
	var slash;
	if(trimAll(currentDate).length > 0){
		slash = currentDate.split("-");
		if(slash.length > 2){
		}else{
			slash = currentDate.split("\\");
			if(slash.length > 2){
			}else{
				slash = currentDate.split("/");
				if(slash.length > 2){
				}else{
					slash = currentDate.split(".");
				}
			}
		}
	}
	if(slash != null && slash.length >= 2){
	    if(slash.length < 3 || slash[2] == null || trimAll(slash[2]).length == 0){
	       var date = new Date;
	       var newdate = slash[0]+'/'+slash[1]+'/'+date.getYear();
	       slash = newdate.split("/");
	    }
		if(slash[2].length == 1)
		   slash[2] = '200'+slash[2];
		if(slash[2].length == 2)
		   slash[2] = '20'+slash[2];
		if(slash[0].length == 1)
		   slash[0] = '0'+slash[0];
		if(slash[1].length == 1)
		   slash[1] = '0'+slash[1];
		val = slash[0]+'-'+slash[1]+'-'+slash[2];
	}	
	
	return val;
}
///RULES Function Handlers
function Rule_01_Editor_OnKeyPress(obj){
	var ar = obj.name.split(':');
	var ob = document.getElementById('Rule_01_Editor:'+ar[1]+':0');
	ob.checked = true;
}
function Rule_01_Editor_Add(obj){
	AjaxManageRules(sysCurrentForm, "Add" , "Rule01table");
}
function Rule_01_Editor_Update(obj){
	AjaxManageRules(sysCurrentForm, "Update" , "Rule01table");
}
function Rule_01_Editor_Delete(obj){
	AjaxManageRules(sysCurrentForm, "Delete" , "Rule01table");
}
function Rule_01_Editor_Refresh(obj){
	AjaxManageRules(sysCurrentForm, "Refresh" , "Rule01table");
}
function Rule_01_Get_Grid_Values(){ 
	var rows = document.getElementById('Rule_01_Rows');
	var title = rows.title.split(':');
	var cnt = title[1];
	//alert(cnt);
	var tmpFormValues="";
	var ob = null;
	try{
		for(var r=0;r<cnt;r++){
			for(var c=0;c<9;c++){
				//alert("GET ID:"+'Rule_01_Editor:'+r+':'+c);
				ob = document.getElementById('Rule_01_Editor:'+r+':'+c);
				if(c==0)
					tmpFormValues += "RowKey:"+r+"=" + ob.title + "&"; 

				var elClass = ob.className;
				var elName  = ob.id;
				if(trimAll(elName).length<1)
					elName = ob.name;
				if(trimAll(elName).length>0){
					var elType  = ob.type;
					var elValue = '';
					switch(elType){
					case 'hidden':
						//alert("getting:"+elName);
						elValue = ob.value; 
						break;
					case 'undefined': 
						return null;
					case 'radio': 
						elValue = ob.checked; 
						if(elValue)
							elValue = "true";
						else
							elValue = "false";
						break;
					case 'checkbox': 
						elValue = ob.checked; 
						if(elValue){
							if(elClass.match("numeric"))
							   elValue = '1';
							else
							   elValue = "true";
						}else{
							if(elClass.match("numeric"))
							   elValue = '0';
							else
							   elValue = "false";
						}
						break;

					default: elValue = ob.value; break;
					}
					if(trimAll(elValue).length > 0){
						if(elClass.match("currency")){
							elValue = removeCurrency(elValue);
						}else if(elClass.match("percent")){
							elValue = removePercent(elValue);
						}else if(elClass.match("interest")){
							elValue = removePercent(elValue);
						}else if(elClass.match("numeric")){
							elValue = removeCommas(elValue);
						}
					}
					if(elValue=="NaN" || elValue=="NaN%")
						elValue = "";
					tmpFormValues += elName + "=" + encodeURIComponent(elValue) + "&"; 
				}
			}
		}
	}catch(e){
		alert("RuleDataLoad Failure:"+e.description);
	}
	return  tmpFormValues;
}
function Rule_01_Get_SummaryGrid_Values(){ 
	var rows = document.getElementById('Rule_01_Rows');
	var tmpFormValues="";
	var ob = null;
	try{
		for(var c=0;c<9;c++){
			//alert("GET ID:"+'Rule_01_Editor:'+r+':'+c);
			ob = document.getElementById('Rule_01_Editor:Summary:'+c);
			var elClass = ob.className;
			var elName  = ob.id;
			if(trimAll(elName).length<1)
				elName = ob.name;
			if(trimAll(elName).length>0){
				var elType  = ob.type;
				var elValue = '';
				switch(elType){
				case 'hidden':
					//alert("getting:"+elName);
					elValue = ob.value; 
					break;
				case 'undefined': 
					return null;
				case 'radio': 
					elValue = ob.checked; 
					if(elValue)
						elValue = "true";
					else
						elValue = "false";
					break;
				case 'checkbox': 
					elValue = ob.checked; 
					if(elValue){
						if(elClass.match("numeric"))
						   elValue = '1';
						else
						   elValue = "true";
					}else{
						if(elClass.match("numeric"))
						   elValue = '0';
						else
						   elValue = "false";
					}
					break;

				default: elValue = ob.value; break;
				}
				if(trimAll(elValue).length > 0){
					if(elClass.match("currency")){
						elValue = removeCurrency(elValue);
					}else if(elClass.match("percent")){
						elValue = removePercent(elValue);
					}else if(elClass.match("interest")){
						elValue = removePercent(elValue);
					}else if(elClass.match("numeric")){
						elValue = removeCommas(elValue);
					}
				}
				if(elValue=="NaN" || elValue=="NaN%")
					elValue = "";
				tmpFormValues += elName + "=" + encodeURIComponent(elValue) + "&"; 
			}
		}
	}catch(e){
		alert("RuleDataLoad Failure:"+e.description);
	}
	return  tmpFormValues;
}
function xmlRule01HTMLResponse(req, Target){
	if (req.readyState == 4 && (req.status == 200)) {
		var htmlReps = req.responseText;
		document.getElementById(Target).innerHTML= htmlReps;

		FWTableRule.Init("Rule_01_Editor");
		try{
			document.getElementById("imgPleaseWait").style['visibility']="hidden";
		}catch(err){
			alert("[sbGeneral].xmlRule01HTMLResponse."+localTransitionForm+": ERROR 0289: Object 'imgPleaseWait' not found on page. \nRemove all references from your JavaScript, or added the image object to the Parent HTML file.");
		}
	} else if (req.readyState == 4 && (req.status != 200)) {
		document.getElementById("imgPleaseWait").style['visibility']="hidden";
		alert("[sbGeneral].xmlRule01HTMLResponse."+sysCurrentForm+": ERROR 0880: Your request may have timed out. Please try again."+req.status);
	}
}
function AjaxManageRules(servletName, Action, Target) {
	try{
		document.getElementById("imgPleaseWait").style['visibility']="visible";
		localTransitionForm = servletName;
		sysAction 			= Action;
		sysAccess 			= 'Rule';
		var cmd;
		var method 			= 'POST';
		servletName 		= "/"+sysProjectName+"/"+servletName;
		var modifiedurl 	= servletName.replace(/^http:\/\/[^\/]+\//i, "http://"+window.location.hostname+":"+window.location.port+"/");
		var url 			= modifiedurl; //replace URL's root domain with dynamic root domain, for ajax security sake
		var req = getRequestObj();
		if(req){
			try{
				try{
					req.onreadystatechange=function(){
						xmlRule01HTMLResponse(req, Target);
					};
		        	var bResult = setGlobalFormValuesFromMemory(sysCurrentForm);
					var toSend;
					try{
						if(Action == "Add")
							toSend = Rule_01_Get_SummaryGrid_Values() + getGlobalValuesFromMemory(sysCurrentForm);
						else
							toSend = Rule_01_Get_Grid_Values() + getGlobalValuesFromMemory(sysCurrentForm);
					}catch(err){
						alert("AjaxRefreshRules FAILED:"+err);
					}
					try{
						try{
							document.getElementById("imgPleaseWait").style['visibility']="visible";
						}catch(err){
							alert("[sbGeneral].AjaxRefreshRules."+localTransitionForm+": ERROR 0289: Object 'imgPleaseWait' not found on page. \nRemove all references from your JavaScript, or added the image object to the Parent HTML file.");
						}
						req.open(method, url, true);
						req.setRequestHeader("Content-length", toSend.length);
						req.setRequestHeader("content-type","application/x-www-form-urlencoded");	        
						req.send(toSend);
					}catch(err){
						alert("[sbGeneral].AjaxRefreshRules."+sysCurrentForm+": ERROR 9901:"+err.description);
						document.getElementById(Target).innerHTML="<p>ERROR: Failed to return proper HTML</p>";
						document.getElementById("imgPleaseWait").style['visibility']="hidden";
					}

		        }catch(err){
		        	alert("[sbGeneral].AjaxRefreshRules."+sysCurrentForm+": ERROR 9902:"+err.description);
		        	document.getElementById("imgPleaseWait").style['visibility']="hidden";
		        }
			}catch(err){
				req = null;
				alert("[sbGeneral].AjaxRefreshRules: ERROR 9903:"+err.description);
				document.getElementById("imgPleaseWait").style['visibility']="hidden";
			}
		}else{
			req = null;
			alert("[sbGeneral].AjaxRefreshRules."+localTransitionForm+": ERROR 9904: Your browser does not seem to support XMLHttpRequest.");
			document.getElementById("imgPleaseWait").style['visibility']="hidden";
		}
	}catch(err){
		req = null;
		alert("[sbGeneral].AjaxRefreshRules."+localTransitionForm+": ERROR 9905:"+err.description);
		document.getElementById("imgPleaseWait").style['visibility']="hidden";
	}
	
}

