// Revised 1.8.06


// RGP 1/11/01
// Modified the original file these functions were contained in (javascript_funcs), took out 
// non form-related funcs and added the formatCurrency func
//
// 2/27/01
// modified email validation function, replacing my own (which had problems) with emailCheck()
// which I got from javasource.com
//
// also changed code for checking whether the email flag was set (in verify()) using f.email.email
// as the check instead of e.email (used to work but now is breaking; don't know why)
//
// alert('loaded');
//

// 3/15/04
// Replaces newlines with char passes as 'delimiter'

function replaceNL(input, delimiter) {
// Converts carriage returns to delimiter

	var output = "";
	for (var i = 0; i < input.length; i++) {
		if (input.charCodeAt(i) == 13 && input.charCodeAt(i + 1) == 10) {
			alert('found 1');
			i++;
			output += delimiter;
		} else if (input.charCodeAt(i) == 13 || input.charCodeAt(i) == 10) {
			output += delimiter;
	   	} else {
	   		output += input.charAt(i);
		}
	}
	return output;
}


// 3/15/04
// ALTERED formatCurrency()
//	added 2nd argument: prefix, which can be used to prefix the number with a currency 
//  symbol, such as a dollar sign '$'
// **************************************************************************
// RGP 3.15.04
// DON'T USE THIS AS IS
// it's buggy, need to rewrite
// to get fixed decimal numbers use the toFixed() method
// Got from javascript source website
//
// function formatCurrency(num, prefix) {
// num = num.toString().replace(/\$|\,/g,'');
// 	if(isNaN(num)) num = "0";
// 	cents = Math.floor((num*100+0.5)%100);
// 	num = Math.floor((num*100+0.5)/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 (prefix + num + '.' + cents);
// }


// **************************************************************************
// Initalizes the optional property of text & textarea form controls to 
// true or false. x is the boolean, f is the form
// Used by a form that also works with verify()
//
function initFormOptional(f, x) {
	if (typeof x == "boolean") {		
		for(var i = 0; i <f.length; i++) {
			var e = f.elements[i];
			if ((e.type == "text") || (e.type == "textarea")) {
				e.optional = x;
//			alert(f.elements[i] = e.optional);
			}
		}
	}
}


// Returns the value of the selected radio button if the button is named,
// otherwise returns the index # of the radiogroup array
function getRadioButton(radiogroup) {
	var x = "";
	for (var i=0; i < radiogroup.length; i++) {
		if (radiogroup[i].checked) {
			if (!isblank(radiogroup[i].value)) x = radiogroup[i].value;
			else x = i;  
		}
	}
	return x;
}

// RGP 2.7.06
// Sets checked property of radio button if
// value is = to 'value'
// Returns true if value matched a button in the group and the button was set checked
function setRadioButton(radiogroup, value) {
	var ret;
	
	for (var i=0; i < radiogroup.length; i++) {
		// alert("value = " + value + "\nradiogroup[i].value = " + radiogroup[i].value);	
		if (radiogroup[i].value == value) {
			// alert("value = true");
			radiogroup[i].checked = true;
			ret = true;
		}
		else {
			// alert("value = false");		
			ret = false;
		}
	}
	return ret;
}

// **************************************************************************
// Returns the value of the selected option(s) from a select
// 
function getSelected(selectgroup) {
	var value = "";
//	alert("selectgroup.options.length: " + selectgroup.options.length);
	
	for (var i = 0; i < selectgroup.options.length; i++)
		if (selectgroup.options[i].selected) {	
			value += selectgroup.options[i].value;	
//			alert("value =" + value);		
		}
		return value;		
}

// **************************************************************************
// Returns the index of the selected option(s) from a select
// RGP created 12/25/02
// 
function getSelectedIndex(selectgroup) {
	var value = "";
	var idx = 0;
//	alert("selectgroup.options.length: " + selectgroup.options.length);
	
	for (var i = 0; i < selectgroup.options.length; i++) 
		if (selectgroup.options[i].selected) {	
			idx = i;
		}
		return idx;		
}

// RGP 2.7.06
// Sets item of selectgroup to 'selected' if value is == to 'value'
// Returns true if value matched and the option selected
function setSelected(selectgroup, value) {
	var ret = false;
	// alert('value = ' + value);
	for (var i = 0; i < selectgroup.options.length; i++) {
		// alert(selectgroup.options[i].value);
		if (selectgroup.options[i].value == value) {	
			// alert('value matches');
			selectgroup.options[i].selected = true;
			ret = true;
		}
	}
	return ret;
}

