// Copyright © 1999, 2001 ACCPAC International Ltd.  All Rights Reserved. 

function clearccfields()
{
}

/****************************************************************************
emailCheckSetFocus()
Wrapper for the emailCheck() function.  This will accept the actual form
object so we can set focus to it if it fails validation.

*****************************************************************************/
function emailCheckSetFocus(theField){
	if(!emailCheck(theField.value)){
		theField.focus();
		return false;
	}
	return true;
}





/* 1.1.2: Fixed a bug where trailing . in e-mail address was passing
            (the bug is actually in the weak regexp engine of the browser; I
            simplified the regexps to make it work).
   1.1.1: Removed restriction that countries must be preceded by a domain,
            so abc@host.uk is now legal.  However, there's still the 
            restriction that an address must end in a two or three letter
            word.
     1.1: Rewrote most of the function to conform more closely to RFC 822.
     1.0: Original  */

// This script and many more are available free online at -->
// The JavaScript Source!! http://javascript.internet.com -->

// Begin
function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")




/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	alert("Please enter a valid email address.  Email address seems incorrect (check @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    alert("Please enter a valid email address.  The username doesn't seem to be valid.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("Please enter a valid email address.  Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("Please enter a valid email address.  The domain name doesn't seem to be valid.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   alert("Please enter a valid email address.  The address must end in a three-letter domain, or two letter country.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="Please enter a valid email address.  This address is missing a hostname!"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}



//Check browser type (IE or not?)
var browserVersion=navigator.appVersion;
var result=browserVersion.match(/MSIE/);
if(result!=null)
	isIE=true;
else
	isIE=false;
	

function setInitialFocus()
{
    if( document.forms.length > 0 )
     if( document.forms[0].name == "formssearch" )
      document.formssearch.ssearch.focus();
}


// The following fixes a bug in the CFFORM checknumber function.
function _CF_checknumber(object_value)
    {
    //Returns true if value is a number or is NULL
    //otherwise returns false	

    if (object_value.length == 0)
        return true;

    // The following line has been inserted for eTransact so that one decimal point is
    // not considered a number.
    if (object_value == ".")
        return false;        

    //Returns true if value is a number defined as
    //   having an optional leading + or -.
    //   having at most 1 decimal point.
    //   otherwise containing only the characters 0-9.
	var start_format = " .+-0123456789";
	var number_format = " .0123456789";
	var check_char;
	var decimal = false;
	var trailing_blank = false;
	var digits = false;

    //The first character can be + - .  blank or a digit.
	check_char = start_format.indexOf(object_value.charAt(0))
    //Was it a decimal?
	if (check_char == 1)
	    decimal = true;
	else if (check_char < 1)
		return false;
        
	//Remaining characters can be only . or a digit, but only one decimal.
	for (var i = 1; i < object_value.length; i++)
	{
		check_char = number_format.indexOf(object_value.charAt(i))
		if (check_char < 0)
			return false;
		else if (check_char == 1)
		{
			if (decimal)		// Second decimal.
				return false;
			else
				decimal = true;
		}
		else if (check_char == 0)
		{
			if (decimal || digits)	
				trailing_blank = true;
        // ignore leading blanks

		}
	        else if (trailing_blank)
			return false;
		else
			digits = true;
	}	
    //All tests passed, so...
    return true
    }
	
	


/********************************************************************
replace()
Author: lars
Replace values in a string with the specified replacement values.
Return the modified string.

Loop through the source string.
	If the index is larger than the length of the string, exit.
	From the index position, read the first chunk that 
	is the same length as the target string.
	If found
		Move the index to the first char after the chunk.
		Write the replacement string to the output string.
	Else
		Copy the current char to the output string.
		Increment the index.
	End if
********************************************************************/
function replace(sourceString, targetString, replacementString){	

	var retString = "";
	var targetLen = targetString.length;
	var sourceLen = sourceString.length;
	var chunk = "";
	var i = 0;
	
	if((targetLen > sourceLen) || sourceString == "" || targetString == "")
		return "";
	
	while(i < sourceString.length){
		chunk = sourceString.substr(i,targetLen);
		if(chunk == targetString){
			retString = retString + replacementString;
			i = i + targetLen;
		}
		else {
			retString = retString + sourceString.substr(i,1);
			i++;
		}
	}
	return retString;
}




/********************************************************************
checkNumEngine
Author: lars	
Parameters:
numberstring = string to test.
maxleftdigits = maximum number of integer digits.
maxrightdigits = maximum number of decimal digits.
tschar = thousands separator character.
dpchar = decimal point character.
strictleftdigits  = true/false
	If true, return false if the number contains no decimal places and
	the number of digits exceeds the maxleftdigit value.
	If false, don't check.
	ie:
	If set to TRUE, 123 with maxleftdigits=2 will return false.
	If set to FALSE, 123 with maxleftdigits=2 will return true.
	
Test if numberstring matches one of these criteria:
1) An integer with no more than x chars where x is the sum of maxleftdigits
   and maxrightdigits.
2) A float with less than maxleftdigits integer digits and less than 
   maxrightdigits decimal digits.

If a float, the decimal point is represented by a dpchar.
Thousands separators are represented by commas tschar and will be stripped out
during the processing.

An empty string returns false.
********************************************************************/
function checkNumEngine(numberstring, maxleftdigits, maxrightdigits, tschar, dpchar, fracOk, strictleftdigits){
	var maxleftdigits = (maxleftdigits - 0);
	var maxrightdigits = (maxrightdigits - 0);
	var maxdigits = maxleftdigits + maxrightdigits;
	var numString = replace(numberstring, tschar, ""); //Strip thousands separators.
	
	//If multiple decimal characters, return false.
	if(numString.indexOf(dpchar, numString.indexOf(dpchar,0)+1)>-1){
		return false;
	}

	var digitString = replace(numString, dpchar, "");

	//Total digit count test.
	if(digitString.length > maxdigits){
		return false;
	}
	//Test for non-digits.
	var result = digitString.match(/[^0123456789]/);
	if(result != null){
		return false;
	}

	//Test for valid number.
	if(isNaN(parseInt(digitString))){
		return false;
	}

	var decPlace=numString.indexOf(dpchar);

	if(decPlace > -1){
		//If fractional quantities not allowed...
		if(!fracOk){
			return false;
		}
		//Test for too many left digits.
		if(decPlace > maxleftdigits){
			return false;
		}
		//Test for too many right digits.
		else if((numString.length - decPlace - 1) > maxrightdigits){
			return false;
		}
		//Test for decimal place if no right digits are allowed
		else if(maxrightdigits < 1){
			return false;
		}
	}
	else if (strictleftdigits) {
		//Test for too many left digits in a number with no decimal place.
		if (digitString.length > maxleftdigits)
			return false;
	}

	return true;

}




















/*********************************************************************
checkNum
Author: lars
A wrapper for the checkNumEngine().
*********************************************************************/
function checkNum(form_object, input_object, object_value){

	var maxleftdigits = input_object.maxleftdigits - 0;
	var maxrightdigits = input_object.maxrightdigits - 0;
	var fracOk = input_object.fracOk;
	var tschar=input_object.tschar;
	var dpchar=input_object.dpchar;
	var strictleftdigits=input_object.isSimply;
	//alert("left:" + maxleftdigits + " right:" + maxrightdigits + " ts:" + tschar + " dp:" + dpchar);

	if(isNaN(maxleftdigits)){
		input_object.focus();
		alert("Missing maxleftdigits passthrough parameter.");
		return false;
	}
	if(isNaN(maxrightdigits)){
		input_object.focus();	
		alert("Missing maxrightdigits passthrough parameter.");
		return false;
	}
	if(!tschar){
		input_object.focus();	
		alert("Missing tschar passthrough parameter.");
		return false;
	}
	if(!dpchar){
		input_object.focus();	
		alert("Missing dpchar passthrough parameter.");
		return false;
	}
	if(typeof(input_object.fracOk) == "undefined"){
		alert("Missing fracOk passthrough parameter.");
		return false;
	}
	result=checkNumEngine(object_value, maxleftdigits, maxrightdigits, tschar, dpchar, fracOk, strictleftdigits);
	if(!result)
		input_object.focus();
		
	return result;
}
	

/*********************************************************************
validateAnItem
Author: lars
Validates the specified field using checkNum() and if successful, 
assigns theRowNumber to currentrow and "add" to submittype.  
This assignment is done to
indicate which item is being submitted.  Then we submit the form.
This function was created to provide the functionality
normally provided by CF's client-side validation.
*********************************************************************/
function validateAnItem(theForm, theField, theRowNumber){
	if(checkNum(theForm, theField, theField.value)){
		//If the validation succeeded, create a mock submit element
		//so the action template knows which item's quantity
		//to update.
		theForm.submittype.value = "add";
		theForm.currentrow.value = theRowNumber;
		theForm.submit();
	}
	else {
		alert(theField.errmsg);
	}
}


/*********************************************************************
validateAllItems
Author: lars
Validates the specified form's fields using checkNum() and if successful, 
assigns "update" to the submittype element and then submits the form.
This function was created to provide the functionality
normally provided by CF's client-side validation.
**********************************************************************/
function validateAllItems(theForm, theSubmitType, theCurrentRow){
// Called when we want to update ALL quantities at once.
// Validate all input fields by walking thru all elements
// of the type, input.
	var theElements = theForm.elements;
	var clean = true;
	for(i=0; i<theElements.length; i++){
		if(theElements[i].type == "text"){
			if(!checkNum(theForm, theElements[i], theElements[i].value)){
				alert(theElements[i].errmsg);
				clean = false;
				break;
			}
		}
	}
	if(clean){
        needReminder = 0;
		theForm.submittype.value=theSubmitType;
		theForm.currentrow.value=theCurrentRow;
		theForm.submit();
	}
}


/*********************************************************************
convertCharToRegexChar
Author: lars
Replace any special chars with its regex equivalent.
*********************************************************************/
function convertCharToRegexChar(inChar){
	var outChar;
	switch(inChar){
		case " ":
			outChar = "\\s";
			break;
		case "/":
			outChar = "\/";
			break;
		case "\\":
			outChar = "\\\\";
			break;
		case ".":
			outChar = "\\.";
			break;
		case "*":
			outChar = "\\*";
			break;
		case "+":
			outChar = "\\+";
			break;
		case "?":
			outChar = "\\?";
			break;
		case "|":
			outChar = "\\|";
			break;
		case "(":
			outChar = "\\(";
			break;
		case ")":
			outChar = "\\)";
			break;
		case "[":
			outChar = "\\[";
			break;
		case "]":
			outChar = "\\]";
			break;
		case "{":
			outChar = "\\{";
			break;
		case "}":
			outChar = "\\}";
			break;
		default:
			outChar = inChar;
	}
	return outChar;
}


/*********************************************************************
convertNumberToStandardChars
Author: lars
Replace custom thousand and dec chars in a string 
with standard comma and dot chars.
*********************************************************************/
function convertNumberToStandardChars(inString, tschar, dpchar){
	var inString;
	var targetPattern = eval("/" + convertCharToRegexChar(unescape(tschar)) + "/g");
	inString = inString.replace(targetPattern, "");
	targetPattern = eval("/" + convertCharToRegexChar(unescape(dpchar)) + "/g");
	inString = inString.replace(targetPattern, ".");
	return inString;
}	

/*********************************************************************
formatDecimalChar
Author: lars
Replace decimal char with value of dpchar.  Assumes inString contains
a numeric string of the format, 9999.99.
*********************************************************************/
function formatDecimalChar(inString, dpchar){
	var inString;
	var targetPattern = /\./;
	inString = inString.replace(targetPattern, unescape(dpchar));
	return inString;
}

/*********************************************************************
padWithZeroes
Pad out a numeric string with zeroes so that the decimal places are
fully represented.  Return the padded string.
*********************************************************************/
function padWithZeroes(inString, decPlaces){
	var outString;
	var addZeroes = 0;
	var outString = inString;
	//If no decPlaces specified, simply return the inString.
	
	if(decPlaces > 0){
		var decPos = inString.indexOf(".");
		var strLen = inString.length;
		
		if(decPos > -1){
			addZeroes = decPlaces - (strLen - (decPos + 1));
		}
		else{
			//If no decimal found in the string...
			outString = outString + ".";
			addZeroes = decPlaces;
		}
		
		//Now pad with additional zeroes if needed
		for(idx=0; idx < addZeroes; idx++){
			outString = outString + "0";
		}
	}
	return outString;
}


/*********************************************************************
versionCommon
Always keep this function at the bottom of the file and update its
return value whenever this file is modified.  It will be called by 
the jsversion.cfm file to show the user
which version of the common.js file is currently in use.
*********************************************************************/
function versionCommon(){
	return '3.3.20021114a';
}
