﻿$(document).ready(function(){
	// aqui eu defino máscaras para classes CSS
	setMask("date", new DateMask());
	setMask("signednumeric", new NumericMask(true));
	setMask("numeric", new NumericMask(false));
	setMask("signedmoney", new MoneyMask(true));
	setMask("money", new MoneyMask(false));
});

function setMask(className, mask) {
	$("." + className).each(function(x,elem) {
		elem.onkeypress = function(evt) { return mask.HandleEvent(elem, evt); };
	});
}

function DateMask() {
	DateMask.prototype.HandleEvent = function(elem, evt) {
		// keycodes das teclas permitidas na manipulação de números
		var allowedKeys = [0, 8, 9, 16, 17, 18, 35, 36, 37, 39, 98, 99, 118, 120];

		// obtem keycode da tecla digitada
		var key = getKey(evt);
		var chr = String.fromCharCode(key);

//		document.getElementById("divDebug").innerHTML = 'key: ' + key + ' - chr: ' + chr;

		// ignora teclas de manipulação (shift, del, etc)
		if (isAllowed(allowedKeys, key)) {
			return true;
		}

		var str = elem.value;
		if (str.length == 0) {
			return (chr == '0' || chr == '1' || chr == '2' || chr == '3'); // dias começam com 1, 2 ou 3
		} else if (str.length == 1) {
			if (str.charAt(0) == '3') {
				return chr == '1'; // não permite dia 32 pra cima
			} else if (str.charAt(0) == '0') {
				return (key > 48 && key <= 57); // permite de 1 a 9
			} else {
				return (key >= 48 && key <= 57); // permite de 0 a 9
			}
		} else if (str.length == 2) {
			elem.value = str + '/';
			if (chr == '0' || chr == '1') elem.value += chr;
			return false;
		} else if (str.length == 3) {
			return (chr == '0' || chr == '1'); // meses começam com 0 ou 1
		} else if (str.length == 4) {
			if (str[3] == '0') {
				return (key > 48 && key <= 57); // permite de 1 a 9 (Jan-Set)
			} else {
				return (chr == '0' || chr == '1' || chr == '2');  // meses 10, 11 e 12
			}
		} else if (str.length == 5) {
			elem.value = str + '/';
			if (chr == '1' || chr == '2') elem.value += chr;
			return false;
		} else if (str.length == 6) {
			return (chr == '1' || chr == '2');  // anos começam com 1 e 2
		} else if (str.length == 7) {
			if (str.charAt(6) == '1') {
				// entre 1900 e 1999 - não vamos aceitar anos anteriores a 1900
				return chr == '9';
			} else {
				return chr == '0'; // também não aceito ano superior a 2099
			}
		} else if (str.length == 8 || str.length == 9) {
			return (key >= 48 && key <= 57); // permite de 0 a 9
		} else { // estourou tamanho de data
			return false;
		}
	}
}

function NumericMask(_allowNegative) {
	this.AllowNegative = _allowNegative;
	NumericMask.prototype.HandleEvent = function(elem, evt) {
		// keycodes das teclas permitidas na manipulação de números
		var allowedKeys = [0, 8, 9, 16, 17, 18, 35, 36, 37, 39, 98, 99, 118, 120];

		// obtem keycode da tecla digitada
		var key = getKey(evt);
		//var chr = String.fromCharCode(key);

		var ok;
		if (key >= 48 && key <= 57) {
			// se está no range numérico (0-9)
			ok = true;
		} else if (isAllowed(allowedKeys, key)) {
			// se for tecla permitida
			ok = true;
		} else if (key == 45 && this.AllowNegative == true && elem.value.length == 0) {
			// se permite números negativos
			ok = true;
		} else {
			ok = false;
		}
		
		return ok;
	}
}

function MoneyMask(_allowNegative) {
	this.AllowNegative = _allowNegative;
	MoneyMask.prototype.HandleEvent = function(elem, evt) {
		var allowedKeys = [0, 8, 9, 16, 17, 18, 35, 36, 37, 39, 98, 99, 118, 120];

		// obtem keycode da tecla digitada
		var key = getKey(evt);

		if (isAllowed(allowedKeys, key)) {
			// se for tecla permitida
			return true;
		}
			
		return MascaraMoeda(elem, '.', ',', evt);
	}
}

function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
	if(objTextBox.value.length > objTextBox.maxLength) return false;
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = getKey(e);
    if (whichCode == 0 || whichCode == 8 || whichCode == 13) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave

    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--) {
	        objTextBox.value += aux2.charAt(i);
	    }
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}


function isAllowed(list, k) {
	for (var i = 0; i < list.length; i++) {
		if (list[i] == k) return true;
	}
	return false;
}

function getKey(evt) {
	var key;
	if (document.all) {
		key = window.event.keyCode;
	} else {
		key = evt.which;
	}
	return key;
}
