﻿

var WebcodaValidation = new function () {

    /// Init and Error reposting code

    var FieldNoteTemplate = "<span id='[CLIENTID]' class='validationFieldNoteContainer'>[IMAGE]<span class='validationFieldNoteText'>[MESSAGE]</span></span>";

    this.Init = function () {
        this.ErrorsList = new Array();
        this.DisplayValidationFieldNote = true;
        this.HasErrors = false;
        this.FocusInputOnError = true;
        this.ErrorIndicatorIcon = "<img src='/NSWBC/images/icons/bullet-red.png' class='validationFieldNoteIcon'/>";
    }

    this.AddError = function (errorMessage) {
        this.HasErrors = true;
        this.ErrorsList[this.ErrorsList.length] = errorMessage;
    };

    //Use this if you want to place all validation together in some box. Call this after ex. (WebcodaValidation.RequiredInput etc.) not before
    var DownErrorTemplate = "<hr /><b><span class='errorMessage'>Please correct following errors</span></b><div id='uiLblMessageInner'></div>";
    this.MoveAllErrors = function (targetDivID) {
        $(".validationFieldNoteContainer").each(function () {
            var validationPnl = $(this).detach();
            if ($('#' + targetDivID).children().length == 0) {
                $(DownErrorTemplate).appendTo('#' + targetDivID);
            }
            validationPnl.appendTo('#uiLblMessageInner');
            validationPnl.css("display", "block");
            $(".validationFieldNoteIcon", validationPnl).hide();
            if ($(this).children().length >= 1) {
                $("#" + targetDivID).show();
            }
        });
        $("#uiLblMessageInner").bind("DOMNodeRemoved", function (objEvent) {
            if ($(this).children().length <= 1) {
                $("#" + targetDivID).hide();
            }
        });
    };

    this.SetInputStatus = function (input, hasErrors, errorMessage) {
        var errorIndicatorID = input.attr("id") + "_ReqAlert";
        if (hasErrors) {
            this.AddError(errorMessage);
            if (this.DisplayValidationFieldNote) {
                try {
                    if ($("#" + errorIndicatorID).length > 0) {
                        //already there, do not add second alert
                    } else {
                        $(FieldNoteTemplate.replace("[CLIENTID]", errorIndicatorID).replace("[IMAGE]", this.ErrorIndicatorIcon).replace("[MESSAGE]", errorMessage)).insertAfter(input);
                        input.change(function () { $("#" + errorIndicatorID).remove(); });
                    }
                } catch (e) { alert(e.Message); }
            }
            if (this.FocusInputOnError) {
                input.focus(); 
            }
        } else {
            if (this.DisplayValidationFieldNote) {
                try {
                    if ($("#" + errorIndicatorID).attr("id")) {
                        $("#" + errorIndicatorID).remove();
                    }
                } catch (e) { }
            }
        }
        //  TODO: wire up on change event to remove the class one content is changed
    };


    this.GetErrorsAsText = function () {
        return this.ErrorsList.join("\n");
    }

    this.GetErrorsAsHtml = function () {
        return this.ErrorsList.join("<br/>");
    }

    this.GetErrorsAsHtmlUL = function () {
        var errors = "<ul class='validationMessage'>";
        for (var x = 0; x < this.ErrorsList.length; x++) {
            errors = errors + "<li>" + this.ErrorsList[x] + "</li>";
        }
        errors = errors + "</ul>";

        return errors;
    }

    this.DisplayError = function (title, containerID) {
        $("#" + containerID).html("<div class='errorMessage'><hr/><b>" + title + "</b><br/>" + this.GetErrorsAsHtml() + "</div>");
    }


    /// Basic validation functions

    this.Trim = function (value) {
        return value.replace(/^\s+|\s+$/g, "");
    };


    this.IsValidEmail = function (value) {
        var re = new RegExp("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
        return re.test(value);
    };


    this.IsValidUrl = function (value) {
        var regexp = /(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
        return regexp.test(value);
    };

    this.IsEmpty = function (value) {
        if (value.replace(/[\s]+/g, "").length == 0) {
            return true;
        } else {
            return false;
        }
    };

    this.IsNumeric = function (value) {
        return (value - 0) == value && value.length > 0;
    };


    /// Form fields validation functions

    this.RequiredNumericInput = function (inputClientId, errorMessage) {
        var input = $("#" + inputClientId);
        var hasErrors = this.IsNumeric(input.val());
        this.SetInputStatus(input, hasErrors, errorMessage);
    };

    this.RequiredInput = function (inputClientId, errorMessage) {
        var input = $("#" + inputClientId);
        var hasErrors = this.IsEmpty(input.val());
        this.SetInputStatus(input, hasErrors, errorMessage);
    };

    this.RequiredSameInput = function (inputOrigClientId, inputConfirmClientId, errorMessage) {
        var inputOrig = $("#" + inputOrigClientId);
        var inputConfirm = $("#" + inputConfirmClientId);
        var hasErrors = (inputOrig.val() != inputConfirm.val());
        this.SetInputStatus(inputConfirm, hasErrors, errorMessage);
    };

    this.RequiredMoreThenZero = function (inputClientId, errorMessage) {
        var input = $("#" + inputClientId);
        var hasErrors = parseInt(input.val()) <= 0;
        this.SetInputStatus(input, hasErrors, errorMessage);
    };

    this.RequiredDropDown = function (inputClientId, errorMessage) {
        var input = $("#" + inputClientId);
        var hasErrors = this.IsEmpty(input.val());
        this.SetInputStatus(input, hasErrors, errorMessage);
    };

    this.RequiredDropDownMultiselect = function (inputClientId, errorMessage) {
        var input = $("#" + inputClientId);
        var hasErrors = input.val() == null || this.IsEmpty(input.val().toString());
        this.SetInputStatus(input, hasErrors, errorMessage);
    };

    this.RequiredCheckBox = function (inputClientId, errorMessage) {
        var inputChecked = $("#" + inputClientId + ":checked");
        var hasErrors = inputChecked.val() == null;
        this.SetInputStatus($("#" + inputClientId), hasErrors, errorMessage);
    };

    this.RequiredEmail = function (inputClientId, errorMessage) {
        var input = $("#" + inputClientId);
        var hasErrors = !this.IsValidEmail(input.val());
        this.SetInputStatus(input, hasErrors, errorMessage);
    };

    this.RequiredUrl = function (inputClientId, errorMessage) {
        var input = $("#" + inputClientId);
        var hasErrors = !this.IsValidUrl(input.val());
        this.SetInputStatus(input, hasErrors, errorMessage);
    };

    //  Rad Controls

    this.RequiredRadInput = function (inputClientId, errorMessage) {
        var input = $find(inputClientId);   //return a reference to RadControl
        var hasErrors = (input.get_value().length == 0);
        this.SetInputStatus($("#" + inputClientId), hasErrors, errorMessage);
    };


    this.RequiredRadEditor = function (inputClientId, errorMessage) {
        var input = $find(inputClientId); //return a reference to RadControl
        var hasErrors = (input.get_text().replace(/[\s]+/g, "").length == 0);
        this.SetInputStatus($("#" + inputClientId), hasErrors, errorMessage);
    };


    this.RequiredRadDate = function (inputClientId, errorMessage) {
        var input = $find(inputClientId);   //return a reference to RadControl
        var hasErrors = (input.get_selectedDate() == null);
        this.SetInputStatus($("#" + inputClientId).parent(), hasErrors, errorMessage);
    };


}


function creditCardValidation(CC) {
    if (CC.length > 19)
        return (false);

    sum = 0; mul = 1; l = CC.length;
    for (i = 0; i < l; i++) {
        digit = CC.substring(l - i - 1, l - i);
        tproduct = parseInt(digit, 10) * mul;
        if (tproduct >= 10)
            sum += (tproduct % 10) + 1;
        else
            sum += tproduct;
        if (mul == 1)
            mul++;
        else
            mul--;
    }
    if ((sum % 10) == 0)
        return (true);
    else
        return (false);
}
