﻿ValidatorClass = function (postBackId, argument, enableSchema) {
    this.validators = new Array();
    this.samples = new Array();
    this.listDependencies = new Array();
    this.submitId = null;
    this.postBackId = postBackId;
    this.postBackArgument = argument;
    this.enableSchema = enableSchema;
    this.valResults = new Object();
}

ValidatorClass.prototype = {
    add: function (type, controlid, labelid, associatedId, required, tip, min, max) {
        if (!labelid) {
            labelid = controlid;
        }

        this.validators.push(
            { controlType: type, controlId: controlid, labelid: labelid, associatedId: associatedId, required: required, tip: tip,
                minValue: min, maxValue: max
            }
        );
    },
    addAssociatedValue: function (type, controlid, labelid, associatedId, associatedValue, required, tip, min, max) {
        if (!labelid) {
            labelid = controlid;
        }

        this.validators.push(
            { controlType: type, controlId: controlid, labelid: labelid, associatedId: associatedId, associatedValue: associatedValue, required: required, tip: tip,
                minValue: min, maxValue: max
            }
        );
    },
    addResetter: function (controlid, targetControls) {


        this.validators.push(
            { controlType: "Reset", controlId: controlid, targetControls: targetControls }
        );
    },
    addRegEx: function (controlid, labelid, regEx, associatedId, associatedValue, required, tip) {
        if (!labelid) {
            labelid = controlid;
        }

        this.validators.push(
            {
                controlType: "RegEx",
                controlId: controlid,
                labelid: labelid,
                associatedId: associatedId,
                associatedValue: associatedValue,
                required: required,
                regularExpression: regEx,
                tip: tip
            }
        );
    },
    addListDependency: function (srcId, tgtId) {

        if ($('#' + srcId + " option").length > 1) {
            var obj = { tgtId: tgtId, options: $('#' + tgtId + " option") };
            this.listDependencies[srcId] = obj;

            var presrcval = $('#' + srcId).val();
            var preVal = $('#' + tgtId).val();

            if (presrcval != "") {
                this.rebindList(srcId);
            }

            if (preVal == '') {
                $('#' + tgtId + " option").remove();
            } else {
                $('#' + tgtId).val(preVal);
            }
        }

    },
    addSampleString: function (controlId, text) {
        this.samples[controlId] = text;
        $("#" + controlId).val(text).addClass("sample");
    },
    addPredefinedString: function (controlId, text) {
        $("#" + controlId).val(text);
    },
    addAutoComplete: function (controlId, associatedId, dependencyId, url, minLength) {
        var self = this;
        $("#" + controlId).autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: url + "?dep=" + $("#" + dependencyId).val() + "&maxRows=" + 12 + "&startsWith=" + request.term,
                    cache: false,
                    dataType: "json",
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert('failure : ' + textStatus);
                    },
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            if (data.d.length == 1) {
                                $("#" + controlId).val(data.d[0].Value);
                                $("#" + associatedId).val(data.d[0].AssociatedValue);

                                self.validate(controlId);
                                self.validate(associatedId);

                                if (self.samples[associatedId] != null) {
                                    $("#" + associatedId).removeClass("sample");
                                }

                                return;

                            }

                            return {
                                label: item.Display,
                                value: item.Value,
                                associatedValue: item.AssociatedValue
                            }
                        }));
                    }
                });
            },
            minLength: minLength,
            select: function (event, ui) {
                $("#" + controlId).val(ui.item.value);
                $("#" + associatedId).val(ui.item.associatedValue);

                self.validate(controlId);
                self.validate(associatedId);
                if (self.samples[associatedId] != null) {
                    $("#" + associatedId).removeClass("sample");
                }
                return false;
            },
            open: function () {
                $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            },
            close: function () {
                $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
            }
        });

    },
    initialize: function (submitId) {
        var self = this;
        this.submitId = submitId;

        if (this.enableSchema) {
            $("#" + submitId).bind("click", function () { return false; });
        } else {
            $("#" + submitId).bind("click", function () { self.validate(self.submitId); });
        }

        try {
            $(".slider-range-min").slider({
                range: "min",
                value: 0,
                min: 0,
                max: 100,
                slide: function (event, ui) {
                    $(this).parent().find('input').val(ui.value + ' %');
                    self.validate();
                }
            });
        } catch (err) {
            ;
        }

        var valEvented = new Array();
        for (var x = 0; x < this.validators.length; x++) {
            var v = this.validators[x];
            if (v.controlType == "Reset") {
                $("#" + v.controlId).change(function () {
                    self.reset(this.id);
                });
            }
            else {
                if (valEvented[v.controlId] == null) {
                    switch (v.controlType) {
                        case "Text":
                        case "Email":
                        case "Associated":
                        case "Date":
                        case "RegEx":
                            $("#" + v.controlId).change(function () {
                                self.validate(this.id);
                            });
                            valEvented[v.controlId] = 1;
                            break;
                        case "Select":
                            if (this.listDependencies[v.controlId] == null) {
                                $("#" + v.controlId).change(function () {
                                    self.validate(this.id);
                                });
                                valEvented[v.controlId] = 1;
                            } else {
                                $("#" + v.controlId).change(function () {
                                    self.validate(this.id);
                                    self.rebindList(this.id);
                                });
                                valEvented[v.controlId] = 1;
                            }
                            break;
                        case "Radios":
                        case "CheckBoxes":
                            $("[id^=" + v.controlId + "]").change(function () {
                                self.validate(this.id);
                            });
                            valEvented[v.controlId] = 1;
                            break;
                    }
                }
            }
        }

        $("input:text").focus(function () {
            var id = this.id;
            if (self.samples[id] != null && $(this).val() == self.samples[id]) {
                $(this).val("").removeClass("sample");
            }
        });

        $(".slider_container input").val('');

    },
    rebindList: function (controlId) {
        var val = $('#' + controlId).val() + "_";
        var obj = this.listDependencies[controlId];
        $('#' + obj.tgtId).val("");
        $('#' + obj.tgtId + " option").remove();
        for (var x = 0; x < obj.options.length; x++) {
            var optValue = $(obj.options[x]).val();
            if (optValue.indexOf("DEPENDENCY") != 0 && $(obj.options[x]).val() != "") {
                if ($(obj.options[x]).val().indexOf(val) == 0) {
                    $('#' + obj.tgtId).append(obj.options[x]);
                }
            } else {
                $('#' + obj.tgtId).append(obj.options[x]);
                if (optValue.indexOf("DEPENDENCY") == 0) {
                    $('#' + obj.tgtId).val("DEPENDENCY");
                }
            }
        }


    },
    reset: function (id) {
        for (var x = 0; x < this.validators.length; x++) {
            var v = this.validators[x];
            if (v.controlType == "Reset" && v.controlId == id) {
                for (var y = 0; y < v.targetControls.length; y++) {
                    $("#" + v.targetControls[y]).val("");
                    this.checkSample(v.targetControls[y]);
              //      this.validate(v.targetControls[y]);
                }
            }
        }
    },
    validate: function (id) {
        this.valResults = new Object();


        var valid = true;

        if (id != null && id != this.submitId) {

            valid = this.validateControl(id);
            this.checkSample(id);
            if (!valid && this.enableSchema) {
                valid = valid & this.validateControl(null);
            }
        }

        if (id == this.submitId) {
            valid = valid & this.validateControl(null);
        }

        var self = this;

        if (this.enableSchema) {
            if (valid) {
                $("#" + this.submitId)
                        .removeClass("disabled")
                        .unbind("click")
                        .bind("click", function () {
                            self.removeSamples();
                            $("#" + self.submitId).addClass("disabled").unbind("click");
                            __doPostBack(self.postBackId, self.postBackArgument);
                        });

            } else {
                $("#" + this.submitId).addClass("disabled").unbind("click").bind("click", function () { return false; });
            }
        } else {
            if (id == this.submitId) {
                if (valid) {
                    self.removeSamples();
                    __doPostBack(self.postBackId, self.postBackArgument);
                }
            }
        }

        if (!valid && id == null) {
            $("#error").show();
        } else {
            $("#error").hide();

        }
        return valid;
    },
    removeSamples: function () {
        for (k in this.samples) {
            var val = this.samples[k];
            if ($("#" + k).val() == val) {
                $("#" + k).val("").removeClass("sample");
            }
        }
    },
    checkSample: function (id) {
        var smp = this.samples[id];

        if (smp != null) {
            var value = $("#" + id).val();
            if (value == null || value.length == 0) {
                $("#" + id).val(smp).addClass("sample");
            }
        }
    },

    validateControl: function (id) {
        valid = true;
        for (var x = 0; x < this.validators.length; x++) {
            var v = this.validators[x];
            if (id == null || v.controlId == id) {
                switch (v.controlType) {
                    case "Associated":
                        var v1 = $("#" + v.controlId).val();
                        var v2 = $("#" + v.associatedId).val();

                        if (v1 == this.samples[v.controlId]) v1 = "";
                        if (v2 == this.samples[v.associatedId]) v2 = "";

                        if (
                            (v1.length == 0 && v2.length == 0)) {
                            valid = false;
                            this.SetOK(v.controlId, v.labelid, false, v.tip);
                            continue;
                        }
                        this.SetOK(v.controlId, v.labelid, true, v.tip);
                        // this.SetOK(v.associatedId, v.labelid, true, v.tip);
                        break;
                    case "Date":
                        if ($("#" + v.controlId).val().length == 0 || (this.samples[v.controlId] != null && $("#" + v.controlId).val() == this.samples[v.controlId])) {
                            continue;
                        }

                        var isValid = true;


                        var thisd = "";
                        try {
                            thisd = $.datepicker.parseDate("dd/mm/yy", $('#' + v.controlId).val());
                        }
                        catch (error) {
                            isValid = false;
                        }

                        if (isValid && v.minValue != '') {
                            try {
                                var min = $.datepicker.parseDate("dd/mm/yy", v.minValue);
                                if (thisd < min) isValid = false;
                            }
                            catch (error) {
                                isValid = false;
                            }
                        }

                        if (isValid && v.maxValue != '') {
                            try {
                                var max = $.datepicker.parseDate("dd/mm/yy", v.maxValue);
                                if (thisd >= max) isValid = false;
                            }
                            catch (error) {
                                isValid = false;
                            }
                        }


                        this.SetOK(v.controlId, v.labelid, isValid, v.tip);
                        break;
                    case "Text":
                        if (v.associatedId != null && v.associatedId != "") {
                            var v1 = $("#" + v.associatedId).val();
                            if (v1 != v.associatedValue) {
                                if (valid) {
                                    this.SetOK(v.controlId, v.labelid, valid, v.tip);
                                }

                                continue;
                            }
                        }

                        if ($("#" + v.controlId).val() == null || $("#" + v.controlId).val().length == 0) {
                            valid = false;
                            this.SetOK(v.controlId, v.labelid, false, v.tip);
                            continue;
                        }
                        if (this.samples[v.controlId] != null && $("#" + v.controlId).val() == this.samples[v.controlId]) {
                            valid = false;
                            this.SetOK(v.controlId, v.labelid, false, v.tip);
                            continue;
                        }

                        this.SetOK(v.controlId, v.labelid, true, v.tip);
                        break;
                    case "Email":
                        var value = $("#" + v.controlId).val();
                        if (v.required) {
                            if (value == null || value.length == 0) {
                                valid = false;
                                this.SetOK(v.controlId, v.labelid, false, v.tip);
                                continue;
                            }
                            if (this.samples[v.controlId] != null && value == this.samples[v.controlId]) {
                                valid = false;
                                this.SetOK(v.controlId, v.labelid, false, v.tip);
                                continue;
                            }
                        }

                        if (value != null && value.length > 0) {
                            var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
                            if (!emailPattern.test($("#" + v.controlId).val())) {
                                this.SetOK(v.controlId, v.labelid, false, v.tip);
                                valid = false;
                                continue;
                            }
                        }
                        this.SetOK(v.controlId, v.labelid, true, v.tip);
                        break;
                    case "Select":
                        if ($("#" + v.controlId).val() == null || $("#" + v.controlId).val().length == 0) {
                            this.SetOK(v.controlId, v.labelid, false, v.tip);
                            valid = false;
                            continue;
                        }
                        this.SetOK(v.controlId, v.labelid, true, v.tip);
                        break;
                    case "Radios":
                    case "CheckBoxes":
                        if ($("[id^=" + v.controlId + "]:checked").length == 0) {
                            this.SetOK(v.controlId, v.labelid, false, v.tip);
                            valid = false;
                            continue;
                        }
                        this.SetOK(v.controlId, v.labelid, true, v.tip);
                        break;
                    case "RegEx":
                        if (v.associatedId != null && v.associatedId != "") {
                            var v1 = $("#" + v.associatedId).val();
                            if (v1 != v.associatedValue) {
                                if (valid) {
                                    this.SetOK(v.controlId, v.labelid, valid, v.tip);
                                }
                                continue;
                            }
                        }

                        var value = $("#" + v.controlId).val();

                        if (v.required) {
                            if (value == null || value.length == 0) {
                                valid = false;
                                this.SetOK(v.controlId, v.labelid, false, v.tip);
                                continue;
                            }
                            if (this.samples[v.controlId] != null && value == this.samples[v.controlId]) {
                                valid = false;
                                this.SetOK(v.controlId, v.labelid, false, v.tip);
                                continue;
                            }
                        }

                        if (value != null && value.length > 0) {
                            var pattern = null;
                            var ok = false;
                            try {
                                pattern = v.regularExpression;
                                ok = pattern.test(value);
                            } catch (e) {
                                pattern = new RegExp(v.regularExpression);
                                ok = pattern.test(value);
                            }

                            if (!ok) {
                                this.SetOK(v.controlId, v.labelid, false, v.tip);
                                valid = false;
                                continue;
                            }
                        }
                        this.SetOK(v.controlId, v.labelid, true, v.tip);
                        break;

                }
            }
        }

        return valid;
    },
    SetOK: function (cid, lblid, valid, tip) {
        if (!valid) {
            var cont = "";
            $("[for='" + lblid + "']").addClass("error");
            $("#" + cid).addClass("error");

            $("[for='" + lblid + "']").tooltip("destroy");
            $("#" + cid).tooltip("destroy");

            if (this.valResults[cid]) {
                this.valResults[cid] += "\r\n" + tip;
            } else {
                this.valResults[cid] = tip
            }


            cont = this.valResults[cid];
            $("[for='" + lblid + "']").attr("title", cont);
            $("#" + cid).attr("title", cont);

            $("[for='" + lblid + "']").tooltip({ position: { my: "right top", at: "right top", offset: "0 -30"} });

        } else {
            if (!this.valResults[cid]) {
                $("[for='" + lblid + "']").removeClass("error").removeAttr("title");
                $("#" + cid).removeClass("error").removeAttr("title");

                $("[for='" + lblid + "']").tooltip("destroy");
                $("#" + cid).tooltip("destroy");
            }

        }
    }


}
