/*############################################################################################################################
Autor: Flávio Caio F. Bruschi, RE: 2863
Alterações:
       Flávio Caio - Criação das funçoes  - 15/12/2006
//###########################################################################################################################*/
try{
    xmlhttp = new XMLHttpRequest();
}catch(ee){
    try{
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            xmlhttp = false;
        }
    }
}
//###########################################################################################################################*/
function setFocus(p){
	elementFocus(document.getElementById(p));
}
//###########################################################################################################################*/
function onLoad(funcao,campo){ //
	if (campo==undefined) campo=0;
	if (document.getElementById("menu")) DynarchMenu.setup('menu', { electric: 250 });
	if (funcao!=undefined && funcao!=""){
		parametros = "";
		funcoes = funcao.split(",");
		for (i=1;i<funcoes.length;i++){
			parametros += "'"+funcoes[i]+"'";
			if (i<funcoes.length-1) parametros += ",";
		}
		setTimeout(funcoes[0]+"("+parametros+")", 0);
	}
	inputs = document.getElementsByTagName("input");
	if (inputs.length>0) elementFocus(inputs[campo]);
}
//###########################################################################################################################*/
function setFocusOnLoad(){ //seta o foco no body="onload"
	if (document.getElementById("usuario"))
		elementFocus(document.getElementById("usuario"));
	if (document.getElementById("pesquisa"))
		elementFocus(document.getElementById("pesquisa"));
	if (document.getElementById("telefone"))
		elementFocus(document.getElementById("telefone"));		
	if (document.getElementById("cpf"))
		elementFocus(document.getElementById("cpf"));		
	if (document.getElementById("nome"))
		elementFocus(document.getElementById("nome"));
	if (document.getElementById("search"))	
		elementFocus(document.getElementById("search"));
}
//############################################################################################################################
IE4 = document.all;
function newAlert(title,mess,icon,mods) {
   (IE4) ? makeMsgBox(title,mess,icon,0,0,mods) : alert(mess);
}
function newConfirm(title,mess,icon,defbut,mods) {
   if (IE4) {
      icon = (icon==0) ? 0 : 2;
      defbut = (defbut==0) ? 0 : 1;
      retVal = makeMsgBox(title,mess,icon,4,defbut,mods);
      retVal = (retVal==6);
   }
   else {
      retVal = confirm(mess);
   }
   return retVal;
}
function IEBox(title,mess,icon,buts,defbut,mods) {
   retVal = (IE4) ? makeMsgBox(title,mess,icon,buts,defbut,mods) : null;
   return retVal;
}
function newPrompt(title,mess,def) {
   retVal = (IE4) ? makeInputBox(title,mess,def) : prompt(mess,def);
   return retVal;
}
//############################################################################################################################
function selectCombo(obj,value){
	for (ii=0;ii<obj.length;ii++){ // é ii pois se for so i confunde com outra variavel do loop da consulta.
		if (obj.options[ii].value==value){
			obj.selectedIndex = ii;
			ii = obj.length;
		}
	}
}
//############################################################################################################################
function exibeFash(swf, width, height){
		monta_swf = "";
		monta_swf += "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0\" width=\""+ width +"\" height=\""+ height +"\" title=\"\">";
		monta_swf += "<param name=\"movie\" value=\""+ swf +"\" />";
		monta_swf += "<param name=\"quality\" value=\"high\" />";
		monta_swf += "<param name=\"menu\" value=\"0\" />";
		monta_swf += "<param name=\"wmode\" value=\"transparent\" />";
		monta_swf += "<embed src=\""+ swf +"\" quality=\"high\" wmode=\"transparent\" pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\" type=\"application/x-shockwave-flash\" width=\""+ width +"\" height=\""+ height +"\"></embed>";
		monta_swf += "</object>";	
		document.write(monta_swf);
}
//############################################################################################################################
function abrirJanela(url,nome,w,h,conf) {  //abre uma janela  conf = toolbar,location,status,menubar,scrollbars,resizable
	var winl = (screen.width - w) / 2;
	var wint = ((screen.height - h) / 2);
	novajanela=window.open(url,nome,'width='+w+',height='+h+',left='+winl+',top='+wint+','+conf);
	novajanela.window.focus();
	return (false);
}//fim function abrirJanela(url,nome,w,h,conf)
//############################################################################################################################
function firstUpper (element) //primeira letra em maiusculo e o resto em minunculo
{
	var txtArray=element.value.split(" ");
	var txt = "";
	for (i=0; i<txtArray.length; i++) {
		first = txtArray[i].substring(0,1);
		rest = txtArray[i].substring(1);
		first = first.toUpperCase();
		rest = rest.toLowerCase();
		txt = txt+first+rest+" ";
	}
	while ( txt.charAt(0) == " " || txt.charAt(0) == "'" ||  txt.charAt(0) == "\"" )
		txt = txt.substring(1,txt.length);
	element.value = txt.superTrim();
}//fim function firstUpper (element
//############################################################################################################################
function lower (element){ //todas as letras em minusculo
	txt = element.value.toLowerCase();
	while ( txt.charAt(0) == " " || txt.charAt(0) == "'" ||  txt.charAt(0) == "\"" )
		txt = txt.substring(1,txt.length);
	element.value = txt.superTrim();
}//fim function lower (element)
//############################################################################################################################
String.prototype.superTrim = superTrim; //Implementa o método superTrim() no objeto String.
function superTrim(){ return( this.replace( /^\s+|\s+$/gi, "" ).replace( /\s{2,}/gi, " " ) ) }
//############################################################################################################################
function elementFocus(element){ //seleciona o foco no elemento do form
	if ( element.type == "text" || element.type == "radio" ){
		element.select();	
		element.focus();	
	}
	if ( element.type == "select-one")
		element.focus();		
}//fim function elementFocus(element)
//############################################################################################################################
function verificarDados(campo,checkStr){ //verifica se os carecteres digitados no campo são válidos 
	checkOK = getChars(campo);
	if (checkStr.charCodeAt()==8) return (true); //Backspace
	if (checkStr.charCodeAt()==0) return (true); //  <- -> del
	var allValid = true;
	for (i = 0;  i < checkStr.length;  i++){
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
			if (ch == checkOK.charAt(j))
			break;
		if (j == checkOK.length){
			allValid = false;
			break;
		}
	}
	if (!allValid)
		return (false);
	else 
		return (true);
}//fim function verificarDados(campo,checkStr)
//############################################################################################################################
function getChars(campo){ //retorna os carecteres permitidos nos campos
   switch(campo){
		case "txt-all":  return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzÀÁÂÃÄÇÈÉÊËÌÍÎÏGÑÒÓÔÕÖÙÚÛÜIàáâãäçèéêëìíîïgñòóôõöùúûü.,0123456789 \t\r\n\f";
		case "txt":  return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,0123456789 \t\r\n\f";
		case "integer": return "0123456789\t\r\n\f";
		case "integer-": return "0123456789-\t\r\n\f"; // cep e telefone
		case "float": return "0123456789.\t\r\n\f";
		case "inscricao":  return "0123456789-.\t\r\n\f";
		case "re": return "aAcCdDeEiItTxX0123456789\t\r\n\f";
		case "moeda": return "0123456789.,\t\r\n\f";
		case "email": return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-@\t\r\n\f";
		case "url": return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-://\t\r\n\f";
	}
}
//############################################################################################################################
function getkey(e){ //retorna a tecla pressionada - Internet Explorer e Netscape
	if (window.event)
		key = window.event.keyCode;
	else
		key = e.which;
	return String.fromCharCode(key);
}//fim function getkey(e)
//############################################################################################################################
function delay(funcao, parametros, tempo){ //chama a função: funcao após o tempo
	setTimeout(funcao+"("+parametros+")", tempo); //tempo: 1000 = 1seg
}
//############################################################################################################################
function pularEdit(n,t,target, e) { //pula automaticamente para o proximo campo a ser preenchido
	//delay("checkKey","'"+window.event.keyCode+"'", 500);
	if (window.event)
		key = window.event.keyCode;
	else
		key = e.which;	
	if (n==t && key!=9 && key!=16){   //9= tab, 16 = shift 
		elementFocus(target);
	}
}
//############################################################################################################################
function goToURL(targ,url) {
  eval(targ+".location='"+url+"'");
}
//############################################################################################################################
function logar(form){
	if (form.login.value==""){
		 alert('O preenchimento do campo RE funcionário é obrigatório.');
		 elementFocus(form.login);
		 return (false);	
	}	
	if (form.senha.value==""){
		 alert('O preenchimento do campo Senha é obrigatório.');
		 elementFocus(form.senha);
		 return (false);	
	}	
	return (true);
}
//############################################################################################################################
function logar2(form){
	if (form.usuario.value==""){
		 alert('O preenchimento do campo Usuário é obrigatório.');
		 elementFocus(form.usuario);
		 return (false);	
	}	
	if (form.senha.value==""){
		 alert('O preenchimento do campo Senha é obrigatório.');
		 elementFocus(form.senha);
		 return (false);	
	}		
	return (true);
}
//############################################################################################################################
function logarCpf(form){
	if(form.cpf1.value=="" || form.cpf2.value=="" || form.cpf3.value=="" || form.cpf4.value==""){
				alert('Preencha o campo CPF.');
				elementFocus(form.cpf1);
				return false;
	}else{
			 cpf=form.cpf1.value+"."+form.cpf2.value+"."+form.cpf3.value+"."+form.cpf4.value;
			 if(!isCPFCNPJ(cpf,0)){
						  alert("Por favor informe um CPF válido.");
						  elementFocus(form.cpf1);
						  return false;
				}	
			}	
	if (form.re.value==""){
		 alert('O preenchimento do campo RE Funcionário é obrigatório.');
		 elementFocus(form.re);
		 return (false);	
	}	
	if (!verificarDados('integer',form.re.value)){
			  alert ('Caracteres inválidos no campo RE Funcionário.');
			  elementFocus(form.re);
			  return (false);
	}		
	form.submit();
}
//############################################################################################################################
function isCPFCNPJ(campo,pType){ 
   if( isEmpty( campo ) ){return false;} 
   var campo_filtrado = "", valor_1 = " ", valor_2 = " ", ch = ""; 
   var valido = false;         
   for (i = 0; i < campo.length; i++){ 
      ch = campo.substring(i, i + 1); 
      if (ch >= "0" && ch <= "9"){ 
         campo_filtrado = campo_filtrado.toString() + ch.toString() 
         valor_1 = valor_2; 
         valor_2 = ch; 
      } 
      if ((valor_1 != " ") && (!valido)) valido = !(valor_1 == valor_2); 
   } 
   if (!valido) campo_filtrado = "12345678912"; 
   if (campo_filtrado.length < 11){ 
      for (i = 1; i <= (11 - campo_filtrado.length); i++){campo_filtrado = "0" + campo_filtrado;} 
   } 
   if(pType <= 1){ 
      if ( ( campo_filtrado.substring(9,11) == checkCPF( campo_filtrado.substring(0,9) ) ) && ( campo_filtrado.substring(11,12)=="") ){return true;} 
   } 
   if((pType == 2) || (pType == 0)){ 
      if (campo_filtrado.length >= 14){ 
         if ( campo_filtrado.substring(12,14) == checkCNPJ( campo_filtrado.substring(0,12) ) ){ return true;} 
      } 
   }    
   return false; 
} 
//############################################################################################################################
function checkCNPJ(vCNPJ){ 
   var mControle = ""; 
   var aTabCNPJ = new Array(5,4,3,2,9,8,7,6,5,4,3,2); 
   for (i = 1 ; i <= 2 ; i++){ 
      mSoma = 0; 
      for (j = 0 ; j < vCNPJ.length ; j++) 
         mSoma = mSoma + (vCNPJ.substring(j,j+1) * aTabCNPJ[j]); 
      if (i == 2 ) mSoma = mSoma + ( 2 * mDigito ); 
      mDigito = ( mSoma * 10 ) % 11; 
      if (mDigito == 10 ) mDigito = 0; 
      mControle1 = mControle ; 
      mControle = mDigito; 
      aTabCNPJ = new Array(6,5,4,3,2,9,8,7,6,5,4,3); 
   } 
   return( (mControle1 * 10) + mControle ); 
} 
//############################################################################################################################
function checkCPF(vCPF){ 
   var mControle = "" 
   var mContIni = 2, mContFim = 10, mDigito = 0; 
   for (j = 1 ; j <= 2 ; j++){ 
      mSoma = 0; 
      for (i = mContIni ; i <= mContFim ; i++) 
         mSoma = mSoma + (vCPF.substring((i-j-1),(i-j)) * (mContFim + 1 + j - i)); 
      if (j == 2 ) mSoma = mSoma + ( 2 * mDigito ); 
      mDigito = ( mSoma * 10 ) % 11; 
      if (mDigito == 10) mDigito = 0; 
      mControle1 = mControle; 
      mControle = mDigito; 
      mContIni = 3; 
      mContFim = 11; 
   } 
   return( (mControle1 * 10) + mControle ); 
} 
//############################################################################################################################
function isEmpty(pStrText){ 
   var   len = pStrText.length; 
   var pos; 
   var vStrnewtext = ""; 

   for (pos=0; pos<len; pos++){ 
      if (pStrText.substring(pos, (pos+1)) != " "){ 
         vStrnewtext = vStrnewtext + pStrText.substring(pos, (pos+1)); 
      } 
   } 

   if (vStrnewtext.length > 0) 
      return false; 
   else 
      return true; 
}
//############################################################################################################################
function mOvr(src,clrOver) {
    if (!src.contains(event.fromElement)) {
	 // src.style.cursor = 'hand';
	  src.bgColor = clrOver;
	}
  }
  
