    
/***
* Descrição.: Formata cores de cada linha em uma lista
*             de acordo com os estilos criados no
*             css (estilos.css)
* 
***/    


function formataLista() {
    var table = document.getElementById("lista");
    var rows = table.getElementsByTagName("tr");

	var impar = false;
	for (i=1; i < rows.length; i++) {
		if (impar == false) {
	     rows[i].onmouseover = function() { this.className='over' };
	     rows[i].onmouseout = function() { this.className='odd' };
	     impar = true;
	 } else {
	     rows[i].onmouseover = function() { this.className='over' };
	     rows[i].onmouseout = function() { this.className='even' };
	 	impar = false;
	 }
	}
}

/***
* Descrição.: formata um campo do formulário de
* acordo com a máscara informada...
* Parâmetros: - objForm (o Objeto Form)
* - strField (string contendo o nome
* do textbox)
* - sMask (mascara que define o
* formato que o dado será apresentado,
* usando o algarismo "9" para
* definir números e o símbolo "!" para
* qualquer caracter...
* - evtKeyPress (evento)
* Uso.......: <input type="textbox"
* name="xxx".....
* onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);">
* Observação: As máscaras podem ser representadas como os exemplos abaixo:
* CEP -> 99.999-999
* CPF -> 999.999.999-99
* CNPJ -> 99.999.999/9999-99
* Data -> 99/99/9999
* Tel Resid -> (99) 999-9999
* Tel Cel -> (99) 9999-9999
* Processo -> 99.999999999/999-99
* C/C -> 999999-!
* E por aí vai...
***/

// function keyWhat(e){
//   if (navigator.appName == 'Microsoft Internet Explorer'){
 		//For shift, ctrl and alt keys
		// 17 => ctrl, 16 => shift, 18 => alt, 78 => n
//		if (event.keyCode == 17 ||event.keyCode == 18 ){ 
//			alert("Teclas <CTRL> e <ALT> desabilitadas !!!");
//			return false;
//		}
//   }
// }//end of function
// document.onkeydown=keyWhat;


function displayWindow(theURL,winName,width,height,features) { //v3.1
// Made by Eddie Traversa modified from Macromedia Code
// http://nirvana.media3.net/
// Exemplo: onLoad="displayWindow('http://nirvana.media3.net','NIRVANA','800','600','toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes')"

	var window_width = width;
    var window_height = height;
    var newfeatures= features;
    //Tarso: comentei a linha abaixo para que o topo seja igual a zero
    //var window_top = (screen.height-window_height)/2;
    var window_top = 0;
    var window_left = (screen.width-window_width)/2;
    newWindow=window.open(''+ theURL + '',''+ winName + '','width=' + window_width + ',height=' + window_height + ',top=' + window_top + ',left=' + window_left + ',features=' + newfeatures + '');
    newWindow.focus();
  
}

function destacaLinha(objLinha, cor) {
	//objLinha.style.cursor = "hand";

	var objCelulas = objLinha.children;
	for (var i = 0; i < objCelulas.length; i++)
		objCelulas[i].style.backgroundColor = cor;
}

function isSubmit(theform) {
  if (document.all || document.getElementById) {
    for (i = 0; i < theform.length; i++) {
      var tempobj = theform.elements[i];
      if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset")
        tempobj.disabled = true;
    }
  }
  setTimeout('alert("Form submetido. Aguarde !!!")', 2000);
  return true;
}

function AnalisaEventoOnChange(form, campo, link) {
//  if (form == "nm_form") { // Exemplo com submit
//    if (campo == "nm_campo") {
//       document.nm_formForm.action=link;
//       document.nm_formForm.submit();
//    } else if (campo == "nm_campo2") {
//        parent.controller.location.href=link;
//    }
//  }
    if (form == "pago" || form == "empenhado") { // Exemplo com submit
      if (campo == "codTipoCusteio") {
        parent.controller.location.href=link;
      }
    }
}

function EventoOnFocusBGColor(strField) {
	document.getElementById(strField).style.backgroundColor='#FFFFEE';
//	document.getElementById(strField).value = document.getElementById(strField).value + '';
}

function EventoOnBlurBGColor(strField) {
    document.getElementById(strField).style.backgroundColor='white';
}

