/* 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" : " * Please Select",
    "phone" : "* (###)###-####",
    "event" : "Choose an Event",
    "start" : "* Choose a Start Time",
    "end" : "* Choose an End Time",
    "start2" : "* Choose a Start Time",
    "end2" : "* Choose an End Time"
};

/* 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,
    "phone" : false,
    "status" : false,
    "event" : false,
    "start" : false,
    "end" : false,
    "start2" : true,
    "end2" : 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 emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
                    if (inputText.match(emailRegex)) {

                            //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;

                case 'phone':

                    //initialize email RegEx (i denotes case insensitive), and check input against it
                    var phoneRegex = /\(?\d{3}([-\/\.\)])?\d{3}([-\/\.])\d{4}/;
                    if (inputText.match(phoneRegex)) {

                            //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;
        }
        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){

    //create the id of the corresponding error <span>
    var error = id + '_error';

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

    //Retreive the specified by name
    eval("var aRadio = document.registration." + 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 and hidden selects
                    if(document.getElementById(field).disabled == true || document.getElementById(field).parentNode.style.display == "none"){
                        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;
}
/* This function sets an elements display element to disabled="true"
 * Accepts an array of id's as input.
 */
function disableElements(array){
    for(var id in array){
        var element = document.getElementById(array[id])
        element.disabled = true;
    }
}

/* This function sets an elements display element to disabled="false"
 * Accepts an array of id's as input.
 */
function enableElements(id){
    var element = document.getElementById(id);
    element.disabled = false;
}

/* Sets the display attribute of a specified element to none.
 * Accepts an array of id's as input
 */
function hideElements(array){
    for(var id in array){
        var element = document.getElementById(array[id])
        element.style.display = "none";
    }
}

/* Sets the display attribute of a specified element to block.
 * Accepts an array of id's as input
 */
function displayElements(array){
    for(var id in array){
        var element = document.getElementById(array[id])
        element.style.display = "block";
    }
}

/* setStart() method sets the options of a corresponding select based on the index of
 * the selected radio button. Option values are stored in individual arrays.
 */
function setStart(id){
//
//    //dynamically construct array?
//    var youth = [];
//
//    //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 null;
}

function constructArray(start, end){
//
//    //starting array like object
//    var times = {0:'Start', 'null':'Not Available'};
//    var time = start;
//
//    //loop to process parts of the time string
//    while(time != end){
//        var aTime = time.split(":")
//        if(aTime[1] == '30'){
//
//            //increment ##:30:## to ##:00:## and incremement hour
//            aTime[0] = parseInt(aTime[0], 10);
//            aTime[0]++
//            aTime[1] = '00';
//        }else{
//
//            //increment ##:00:## to ##:30:##
//            aTime[1] = '30';
//        }
//
//        //append upadted parts to make new string
//        var newTime = "";
//        for(var part in aTime){var substring = aTime[part.toString()];
//             //alert('aTime[part]: ' + aTime[part.toString()]);
//             newTime = newTime.concat(substring,':');
//             //alert(newTime);
//        }
//        time = newTime.slice(0,(newTime.length-1));
//        //alert('time: '+ time);
//
//        times[time]='foo';
//        alert(times[time]);
//    }
//    for (var value in times){
//        alert('value: ' + value + ', time[value]: ' + times[value]);
//    }
    return null;
}
////constructArray('09:00:00','11:30:00');

function changeSelect(value){

    var start = document.getElementById('start_label');
    var end = document.getElementById('end_label');
    var start2 = document.getElementById('start2_label');
    var end2 = document.getElementById('end2_label');

    if (value == 8){
        var UW = "Feb 21, UW";

        start.innerHTML = UW;
        end.innerHTML = UW;
    }

    if (value == 9){
        var marymoor = "March 6, Marymoor";
        var lakeside = "March 7, Lakeside";

        start.innerHTML =  marymoor;
        end.innerHTML = marymoor;
        start2.innerHTML = lakeside;
        end2.innerHTML = lakeside;
    }
    
    if (value == 11){
        var auburn = "March 14, Auburn HS";

        start.innerHTML = auburn;
        end.innerHTML = auburn;
    }

}

