/* ------------------------------------------------------------------------------

Filename:  js_common.js
Author:  None, retrieved most from internet
Date Created:  5/22/03
Project:  M&M Server
       
Notes
*****
Many common JavaScript functions.

Revision History
****************
Change date: 
Change by: 
Change notes: 
------------------------------------------------------------------------------- */
<!--
var whitespace = " \t\n\r";
var defaultEmptyOK = false

function uncheck(checkbox_field,checkbox_value,nbr_items) {
// see if any other items have been checked.  If so, uncheck them (excluding the one we just checked)
if (nbr_items > 1) {
    for (var idx = 0; idx < checkbox_field.length;idx++) {
        if (checkbox_field[idx].checked && (checkbox_field[idx].value != checkbox_value)) 
            checkbox_field[idx].checked = false;
    }
}
return;
}

function isNumber(inputStr) {
// see if a valid number
var num = parseInt(inputStr, 10);
if (isNaN(num))
    return false;
return true;
}

function inRange(inputStr, lo, hi) {
// see if number is in range
var num = parseInt(inputStr, 10);
if (num < lo || num > hi)
        return false;
return true;
}

function fieldIsEmpty(fieldname,fieldtitle) {
// if form field is empty, display alert and set focus
var fieldval = fieldname.value;
if (isWhitespace(fieldval)) {
    return_err(fieldtitle + ' must not be empty.',fieldname);
    return true;
}
return false;
}

function fieldIsPositiveNumber(fieldname,fieldtitle,minvalue) {
// if form is NOT positive number, display alert and set focus
var fieldval = fieldname.value;
disperr = false;
if (isNumber(fieldval)) {
    if (parseInt(fieldval,10) <  minvalue) disperr = true;
} else disperr = true;
if (disperr) 
    return return_err(fieldtitle + ' must be a positive integer greater than or equal to ' + minvalue + '.',fieldname);
return true;
}

function isChecked(nbr_items,fieldname) {
// return checked item (if any)
if (nbr_items == 1) {
    if (fieldname.checked) return fieldname.value;
} else {
    for (var idx=0; idx < nbr_items; idx++) {
        if (fieldname[idx].checked) return fieldname[idx].value;
    }
}
return 0;
}

function radioIsChecked(fieldname) {
// return checked item (if any)
for (var idx=0; idx < fieldname.length; idx++) {
    if (fieldname[idx].checked) return 1;
}
return 0;
}

// PURPOSE:  Check to see if the string passed in is a valid time.
//	A valid time is defined as a string which is postfixed with either
//  "PM" or "AM".  Next it checks to see if there is a colon in the
//  string.  If there is, it makes sure that at least one digit preceeds
//  it and two proceed it.

function IsTime(strTime)
{
var strTestTime = new String(strTime);
strTestTime.toUpperCase();

var bolTime = false;

if (strTestTime.indexOf("PM",1) != -1 || strTestTime.indexOf("AM",1))
bolTime = true;

if (bolTime && strTestTime.indexOf(":",0) == 0)
bolTime = false;

var nColonPlace = strTestTime.indexOf(":",1);
if (bolTime && ((parseInt(nColonPlace) + 5) < (strTestTime.length - 1) || (parseInt(nColonPlace) + 4) > (strTestTime.length - 1)))
bolTime = false;

return bolTime;
}

/****************************************************************/

function replaceAll (s, fromStr, toStr)
{
var new_s = s;
for (i = 0; i < 100 && new_s.indexOf (fromStr) != -1; i++)
{
    new_s = new_s.replace (fromStr, toStr);
}
return new_s;
}

/****************************************************************/

/* PURPOSE:  Since we are using the single tick mark as the
	string delimiter to construct our SQL queries, a string with
	a tick mark in it will cause a SQL error.  Therefore we replace
	all "'" with "''", which eliminates the possibility of a SQL error.
*/

function sqlSafe (s)
{
var new_s = s;
new_s = replaceAll (new_s, "'", "|");
new_s = replaceAll (new_s, "|", "''");
new_s = replaceAll (new_s, "\"", "|");
new_s = replaceAll (new_s, "|", "''");
return new_s;
}

/****************************************************************/

function makeSafe (i)
{
	i.value = sqlSafe (i.value);
}

/****************************************************************/
function makeFormSafe(formname) {
    for (var i = 0; i < formname.elements.length; i++) {
        if ((formname.elements[i].type == 'text') || (formname.elements[i].type == 'textarea'))
            makeSafe(formname.elements[i]);
    }
}
/****************************************************************/

// Check whether string s is empty.

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

/****************************************************************/

// Returns true if string s is empty or 
// whitespace characters only.

function isWhitespace (s)

