
/* start form validation code */
// returns true if all the characters in value are in str
function isOnly(value, str) {

    // check if character 'c' from value is in str
    for (var i = 0 ; i < value.length ; i++) {
        var c = value.charAt(i);
        if (str.indexOf(c) == -1)
            return false;
    }
    return true;
}

// function to test for a valid element
function isValid(value) {

    // for for null and empty
    if ((value == null) || (value == ""))
        return false;

    // check for all blank
    return !isOnly(value, " \t\n");
}

// this checks for a valid number
function isValidNumber(value) {

    if (!isValid(value))
        return false;

    return isOnly(value, "0123456789");
}

function isValidCreditMonth(value) {

    if (!isValid(value))
        return false;

    return isOnly(value, "0123456789") && value.length == 2 && 1 <= value && value <= 12;
}


function isValidCreditYear(value) {

    if (!isValid(value))
        return false;

    // tricky as year is NOT Y2K at all, have a 2 digit value between 00 and 99
    return isOnly(value, "0123456789") && value.length == 2 && 0 <= value && value <= 99;
}

// this checks for a phone valid number
function isValidPhoneNumber(value) {

    if (!isValid(value))
        return false;

    // now check for a number, perhaps with '-', '(', ')' and '+' in it ' '
    return isOnly(value, "-|+0123456789() ");
}

// this checks for a valid username
function isValidUsername(value) {

    if (!isValid(value))
        return false;

    // Check that length is 4-12.
    // Check that charset is valid.
    return ((value.length >= 1) && (value.length <= 30)) && (isOnly(value, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-"))
}

function isValidPassword(value) {

    if (!isValid(value))
        return false;

    // Check that length is 4-15.
    return ((value.length >= 1) && (value.length <= 30));
}

function isValidEmail(value) {

    if (!isValid(value))
        return false;

    if(value.length < 3)
		return false;
		
	if(!isOnly(value.trim(), "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-@"))
		return false;

    // check that it has some text, a '@' and then some more text
    var at_sign = value.indexOf('@');
    return at_sign != -1 && at_sign != 0 && at_sign != value.length;
}

function validate(data_form) {

    // assume valid, until shown otherwise
    var valid_form = true;

    // the error message string for display
    var empty_elements = "";

    // the first empty element
    var first_element = null;

    // Initialize the values for button types; radio & checkbox
    var thisButton = '';
    var thisButtonLength = 1;
    var buttonChecked = false;
    var buttonReguired = false;
    var index = 1;

    // loop through the form looking for fields that are required
    // as these are required fields and must have input.
    
    for (var i = 0 ; i < data_form.length ; i++) {

		if((data_form.elements[i].name != '') && document.getElementById(data_form.elements[i].name)) {
		
			var elementValue = '';

			var element = data_form.elements[i];

			// If this element is list, use diffent value.
			if(element.type == "select-one")
				elementValue = data_form.elements[i].options[data_form.elements[i].selectedIndex].value;

			else
				elementValue = data_form.elements[i].value;

			//if(element.type != "hidden")
			//  alert('element.display_name = ' + element.display_name + ', elementValue = ' + elementValue);

			// the data is invalid if either
			//  element is not required, something is supplied and it has a validation routine it fails
			//   or
			//  element is required, it has a validation routine it fails or it fails the default one

			// If it is a button, use differet way to validate it.
			if((element.type == "radio") || (element.type == "checkbox")){

				// If it is different button group,
				// change thisButton and initiate variables.
				if(thisButton != element.name) {
					thisButton = element.name;

					// Get the real button length excluding the hidden fields.
					thisButtonLength = eval('data_form.' + element.name + '.length');
					var tempLength = 0;

					for(var j=0; j<thisButtonLength; j++)
						if( (eval('data_form.' + element.name + '[' + j +'].type') == 'radio') || (eval('data_form.' + element.name + '[' + j +'].type') == 'checkbox'))
							tempLength++;

					// If the two lengths are not same, there are hidden type with this button name.
					if(thisButtonLength != tempLength)
						thisButtonLength = tempLength;

					// Because display_name & required are given only to the first button in the button group, we have to keep them.

					// If element.display_name is not defined, get it straigt from form.
					if( element.display_name == null) {
						thisDisplayName = eval('data_form.' + element.name +'.display_name');
						buttonRequired = eval('data_form.' + element.name +'.required');
					}
					else {
						thisDisplayName = element.display_name;
						buttonRequired = element.required;
					}

					buttonChecked = false;
					index = 1;
				}

				// Do all the other checking only if this button is required to be checked.
				if(buttonRequired) {

					// Check if this button is checked.
					if(element.checked || buttonChecked)
						buttonChecked = true;


					// If no button is checked until the last button, return false.
					if((index == thisButtonLength) && !buttonChecked) {

						// so the form do not submit
						valid_form = false;

						// for the error message (clean it up for display)
						empty_elements += "   - " + thisDisplayName + "\n";

						// set the first element that is empty for focus (and not hidden)
						if (first_element == null && (element.type != "hidden"))
							first_element = element;
					}
					index++;
				}
			}
			else if
			(
				(!element.required && (isValid(elementValue) && element.validate != null && !element.validate(elementValue)))
				||
				(element.required && ((element.validate != null && !element.validate(elementValue)) || !isValid(elementValue)))
			)
			{

				// so the form does not submit
				valid_form = false;

				// for the error message (clean it up for display)
				empty_elements += "   - " + element.display_name + "\n";

				// set the first element that is empty for focus (and not hidden)
				if (first_element == null && (element.type != "hidden"))
					first_element = element;
			}
        }		// ((data_form.elements[i].name != '') && document.getElementById(data_form.elements[i].name))
    }
	
		
    if (!valid_form) {

        var error_message = "";

        // build the error message
        if (empty_elements != "")
            error_message = "These fields do not have correct values:\n\n" + empty_elements;

        // and display for all to see
        alert(error_message);

        // and jump to the first element
        if (first_element != null)
            first_element.focus();

    }

    // if cookie code is being used, the call to cookie.save() is made here
    // if there are no errors in the validation of the form
    // if (valid_form)
        // save_data();

    return valid_form;
}
/* end form validation code */

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

