﻿/// <reference path="../../jquery-1.3.2.min.js"/>

var QuestionType = { "Text": "1", "Phone": "2", "Number": "3", "Currency": "4", "Date": "5", "Percentage": "6", "Checkbox": "7", "Dropdown": "8", "Multiselect": "9" };
var ContactField = { "PersonalEmail" : "9", "BizEmail" : "10"};

CustomForm = function() {

    var datepickerImgUrl;
    var emailValRegExpObj;

    var isFormValid;

    this.PageLoad = function(datepickerImg, emailValRegExp, noSubmit) {

        datepickerImgUrl = datepickerImg;
        emailValRegExpObj = new RegExp(emailValRegExp);

        BindBirthDayControls();
        BindCalendarControls();
        
        if (!noSubmit) {
            BindSubmit();
        }

    };

    var BindBirthDayControls = function() {
        var calQstns = $("#questions input.birthday:visible");  //  Bind the datepicker only to the visible birthday fields
        var defaultYr = 2000
        calQstns.each(function() {
            $(this)                
                .datepicker(
                {
                    showOn: "button",
                    buttonImage: datepickerImgUrl,
                    buttonImageOnly: true,
                    dateFormat: "MM d",
                    buttonText: "Open the calendar popup.",
                    defaultDate : new Date(defaultYr, 0, 1),
                    minDate : new Date(defaultYr, 0, 1),
                    maxDate : new Date(defaultYr, 11, 31),
                    beforeShow : function(input, inst) {
                        $(inst.dpDiv).addClass("birthday");
                    }
                }
			);
            // this is to hide the date picker prior to the
            // user activating the calendar
            $("#ui-datepicker-div").css('display', 'none');
        });
    };
    
    var BindCalendarControls = function() {

        var calQstns = $("#questions input[fType='5']:not(.birthday)"); //  Non-birthday date fields
        calQstns.each(function() {
            $(this)
                .datepicker(
                {
                    showOn: "button",
                    buttonImage: datepickerImgUrl,
                    buttonImageOnly: true,
                    dateFormat: "mm/dd/yy",
                    buttonText: "Open the calendar popup.",
                    changeMonth : true,
                    changeYear : true,
                    beforeShow : function(input, inst) {
                        $(inst.dpDiv).removeClass("birthday");
                    }                   
                }
			);
            // this is to hide the date picker prior to the
            // user activating the calendar
            $("#ui-datepicker-div").css('display', 'none');
        });
    };

    var BindSubmit = function() {
        $("#submitBtn").bind("click", SubmitForm);

    };

    var SubmitForm = function() {
        var shouldSubmit = ValidateForm();

        if (shouldSubmit) {
            //  Prepare birthday values for submission
            var birthdays = $("input.birthday:visible");
            birthdays.each(PrepareBirthdays);
        }
        
        return shouldSubmit;
    };

    var ValidateForm = function() {
        
        isFormValid = true;
        $("#questions .validation-msg").text("");
        var allInputs = $("#questions input[ftype!='9']:not(.birthday)"); // no multiselects and no birthdays
        allInputs.each(ValidateInput);
        
        var birthdays = $("#questions input.birthday:visible"); //  Validate only the visible birthday input
        birthdays.each(ValidateBirthday);
                
        var allReqMulti = $("div[isRequired='True'][fType='9']");
        allReqMulti.each(ValidateMultiselect);
        
        var allSelects = $("#questions select");
        allSelects.each(ValidateInput);

        if (isFormValid) {
            return true;
        } else {
            return false;
        }
    };

    var PrepareBirthdays = function() {
        var input = $(this);
        var value = jQuery.trim(input.val());
        value += ", 2000";  //  Add the default year
        
        //  Get a new date
        var date = new Date(value);
        
        //  Find the hidden field to use for submission
        var name = input.attr("name");
        var id = name.substr(0, name.indexOf("_"));
        var submitField = $("input[name='" + id + "']");
        submitField.val(date.format("MM/dd/yyyy"));
    };
    
    var ValidateBirthday = function() {
        var input = $(this);
        var errorMSg = "";
        var value = jQuery.trim(input.val());
        if (value == "") {
            if (input.attr("isRequired") == "True") {
                errorMSg += "Field required. Please enter a value";
            }
        } else {
            // Expecting Month day (eg January 31)
            value += ", 2000";  //  Add the default year
            
            if (isNaN(Date.parse(value)))
                errorMSg += "Please enter a valid birthday (ex: January 31)";
        }
        
        if (errorMSg != "") {
            $(".validation-msg", input.parents(".question")).text(errorMSg);
            isFormValid = false;
        }
    };

    var ValidateInput = function() {

        var input = $(this);
        var errorMSg = "";
        var value = jQuery.trim(input.val());
        if (value == "") {
            if (input.attr("isRequired") == "True") {
                errorMSg += "Field required. Please enter a value";
            }
        } else {

            switch (input.attr("name")) {
                case ContactField.PersonalEmail:
                    if (!emailValRegExpObj.test(value)) {
                        errorMSg += "Invalid email address ";
                    }
                    break;
                case ContactField.BizEmail:
                    if (!emailValRegExpObj.test(value)) {
                        errorMSg += "Invalid email address ";
                    }
                    break;
            }



            switch (input.attr("fType")) {
                case QuestionType.Text:
                    var allowedStringLength = input.attr("maxLength");
                    if (!Validation.IsValidTextValue(value, allowedStringLength)) {
                        errorMSg += "Please enter a text value that does not exceed " + allowedStringLength + " characters.";
                    }
                    break;
                case QuestionType.Phone:
                    if (!Validation.IsValidPhoneNumber(value)) {
                        errorMSg += "Please enter a valid phone number";
                    } else {
                        if (!Validation.IsValidPhoneExtensionNumber(input.next().val(), 0)) {
                            errorMSg += "Please enter a valid phone extension";
                        }
                    }
                    break;
                case QuestionType.Date:
                    if (!Validation.IsValidDate(value)) {
                        errorMSg += "Please enter a valid date (mm/dd/yyyy)";
                    }
                    break;
                case QuestionType.Number:
                    var allowedDecimalPlaces = input.attr("decimalPlaces");
                    if (!Validation.IsValidNumber(value, allowedDecimalPlaces)) {
                        errorMSg += "Please enter a valid number (Max. decimal places: " + allowedDecimalPlaces + ")";
                    }
                    break;
                case QuestionType.Percentage:
                    var allowedDecimalPlaces = input.attr("decimalPlaces");
                    if (!Validation.IsValidNumber(value, allowedDecimalPlaces)) {
                        errorMSg += "Please enter a valid percent number (Max. decimal places: " + allowedDecimalPlaces + ")";
                    }
                    break;
                case QuestionType.Currency:
                    if (!Validation.IsValidNumber(value, 2)) {
                        errorMSg += "Please enter a valid currency (Max. decimal places: 2)";
                    }
                    break;
            }
        }
        if (errorMSg != "") {
            $(".validation-msg", input.parents(".question")).text(errorMSg);
            isFormValid = false;
        }
    };

    var ValidateMultiselect = function() {
        var multi = $(this);
        var sel = $("input:checked", multi);
        if (sel.length == 0) {
            isFormValid = false;
            $(".validation-msg", multi.parents(".question")).text("Please select at least one");
        }
    };

};
