var TICK_INT = 5 * 60 * 1000;//5 min

var unitML = 'caracteres';

//showMandatory -> definir na página

$(document).ready(function() {
    window.setTimeout(tick, TICK_INT);

    $(".sNumber, .sDecimal").attr("maxlength", "14");
    $(".sEuro").attr("maxlength", "16");
    $(".sCP7").attr("maxlength", "8");
    $(".sDate").attr("maxlength", "10");

    $(".sEuro").attr("title", function () {
        var t = $(this).attr("title");
        return (t != null && t.length ? t + "<br/>" : "" ) + "formato: <strong>xxx,xxx.xx</strong>";
    });

    $(".sDate").attr("title", function () {
        var t = $(this).attr("title");
        return (t != null && t.length ? t + "<br/>" : "" ) + "formato: <strong>aaaa/mm/dd</strong>";
    });

    $(".sPerc").attr("title", function () {
        var t = $(this).attr("title");
        return (t != null && t.length ? t + "<br/>" : "" ) + "formato: <strong>xxx.xx%</strong>";
    });


    //JAVASCRIPT CHECKERS
    $(".sPerc").bind("keyup", checkPerc);
    $(".sNumber").bind("keyup", checkNumber);
    $(".sDate").bind("keyup", checkDate);
    $(".sDate").bind("change", checkDate);
    $(".sCP7").bind("change", checkCP7);
    $(".sNif").bind("change", checkNIF);
    $(".sEmail").bind("change", checkEmail);
    $(".sEuro").bind("keyup", checkEuro);
    $(".sDecimal").bind("keyup", checkDecimal);


    $(".repeatable input,.repeatable select,.repeatable textarea").bind("change", repeatableChange);

    $(document.body).append("<div id='helpbox' style='display:none'></div>");

    fireupMandatoryShow();


    //CHANGED FORMULARIO
    $("#formulario").bind("submit", function() {
        $('#formulario').attr('changed', 'false');
        return true;
    });

    $("input, select, textarea", $("#formulario")).bind("change", function() {
        $("#formulario").attr("changed", "true");
    });

    $("#formulario input,#formulario textarea").focus(ifocus);
    $("#formulario input,#formulario textarea").blur(iblur);

    //MAX LENGTH
    if (typeof maxLength == "undefined" || typeof unitML == "undefined") return;
    jQuery.each(maxLength, function(name, val) {
        var el = $("#" + name).not(".sNML");
        if (el.length && el.attr("name")) {
            el = $("*[name=" + el.attr("name") + "]");
        }
        el.attr("myMax", val);
        if (typeof el.attr("title") != "undefined" && jQuery.trim(el.attr("title")).length > 0) {
            el.attr("title", el.attr("title") + "<br/>" + "Máximo:" + val + " " + unitML);
        } else {
            el.attr("title", "Máximo:" + val + " " + unitML);
        }
    });
});

function tick() {
    jQuery.post("/si/ws");
    window.setTimeout(tick, TICK_INT);
}


function repeatableChange() {
    if ($(this).val()) {
        var rep = $(this).parents(".repeatable")[0];
        var isLastRow = !$(rep).next().hasClass("repeatable");
        if (isLastRow) {
            var doClone = true;


            if (doClone)
            {
                var el = $(rep).clone(true);
                $(el).insertAfter($(rep));
                $("input, textarea", el).each(function () {
                    $(this).val("");
                    if ($(this).hasClass("sPerc")) $(this).val("0.00%");
                });
                $(".iinfo", el).remove();
                $(document).trigger("repeatableChange",el);
            }

        }
    }
}


function handleNumber() {
    var dt = $(this).val();
    $(this).next(".errInfo").remove();
    if (dt != null && dt != "" && !new RegExp("^\\d+$").test(dt)) $(this).after("<span class='errInfo'>Número inválido</span>");
}


function fireupMandatoryShow() {
    if (typeof showMandatory != "undefined") {
        jQuery.each(showMandatory, function() {
            var el = $("label[for=" + this + "]");
            if (el.length && el.text().indexOf("*") < 0) {
                el.text($(el[0]).text() + "*");
            }
        });
    }
}

