﻿(function ($) {
    $.xlib = { version: '0.9.0' };
    $.xlib.debug = false; // kad je debug mod prikazuju se greške
    $.xlib.msgRequired = "Obavezan podatak.";
    $.xlib.msgMinLength = "Morate upisati najmanje {0} znakova.";
    $.xlib.msgNumbersOnly = "Dozvoljene su samo znamenke.";
    $.xlib.msgEqual = "Vrijednosti za '{0}' i '{1}' nisu identične.";
    $.xlib.iValMinLength = 4;

    // dodaje watermark zadanom elementu
    //npr. $("#input").addWatermark("upišite text...");
    $.fn.addWatermark = function (defvalue) {
        $(this.selector).each(function () {
            if ($.trim(this.value) == "") {
                this.value = defvalue;
                this.style.color = "#cccccc"
            }
        });

        $(this.selector).focus(function () {
            if (this.value == defvalue) {
                this.value = "";
                this.style.color = "black";
            }
        });

        $(this.selector).blur(function () {
            if ($.trim(this.value) == "") {
                this.value = defvalue;
                this.style.color = "#cccccc"
            }
        });
    }


})(jQuery);


$.ltrim = function (value) {
    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
};

$.rtrim = function (value) {
    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");
};

$.isUndefined = function (x) { var u; return x === u; }

$.isUndefinedEx = function (x) { return this.isUndefined(x) || x == null || (typeof (x) == "string" && x.length == 0); }

$.parseIntEx = function (x) {
    var res = 0;

    try {
        res = parseInt(x);
        if (isNaN(res)) res = 0;
    }
    catch (ex) {
        res = 0;
    }

    return res;
}

$.xlib.validate = function (params) {
    /* primjer poslanih parametara za validaciju
    [
    {
    type: "required",               required, equal, minlen, password
    //                              password uključuje required i minlen
    element: "txtLogin",            kontrole za validaciju, array ako je tip = equal, npr ["txtPassword", "txtPasswordConfirm"]
    label: "Korisničko ime"         nazivi koji se ispisuju u pojedinim porukama, npr kod tipa equal; string ili Array
    display: "valLogin",            element na kojem će biti prikazana poruka; podržani elementi: 
    //                              img - poruka se nalazi u title -u
    message: "Obavezan podatak"     ukoliko se tip sastoji od više podtipova message treba biti Array, npr. za password
    //                              ["Obavezan podatak", "Ne smije biti upisano manje od {0} znakova."]  
    //                              ukoliko se ovaj property ne definira uzimaju se defaultne vrijednosti
    },
    {
    type: "password", 
    len: 5,                         ukoliko je tip = minlen, defaultna vrijednost = 6
    element: "txtPassword",     
    display: "valPassword",         
    message: ["Obavezan podatak", "Ne smije biti upisano manje od {0} znakova."]                
    }   
    ]
    */

    var sxv = "xlib.validate: ";

    if ((params == null) || !$.isArray(params) || (params.length == 0)) {
        if (this.debug)
            alert(sxv + 'ulazni parametar mora biti array');

        return false;
    }

    var foo, type, el, el1, vld, val, val1, msg;
    result = true;
    _focus = false;

    try {
        for (var i = 0, x = params.length; i < x; i++) {
            type = params[i].type;

            if ($.isUndefinedEx(type) || (typeof (type) != "string")) {
                if (!this.debug) continue;
                else throw sxv + "tip nije definiran";
            }

            type = $.trim(type).toLowerCase();

            foo = params[i].element;

            if (!$.isUndefinedEx(foo)) {
                if (typeof (foo) == "string") el = $.trim(foo);
                else if ($.isArray(foo) && foo.length > 0) {
                    el = foo[0];
                    el1 = (foo.length > 1) ? foo[1] : "";
                }
            }

            el = $("#" + el);

            if (el.length == 0) {
                if (!this.debug) continue;
                else throw sxv + "nije definiran parametar 'element'";
            }

            vld = $("#" + params[i].display);

            if (vld.length == 0) {
                if (!this.debug) continue;
                else throw sxv + "nije definiran HTML element na kojem se prikazuje poruka";
            }

            //TODO: riješiti slučajeve kad nije textbox
            val = $.trim(el.val());
            el.val(val);

            foo = params[i].message;

            if (!$.isUndefinedEx(foo)) {
                if (typeof (foo) == "string")
                    msg = foo;
                else // array?
                    if (!$.isUndefinedEx(foo[0])) msg = foo[0];
            }
            else
                msg = null;

            switch (type) {
                case "required":
                    ValidateRequired();
                    break;
                case "equal":
                    el1 = $("#" + el1);

                    if (el1.length == 0) {
                        if (!this.debug) continue;
                        else throw sxv + "nije definiran drugi element";
                    }

                    //TODO: riješiti slučajeve kad nije textbox
                    val1 = $.trim(el1.val());
                    el1.val(val1);

                    if (val != val1) {
                        result = false;
                        vld.css("display", "");
                        foo = params[i].label;

                        if ($.isUndefinedEx(foo))
                            foo = ['?', '?'];

                        if ($.isUndefinedEx(msg))
                            msg = $.xlib.msgEqual;

                        msg = msg.replace("{0}", foo[0]).replace("{1}", foo[1]);

                        if (vld.is("img"))
                            vld.attr("title", msg);

                        if (!_focus) {
                            el.focus();
                            _focus = true;
                        }
                    }
                    else {
                        vld.css("display", "none");
                    }

                    break;
                case "minlen":
                    ValidateMinlen();
                    break;
                case "password":
                    ValidateRequired();

                    if (result) {
                        if (typeof (params[i].message) == "array")
                            msg = params[i].message[1];

                        ValidateMinlen();
                    }
                    break;
                default:
                    throw "xlib.validate: tip '" + type + "' nije podržan";
                    break;
            }

        }

    }
    catch (ex) {
        if (this.debug) {
            if (typeof (ex) == "string") alert(ex);
            else alert(ex.message)
        }

        result = false;
    }

    return result;


    function ValidateRequired() {
        if (val.length == 0) {
            result = false;
            vld.css("display", "");

            if ($.isUndefinedEx(msg))
                msg = $.xlib.msgRequired;

            if (vld.is("img"))
                vld.attr("title", msg);

            if (!_focus) {
                el.focus();
                _focus = true;
            }
        }
        else {
            vld.css("display", "none");
        }
    };

    function ValidateMinlen() {
        foo = $.parseIntEx(params[i].len);

        if (foo == 0)
            foo = $.xlib.iValMinLength;

        if (val.length < foo) {
            result = false;
            vld.css("display", "");

            if ($.isUndefinedEx(msg))
                msg = $.xlib.msgMinLength;

            msg = msg.replace("{0}", foo);

            if (vld.is("img"))
                vld.attr("title", msg);

            if (!_focus) {
                el.focus();
                _focus = true;
            }
        }
        else {
            vld.css("display", "none");
        }
    }

};
