﻿/// <reference path="jquery-1.3.2-vsdoc.js" />

/*
*  Copyright 2006/2010 Minha Vida (http://www.minhavida.com.br)
*/

jQuery.fn.tags = function (strArrCharValidos, totalCaracteresTag, delimitador, temAlerta) {
    if (!strArrCharValidos.contains(' ')) {
        strArrCharValidos = strArrCharValidos + ' ';
    }

    if (temAlerta == null || temAlerta == undefined) {
        temAlerta = false;
    }

    this.keypress(function (event) {
        var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
        var isValid = false;
        //: Tratamentos para a chave pressionada.
        isValid = true;
        

        //: Tratamento para as tags
        if (isValid) {

            var tags = this.value.split(delimitador);
            var ultimaTag = tags[tags.length - 1];

            if (tags.length > 1) {
                //: Valida as tags anteriores
                var montaTag = '';
                for (var i = 0; i < tags.length; i++) {
                    var tag = tags[i];
                    if (tag.length > totalCaracteresTag) {
                        tag.substr(0, totalCaracteresTag);
                    }
                    if (i == (tags.length - 1)) {
                        montaTag += tag;
                    }
                    else {
                        montaTag += tag + delimitador;
                    }
                }
                this.value = montaTag;
            }


            if (ultimaTag.length == totalCaracteresTag && key != getKeyType(delimitador)) {
                isValid = false;
                if (temAlerta) {
                    alert("Alcançou o limite de " + totalCaracteresTag + " caracteres. \n Acrescente '" + delimitador + "' para continuar.");
                }
            }

            if ((ultimaTag.replace(' ', '') == '' || ultimaTag.charAt(this.value.length - 1) == delimitador) && key == getKeyType(delimitador)) {
                return false;
            }
        }

        return isValid;

    }).keydown(function (event) {
        var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
        if (event.ctrlKey && key == 118 || event.ctrlKey && key == 86) {
            return false;
        }
    });
}

jQuery.fn.marcaDagua = function (texto) {
    this.ready(function () {
        if (jQuery(this).val().trim() == "") {
            jQuery(this).val(texto);
        }
    }).click(function () {
        if (jQuery(this).val() == texto) {
            jQuery(this).val("");
        }
    }).blur(function () {
        if (jQuery(this).val().trim() == "") {
            jQuery(this).val(texto);
        }
    });
}

jQuery.fn.marcaDaguaSenha = function (texto) {
    this.focus(function () {
        if (jQuery(this).val() == texto) {
            var elementoAtual = jQuery(this);
            var novoInput = document.createElement("INPUT");
            novoInput.setAttribute("type", "password");
            novoInput.setAttribute("id", jQuery(this).attr("id"));
            novoInput.setAttribute("name", jQuery(this).attr("name"));
            novoInput.setAttribute("class", jQuery(this).attr("class"));

            elementoAtual.after(novoInput);
            elementoAtual.remove();
            jQuery(novoInput).marcaDaguaSenha(texto);
            jQuery(novoInput).focus();
        }
    }).blur(function () {
        if (jQuery(this).val() == '') {
            var elementoAtual = jQuery(this);
            var novoInput = document.createElement("INPUT");
            novoInput.setAttribute("type", "text");
            novoInput.setAttribute("id", jQuery(this).attr("id"));
            novoInput.setAttribute("name", jQuery(this).attr("name"));
            novoInput.setAttribute("class", jQuery(this).attr("class"));
            novoInput.setAttribute("value", texto);
            elementoAtual.after(novoInput);
            elementoAtual.remove();
            jQuery(novoInput).marcaDaguaSenha(texto);
        }
    });
}

jQuery.fn.formatarNumeros = function (opcoes) {
    var defaults = {
        prefixo: '', // Caso queira acrescentar algo na frente Ex: R$
        delimitadorFracionais: ',', //delimitador de valores fracionais
        delimitadorDecimais: '.', //delimitador de valores decimais
        totalFracionais: 3 //total de casas fracionais
    };
    var opcoes = jQuery.extend(defaults, opcoes);
    var objeto = jQuery(this);

    this.each(function () {
        //Carregar os valores do plugin
        var prefixo = opcoes.prefixo;
        var fracionais = opcoes.delimitadorFracionais;
        var decimais = opcoes.delimitadorDecimais;
        var totalFracionais = opcoes.totalFracionais;
        var valorFinal = UtilTeste.formatoPreco(opcoes, jQuery(this).html());
        jQuery(this).html(valorFinal);
    });
}

/*
*  Valores parecidos no teclado estão em um array
*  para questões de validação verifique se a tecla shift foi pressionada junto com ela
*  Ex: var doisPontos = event.shiftKey && key = 191 // dois pontos
*  T : teclado normal
*  N : teclado numérico
*  sT: Shift + teclado normal
*/

