
// 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.

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){
	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;
		}
	}

	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;
	//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);
	if(!result)
		input_object.focus();
		
	return result;
}
	





/*********************************************************************
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;
}

/* -- unused function? -- */
function checkOrderInput(form)
{
	if (form.txtOrderInput.value == "")
	{
		alert("Please complete the Order Input field.");
		return false;
	}
	else
	{
		return true;
	}
}


/*********************************************************************
validateQty
verifies a value was supplied for the quantity field.
*********************************************************************/
function validateQty(qty)
{
	if (isNaN(qty))
	{
		alert("Please enter a valid quantity.");
		return false;
	}
	else
	{
		if (qty < 1)
		{
			alert("You must enter a positive number.");
			return false;
		}
		else
		{
			return true;
		}
	}
}


// Formats a given 10 digit number into a nice looking phone number
// Example: given strNumber of 6041234567 you get (604) 123-4567
function FormatPhoneNumber(Number)
{
	var strInput;		// string to hold number entered
	var strTemp;		// temporary string to hold working text
	var strCurrentChar	// used to store each character for eval
	var	x				// used for looping

	strTemp = new String();
	strInput = new String(Number.value);

	// loop thru each character in string and keep only numbers and letters
	for(x=0;x<strInput.length;x++)
	{
		strCurrentChar = strInput.charAt(x);

		if ("0" <= strCurrentChar && strCurrentChar <= "9")
		{
			strTemp = strTemp.concat(strCurrentChar.toString());
		}
		if ("A" <= strCurrentChar.toUpperCase() && strCurrentChar.toUpperCase() <= "Z")
		{
			strTemp = strTemp.concat(strCurrentChar.toString());
		}
	}

	strInput = strTemp;
	strTemp = "";

	// remove leading + if present
	if (strInput.charAt(0) == "+")
	{
		strInput = strInput.substr(1,strInput.length)
	}

	// Remove leading 1 if present
	if (strInput.charAt(0) == "1")
	{
		strInput = strInput.substr(1,strInput.length)
	}

	// check if strInput is proper length (10 char including area code)
	if (strInput.length == 10)
	{
		strTemp = FormatTenDigits(strInput);
		Number.value = strTemp;
	}
	else if (strInput.length > 10)	// assume first 10 digits are number and rest is extension
	{
		strTemp = FormatTenDigits(strInput.substr(0,10));
		strTemp = strTemp.concat(" ");	// add space
		strTemp = strTemp.concat(strInput.substr(10,strInput.length-1));
		Number.value = strTemp;
	}
	else	// less than 10 digits so give back as is
	{
		Number.value = strInput;
	}
}

function FormatTenDigits(Number)
{
	var strTemp;
	strTemp = new String();
	// format output string
	// (xxx) xxx-xxxx
	strTemp = strTemp.concat("(")						// "("
	strTemp = strTemp.concat(Number.substr(0,3))		// Area code
	strTemp = strTemp.concat(") ")						// ") "
	strTemp = strTemp.concat(Number.substr(3,3))		// 3-digit part
	strTemp = strTemp.concat("-")						// "-"
	strTemp = strTemp.concat(Number.substr(6,4))		// 4-digit part	
	return strTemp;
}
	
function winPopup(strURL)
{
	var intWidth, intHeight, intTop, intLeft;
	if (window.screen.availWidth <= 1024) {
		intWidth = window.screen.availWidth-200;
		intHeight = window.screen.availHeight-200;
		intTop = 50;
		intLeft = 50;
	} else {
		intWidth = 900;
		intHeight = 700;
		intTop = (window.screen.availHeight-700)/2;
		intLeft = (window.screen.availWidth-900)/2;
	}
	window.open(strURL,"popup","width="+intWidth+",height="+intHeight+",left="+intLeft+",top="+intTop+",menubar=no,scrollbars=yes")
}	

function calendarPicker(strField)
{	var strURL, intWidth, intHeight, intTop, intLeft;
	strURL = "DatePicker.aspx?field=" + strField
	intWidth = 250;
	intHeight = 200;
	intTop = (window.screen.availHeight-intHeight)/2;
	intLeft = (window.screen.availWidth-intWidth)/2;
	window.open(strURL,"calendarPopup","width=" + intWidth + ",height=" + intHeight + ",left=" + intLeft + ",top=" +intTop + ",resizable=yes");
}
