// teclado.js - inicio ------------------------------------------------------------
var ver;
netscape = "";
ver = navigator.appVersion; 

var iln;
for(iln = 0; iln < ver.length; iln++) {
    if (ver.charAt(iln) == "(") break;
}
netscape = (ver.charAt(iln+1).toUpperCase() != "C");


var cpoCorrente		= '';
var cpoProximo		= '';

function aoTeclar(DnEvents) {
	try {
		var result = false;
		var inclui = false;
		// ve quando e o netscape ou IE
		//var tecla = (netscape) ? DnEvents.which : window.event.keyCode;
		var tecla;
		if(netscape) {
			tecla = DnEvents.charCode ? DnEvents.charCode : DnEvents.which;
		} else {
			tecla = window.event.keyCode;
		}
		var targ = null;

		//(netscape) ? DnEvents.target : window.event.target;
		if(!DnEvents) var DnEvents = window.event;
		if(DnEvents.target) {
			targ = DnEvents.target;
		}
		else if(DnEvents.srcElement) {
			targ = DnEvents.srcElement;
		}

		var cpoCorrente = null;
		if(targ.id && targ.id.length>0) {
			cpoCorrente = targ.id;
		} else {
			if(targ.name && targ.name.length>0) {
				cpoCorrente = targ.name;
			} else {
				//alert('Não foi possível identificar o campo corrente.');
				//return false;
			}
		} 

		// inseri o teste abaixo pois estava ocorrendo erro em que o cpoCorrente nao estava definido.
		/*
		if((!cpoCorrente) || (cpoCorrente.length<1) || (!$(cpoCorrente))) {
		    return false;
		}
		*/

		// Se for um campo de leitura, não deixa digitar nada.
		if(targ.className=="cpoLeitura") {
			return false;
		}

		var teclado_PermitirAcentuacao = false;
		if(cpoCorrente!=null) {
			//teclado_PermitirAcentuacao = $(cpoCorrente).attributes.flgAcentuar ? true : false;
			teclado_PermitirAcentuacao = targ.attributes.flgAcentuar ? true : false;
		}

		if (tecla<32 || tecla>255) {
			/*if($(cpoCorrente) != null && $(cpoCorrente).attributes.enter2tab) {*/
				/*
				if(targ.attributes.enter2tab) {
			        //if((!$(cpoCorrente)) && $(cpoCorrente).attributes.enter2tab) {
				tecla = 9;
			} 
			*/
			return true;
		} else if(targ.attributes.critica) {
			inclui = eval(targ.attributes.critica.value + "(" + tecla + ")");
			result = inclui;
		} else { // o que é isto???
			var cTecla = String.fromCharCode(tecla);
			switch (cTecla) {
				case 'á': 
				case 'à': 
				case 'ã':
				case 'â':
				case 'ä':
					//return false;
					if(!teclado_PermitirAcentuacao) return false; //tecla = "a".charCodeAt(); 
					break;
				case 'é':
				case 'è':
				case 'ê':
				case 'ë':
					//return false;
					if(!teclado_PermitirAcentuacao) return false; //tecla = "e".charCodeAt(); 
					break;
				case 'í':
				case 'ì':
				case 'î':
				case 'ï':
					//return false;
					if(!teclado_PermitirAcentuacao) return false; //tecla = "i".charCodeAt(); 
					break; 
				case 'ó':
				case 'ò':
				case 'õ':
				case 'ô':
				case 'ö':
					//return false;
					if(!teclado_PermitirAcentuacao) return false; //tecla = "o".charCodeAt(); 
					break;
				case 'ú':
				case 'ù':
				case 'û':
				case 'ü':
					//return false;
					if(!teclado_PermitirAcentuacao) return false; //tecla = "u".charCodeAt(); 
					break;
				case 'ç':
					//return false;
					if(!teclado_PermitirAcentuacao) return false; //tecla = "c".charCodeAt();  
					break;
				
				case 'Á':
				case 'À':
				case 'Ã':
				case 'Â':
				case 'Ä':
					//return false;
					if(!teclado_PermitirAcentuacao) return false; //tecla = "A".charCodeAt();  
					break;		
				case 'É':
				case 'È':
				case 'Ê':
				case 'Ë':
					//return false;
					if(!teclado_PermitirAcentuacao) return false; //tecla = "E".charCodeAt();  
					break;
				case 'Í':
				case 'Ì':
				case 'Î':
				case 'Ï':
					//return false;
					if(!teclado_PermitirAcentuacao) return false; //tecla = "I".charCodeAt();  
					break;
				case 'Ó':
				case 'Ò':
				case 'Õ':
				case 'Ô':
				case 'Ö':
					//return false;
					if(!teclado_PermitirAcentuacao) return false; //tecla = "O".charCodeAt();  
					break;
				case 'Ú':
				case 'Ù':
				case 'Û':
				case 'Ü':
					//return false;
					if(!teclado_PermitirAcentuacao) return false; //tecla = "U".charCodeAt();  
					break;
				case 'Ç':
					//return false;
					if(!teclado_PermitirAcentuacao) return false; //tecla = "C".charCodeAt();  
					break;
				case '\'': // Não permitido por causa do postgres.
				case '\\': // Não permitido pois é o escape para caracteres especiais.
				case '|': // Não permitido por causa do K2.
				case '^': // Não permitodo pois é separador de subcampo.
					return false;
			}
			
			return true;
		}
	}
	catch(err) {
		msgErro('tecladoJS.aoTeclar: ' + err.toString());
	}
	return result;
}