function EventoOnFocusMensagemCampo(mensagem) {
  object = document.getElementById("msg");
  object.innerText = mensagem;
}

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
  var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

  if(document.all) { // Internet Explorer
    nTecla = evtKeyPress.keyCode; }
  else if(document.layers) { // Nestcape
    nTecla = evtKeyPress.which;
  }

  sValue = objForm[strField].value;
  
  // Limpa todos os caracteres de formatação que
  // já estiverem no campo.
  sValue = sValue.toString().replace( "-", "" );
  sValue = sValue.toString().replace( "-", "" );
  sValue = sValue.toString().replace( ".", "" );
  sValue = sValue.toString().replace( ".", "" );
  sValue = sValue.toString().replace( "/", "" );
  sValue = sValue.toString().replace( "/", "" );
  sValue = sValue.toString().replace( "(", "" );
  sValue = sValue.toString().replace( "(", "" );
  sValue = sValue.toString().replace( ")", "" );
  sValue = sValue.toString().replace( ")", "" );
  sValue = sValue.toString().replace( ":", "" );
  sValue = sValue.toString().replace( ":", "" );
  sValue = sValue.toString().replace( " ", "" );
  sValue = sValue.toString().replace( " ", "" );
  fldLen = sValue.length;
  mskLen = sMask.length;

  i = 0;
  nCount = 0;
  sCod = "";
  mskLen = fldLen;

  while (i <= mskLen) {
    bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
    bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == ":") || (sMask.charAt(i) == " "))

    if (bolMask) {
      sCod += sMask.charAt(i);
      mskLen++; }
    else {
      sCod += sValue.charAt(nCount);
      nCount++;
    }

    i++;
  }

  objForm[strField].value = sCod;
  
  if (nTecla != 8) { // backspace
    if (sCod.length == sMask.length) { // Campo totalmente preenchido
//		alert("Tecla: " + nTecla + " i: " + i + " sMask.charAt(i-1): " + sMask.charAt(i-2));    
    	if ((sMask.charAt(i-2) == "9") && ((nTecla > 47) && (nTecla < 58))) { // apenas números...
//	    	objForm[strField].value = "";
//	    	objForm[strField].value = sCod;
    		return true;
    	} else {
			objForm[strField].select();
			objForm[strField].focus();
    		return false;
    	}
    } 
	if (sMask.charAt(i-1) == "9") { // apenas números...
      return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
    else { // qualquer caracter...
      return true;
    }
  } else {
    return true;
  }
}


function isSubmit(theform) {
 if (document.all || document.getElementById) {
    var tagsInput = document.getElementsByTagName("input");
    for (i = 0; i < tagsInput.length; i++) {
      var tempobj = tagsInput[i];
      if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset")
        tempobj.disabled = true;
    }
  }
  setTimeout('alert("Função já foi submetida, aguarde.")', 20000);
  return true;
}


function doCount(ev) {
  var tt_enter = 0;
  for(var i=0; i<document.f.text1.value.length; i++) {
    letra = document.f.text1.value.substr(i, 1);
    if (letra.charCodeAt(0)==13) {
      tt_enter++;
    };
  }
  document.f.cnt.value = 100 - document.f.text1.value.length + tt_enter;
}

function doInit(event) {
  doCount(event)
}

function teclaOnKeydown(evtKeydown) {
  var nTecla;

  if(document.all) { // Internet Explorer
    nTecla = evtKeydown.keyCode;
  } else if(document.layers) { // Nestcape
    nTecla = evtKeydown.which;
  }

//  alert('tecla digitada: ' + nTecla);

  if (nTecla == 33 || nTecla == 45 || nTecla == 46 || nTecla == 144 || (nTecla > 35 && nTecla < 41)) { // del, NumLock, home ou setas
	alert('Para limpar o conteúdo do campo, pressione a tecla <Backspace>');
    return false;
  }
  
  return true;
}  

function CheckLength(length) {
  var abc=window.event.srcElement.value
  var MAXLENGTH=100

  var tt_enter = 0;
  for(var i=0; i < window.event.srcElement.value.length; i++) {
    letra = abc.substr(i, 1);
    if (letra.charCodeAt(0)==13) {
      tt_enter++;
    };
  }

  if (window.event.srcElement.value.length - tt_enter >= length) {
    window.event.srcElement.value=abc.substring(0,window.event.srcElement.value.length)

    return false;
  }
}

function Inteiro(e) //Aceita a digitacao apenas de numeros
{

   if(document.all) // Internet Explorer
     var tecla = event.keyCode;
   else if(document.layers) // Nestcape
     var tecla = e.which;
   if(tecla > 47 && tecla < 58) // numeros de 0 a 9
     return true;
   else
   {
     if ((tecla != 8) && (tecla != 13)) // backspace
       return false;
     else
       return true;
   }
}

