﻿// Setup jQuery.validate
$.validator.setDefaults({
    ignore: ".ignore",       
    onsubmit: false,
    onfocusout: false,
    onkeyup: false,
    onclick: false,            
    errorClass: "invalid",
    errorElement: "em",
    errorPlacement: function(error, element) {
        error.prependTo(element.parent());
    },
    showErrors: function(errorMap, errorList) {
        if (this.numberOfInvalids() == 1)
        {
            $("h3", this.settings.errorContainer).text(this.numberOfInvalids() + " field has an invalid value.");
        }
        else
        {
            $("h3", this.settings.errorContainer).text(this.numberOfInvalids() + " fields have invalid values.");
        }
        this.defaultShowErrors();
    },
    highlight: function(element, errorClass) {
        $(element).parent().addClass(errorClass);
    },
    unhighlight: function(element, errorClass) {
        $(element).parent().removeClass(errorClass);
    }
});

// Custom validator for date made up of 3 text boxes...
$.validator.addMethod(
    "validdate",
    function(value, element, params){
        var day = $.trim(value), month = $.trim($(params.month).val()), year = $.trim($(params.year).val());
        
        // First case is special and handled by jQuery validate rule "required"...
        if (day == "" && month == "" && year == "") {
            return true;
        }
        else if (day == "" || isNaN(day) || month == "" || isNaN(month) || year == "" || isNaN(year)) {
            return false;
        }
        else {
            day = Number(day);
            month = Number(month);
            year = Number(year);
        }
        
        /* Validation of month*/
        if (month < 1 || month > 12) {
            return false;
        }
        
        /* Validation of day*/
        if (day < 1) {
            return false;
        }
        
        /* Validation leap-year / february / day */
        if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
            if (month == 2 && day > 29) {
                return false;
            }
        }
        else {
            if (month == 2 && day > 28) {
                return false;
            }
        }
        
        /* Validation of other months */
        if (day > 31) {
            return false;
        }
        
        if (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11)) {
            return false;
        }

        return true;                
    },
    "Please enter a valid date."
);
