﻿var dateValidationRegEx = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
var emailValidationRegEx = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i

var AlertQueue = new Array();
var vGroup = null;
var hkValidateForm = function(group, clear) {
    try { tb_remove(); }
    catch (ex) { }
    //var group = sender.getAttribute('vgroup');
    //vGroup = group;
    AlertQueue = new Array();
    var filter = "[validate='true']";
    var filter2 = "[vgroup='" + group + "']";
    var vFields = $(filter + filter2);
    for (var i = 0; i < vFields.length; i++) {
        var field = vFields.get(i);
        var field2 = null;
        if (field) {
            if (field.nodeName.toLowerCase() == "span")
                field2 = field.firstChild;
            var origLen = AlertQueue.length;
            var errMsg = field.getAttribute('errMsg');
            var errElem = field.getAttribute('errElement');
            if (!IsNullOrEmpty(errElem))
                $("#" + errElem).css({ color: '' });
            else
                $(field).css({ color: '' });
            var friendlyName = field.getAttribute('friendlyName');
            var validationType = field.getAttribute('validationType').toLowerCase();
            var arrVType = new Array();
            var nodeType = field2 == null ? field.getAttribute('type') : field2.getAttribute('type');
            if (field.nodeName.toLowerCase() == 'select')
                nodeType = "select";
            if (field.nodeName.toLowerCase() == 'textarea')
                nodeType = "text";
            arrVType = validationType.split(" ");
            var required = ($.inArray("required", arrVType) != -1);
            var dateValidate = ($.inArray("date", arrVType) != -1);
            var emailValidate = ($.inArray("email", arrVType) != -1);
            var phoneValidate = ($.inArray("phone", arrVType) != -1);
            var regexValidate = ($.inArray("regex", arrVType) != -1);
            var numberValidate = ($.inArray("number", arrVType) != -1);
            var conditionalValidate = ($.inArray("conditional", arrVType) != -1);
            var condition = field.getAttribute('condition');
            var regularExpression = new RegExp(field.getAttribute('regex'), 'i');
            regularExpression.ignoreCase = true;
            var conditionalError = field.getAttribute('conditionalErrMsg');

            if (conditionalValidate) {
                if (eval(condition)) {
                    if (nodeType.toLowerCase() == 'checkbox' || nodeType.toLowerCase() == 'radio') {
                        if (field2) {
                            if (required && !field2.checked)
                                AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " is required.", type: "error" };
                        } else {
                            if (required && !field.checked)
                                AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " is required.", type: "error" };
                        }
                    } else {
                        if (required && IsNullOrEmpty(field.value)) {
                            AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " is required.", type: "error" };
                        } else {
                            if (dateValidate)
                                if (!field.value.match(dateValidationRegEx))
                                AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " must be a valid date.", type: "error" };
                            if (emailValidate)
                                if (!field.value.match(emailValidationRegEx))
                                AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " must be a valid email.", type: "error" };
                            if (numberValidate)
                                if (!IsNumeric(field.value))
                                AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " must be a valid number.", type: "error" };
                            if (regexValidate)
                                if (!field.value.match(regularExpression))
                                AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " must match the regex.", type: "error" };
                        }
                    }
                } else {
                    AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(conditionalError) ? conditionalError : friendlyName + " must meet its condition.", type: "error" };
                }
            } else {
                if (nodeType.toLowerCase() == 'checkbox') {
                    if (field2) {
                        if (required && !field2.checked)
                            AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " is required.", type: "error" };
                    } else {
                        if (required && !field.checked)
                            AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " is required.", type: "error" };
                    }
                } else {
                    if (required && IsNullOrEmpty(field.value)) {
                        AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " is required.", type: "error" };
                    } else {
                        if (dateValidate)
                            if (!IsNullOrEmpty(field.value) && !field.value.match(dateValidationRegEx))
                            AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " must be a valid date.", type: "error" };
                        if (emailValidate)
                            if (!IsNullOrEmpty(field.value) && !field.value.match(emailValidationRegEx))
                            AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " must be a valid email.", type: "error" };
                        if (numberValidate)
                            if (!IsNullOrEmpty(field.value) && !IsNumeric(field.value))
                            AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " must be a valid number.", type: "error" };
                        if (regexValidate)
                            if (!field.value.match(regularExpression))
                            AlertQueue[AlertQueue.length] = { msg: !IsNullOrEmpty(errMsg) ? errMsg : friendlyName + " must match the regex.", type: "error" };
                    }
                }
            }
            if (AlertQueue.length != origLen) {
                if (!IsNullOrEmpty(errElem))
                    $("#" + errElem).css({ color: '#A22' });
                else
                    $(field).css({ color: '#A22' });
            }
        }
    }
    vGroup = '';
    return ShowNotification();
};