// **************************************************************************
// My (RGP) modified version of example 16.2, form verification from
// Javascript: The Definitive Guide. Made the msg variable global so it could be
// read by its child window. Changed newlines to <br> so message can be displayed 
// in an HTML window, rather than in an alert (Navigator 4.5 has limit on 
// character length in alerts).
// 
// DATE CREATED: 4/7/99
// 
// REVISIONS:	4/18/99 Added emailVerify function to verify valid email address
// 				4/20/99 Added 'msg2' argument to verify(). This is a message generated
// 						in the form that calls verify to be appended to msg
//				2/26/01	Replaced my emaiething I got from javascript source,
//						mine did'nt check for extra '.'s i.e. randy.perry@systame.com
// 						
// <SCRIPT LANGUAGE="JavaScript1.1">

// make msg variable global so the child window can read it (IT'S COMMENTED
// HERE BECAUSE IT NEEDS TO BE SET IN THE FORM WHICH CALLS VERIFY)
// msg=""

// ***************************************************************************
//	AUTHOR: Sandeep V. Tamhankar (stamhankar@hotmail.com)
//	SOURCE: http://javascript.internet.com/forms/check-email.html#source
// ***************************************************************************

function emailCheck (emailStr) {
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"

	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]

	// See if "user" is valid 
	if (user.match(userPat)==null) {
	    // user is not valid
	    return false
	}

	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
	    // this is an IP address
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
				return false
		    }
	    }
	    return true
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
	    return false
	}

	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>4) {
	   // the address must end in a two letter or three letter word.
	   // RGP revised 12/25/02: because of .info, .name need to allow 4-letter words
	   return false
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   var errStr="This address is missing a hostname!"
	   return false
	}

	// If we've gotten this far, everything's valid!
	return true;
}



// A utility function that returns true if a string contains only 
// whitespace characters.
function isblank(s)
{
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

// This is the function that performs form verification.  It will be invoked
// from the onSubmit() (or called before form.submit()) event handler.  
// The handler should return whatever value this function returns.
// REVISIONS
//				2/7/01	Had to modify script to deal with a bug in Win IE 5.5
//						Scope problem with msg variable, IE couldn't read it so I changed
//						the program to return 'msg' instead of returing true/false and 
//						modified the calling form accordingly. Removed error_win function
//						which opened a window and presented errors. Leave it to the calling
//						program to handle this now.
//			  12/28/02	Added this check, e.type.indexOf('select') != -1, to allow select values to be verified
//						and set the value of e.value with getSelected()
//			  12/29/02	Added check for typeof f.email; if undefined it isn't looked at

function verify(f, msg2)
{

	var empty_fields = "";
    var errors = "";
	var bad_email = "";	
	var msg = "";

	if (msg2 == null || isblank(msg2)) msg2 = "";

	
    // Loop through the elements of the form, looking for all 
    // text and textarea elements that don't have an "optional" property
    // defined.  Then, check for fields that are empty and make a list of them.
    // Also, if any of these elements have a "min" or a "max" property defined,
    // then verify that they are numbers and that they are in the right range.
    // Put together error messages for fields that are wrong.
    for(var i = 0; i < f.length; i++) {
        var e = f.elements[i];
		
        if (((e.type == "text") || (e.type == "textarea") || e.type.indexOf('select') != -1) && !e.optional) {
			// if it's a select obj, get the value and place in e.value
			if (e.type.indexOf('select') != -1) {
				e.value = getSelected(e);
			}
            // first check if the field is empty
            if ((e.value == null) || (e.value == "") || isblank(e.value)) {
                empty_fields += "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>" + (e.label != null ? e.label : e.name) + "</b>";
                continue;
            }

            // Now check for fields that are supposed to be numeric.
            if (e.numeric || (e.min != null) || (e.max != null)) { 
                var v = parseFloat(e.value);
                if (isNaN(v) || 
                    ((e.min != null) && (v < e.min)) || 
                    ((e.max != null) && (v > e.max))) {
                    errors += "- The field " + e.name + " must be a number";
                    if (e.min != null) 
                        errors += " that is greater than " + e.min;
                    if (e.max != null && e.min != null) 
                        errors += " and less than " + e.max;
                    else if (e.max != null)
                        errors += " that is less than " + e.max;
                    errors += ".<br>";
                }
            }
			if (typeof e.email != 'undefined') {
				if (e.email==true) {
					if (!emailCheck(e.value)) {
						bad_email = "<br>&#149; The <b>email</b> address you entered, &quot;" + e.value + ",&quot; is not valid. <br>";
						bad_email += "Please enter a valid email address.<br>";
					}
				}
			}
					
        }
    }

    // Now, if there were any errors, then display the messages, and
    // return true to prevent the form from being submitted.  Otherwise
    // return false
	//
	// RGP
	// added bad_email and msg2 checks
	//
    if (!empty_fields && !errors && !bad_email &&!msg2) {
    	return "";
    }
    

    if (empty_fields) {
        msg += "&#149; The following required field(s) are empty:"  + empty_fields + "<br>";
    
      if (errors) msg += "<br>";
    }
    msg += errors;
	msg += bad_email;
	msg += msg2;	
    return msg;
}
// </script>

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

