/*global $ Form application applicationData mainForm */
var camperForm = {
    fieldList : [ "firstName", "lastName", "age", "gender", "member",
                  "firstTime", "smoker", "food", "foodNotes", "job",
                  "street", "city", "state", "zip", "email", "phone" ],
    hints : {
      "firstName" : "First Name",
      "lastName" : "Last Name"
    },
    
    initialize : function () {
        var textNode = document.createTextNode(application.firstWeekendDate.DAY);
        $("firstWeekendFridayDate").appendChild(textNode);
        $("age").onchange = camperForm.updateFees;
        $("member").onchange = camperForm.updateFees;
        $("addAddressLink").onclick = camperForm.showAddress;
        $("removeAddressLink").onclick = camperForm.hideAddress;
        $("done").onclick = camperForm.validateAndSaveForm;
        $("cancelCamper").onclick = application.cancelCamper;
        $("jobQuestion").onclick = camperForm.displayJobHelp;
        $("firstName").onfocus = camperForm.focuser;
        $("firstName").onblur = camperForm.blurer;
        $("lastName").onfocus = camperForm.focuser;
        $("lastName").onblur = camperForm.blurer;
    },

    addAnotherCamper : function () {
        if (this.validateAndSaveForm()) {
            application.addCamper();
        }
    },

    setHints : function (camper) {
        var fieldName;
        for (fieldName in this.hints) {
            if (0 === camper[fieldName].length) {
                $(fieldName).value = this.hints[fieldName];
                $(fieldName).addClassName("empty");
            }
            else {
                $(fieldName).removeClassName("empty");
            }
        }
    },

    focuser : function () {
        if (this.hasClassName("empty")) {
            this.removeClassName("empty");
            this.value = "";
        }
        return true;
    },
    
    blurer : function () {
        if (this.value.length === 0) {
            this.value = camperForm.hints[this.id];
            this.addClassName("empty");
        }
        return true;
    },
    
//    handleHint : function (node) {
//        var id = node.id;
//        if (node.value === hints[id])
//    },
    
    load : function (camper, isContact) {
        var camperLabel = "";
        var i = 0;
        var fieldName;
        var firstNameHint = "First Name";
        var lastNameHint = "Last Name";
        application.deleteChildren("camperLabel");
        application.deleteChildren("errorMessage");

        if (isContact) {
            camperLabel = "Contact person";
            $("useEmail").disabled = false;
            $("useEmail").checked = applicationData.useEmail;
            $("useEmailLabel").style.color = "black";
        }
        else {
            camperLabel = "Camper " + (applicationData.currentCamperIndex + 1);
            $("useEmail").checked = false;
            $("useEmail").diabled = true;
            $("useEmailLabel").style.color = "gray";
        }
        $("camperLabel").appendChild(document.createTextNode(camperLabel));

        for (i = 0; i < this.fieldList.length; i++) {
            fieldName = this.fieldList[i];
            Form.Element.setValue(fieldName, camper[fieldName]);
        }

        this.setHints(camper);
        
        if (isContact) {
            $("addAddress").style.display = "none";
            $("removeAddress").style.display = "none";
            $("addressForm").style.display = "";
        }
        else {
            if (this.isBlankContactInfo()) {
                this.hideAddress();
            }
            else {
                this.showAddress();
            }
        }

        this.updateFees();
    },

    showAddress : function () {
        $("addAddress").style.display = "none";
        $("removeAddress").style.display = "";
        $("addressForm").style.display = "";
        return false;
    },

    hideAddress : function () {
        var addressFieldList =
            ["street", "city", "state", "zip", "email", "phone"];
        for (var i = 0; i < addressFieldList.length; i++) {
            Form.Element.setValue(addressFieldList[i], "");
        }

        $("addAddress").style.display = "";
        $("removeAddress").style.display = "none";
        $("addressForm").style.display = "none";
        return false;
    },
    
    isBlankContactInfo : function () {
        return !($("street").present() || $("city").present() ||
                $("state").present() || $("zip").present() ||
                $("phone").present() || $("email").present());
    },
    
    displayJobHelp : function () {
        window.open("jobinformation.html",
                    "JobHelp",
                    "resizable=yes,scrollbars=yes,width=400,height=500," +
                    "left=0,top=0");
        return false;
    },
    
    appendError : function (errorText, ul) {
        var li = new Object();
        var textNode = new Object();
        li = document.createElement("li");
        textNode = document.createTextNode(errorText);
        li.appendChild(textNode);
        ul.appendChild(li);
    },
    
    validateRequiredField : function (fieldName, errorText, ul) {
        // Even if a field has a value, if it has the empty class, then
        // the value is a hint, not an actual value.
        var present = $(fieldName).present() &&
                 !$(fieldName).hasClassName("empty"); 
        
        if (!present) {
            camperForm.appendError(errorText, ul);
        }
        return present;
    },
    
    validateZip : function (required, ul) {
        var valid = true;
        var pattern = /^\d{5}(-\d{4})?$/;
        var zip = $("zip");
        
        if (zip.present()) {
            valid = pattern.test(zip.getValue());
            if (!valid) {
                camperForm.appendError("Valid ZIP", ul);
            }
        }
        else if (required) {
            valid = camperForm.validateRequiredField("zip", "ZIP", ul);
        }
        
        return valid;
    },
    
    validatePhone : function (required, ul) {
        var valid = true;
        var pattern = /^\d{3}-\d{3}-\d{4}$/;
        var phone = $("phone");
        
        if (phone.present()) {
            valid = pattern.test(phone.getValue());
            if (!valid) {
                camperForm.appendError("Valid phone", ul);
            }
        }
        else if (required) {
            valid = camperForm.validateRequiredField("phone", "Phone", ul);
        }
        
        return valid;
    },
    
    validateEmail : function (required, ul) {
        var valid = true;
        var email = $("email");
        var pattern = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/;
        
        if (email.present()) {
            valid =  pattern.test(email.getValue());
        }

        if (!valid) {
            camperForm.appendError("Valid email", ul);
        }
        else if (required) {
            valid = camperForm.validateRequiredField("email", "Email", ul);
        }
        
        return valid;
    },

    validateAndSaveForm : function () {
        var retVal = false;
        var errorMessage = $("errorMessage");
        var ul = document.createElement("ul");
        var isContact = (0 === applicationData.currentCamperIndex);
        var camper = null;
        var fieldName = null;

        application.deleteChildren("errorMessage");
        
        ul.setAttribute("class", "errorList");
        ul.style.color = "red";

        camperForm.validateRequiredField("firstName", "First Name", ul);
        camperForm.validateRequiredField("lastName", "Last Name", ul);
        if ($("age").getValue() === "-1") {
            camperForm.appendError("Age", ul);
        }
        camperForm.validateRequiredField("gender", "Gender", ul);
        if ($("food").getValue() === application.Food.SPECIAL) {
            camperForm.validateRequiredField("foodNotes",
                                             "Special diet notes",
                                             ul);
        }

        if (isContact) {
            camperForm.validateRequiredField("street", "Street", ul);
            camperForm.validateRequiredField("city", "City", ul);
            camperForm.validateRequiredField("state", "State", ul);
        }
        
        camperForm.validateZip(isContact, ul);

        camperForm.validatePhone(isContact, ul);

        camperForm.validateEmail(isContact, ul);
        
        if (ul.hasChildNodes()) {
            errorMessage.appendChild(document.createTextNode("Please fill in:"));
            errorMessage.appendChild(ul);
        }
        else {
            camper = applicationData.campers[applicationData.currentCamperIndex];
            for (var i = 0; i < camperForm.fieldList.length; i++) {
                fieldName = camperForm.fieldList[i];
                camper[fieldName] = $(fieldName).getValue();
            }
            if (!$('useEmail').disabled) {
                applicationData.useEmail = $("useEmail").getValue();
            }
            application.saveApplicationData();
            mainForm.load();
            $("camperForm").style.display = "none";
            $("submitCancelButtons").style.display = "";
            $("mainForm").style.display = "";
            retVal = true;
        }
        return retVal;
    },

//    updateUseEmail : function () {
//        var disable = !($("email").present());
//        var node = $("useEmail");
//        
//        if (applicationData.currentCamperIndex !== 0) {
//            disable = true;
//        }
//
//        // If current state is different than new state, change it.
//        if (node.disabled !== disable) {
//            
//            node.checked = !disable;
//            node.disabled = disable;
//        }
//        $("useEmailLabel").style.color = node.disabled ? "gray" : "black";
//    },
    
    updateFees : function () {
        var fee = 0;
        var deposit = 0;
        var node = $("age");
        var age = parseInt(node.options[node.selectedIndex].value);
        if (age >= 0) {
            fee = application.calculateFee($("age").getValue(),
                                           $("member").getValue());
            deposit = application.calculateDeposit($("age").getValue(),
                                                   $("member").getValue());
        }
        $("fee").value = "$" + fee;
        $("deposit").value = "$" + deposit;
    }
};
