/*
    Validate the given field
    Params: value - the value to be checked
            checkType - The datatype to validate this field against
            msg - The message to be displayed if the field doesn'y conform to the datatype
    Returns: True if the field is valid, Also has the side effect of displaying the message if 
             value if invalid            
    Author: Tom Dyson (tom@torchbox.com)             
*/
function validateValue(value,checktype,msg) {
	
    // Set up the required regular expression, based on the checkType
    switch(checktype) {
        
        // Peform no validate on this field
		case 'none':
		    return true;

        // must be numbers
		case 'numeric':
			pat = /^([0-9])+$/;
            break;
                        
        // must be letters, numbers, underscores, exclaimation marks, questions marks, hyphens, spaces and quotes, or nothing
		case 'title':
			pat = /^(([a-z]|[A-Z]|\d|_| |'|"|\?|&|!|-)+)$/;
            
        // make sure the value is a valid date in the format dd/mm/yy
		case 'date':
			pat = /^(([0-3][0-9]\/[0-1][0-9]\/[0-9][0-9])+)$/;
		    break;
        
        // make sure the value is a valid email
		case 'email':
			pat = /^([a-zA-Z0-9-_]+\.)*[a-zA-Z0-9-_]+\@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]+$/;
		    break;

        // Make sure the value is a valid telephone number
        case 'telephone':
            pat = /^([0-9() ])+$/;
            break;
            
		default:
			alert('CheckType of type ' + checktype + ' is unknown');
    }
		
    // only check if there is a value
    if (value != '') {
        
        // If the field is not valid according to the Reg Expression, display message           
        if (!pat.test(value)) {
            alert(msg);
            return false;
         }
    }	

    // Passed through the validation, so field is valid
    return true;
}

/*
    Validates field on the given form.  It searches the given form for any fields subprefixed with
    _validate, the first part of the field name is used as the element to check.  For example
    CompanyName_validate will validate the CompanyName field.  The value of the _validate field should
    be in the format DataType|Message, The datatype being the type to check the field against, and the
    message being what should be displayed if the validation fails.

    Params: formName - The form to check
    Returns: True if the form passes the validation checks
    Author: Tom Dyson
*/
function validateForm(form) {

    // Get a reference to the form, if a string was passed in
    if (typeof(form) == "String") {
    
        // Get a pointer to the required form
        var checkForm = document.forms[form];
    }
    else {
        var checkForm = form;
    }

    // Assume the form is valid
    var valid = true;
    
    //loop over form fields to check if each one needs validation.
    for (var i = 0; i< checkForm.elements.length && valid; i++) {
        var elementName = checkForm.elements[i].name;

        // If the name ends in _validate, process it
        if (elementName.indexOf("_validate") != -1){ 
        
            // Remove the _validate from the elementName to give the real field
            var fieldName = elementName.substring(0,elementName.length - 9);

            // Get the actual field that needs checking
            var validationField = checkForm[fieldName];

            // If the field isn't found, display a debugging message
            if (validationField == null) {
                alert('Field ' + fieldName + ' Not found on form ' + formName);
            }
            else {
                // get the value of the validation message and type
                var validationSplit = checkForm.elements[i].value.split("|");
                var validationType = validationSplit[0];            
                var validationMsg = validationSplit[1];            
    
                // Only validate if a value has been provided
                if (validationField.value != "") { 
    
                    // Perform the validation (using the ValidateValue function)
                    if (!validateValue(validationField.value,validationType,validationMsg)) {
                    
                        // Validation failed, so set the cursor to the field, and stop the form submit
                        validationField.focus();
                        valid = false;
                    }
                } 
            }
        } 
    }        
    
    return valid;
}

/*
    Checks the form for any elements whos name ends in _required

*/
function checkRequiredFields(form) {
     // Get a reference to the form, if a string was passed in
    if (typeof(form) == 'string') {
    
        // Get a pointer to the required form
        var checkForm = document.forms[form];
    }
    else {
        var checkForm = form;
    }   

    // Assume the form is valid
    var valid = true;
    
    //loop over form fields to check if each one needs validation.
    for (var i = 0; i< checkForm.elements.length && valid; i++) {
        var elementName = checkForm.elements[i].name;

        // If the name ends in _required, process it
        if (elementName.indexOf("_required") != -1){ 
        
            // Remove the _required from the elementName to give the real field
            var fieldName = elementName.substring(0,elementName.length - 9);

            // Get the actual field that needs checking
            var requiredField = checkForm[fieldName];

            // If the field isn't found, display a debugging message
            if (requiredField == null) {
                alert('Required Field ' + fieldName + ' Not found on form ' + formName);
            }
            else {
                // get the display name of the required field
                var displayName = checkForm.elements[i].value;
    
                // Only validate if a value has been provided
                if (requiredField.value == '') { 

                    alert(displayName + ' is required');                        

                    // Validation failed, so set the cursor to the field, and stop the form submit
                    requiredField.focus();
                    valid = false;
                } 
            }
        } 
    }        
    
    return valid;
}