var IsNullOrEmpty = function(value) {
    return (value == null || value == "");
}

var ShowNotification = function() {
    $("#validationResponse").remove();
    if (AlertQueue.length == 0)
        return true;
    var ErrValidationLightBox = "<div id='validationResponse' style='display:none;'>" +
     "<div style='background-color: #fff; border-width: 1px; border-style: solid; border-color: #999999;" +
     "width: 330px; height: 200px; padding: 15px;'><div style='margin-left:15px; float:right; text-align:left; display: inline; cursor: pointer;'>" +
     "<img src='/images/closeBtn.gif' alt='close' width='54' height='8' border='0' onclick='tb_remove();' /></div>" +
     "<div style='background-color: #fff; float:left; height: 160px; width:300px; overflow: auto; text-align:left; padding:15px; display: inline;'>" +
     "<p style='color: red; font-weight: bold'>The following errors must be corrected before you can submit this form:</p><ol>";
    for (var i = 0; AlertQueue[i]; i++) {
        if (AlertQueue[i].type == "error")
            ErrValidationLightBox += "<li style='color:red; margin-left: 30px;'>" + AlertQueue[i].msg + "</li>";
    }
    ErrValidationLightBox += "</ol></div></div>";
    $("body").append(ErrValidationLightBox);
    tb_show('Errors!', '#TB_inline?height=300&width=400&modal=true&inlineId=validationResponse', null);
    return false;
}

function IsNumeric(sText) {
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;

    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

function DateDiff(date1, date2) {
    if (IsNullOrEmpty(date1))
        return 1;
    var dt1 = Date.parse(date1);
    var dt2 = Date.parse(date2);
    return dt1 - dt2;
}

$(document).ready(function() {
    $("textarea[maxlen][label]").each(
        function(i) {
            var CountLabel = $(this).attr("label");
            var MaxLen = $(this).attr("maxlen");
            var CurLen = $(this)[0].value.length;
            var value = $(this)[0].value;
            if (!IsNullOrEmpty(CountLabel)) {
                $("#" + CountLabel).text(MaxLen - CurLen);
            }
        }
    );
    $("textarea[maxlen][label]").keydown(function() {
        var CountLabel = $(this).attr("label");
        var MaxLen = $(this).attr("maxlen");
        var CurLen = $(this)[0].value.length;
        var value = $(this)[0].value;
        if (MaxLen - CurLen < 0) {
            $(this).val(value.substring(0, MaxLen));
            return false;
        }
        if (!IsNullOrEmpty(CountLabel)) {
            $("#" + CountLabel).text(MaxLen - CurLen);
        }
    });
    $("textarea[maxlen][label]").keyup(function() {
        var CountLabel = $(this).attr("label");
        var MaxLen = $(this).attr("maxlen");
        var CurLen = $(this)[0].value.length;
        var value = $(this)[0].value;
        if (MaxLen - CurLen < 0) {
            $(this).val(value.substring(0, MaxLen));
            return false;
        }
        if (!IsNullOrEmpty(CountLabel)) {
            $("#" + CountLabel).text(MaxLen - CurLen);
        }
    });
});