function go(uri) {
    document.location.href = uri;
    return false;
}


function ifocus() {
    var el = $(this);
    var h = el.attr("title");

    var f = el.attr("validationFailure");
    if (h)
    {
        var bhelp = $("#helpbox");
        bhelp.css("opacity",.9)
        bhelp.html(h);
        if (f && f.length)
            bhelp.html(bhelp.html() + "<div class='helpFailure'>" + f + "</div>");

        bhelp.css("top", el.offset().top + el.outerHeight() + 2);
        bhelp.css("left", el.offset().left);

        bhelp.show();

    }
}
function iblur() {
    var el = $(this);
    var max = el.attr("myMax");
    if (max) {
        if (el.val() != null) {
            var len = jQuery.trim(el.val()).length;
            if (len > max) {
                setJSError(this, "Máximo de " + max + " excedido em " + (len - max) + " " + unitML);
            }
            else setJSError(this, null);
        }
    }

    $("#helpbox").hide();
}


function checkNumber() {
    var v = $(this).val();
    var m = "";
    if (v && !v.match(/^\d*$/)) {
        m = "número inválido";
    }
    setJSError(this, m);
}

function checkEuro() {
    var v = $(this).val();
    v = v.replace(/,/g, "");
    var m = "";
    if (v && !v.match(/^\d{0,13}$/) && !v.match(/^\d{0,13}\.\d{1,2}$/)) {
        m = "valor inválido";
    }
    setJSError(this, m);

}

function checkDecimal() {
    var v = $(this).val();
    v = v.replace(/,/g, "");
    var m = "";
    if (v && !v.match(/^-?\d*$/) && !v.match(/^-?\d*\.\d*$/)) {
        m = "número inválido";
    }
    setJSError(this, m);

}


function checkPerc() {
    var v = $(this).val();

    var m = "";
    if (v && !v.match(/^\d+%$/) && !v.match(/^\d*\.\d+%$/)) {
        m = "percentagem inválida";
    } else {
        if (parseFloat(v) > 100)
            m = "percentagem inválida";
    }
    setJSError(this, m);

}
function checkDate() {
    var v = $(this).val();
    var m = "";
    if (v && !v.match(/^\d\d\d\d\/[0,1]?\d\/[0,1,2,3]?\d$/)) {
        m = "data inválida";
    }
    setJSError(this, m);

}

function checkCP7() {
    var v = $(this).val();

    var m = "";
    if (v && !v.match(/^\d\d\d\d-\d\d\d$/)) {
        m = "inválido";
    } else {
        /* $.getJSON("isCP7.jsp", {cp7:v}, function(ok) {
         if (!ok)
         {
         m = "código inexistente";
         } else {
         $(inpLoc).val(ok.localidade);
         m ="";
         }

         setJSError(inp, m);
         });  */
    }

    setJSError(this, m);
}

function checkNIF() {
    var v = $(this).val();
    var m = "";
    var ok = true;

    if (v.length != 9)
        ok = false;
    else {
        var c = v.charAt(0);
        if ((c == '0') || (c == '3') || (c == '4') || (c == '7') || (c == '8'))
            ok = false;
        else
            ok = AlgoritmoValidacao(v);
    }

    if (v && !ok) {
        m = "NIF inválido";
    }

    setJSError(this, m);


    return m.length == 0;
}


function checkEmail() {
    var email = $(this).val();
    var m = "";

    if (email && email.match("[^ ]+@[^ ]+\\.[^ ]+") == null)
        m = "email inválido";

    setJSError(this, m);

}

function setJSError(obj, err)
{
    $(".iinfo", $(obj).parent()).remove();
    if (err)
        $(obj).after("<span class='iinfo'>" + err + "</span>");


}

function AlgoritmoValidacao(numFormated) {
    var pos, ctl, val = 0;
    for (pos = 0; pos < 8; ++pos) {
        val += parseInt(numFormated.charAt(pos)) * (9 - pos);
    }

    ctl = 0;
    if ((val % 11) != 0)
        ctl = (11 - val % 11) % 10;
    return ctl == parseInt(numFormated.charAt(8));
}