function InteiroEVirgula(strField, MaxLengthStrField, evtKeyPress) { //Aceita a digitacao apenas de numeros e de virgula
   var i, tam, tecla, lengthInt, lengthDec, qtdeInt, qtdeDec, charAtDecimal;

   lengthInt = MaxLengthStrField - 3;
   lengthDec = 2;

// alert(strField);
// alert(lengthInt);

   if(document.all) // Internet Explorer
     tecla = evtKeyPress.keyCode;
   else if(document.layers) // Nestcape
     tecla = evtKeyPress.which;

//   alert(tecla);

   qtdeInt = 0;
   qtdeDec = 0;
   charAtDecimal = false;
   if ((tecla > 47 && tecla < 58)) { // numeros de 0 a 9 
      i = 0;
      tam = strField.length;
      // Se as duas teclas iniciais forem zero, não permite
      if (tam == 1)
        if (strField.charAt(0) == "0" && tecla == 48)
          return false;
      // Verifica a qtde de inteiros e decimais informados
      while (i < tam) {
        if (strField.charAt(i) == ",") {
            charAtDecimal = true;
            i++;
	    continue;
        }
        if (charAtDecimal)
	  qtdeDec++;
        else
          qtdeInt++;

        i++;
      }

   //   alert("qtdeInt: " + qtdeInt + "   qtdeDec: " + qtdeDec);

      // Não permite que a qtde de inteiros ultrapasse o limite
      if (qtdeInt > lengthInt)
        return false;

      // Não permite que a qtde de decimais ultrapasse o limite
      if (qtdeDec > lengthDec)
        return false;

      return true; 
   }
   
   if (tecla == 44) { // Vírgula
      i = 0;
      tam = strField.length;
      while (i <= tam) {
        // Não permite duas virgulas no conteudo do campo
        if (strField.charAt(i) == ",")
            return false;
        i++;
      }
      // Não permite a virgula na primeira posição
      if (tecla == 44 && tam == 0)
        return false;

      return true; 
   }

   if ((tecla != 8) && (tecla != 13)) // backspace
      return false;
   else
      return true;
}

function checkdate(objName, mask) {
  var datefield = objName;

  if (chkdate(objName, mask) == false) {
      datefield.value = "";
      alert("A data é inválida.");
      datefield.focus();
      return false;
  } else {
      return true; 
  }
}

function chkdate(objName, mask) {
  var strDatestyle = "EU";  //European date style
  var strDate;
  var strDateArray = "";
  var strDay;
  var strMonth;
  var strYear;
  var intday;
  var intMonth;
  var intYear;
  var booFound = false;
  var datefield = objName;
  var strSeparatorArray = new Array("-"," ","/",".");
  var intElementNr;
  var err = 0;
  var strMonthArray = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
  var strNMArray = new Array("01","02","03","04","05","06","07","08","09","10","11","12");
  strDate = datefield.value;

  if (strDate.length < 1) {
     return true;
  }
  for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
      if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
          strDateArray = strDate.split(strSeparatorArray[intElementNr]);

          if (mask == 'dd/mm/yyyy') {
              if (strDateArray.length != 3) {
                err = 1;
                return false;
              } else {
                strDay = strDateArray[0];
                strMonth = strDateArray[1];
                strYear = strDateArray[2];
              }
              booFound = true;
          } else if (mask == 'dd/mm') {
              if (strDateArray.length != 2) {
                err = 1;
                return false;
              } else {
                strDay = strDateArray[0];
                strMonth = strDateArray[1];
                strYear = '2004'; // So para passar
              }
              booFound = true;
          } else if (mask == 'mm/yyyy') {
              if (strDateArray.length != 2) {
                err = 1;
                return false;
              } else {
                strDay = '01'; // So para passar
                strMonth = strDateArray[0];
                strYear = strDateArray[1];
              }
              booFound = true;
          }
      }
  }
  if (booFound == false) {
     if (strDate.length>5) {
        strDay = strDate.substr(0, 2);
        strMonth = strDate.substr(2, 2);
        strYear = strDate.substr(4);
     }
  }
  
//  if (strYear.length == 2) {
//      strYear = '20' + strYear;
//  } 
    if (strDateArray.length > 0) {
      if (strMonth.length != 2) {
        err = 1;
        return false;
      }
      if (strYear.length != 4) {
        err = 1;
        return false;
      }
    }
  
  // US style
  if (strDatestyle == "US") {
     strTemp = strDay;
     strDay = strMonth;
     strMonth = strTemp;
  }
  
  intday = parseInt(strDay, 10);
  if (isNaN(intday)) {
     err = 2;
     return false;
  }
  intMonth = parseInt(strMonth, 10);
  if (isNaN(intMonth)) {
     for (i = 0;i<12;i++) {
         if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
            intMonth = i+1;
            strMonth = strMonthArray[i];
            i = 12;
         }
     }
     if (isNaN(intMonth)) {
        err = 3;
        return false;
     }
  }
  
  intYear = parseInt(strYear, 10);
  if (isNaN(intYear)) {
     err = 4;
     return false;
  }
  
  if (intMonth>12 || intMonth<1) {
     err = 5;
     return false;
  }
  if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
     err = 6;
     return false;
  }
  if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
     err = 7;
     return false;
  }
  if (intMonth == 2) {
     if (intday < 1) {
        err = 8;
        return false;
     }
     if (LeapYear(intYear) == true) {
        if (intday > 29) {
            err = 9;
            return false;
        }
     } else {
        if (intday > 28) {
           err = 10;
           return false;
        }
     }
  }
  