{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
	// Check that current character isn't whitespace.
	var c = s.charAt(i);

	if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

// validate that password is at least 8 characters long, begins with an alpha, and contains no whitespace
function validate_password(password) {

if (password.length < 8) {
	alert('Error, password must be at least 8 characters long.');
	return false;
}

var whitespace = password.match(/\s/g);
if (whitespace != null) {
	alert('Error, password must not contain any whitespace characters.');
	return false;
}

var char1 = password.match(/^[a-zA-Z]/);
if (char1 == null) {
	alert('Error, first character of password must be a letter.');
	return false;
}
return true;
}

/****************************************************************/

// isEmail (STRING s [, BOOLEAN emptyOK])
// 
// Email address must be of form a@b.c ... in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//

function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

/****************************************************************/

// Checks to see if a required field is blank.  If it is, a warning
// message is displayed...

function ForceEntry(objField, FieldName)
{
	var strField = new String(objField.value);
	if (isWhitespace(strField)) {
		alert("You need to enter information for " + FieldName);
		objField.focus();
		objField.select();
		return false;
	}

	return true;
}
		
/****************************************************************/

// Returns true if the string passed in is a valid number
//  (no alpha characters), else it displays an error message

function ForceNumber(objField, FieldName)
{
	var strField = new String(objField.value);
	
	if (isWhitespace(strField)) return true;

	var i = 0;

	for (i = 0; i < strField.length; i++)
		if (strField.charAt(i) < '0' || strField.charAt(i) > '9') {
			alert(FieldName + " must be a valid numeric entry.  Please do not use commas or dollar signs or any non-numeric symbols.");
			objField.focus();
			return false;
		}

	return true;
}

function return_err(err_str,focus_field) {
    alert(err_str);
    if (focus_field) focus_field.focus();
    return false;
}

function capitalize(str) {
var first_letter = str.charAt(0);
first_letter = first_letter.toUpperCase();
var rest_of_str = str.slice(1);
rest_of_str = rest_of_str.toLowerCase();
var new_str = first_letter + rest_of_str;
return new_str;
}

// Amy's stuff

function firstcap(str) {
var first_letter = str.charAt(0);
first_letter = first_letter.toUpperCase();
var rest_of_str = str.slice(1);
var new_str = first_letter + rest_of_str;
return new_str;
}

function IsSelected(fieldname) {
for (var idx=0; idx < fieldname.length; idx++) {
    if (fieldname[idx].selected) return true;
}
return false;
}

var digits = "0123456789";
// non-digit characters which are allowed in 
// Social Security Numbers
var SSNDelimiters = "- ";

// characters which are allowed in Social Security Numbers
var validSSNChars = digits + SSNDelimiters;

// U.S. Social Security Numbers have 9 digits.
// They are formatted as 123-45-6789.
var digitsInSocialSecurityNumber = 9;

// isInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if all characters in string s are numbers.
//
// Accepts non-signed integers only. Does not accept floating 
// point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// By default, returns defaultEmptyOK if s is empty.
// There is an optional second argument called emptyOK.
// emptyOK is used to override for a single function call
//      the default behavior which is specified globally by
//      defaultEmptyOK.
// If emptyOK is false (or any value other than true), 
//      the function will return false if s is empty.
// If emptyOK is true, the function will return true if s is empty.
//
// EXAMPLE FUNCTION CALL:     RESULT:
// isInteger ("5")            true 
// isInteger ("")             defaultEmptyOK
// isInteger ("-5")           false
// isInteger ("", true)       true
// isInteger ("", false)      false
// isInteger ("5", false)     true

function isInteger (s)
{   var i;
    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);
    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (!isDigit(c)) return false;
    }
    // All characters are numbers.
    return true;
}

// isSSN (STRING s [, BOOLEAN emptyOK])
// 
// isSSN returns true if string s is a valid U.S. Social
// Security Number.  Must be 9 digits.
//
// NOTE: Strip out any delimiters (spaces, hyphens, etc.)
// from string s before calling this function.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function isSSN (s)
{   if (isEmpty(s)) 
       if (isSSN.arguments.length == 1) return defaultEmptyOK;
       else return (isSSN.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInSocialSecurityNumber)
}

// Returns true if character c is a digit 
// (0 .. 9).

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

// isAlphabetic (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isAlphabetic (s)

{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-alphabetic character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }

    // All characters are letters.
    return true;
}

// Returns true if character c is an English letter 
// (A .. Z, a..z).
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) || (c == "." ) || (c == " ") )
}

// This submits the form if the enter key is pressed
var isNetscape = false;
var isIE = false;
var isWhoKnows = false;

// This determines which browser the user is using
if (parseInt(navigator.appVersion) >= 4) {
if(navigator.appName == "Netscape") {
  isNetscape = true;
}else if (navigator.appName == "Microsoft Internet Explorer"){
  isIE = true;
}else {
	isWhoKnows = true;
}
}

// This stuff captures the events of the user
if(isNetscape) {
document.captureEvents(Event.KEYUP);
}
document.onkeyup = checkValue

function checkValue(evt){
var theButtonPressed;
if (isNetscape) {
	// if(evt.target.type == "text"){ 
		//--> you can specify which type of element you want this to trigger for
	// if(evt.target.name == "myText"){
		//--> or you can specify the actual name of the element
		theButtonPressed = evt.which;
	// }
      }else if(isIE) {
	// if (window.event.srcElement.type == "text") {
		//--> same as above, but for IE
		theButtonPressed = window.event.keyCode;
	// }
}else if(isWhoKnows) {
	alert("Please hit the submit button to process form");
}

if (theButtonPressed == 13) {
	form_validate();
}
}
// -->