function selecionaCampo(cpo) {
    try {
	var aCampo = cpo.split("_");
	if(aCampo.length>1) {
	    if(menuRaiz.menuCorrente != aCampo[0]) {
		menuRaiz.selecionaMenu(aCampo[0]);
	    }
	}
	// vai para o proximo
	try {
	    $(cpo).focus();
	} catch(e) {
	    // Nem todos os campos tem a funcao select.	
	}
	try {
	    $(cpo).select();
	} catch(e) {
	    // Nem todos os campos tem a funcao select.	
	}
    } catch(e) {
	msgErro("Teclado.selecionaCampo:" + e.toString())
    }
}

function getCaretPosition(ctrl) {
    var CaretPos = 0;	
    // IE Support	
    if (document.selection) {		
	ctrl.focus();		
	var Sel = document.selection.createRange();		
	Sel.moveStart('character', -ctrl.value.length);		
	CaretPos = Sel.text.length;	
    } else if (ctrl.selectionStart || ctrl.selectionStart == '0') // Firefox support	
	CaretPos = ctrl.selectionStart;	
    
    return (CaretPos);
}

function setCaretPosition(ctrl, pos) {	
    if(ctrl.setSelectionRange)	{		
	ctrl.focus();		
	ctrl.setSelectionRange(pos,pos);	
    } else if (ctrl.createTextRange) {	
	var range = ctrl.createTextRange();
	range.collapse(true);
	range.moveEnd('character', pos);
	range.moveStart('character', pos);
	range.select();
    }
}

var ctrlCip = "";
var ctrlVisita = "";

var auxCip	= "";
var auxVisita	= "";
var auxMedico	= "";
function setaProx(fld, prox) {
    if(fld != null) {
	var aAnterior = cpoCorrente.split("_");
	var aCorrente = fld.id.split("_");
	cpoCorrente = fld.id;
    }
    cpoProximo = prox;
}

//document.onkeydown = aoTeclarControle;
//document.onkeydown = keyDown; // work together to analyze keystrokes

document.onkeypress = aoTeclar; // work together to analyze keystrokes

//document.onkeydown = aoTeclar; // work together to analyze keystrokes
//if (netscape) document.captureEvents(Event.KEYDOWN|Event.KEYUP);

function enviaInsKey() {
    var fireOnThis = $(cpoCorrente);
    if( document.createEvent ) {
	var evObj = document.createEvent('KeyboardEvent');
	
	evObj.initKeyEvent(                                                                                      
	"keypress",        //  in DOMString typeArg,                                                           
	true,             //  in boolean canBubbleArg,                                                        
	true,             //  in boolean cancelableArg,                                                       
	null,             //  in nsIDOMAbstractView viewArg,  Specifies UIEvent.view. This value may be null.     
	false,            //  in boolean ctrlKeyArg,                                                               
	false,            //  in boolean altKeyArg,                                                        
	false,            //  in boolean shiftKeyArg,                                                      
	false,            //  in boolean metaKeyArg,                                                       
	45,              //  in unsigned long keyCodeArg,                                                      
	0);              //  in unsigned long charCodeArg);              
	
	fireOnThis.dispatchEvent(evObj);
    } else if( document.createEventObject ) { //IE
	var evObj = document.createEventObject();
	evObj.keyCode=45;
	//evObj.repeat = false;
	//evObj.returnValue = true;
	fireOnThis.fireEvent('onkeydown',evObj);
    }
    fireOnThis.focus();
}