//  if (strDatestyle == "US") {
//     datefield.value = strNMArray[intMonth-1] + "/" + intday+"/" + strYear;
//  }
//  else {
//     datefield.value = intday + "/" + strNMArray[intMonth-1] + "/" + strYear;
//  }
  return true;
}

function LeapYear(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) { 
			return true; 
		}
	} else {
		if ((intYear % 4) == 0) { 
			return true; 
		}
	}
	return false;
}

function checkValor(strField, MaxLengthStrField) {
   var i, tam,lengthInt, lengthDec, qtdeInt, qtdeDec, charAtDecimal;

   lengthInt = MaxLengthStrField - 3;
   lengthDec = 2;

   qtdeInt = 0;
   qtdeDec = 0;
   charAtDecimal = false;
   i = 0;
   tam = strField.length;

   // Se as duas teclas iniciais forem zero, não permite
   if (tam == 1)
      if (strField.charAt(0) == "0" && tecla == 48)
         return false;

   // Verifica a qtde de inteiros e decimais informados
   while (i < tam) {
     if (strField.charAt(i) == ",") {
       charAtDecimal = true;
       i++;
       continue;
     }
     if (charAtDecimal)
       qtdeDec++;
     else
       qtdeInt++;

     i++;
   }

   // alert("qtdeInt: " + qtdeInt + "   qtdeDec: " + qtdeDec);

   // Não permite que a qtde de inteiros ultrapasse o limite
   if (qtdeInt > lengthInt) {
     alert("Qtde de inteiros do campo ultrapassa o limite permitido que é de " + lengthInt);
     return false;
   }

   // Não permite que a qtde de decimais ultrapasse o limite
   if (qtdeDec > lengthDec) {
     alert("Qtde de decimais do campo ultrapassa o limite permitido que é de " + lengthDec);
     return false;
   }

   return true;
}

function checkhora(objName, mask) {
	var horafield = objName.value;
	var retorno = true;
	
	if ((horafield.length != mask.length) && (horafield.length > 0)) {
		retorno = false;
	} else {
        strHH = horafield.substr(0, 2);
        strMM = horafield.substr(3, 2);
        strSS = horafield.substr(6);

		if (strHH > 24) {
			retorno = false;
		} else if ((strHH == 24) && (strMM > 0 || strSS > 0)) {
			retorno = false;
		} else if (strMM > 59 || strSS > 59) {
			retorno = false;
		}
	}
	if (retorno == false) {
		alert("A hora é inválida.");
		objName.value = "";
		objName.focus();
		return false;
	} else {
		return true;
	}
}

function LengthTextarea (strField, MaxLengthStrField, evtKeyPress) { 
   var tecla;   

   if (strField.length >= MaxLengthStrField)
     return false;

   if(document.all) // Internet Explorer
     tecla = evtKeyPress.keyCode;
   else if(document.layers) // Nestcape
     tecla = evtKeyPress.which;

   if (tecla == 13) // Enter
     if (strField.length >= MaxLengthStrField-1)
       return false;
}

function Recarregar() {
    window.reload();
}

/* Altera o conteúdo de uma String por outro. */
function replaceAll(str, oldStr, newStr) {
	var strText = str;
	var intIndexOfMatch = strText.indexOf( oldStr );

	while (intIndexOfMatch != -1){
		strText = strText.replace( oldStr, newStr )
 
		intIndexOfMatch = strText.indexOf( oldStr );
	}

	return( strText );
}

/**** AJAX ***/
function GetXmlHttpObject(handler){ 
	var objXmlHttp=null

	if (navigator.userAgent.indexOf("Opera")>=0){
		alert("This example doesn't work in Opera") 
		return 
	}
	
	if (navigator.userAgent.indexOf("MSIE")>=0){ 
		var strName="Msxml2.XMLHTTP"
		if (navigator.appVersion.indexOf("MSIE 5.5")>=0){
			strName="Microsoft.XMLHTTP"
		} 
		
		try {
			objXmlHttp=new ActiveXObject(strName)
			objXmlHttp.onreadystatechange=handler 
			return objXmlHttp
		} catch(e) { 
			alert("Error. Scripting for ActiveX might be disabled") 
			return 
		} 
	}
	 
	if (navigator.userAgent.indexOf("Mozilla")>=0){
		objXmlHttp=new XMLHttpRequest()
		objXmlHttp.onload=handler
		objXmlHttp.onerror=handler 
		return objXmlHttp
	}
}
/*** Fim das funções do AJAX ***/