function mOut(src,clrIn) {
	if (!src.contains(event.toElement)) {
	 // src.style.cursor = 'default';
	  src.bgColor = clrIn;
	}
  }
//############################################################################################################################
function getNodeText(node,ignorewhitespace)
{
	var text = "";
	if(node.hasChildNodes())
	{
		var children = node.childNodes;
		for(var i=0; i<children.length; i++)
		{
			if(children[i].nodeName == "#text")
			{
				if(ignorewhitespace)
				{
					if(!/^\s+$/.test(children[i].nodeValue))
					{
						text += children[i].nodeValue;
					}
				}
				else
				{
					text += children[i].nodeValue;
				}
			}
			else {
				var attributes = '';
				for(var j=0; j<children[i].attributes.length; j++){
					attName =  children[i].attributes[j].name;
					attValue =  children[i].attributes[j].value;
					attributes += ' '+attName+'="'+attValue+'"';
				}					
				text += '<'+children[i].nodeName+attributes+' >'+getNodeText(children[i],ignorewhitespace)+'</'+children[i].nodeName+'>';
			}
			
		}
	}
	return text;
}
//############################################################################################################################
function exibeTroca(){
    if (document.getElementById("altera").className == "invisible" ) {
        document.getElementById("altera").className = "visible";
        document.getElementById("novasenha").value = '';
    	document.getElementById("confirmasenha").value = '';
    } else {
        document.getElementById("altera").className = "invisible";
    }
    return null;
}