/*******************************************************************************
 * Display a generic error alert dialog box.
 *
 * input: 
 *      title - is the error title to display
 *      msg   - is the error message to display
 *******************************************************************************
 */
function jssd_DisplayError( title, msg )
{
    var headingLine = "_____________________________________\n";
    alert( "\n" + title + "\n" + headingLine + "\n" + msg );
}
			
/*******************************************************************************
 * Runs through a list of required fields to determine if data has been entered 
 * for the field. 
 *
 * To use this method, a Required object must be defined for the form being
 * validated. The object consists of an array member object for each form 
 * element to validate. Each array object is defined as follows:
 *	     
 *    new Array( element_name, error_message, validation_function (optional) )		
 * 
 *  This method performs the following validation process:
 *		- If the required element has it's own requirement validation function
 *        (oRequired[x][2] != undefined ), executed the function. The function 
 *        must return true if the requirement validation is successful.
 *      - validate the element if it is an INPUT element of the type: text,
 *        textarea, password, radio or checkbox.
 *      - validate the element if it is a node of radio or checkbox elements. 
 *
 * Input:
 *     form - the form containing the elements
 *
 * Return: True if the form validation is successful
 *******************************************************************************
 */
function jssd_ValidateRequired(form)
{
    var undefined;
    var isValid        = true;
    var invalidElement = false;
    var focusField     = null;
    var i              = 0;
    var errMsg         = new Array();
    var oRequired      = new Required();
    var element        = null;

    for(x in oRequired)
    {
        element = form[oRequired[x][0]];
        isValid = true;
        if( oRequired[x][2] != undefined  )
        {
            // Element had it's own requirment criteria function
            isValid = oRequired[x][2](form);
        }
        else
        {
            // No function provided
            if( element.tagName != undefined )
            {
                if(element.tagName == "INPUT" )
                {
                    if(((element.type  == "text" || element.type  == "password")&&
                         element.value == "") ||
                       ((element.type == "radio" || element.type == "checkbox") && !element.checked ))
                    {
                        isValid = false;
                    }
                }
                else if( element.tagName == "TEXTAREA")
                {
                    if( element.value == "")
                    {
                        isValid = false;
                    }
                
                }
                else if( element.tagName == "SELECT" )
                {
                    if(element.length > 0 )
                    {
                        isValid = ( element.options( 0 ).value == "" ? element.selectedIndex > 0 : 
                            element.selectedIndex > -1 );
                    }
                    else
                    {
                        invalidElement = true;
                    }
                }
                else
                {
                    invalidElement = true;
                }
            }
            else if( element.length != undefined && ( element[0].type == "radio" || element[0].type == "checkbox" ))
            {
                // This is a node list of radio or checkbox elements
                isValid = jssd_IsChecked( element );
                element = element[0];
            }
            else
            {
                invalidElement = true;
            }
        }
        if( ! isValid )
        {
            if (i == 0)
            {
                focusField = element;
            }
            errMsg[i++] = oRequired[x][1];
        }
    }
    if (errMsg.length > 0)
    {
       focusField.focus();
       jssd_DisplayError("Required Information", errMsg.join("\n"));
       return false;
    }
    else
    {
        return true;
    }
}
			
/*******************************************************************************
 * Determines if a radio group or a checkbox group has been checked.
 *
 * Input:
 *		ctrlArray - the input form element to check. This element must be a 
 *                  radio or a checkbox, all other elements will return true.
 *
 * Return: True if any of the radio / checkbox elements have been checked.
 *******************************************************************************
 */
function jssd_IsChecked( ctrlArray )
{
    var checked = true;
    var undefined;
    if( ctrlArray.length != undefined &&
        (ctrlArray[0].type == "radio" || ctrlArray[0].type == "checkbox"))
    {
        var i = 0;
        do        
        {
            checked =  ctrlArray[i++].checked;
        }while( i < ctrlArray.length && !checked )
    }
    return checked;
}

/*******************************************************************************
 * Check the input element to determine if it represents a valid email address.
 * This method will only validate text and textarea input elements.
 *
 * To use this method, a Email object must be defined for the form being
 * validated. The object consists of an array member object for each input 
 * element to validate. Each array object is defined as follows:
 *	     
 *    new Array( element_name, error_message )		
 * 
 * Input:
 *     form - the form containing the input element to validate
 *
 * Return: True if it is a valid email address, false otherwise
 *******************************************************************************
 */
function jssd_ValidateEmail( form )
{
    var bValid     = true;
    var focusField = null;
    var i          = 0;
    var errMsg     = new Array();
    oEmail         = new Email();
    for( x in oEmail )
    {
        if( form[oEmail[x][0]].type == "text" &&
            form[oEmail[x][0]].value.length > 0 )
        {
            if ( !checkEmail( form[oEmail[x][0]].value ) )
            {
                if ( i == 0 )
                {
                    focusField = form[oEmail[x][0]];
                }
                errMsg[i++] = oEmail[x][1];
                bValid = false;
            }
        }
    }
    if( errMsg.length > 0 )
    {
        focusField.focus();
        jssd_DisplayError( "Invalid Data", errMsg.join('\n') );
    }
    return bValid;
}

/**
 * Reference: Sandeep V. Tamhankar (stamhankar@hotmail.com),
 * http://javascript.internet.com
 */
function checkEmail(emailStr) {
   if (emailStr.length == 0) {
       return true;
   }
   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 + ")";
   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];
   if (user.match(userPat) == null) {
       return false;
   }
   var IPArray = domain.match(ipDomainPat);
   if (IPArray != null) {
       for (var i = 1; i <= 4; i++) {
          if (IPArray[i] > 255) {
             return false;
          }
       }
       return true;
   }
   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 > 3)) {
       return false;
   }
   if (len < 2) {
       return false;
   }
   return true;
}
