/* An associative array like object to store fields (keys) for corresponding
 * error messages (values), as pairs.
 */
var errors = {"fname" : " * Letters Only, No Spaces", "lname" : " * Letters Only, No Spaces",
        "email" : " * Not a Valid Email", "email_match" : " * Emails Do Not Match ",
        "status" : " * Select New or Returning", "new_clinic" : "* Choose a Training Option",
        "return_clinic" : "* Choose a Training Option"
    };

/* field status is an associative array storing the results of each field's validation status -
 * false and null are the default values depending on whether the field is present by default on the form.
 * ValidationStatus changes the boolean (value) of the key:value pair.
 */
var fieldStatus = {"fname" : false, "lname" : false, "email" : false, "email_match" : false, 
    "status" : false, "new_clinic" : true, "return_clinic" : true};

/* validateText() function stores all of the validation rules for the text fields on this page.
 * Rules are stored in a switch that is accessed using the id variable passed into the switch
 * from the form using the this.id DOM property of the HTML input element. A failed validation
 * calls the printError function with the element id. Results of the validation are appended
 * as a boolean to an object that is inspected during the form's 'onsubmit' action.
 */
function validateText(id){

        //Retrieve the text input of the text field specified by the id var
        var inputText = document.getElementById(id).value;

        //get the error location for the specified id
        var errorSpan = document.getElementById(id + '_error');

        //A switch to house the validation code for each field
        switch (id) {

                //fall through case - matches two cases that utilize the same code
                case 'fname': case 'lname':

                        //check if the length is appropriate
                        if (inputText.length >= 2) {

                                //create an array of characters from the input text
                                var aCharacters = inputText.split("");

                                //Create RegExp Object for use in for loop
                                var characterRegEx = /[\d|\W]/;

                                //iterate through the array and check for digits or non-word (not:[a-z,A-Z) characters
                                for (i=0; i<aCharacters.length; i++) {

                                        //a match with digits or non-words set the validation to false and calls the error
                                        if (aCharacters[i].match(characterRegEx)) {
                                                validationStatus(id, false);
                                                printError(errors, id);

                                                //return false here - leaves function and avoids the clear error outside this FOR loop
                                                return false;
                                        }
                                }//END inspect characters FOR

                                //clear error and set validation to true
                                errorSpan.innerHTML = "";
                                validationStatus(id, true);

                        //length doesn't validate, show error and set validation
                        }else {
                                printError(errors, id);
                                validationStatus(id, false);
                        }
                        break;

                case 'email':

                        //initialize email RegEx (i denotes case insensitive), and check input against it
                        var regex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
                        if (inputText.match(regex)) {

                                //clear error and set validation to true
                                errorSpan.innerHTML = "";
                                validationStatus(id, true);

                        //fail, call the error and set validation to false
                        }else {
                                printError(errors, id);
                                validationStatus(id, false);
                        }
                        break;

                case 'email_match':

                        //get the input text and text from the password field.
                        var email = document.getElementById('email').value;
                        var verify = document.getElementById('email_match').value;

                        //Compare password and confirmation, also make sure the field is not empty
                        if(email == verify && verify != null && verify != ""){

                                //pass, clear error and set to valid
                                errorSpan.innerHTML = "";
                                validationStatus(id, true);
                        }else{

                                //fail, call the error, mark as not valid
                                printError(errors, id);
                                validationStatus(id, false);
                        }

                        break;
        }
        return false;
}

/* validateRadio() method fetches an array of elements by name and iterates through them
 * to determine if one of them has been selected. Absence of selections calls the printError() method.
 * The method also calls validationStatus().
 */
function validateRadio(id){

    //test
    var error = id + '_error';

    //get the error location for the specified id (id is actually String this.name)
    var errorSpan = document.getElementById(error);

    //Retreive the elements by name
    var aRadio = document.getElementsByName(id);
    var selectedOption = -1;

    //iterate through and check for selected option
    for(var i = aRadio.length-1; i > -1; i--){
        if(aRadio[i].checked){
            selectedOption = i;
            i=-1;
        }
    }

    //Checks for no selection and calls error related methods
    if(selectedOption == -1){
        printError(errors, id);
        validationStatus(id, false);

        //select a button to avoid later errors
        aRadio[0].checked = true;
        aRadio[0].checked = false;
    }else{

        //pass, clear error and set to valid
        errorSpan.innerHTML = "";
        validationStatus(id, true);
    }
    return false;
}

/* validateRadio() method fetches an array of elements by name and iterates through them
 * to determine if one of them has been selected. Absence of selections calls the printError() method.
 * The method also calls validationStatus().
 */
function validateSelect(id){

        //get the error location for the specified id (id is actually String this.name)
        var errorSpan = document.getElementById(id + '_error');

        //Retreive the elements by name
        var select = document.getElementById(id);
        var option = select.selectedIndex;
        var disabled = select.disabled;

        //Checks for no selection and calls error related methods
        if(option == 0 && disabled == false){
            printError(errors, id);
            validationStatus(id, false);
        }else{

            //pass, clear error and set to valid
            errorSpan.innerHTML = "";
            validationStatus(id, true);
        }
        return false;
}

/* printError uses an associative array of id's and errors to display an error message in
 * a span associated with the form with the specified id.
 */
function printError(hashmap, id){

        //get the error area for the specified id
        var errorSpan = document.getElementById(id + '_error');

        //iterate through the hashmap and look for a match
        for (key in hashmap){
                if(key = id){

                        //get the message for the id
                        var message = hashmap[key];
                }

        //print the message
        errorSpan.innerHTML = message;
        }
        return false;
}


function validationStatus(key, booleanValue){
        fieldStatus[key] = booleanValue;
}

/* confirmValidation triggers validation on all fields by focusing through them. It then checks
 * the fieldStatus object to identify failing fields. These fields are posted in an alert
 * after some formatting. If everything is valid a short message is displayed.
 */

function confirmValidation(hashmap){

        //set a variable to monitor if all fields contain valid data.
        var allTrue = true;

        //check that our radio is set, to avoid later errors
        //validateRadio('status');

        //iterate through the object containing the validation results
        for (var field in hashmap) {

                //check for nulls and continue...nothing to see here. Allows for names or id based selection
                if (document.getElementById(field) == null) {
                    if(document.getElementsByName(field)== null){
                        continue;
                    }else {
                        if(field == 'status'){
                            //calling this function prevents errors...trust me
                            validateRadio(field)                           
                        }
                    }
                    continue;

                //set focus on each field specified in the object. This triggers each field's validation function.
                }else {

                    //skip over disabled selects
                    if(document.getElementById(field).disabled == true){
                        continue;
                    }
                    document.getElementById(field).focus();
                }
        }

        //set focus on the button when all fields are visited
        document.getElementById('register').focus();

        //iterate through the object
        for (field in hashmap) {

                //check for false values
                if (hashmap[field] == false){

                        //set out var to false when a false is encountered
                        allTrue = false;
                }
        }
        if (allTrue == false) {
                alert('Please correct the errors and resubmit.');
                return false;
        }
        else {
            document.registration.submit();
            return true;
        }
}

function enableSelect(value){
    var aSelect = document.getElementsByTagName('select');

    //disable both select elements
    for(element in aSelect){
        aSelect[element].disabled = true;

        //clear any errors - not very elegant, but I'm tired...
        var error1 = document.getElementById('return_clinic_error');
        var error2 = document.getElementById('new_clinic_error');
        error1.innerHTML = ""
        error2.innerHTML = "";
        }


    //enable the desired select element
    var target = value + "_clinic";
    var select = document.getElementById(target);
    select.disabled = false;
}