function enviaTecla(tecla) {
    var fireOnThis = $(cpoCorrente);
    if( document.createEvent ) {
	var evObj = document.createEvent('KeyboardEvent');
	
	evObj.initKeyEvent(                                                                                      
	"keypress",        //  in DOMString typeArg,                                                           
	true,             //  in boolean canBubbleArg,                                                        
	true,             //  in boolean cancelableArg,                                                       
	null,             //  in nsIDOMAbstractView viewArg,  Specifies UIEvent.view. This value may be null.     
	false,            //  in boolean ctrlKeyArg,                                                               
	false,            //  in boolean altKeyArg,                                                        
	false,            //  in boolean shiftKeyArg,                                                      
	false,            //  in boolean metaKeyArg,                                                       
	tecla,            //  in unsigned long keyCodeArg,                                                      
	0);              //  in unsigned long charCodeArg);              
	
	fireOnThis.dispatchEvent(evObj);
    } else if( document.createEventObject ) { //IE
	var evObj = document.createEventObject();
	evObj.keyCode=tecla;
	//evObj.repeat = false;
	//evObj.returnValue = true;
	fireOnThis.fireEvent('onkeydown',evObj);
    }
    fireOnThis.focus();
}

var tecla_A =  65;
var tecla_Z =  90;
var tecla_a =  97;
var tecla_z = 120;
var tecla_0 =  48;
var tecla_9 =  57;

function digitos(tecla) {
    try {
	return ((tecla >=tecla_0) && (tecla<=tecla_9)); 0-9
    } catch(e) {
	msgErro("Teclado.digitos: " + e.toString());
	return false;
    }
}
function numerico(tecla) {
    try {
	return (digitos(tecla) || (tecla==46)); // digitos ou .
    } catch(e) {
	msgErro("Teclado.numerico: " + e.toString());
	return false;
    }
}
function maiuscula(tecla) {
    try {
	return ((tecla>=tecla_A) && (tecla<=tecla_Z)); // maiusculas
    } catch(e) {
	msgErro("Teclado.maiuscula: " + e.toString());
    } 
}
function minuscula(tecla) {
    try {
	return ((tecla>=tecla_a) && (tecla<=tecla_z)); // minusculas
    } catch(e) {
	msgErro("Teclado.minuscula: " + e.toString());
    }
}
function alfabetico(tecla) {
    try {
	return (maiuscula(tecla) || minuscula(tecla)); // maiusculas e minusculas
    } catch(e) {
	msgErro("Teclado.alfabetico: " + e.toString());
    }
}
function alfanumerico(tecla) {
    try {
	return digitos(tecla) || alfabetico(tecla); // digitos e letras
    } catch(e) {
	msgErro("Teclado.alfanumerico: " + e.toString());
    }
}

function critEmail(tecla) {
	try {
		return 
			digitos(tecla) ||
			alfabetico(tecla) ||
			("-.@".indexOf(String.fromCharCode(45))>-1);
	} catch(e) {
		msgErro("Teclado.email: " + e.toString());
	}
}

function critTelefone(cpo,obrigatorio) {
    try {
	if(obrigatorio && cpo.value=="") {
	    msgErro("Campo obrigatorio.");
	    cpo.select();
	    cpo.focus();
	    return false;
	}
		// regex validos
		// restritivo -> /^\d{0,3}\(\d{3,4}\)\d{8}$/
		// generico impreciso -> /^\d*\(?\d*\)?\d*\-?\d*$/
		// ex: 55(021)12345678
		return cpo.value.match(/^\d{0,3}\(\d{3,4}\)\d{8}$/);
    } catch(e) {
		msgErro("Teclado.critTelefone: " + e.toString());
    }
    return false;
}