getKeyType = function (char) {
    json = {
        keys: {
            ' ': 32,
            '!': 33,
            '"': 34,
            '#': 35,
            '$': 36,
            '%': 37,
            '&': 38,
            "'": 39,
            '(': 40,
            ')': 41,
            '*': 42,
            '+': 43,
            ',': 44,
            '-': 45,
            '.': 46,
            '/': 47,
            '0': 48,
            '1': 49,
            '2': 50,
            '3': 51,
            '4': 52,
            '5': 53,
            '6': 54,
            '7': 55,
            '8': 56,
            '9': 57,
            ':': 58,
            ';': 59,
            '<': 60,
            '=': 61,
            '>': 62,
            '?': 63,
            '@': 64,
            'A': 65,
            'B': 66,
            'C': 67,
            'D': 68,
            'E': 69,
            'F': 70,
            'G': 71,
            'H': 72,
            'I': 73,
            'J': 74,
            'K': 75,
            'L': 76,
            'M': 77,
            'N': 78,
            'O': 79,
            'P': 80,
            'Q': 81,
            'R': 82,
            'S': 83,
            'T': 84,
            'U': 85,
            'V': 86,
            'W': 87,
            'X': 88,
            'Y': 89,
            'Z': 90,
            '[': 91,
            '\\': 92,
            ']': 93,
            '^': 94,
            '_': 95,
            '`': 96,
            'a': 97,
            'b': 98,
            'c': 99,
            'd': 100,
            'e': 101,
            'f': 102,
            'g': 103,
            'h': 104,
            'i': 105,
            'j': 106,
            'k': 107,
            'l': 108,
            'm': 109,
            'n': 110,
            'o': 111,
            'p': 112,
            'q': 113,
            'r': 114,
            's': 115,
            't': 116,
            'u': 117,
            'v': 118,
            'w': 119,
            'x': 120,
            'y': 121,
            'z': 122,
            '{': 123,
            '|': 124,
            '}': 125,
            '~': 126,
            'undefined': 127,
            'Ç': 128,
            'ü': 129,
            'é': 130,
            'â': 131,
            'ä': 132,
            'à': 133,
            'ã': 134,
            'ç': 135,
            'ê': 136,
            'ë': 137,
            'è': 138,
            'ï': 139,
            'î': 140,
            'ì': 141,
            'Ä': 142,
            'Ã': 143,
            'É': 144,
            'æ': 145,
            'Æ': 146,
            'ô': 147,
            'ö': 148,
            'ò': 149,
            'û': 150,
            'ù': 151,
            'ÿ': 152,
            'Ö': 153,
            'Ü': 154,
            '¢': 155,
            '£': 156,
            '¥': 157
        }
    };
    return json.keys[char];
};


getSpecialKeys = function () {
    return { keys: {
        'apagar': 8,
        'delete': 2,
        'insert': 3
    }
    }

}

/*
*  Eduardo Bergantini: Todas as funções de tratamento de String que não
*                      existem no Javascript (http://www.w3schools.com/jsref/jsref_obj_string.asp)
*                      e nem no jQuery (http://docs.jquery.com/Types#String) adicionei aqui
*/

String.prototype.endsWith = function (str) {
    var d = this.length - str.length;
    return d >= 0 && this.lastIndexOf(str) === d;
};

String.prototype.startsWith = function (str) {
    return (this.match("^" + str) == str);
};

String.prototype.trim = function () {
    return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));
};

String.prototype.contains = function (str) {
    var total = this.length;
    if (this.replace(str, "").length < total)
        return true;
    return false;
};

Util = {
    dateDiff: function (strDate1, strDate2) {
        return (((Date.parse(strDate2)) - (Date.parse(strDate1))) / (1000)).toFixed(0);
    }
};

UtilTeste = {
    formatoPreco: function (opcoes, strNumero) {

        var defaults = {
            prefixo: '', // Caso queira acrescentar algo na frente Ex: R$
            delimitadorFracionais: ',', //delimitador de valores fracionais
            delimitadorDecimais: '.', //delimitador de valores decimais
            totalCasasFracionais: 3 //total de casas fracionais
        };

        var opcoes = jQuery.extend(defaults, opcoes);
        var valorFormatado = Convert.toInt32(strNumero);
        var milharFormatado = '';
        var contadorMilhar = 0;

        var valorFracional = valorFormatado.substr(valorFormatado.length - opcoes.totalCasasFracionais, opcoes.totalCasasFracionais);
        var valorInteiro = valorFormatado.substr(0, valorFormatado.length - opcoes.totalCasasFracionais);

        valorFormatado = valorInteiro + opcoes.delimitadorFracionais + valorFracional;

        for (var i = valorInteiro.length; i > 0; i--) {
            var char = valorInteiro.substr(i - 1, 1);
            contadorMilhar++;
            if (contadorMilhar % 3 == 0) {
                char = opcoes.delimitadorDecimais + char;
            }
            milharFormatado = char + milharFormatado;
        }
        if (milharFormatado.substr(0, 1) == opcoes.delimitadorDecimais) {
            milharFormatado = milharFormatado.substring(1, milharFormatado.length);
        }
        valorFormatado = milharFormatado + opcoes.delimitadorFracionais + valorFracional;

        return valorFormatado;
    }
}

Convert = {
    toInt32: function (strNumero) {
        var formatado = '';
        isNumero = /[0-9]/;
        for (var i = 0; i < (strNumero.length); i++) {
            var char = strNumero.charAt(i);
            if (formatado.length == 0 && char == 0) { char = false; }
            if (char && char.match(isNumero)) {
                formatado = formatado + char;
            }
        }
        return formatado;
    }
};
