if (typeof sistema == undefined || typeof sistema == 'undefined') {
    var sistema = {};
}

sistema.extendPlugins = {
    validate: function() {
        $.extend($.validate.methods, {
            required: function (string) {
                return (string == $.trim(string));
            },
            positive: function (number) {
                number = parseFloat(number);
                if(number < 0) {
                    return false;
                }
                return true;
            },
            cnpj: function(string) {
                // Only accepts non-formated and full-formated
                if (!string.match(/^[0-9]{14}$/) && !string.match(/^[0-9]{2}.[0-9]{3}.[0-9]{3}\/[0-9]{4}-[0-9]{2}$/)) {
                    return false;
                }
                var cnpj = string.replace(/\D/g, '');

                // Verify 0-9 sequences
                for (var i = 0; i <= 9; i++) {
                    if (new Array(15).join(new String(i)) == cnpj) {
                        return false;
                    }
                }

                // Validates the document
                var a = [];
                var b = new Number;
                var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
                for (i=0; i < 12; i++) {
                    a[i] = cnpj.charAt(i);
                    b += a[i] * c[i+1];
                }
                if ((x = b % 11) < 2) {
                    a[12] = 0;
                } else {
                    a[12] = 11 - x;
                }
                b = 0;

                for (y=0; y<13; y++) {
                    b += (a[y] * c[y]);
                }
                if ((x = b % 11) < 2) {
                    a[13] = 0;
                } else {
                    a[13] = 11 - x;
                }

                if (cnpj.charAt(12) != a[12] || cnpj.charAt(13) != a[13]){
                    return false;
                }

                return true;
            },

            cpf: function(string) {
                // Only accepts non-formated and full-formated
                if (!string.match(/^[0-9]{11}$/) && !string.match(/^[0-9]{3}.[0-9]{3}.[0-9]{3}-[0-9]{2}$/)) {
                    return false;
                }
                var cpf = string.replace(/\D/g, '');

                // Verify 0-9 sequences
                for (var i = 0; i <= 9; i++) {
                    if (new Array(12).join(new String(i)) == cpf) {
                        return false;
                    }
                }

                // Validates the document
                var a = [];
                var b = new Number;
                var c = 11;
                for (var k = 0; k < 11; i++) {
                    a[k] = cpf.charAt(i);
                    if (k < 9) {
                        b += (a[k] * --c);
                    }
                }
                if ((x = b % 11) < 2) {
                    a[9] = 0;
                } else {
                    a[9] = 11 - x;
                }

                b = 0;
                c = 11;
                for (var y = 0; y < 10; y++) {
                    b += (a[y] * c--);
                }
                if ((x = b % 11) < 2) {
                    a[10] = 0;
                } else {
                    a[10] = 11 - x;
                }
                if (cpf.charAt(9) != a[9] || cpf.charAt(10) != a[10]){
                    return false;
                }

                return true;
            },
            cep: function(string) {
                // Only accepts non-formated and full-formated
                if (!string.match(/^[0-9]{8}$/) && !string.match(/^[0-9]{5}-[0-9]{3}$/)) {
                    return false;
                }
                return true;
            }
        });

        $.extend($.validate._messages, {
            'positive': 'Preencha o campo "%(title)s" com um número positivo',
            'cnpj': 'O campo "%(title)s" deve ser preenchido com um CNPJ válido',
            'cpf': 'O campo "%(title)s" deve ser preenchido com um CPF válido',
            'cep': 'O campo "%(title)s" deve ser preenchido com um CEP válido'

        });

        $.extend($.validate, {
            applyMasks: function(form, validations) {
                $(form).find('label').each(function() {
                    $(this).removeClass('validate-required');
                    $(this).children('strong').remove();
                });
                for (id in validations) {
                    var field = $('#' + id);
                    for (var i = 0; i < validations[id].length; i++) {
                        var validation = validations[id][i];
                        if(!$(field).parent('label').is('.validate-required')) {
                            $(field).parent().addClass('validate-required');
                        }
                        if (typeof $.validate.masks[validation.rule] == 'string') {
                            field.unmask();
                            field.mask($.validate.masks[validation.rule]);
                        } else if (typeof $.validate.masks[validation.rule] == 'function') {
                            $.validate.masks[validation.rule](field, validation.options);
                        }
                    }
                    $(field).bind('change', function() {
                        $(this).parent().removeClass('validate-required');
                    });
                }
                return true;
            }
        });

        $.extend($.validate, {
            showErrors: function(errors) {
                // Has errors?
                if (!(errors instanceof Array) || errors.length == 0) {
                    return false;
                }
                // Verify if error container exists
                if ($('#validateError').html() == null) {
                    $('body').append('<li id="validateError" onclick="$(this).remove();"></li>');
                }
                // Add class to all inputs
                for (i in errors) {
                    var error = errors[i];
                    var field = $('#' + error.id);
                    // Show first error
                    if (i == 0) {
                        var element = $.validate.container(field).parent();
                        $('#validateError').html('<span>' + error.message + '</span>').insertBefore(element);
                    }
                }

                // Scroll to message
                var offset = ($('#validateError').outerHeight({
                    margin: true
                }) - $('#validateError').height()) / 2;
                $.scrollTo($('#validateError'), 500, {
                    offset: - offset
                    });
                // window.setTimeout('$(\'#validateError\').remove();', 5000);

                return true;
            }
        });

        $.extend($.validate.masks, {
            cnpj: '99.999.999/9999-99',
            cpf: '999.999.999-99',
            cep: '99999-999'
        });
    }
}