function critData(dia, mes, ano) {
    var result = true;
    try {
		var dt = new Date(ano, mes-1, dia);
		if((dt.getDate()!=dia) || (dt.getMonth()+1!=mes) || (dt.getFullYear()!=ano)) {
		    result = false;
		}
    } catch(e) {
		msgErro("Teclado.critData: " + e.toString());
    }
    
    return result;
}

function critDataFmt(cpo,obrigatorio,fmt) {
	var result = false;
	try {
	if(obrigatorio && cpo.value=="") {
		msgErro("Campo obrigatorio.");
		cpo.select();
		cpo.focus();
	} else {
		var i,j;
		var vfmt = (new String(fmt)).split('/');
		var ano=0;
		var mes=0;
		var dia=0;
		j=0;
		for(i=0;i<3;i++) {
			switch(vfmt[i]) {
				case 'a':
					ano = cpo.value.substring(j,j+4).toInteger();
					j+=4;
					break;
				case 'm':
					mes = cpo.value.substring(j,j+2).toInteger();
					j+=2;
					break;
				default:
					dia = cpo.value.substring(j,j+2).toInteger();
					j+=2;
					break;
			}
		}
		if(!critData(dia, mes, ano)) {
		msgErro("Data inválida [" + cpo.value + "]");
		cpo.select();
		cpo.focus();
		result = true;
		} else {
		result = true;
		}
	}	
	/*
	if(result) 
		msgLimpa();
	*/
	} catch(e) {
		msgErro("Teclado.critDataAMD: " + e.toString());
	}
	return result;
}

function critDataDMA(cpo,obrigatorio) {
    var result = false;
    try {
	if(obrigatorio && cpo.value=="") {
	    msgErro("Campo obrigatorio.");
	    cpo.select();
	    cpo.focus();
	} else {
	    var dia = cpo.value.substring(0,2);
	    var mes = cpo.value.substring(2,4);
	    var ano = cpo.value.substring(4);
	    if(!critData(dia, mes, ano)) {
			msgErro("Data inválida [" + cpo.value + "]");
			cpo.select();
			cpo.focus();
			return false;
			result = false;
		} else {
			result = true;
	    }
	}
	/*
	if(result) 
	    msgLimpa();
	 */
    } catch(e) {
		msgErro("Teclado.critDataDMA: " + e.toString());
    }
    return result;
}

function critDataAMD(cpo,obrigatorio) {
    var result = false;
    try {
	if(obrigatorio && cpo.value=="") {
	    msgErro("Campo obrigatorio.");
	    cpo.select();
	    cpo.focus();
	} else {
	    var dia = cpo.value.substring(6);
	    var mes = cpo.value.substring(4,6);
	    var ano = cpo.value.substring(0,4);
	    if(!critData(dia, mes, ano)) {
		msgErro("Data inválida [" + cpo.value + "]");
		cpo.select();
		cpo.focus();
		result = true;
	    } else {
		result = true;
	    }
	}
	/*
	if(result) 
	    msgLimpa();
	 */
    } catch(e) {
	msgErro("Teclado.critDataAMD: " + e.toString());
    }
    return result;
}

function critHora(cpo,obrigatorio) {
    var result = false;
    try {
	if(obrigatorio && cpo.value == "") {
	    msgErro("Campo obrigatorio.");
	    cpo.select();
	    cpo.focus();
	} else {
	    var h = Number(cpo.value.substring(0,2)).valueOf();
	    if((h<0) || (h>23)) {
		msgErro("TecladoJS.critHora: Hora inválida (0-23)");
		return false;
	    }
	    
	    var m = Number(cpo.value.substring(2,2)).valueOf();
	    if((m<0) || (m>59)) {
		msgErro("TecladoJS.critHora: Minuto inválido (0-59)");
		return false;
	    }
	    
	    var s = Number(cpo.value.substring(4,2)).valueOf();
	    if((s<0) || (s>59)) {
		msgErro("TecladoJS.critHora: Segundo inválido (0-59)");
		return false;
	    }
	}
    } catch(e) {
	msgErro("Teclado.critHora: " + e.toString());
    }
    return result;
}

// rps.js - fim ------------------------------------------------------------

