//Função que só permite digitação de números
//Utilização => onkeydown="so_numero();"
function so_numero()
{
   var tecla = window.event.keyCode;
	//alert(tecla);
   if((tecla != 8) && (tecla != 46) && (tecla != 37) && (tecla != 39) && (tecla != 9))
   {
      if((tecla < 48) || (tecla > 57))
      {
         if((tecla < 96) || (tecla > 105))
         {
            event.returnValue = false;
         }
      }
   }
}
//------------------------------------------------------------

function formata_moeda(v)
{
   v=v.replace(/(\d{1})(\d{11})$/,"$1.$2")  //coloca ponto antes dos últimos 11 digitos
   v=v.replace(/(\d{1})(\d{8})$/,"$1.$2")  //coloca ponto antes dos últimos 8 digitos
   v=v.replace(/(\d{1})(\d{5})$/,"$1.$2")  //coloca ponto antes dos últimos 5 digitos
   v=v.replace(/(\d{1})(\d{2})$/,"$1,$2") //coloca virgula antes dos últimos 2 digitos

   return v;
}
/*
//Função que utiliza expressão regular para máscara de telefone
//Utilização => onkeydown="masc_telefone(this, telefone);"
function masc_telefone(o,f)
{
   v_obj = o;
   v_fun = f;

   setTimeout("ExecMask()", 1);
}

function ExecMask()
{
   v_obj.value = v_fun(v_obj.value);
}

function telefone(v)
{
   v=v.replace(/\D/g,"");
   v=v.replace(/(\d{4})(\d)/,"$1-$2");

   return v;
}*/

//------------------------------------------------------------

//Função que utiliza expressão regular para máscara de telefone
//Utilização => onkeyup="masc_telefone(this);"
//Para incluir o DDD na máscara basta definir o parâmetro ddd como true
//Ex.: onkeyup="masc_telefone(this, true);"
function masc_telefone(campo, ddd)
{
   var v = campo.value;

   v = v.replace(/\D/g,"")  //permite digitar apenas números

   if(ddd)
   {
      v = v.replace(/[0-9]{11}/,"inválido")   //limita pra máximo (99) 9999-9999
   }
   else
   {
      v = v.replace(/[0-9]{9}/,"inválido")   //limita pra máximo 9999-9999
   }

   if(ddd)
   {
      v = v.replace(/(\d{2})(\d{8})$/,"($1) $2")  //coloca traço antes dos últimos 8 digitos
   }

   v = v.replace(/(\d{1})(\d{4})$/,"$1-$2")  //coloca traço antes dos últimos 4 digitos

   campo.value = v;
}
//------------------------------------------------------------

//Função que utiliza expressão regular para máscara de cep
//Utilização => onkeydown="masc_cep(this, cep);"
function masc_cep(o,f)
{
   v_obj = o;
   v_fun = f;

   setTimeout("ExecMask()", 1);
}

function ExecMask()
{
   v_obj.value = v_fun(v_obj.value);
}

function cep(v)
{
   v=v.replace(/\D/g,"");
   v=v.replace(/(\d{5})(\d)/,"$1-$2");

   return v;
}
//------------------------------------------------------------

function valida_data(data)
{
   var expReg = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/(19|20)?\d{2}$/;
   var aRet = true;

   if((data) && (data.match(expReg)) && (data != ""))
   {
      var dia = data.substring(0,2);
      var mes = data.substring(3,5);
      var ano = data.substring(6,10);

      if((mes == 4 || mes == 6 || mes == 9 || mes == 11) && dia > 30)
      {
         aRet = false;
      }
      else
      {
         if((ano % 4) != 0 && mes == 2 && dia > 28)
         {
            aRet = false;
         }
         else
         {
            if((ano%4) == 0 && mes == 2 && dia > 29)
            {
               aRet = false;
            }
         }
      }
   }
   else
   {
      aRet = false;
   }

   return aRet;
}

//Função que utiliza expressão regular para máscara de data
//Utilização => onkeydown="masc_data(this, Data);"
function masc_data(o,f)
{
   v_obj = o;
   v_fun = f;

   setTimeout("ExecMask()",1);
}

function ExecMask()
{
   v_obj.value = v_fun(v_obj.value);
}

function Data(v)
{
   v=v.replace(/\D/g,"");
   v=v.replace(/(\d{2})(\d)/,"$1/$2");
   v=v.replace(/(\d{2})(\d)/,"$1/$2");
   v=v.replace(/(\d{2})(\d{2})$/,"$1$2");
   
   return v;
}
//------------------------------------------------------------

function valida_email(email)
{
	return email.search(/(\w[\w\.\+]+)@(.+)\.(\w+)$/) == 0;
}

//Ajax
// Esta função instancia o objeto XMLHttpRequest
function openAjax()
{
	var ajax;
	try
	{
		ajax = new XMLHttpRequest();
	}
	catch(ee)
	{
		try
		{
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			try
			{
				ajax = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(E)
			{
				ajax = false;
			}
		}
	}

	return ajax;
}

//Função para exibição de mensagem de erro
function mensagem(msg, largura, y, intervalo)
{
   var caixa = document.createElement("div");
   var margem_esq = (eval(largura) / 2) - ((eval(largura) / 2) * 2);

   caixa.setAttribute('id','msn');

   caixa.style.position = "absolute";
   caixa.style.visibility = "visible";
   caixa.style.width = largura + "px";
   caixa.style.top = y + "px";
   caixa.style.left = "50%";
   caixa.style.marginLeft = margem_esq + "px";

	caixa.innerHTML = msg;

   document.getElementsByTagName("body")[0].appendChild(caixa);

   this.oculta_mensagem = function(id)
   {
      var cx = document.getElementById(id)
      document.getElementsByTagName("body")[0].removeChild(cx);
      clearInterval(tempo);
   };

   if(intervalo > 0)
   {
      this.tempo = setInterval("this.oculta_mensagem('" + caixa.id + "')", intervalo);
   }
}

function carregando(exibe, largura, y)
{
   var msg = "<div style='width:126px;height:22px;'>Aguarde...</div>";

   if(exibe)
   {
      mensagem(msg, largura, y, 0);
   }
   else
   {
      var mens = document.getElementById("msn");

      document.getElementsByTagName("body")[0].removeChild(mens);
   }
}

/**
 * IAF - 25/05/2010
 * Verificação de senha forte
 * A função original foi alterada para atender as necessidades
 * Original em http://passwordmeter.com
 */
/*
**    Original File: pwd_meter.js
**    Created by: Jeff Todnem (http://www.todnem.com/)
**    Created on: 2007-08-14
**    Last modified: 2007-08-30
**
**    License Information:
**    -------------------------------------------------------------------------
**    Copyright (C) 2007 Jeff Todnem
**
**    This program is free software; you can redistribute it and/or modify it
**    under the terms of the GNU General Public License as published by the
**    Free Software Foundation; either version 2 of the License, or (at your
**    option) any later version.
**
**    This program is distributed in the hope that it will be useful, but
**    WITHOUT ANY WARRANTY; without even the implied warranty of
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
**    General Public License for more details.
**
**    You should have received a copy of the GNU General Public License along
**    with this program; if not, write to the Free Software Foundation, Inc.,
**    59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**
**
*/
String.prototype.strReverse = function() {
	var newstring = "";
	for (var s=0; s < this.length; s++) {
		newstring = this.charAt(s) + newstring;
	}
	return newstring;
	//strOrig = ' texttotrim ';
	//strReversed = strOrig.revstring();
};

function chkPass(pwd) {
	var oScorebar = document.getElementById("scorebar");
	var oScore = document.getElementById("score");
	var oComplexity = document.getElementById("complexity");
	var nScore = 0;
	var nLength = 0;
	var nAlphaUC = 0;
	var nAlphaLC = 0;
	var nNumber = 0;
	var nSymbol = 0;
	var nMidChar = 0;
	var nRequirements = 0;
	var nAlphasOnly = 0;
	var nNumbersOnly = 0;
	var nRepChar = 0;
	var nConsecAlphaUC = 0;
	var nConsecAlphaLC = 0;
	var nConsecNumber = 0;
	var nConsecSymbol = 0;
	var nConsecCharType = 0;
	var nSeqAlpha = 0;
	var nSeqNumber = 0;
	var nSeqChar = 0;
	var nReqChar = 0;
	var nReqCharType = 3;
	var nMultLength = 4;
	var nMultAlphaUC = 3;
	var nMultAlphaLC = 3;
	var nMultNumber = 4;
	var nMultSymbol = 6;
	var nMultMidChar = 2;
	var nMultRequirements = 2;
	var nMultRepChar = 1;
	var nMultConsecAlphaUC = 2;
	var nMultConsecAlphaLC = 2;
	var nMultConsecNumber = 2;
	var nMultConsecSymbol = 1;
	var nMultConsecCharType = 0;
	var nMultSeqAlpha = 3;
	var nMultSeqNumber = 3;
	var nTmpAlphaUC = "";
	var nTmpAlphaLC = "";
	var nTmpNumber = "";
	var nTmpSymbol = "";
	var sAlphaUC = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sAlphaLC = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sNumber = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sSymbol = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sMidChar = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sRequirements = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sAlphasOnly = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sNumbersOnly = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sRepChar = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sConsecAlphaUC = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sConsecAlphaLC = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sConsecNumber = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sSeqAlpha = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sSeqNumber = "&nbsp;&nbsp;&nbsp;&nbsp;0";
	var sAlphas = "abcdefghijklmnopqrstuvwxyz";
	var sNumerics = "01234567890";
	var sComplexity = "Muito curta";
	var sStandards = "Abaixo";
	var nMinPwdLen = 6;
	if (document.all) { var nd = 0; } else { var nd = 1; }
	if (pwd) {
		nScore = parseInt(pwd.length * nMultLength);
		nLength = pwd.length;
		var arrPwd = pwd.replace (/\s+/g,"").split(/\s*/);
		var arrPwdLen = arrPwd.length;

		/* Loop through password to check for Symbol, Numeric, Lowercase and Uppercase pattern matches */
		for (var a=0; a < arrPwdLen; a++) {
			if (arrPwd[a].match(new RegExp(/[A-Z]/g))) {
				if (nTmpAlphaUC !== "") { if ((nTmpAlphaUC + 1) == a) { nConsecAlphaUC++; nConsecCharType++; } }
				nTmpAlphaUC = a;
				nAlphaUC++;
			}
			else if (arrPwd[a].match(new RegExp(/[a-z]/g))) {
				if (nTmpAlphaLC !== "") { if ((nTmpAlphaLC + 1) == a) { nConsecAlphaLC++; nConsecCharType++; } }
				nTmpAlphaLC = a;
				nAlphaLC++;
			}
			else if (arrPwd[a].match(new RegExp(/[0-9]/g))) {
				if (a > 0 && a < (arrPwdLen - 1)) { nMidChar++; }
				if (nTmpNumber !== "") { if ((nTmpNumber + 1) == a) { nConsecNumber++; nConsecCharType++; } }
				nTmpNumber = a;
				nNumber++;
			}
			else if (arrPwd[a].match(new RegExp(/[^a-zA-Z0-9_]/g))) {
				if (a > 0 && a < (arrPwdLen - 1)) { nMidChar++; }
				if (nTmpSymbol !== "") { if ((nTmpSymbol + 1) == a) { nConsecSymbol++; nConsecCharType++; } }
				nTmpSymbol = a;
				nSymbol++;
			}
			/* Internal loop through password to check for repeated characters */
			for (var b=0; b < arrPwdLen; b++) {
				if (arrPwd[a].toLowerCase() == arrPwd[b].toLowerCase() && a != b) { nRepChar++; }
			}
		}

		/* Check for sequential alpha string patterns (forward and reverse) */
		for (var s=0; s < 23; s++) {
			var sFwd = sAlphas.substring(s,parseInt(s+3));
			var sRev = sFwd.strReverse();
			if (pwd.toLowerCase().indexOf(sFwd) != -1 || pwd.toLowerCase().indexOf(sRev) != -1) { nSeqAlpha++; nSeqChar++;}
		}

		/* Check for sequential numeric string patterns (forward and reverse) */
		for (var s=0; s < 8; s++) {
			var sFwd = sNumerics.substring(s,parseInt(s+3));
			var sRev = sFwd.strReverse();
			if (pwd.toLowerCase().indexOf(sFwd) != -1 || pwd.toLowerCase().indexOf(sRev) != -1) { nSeqNumber++; nSeqChar++;}
		}

	/* Modify overall score value based on usage vs requirements */

		/* General point assignment */
		if (nAlphaUC > 0 && nAlphaUC < nLength) {
			nScore = parseInt(nScore + ((nLength - nAlphaUC) * 2));
			sAlphaUC = "+ " + parseInt((nLength - nAlphaUC) * 2);
		}
		if (nAlphaLC > 0 && nAlphaLC < nLength) {
			nScore = parseInt(nScore + ((nLength - nAlphaLC) * 2));
			sAlphaLC = "+ " + parseInt((nLength - nAlphaLC) * 2);
		}
		if (nNumber > 0 && nNumber < nLength) {
			nScore = parseInt(nScore + (nNumber * nMultNumber));
			sNumber = "+ " + parseInt(nNumber * nMultNumber);
		}
		if (nSymbol > 0) {
			nScore = parseInt(nScore + (nSymbol * nMultSymbol));
			sSymbol = "+ " + parseInt(nSymbol * nMultSymbol);
		}
		if (nMidChar > 0) {
			nScore = parseInt(nScore + (nMidChar * nMultMidChar));
			sMidChar = "+ " + parseInt(nMidChar * nMultMidChar);
		}

		/* Point deductions for poor practices */
		if ((nAlphaLC > 0 || nAlphaUC > 0) && nSymbol === 0 && nNumber === 0) {  // Only Letters
			nScore = parseInt(nScore - nLength);
			nAlphasOnly = nLength;
			sAlphasOnly = "- " + nLength;
		}
		if (nAlphaLC === 0 && nAlphaUC === 0 && nSymbol === 0 && nNumber > 0) {  // Only Numbers
			nScore = parseInt(nScore - nLength);
			nNumbersOnly = nLength;
			sNumbersOnly = "- " + nLength;
		}
		if (nRepChar > 0) {  // Same character exists more than once
			nScore = parseInt(nScore - (nRepChar * nRepChar));
			sRepChar = "- " + nRepChar;
		}
		if (nConsecAlphaUC > 0) {  // Consecutive Uppercase Letters exist
			nScore = parseInt(nScore - (nConsecAlphaUC * nMultConsecAlphaUC));
			sConsecAlphaUC = "- " + parseInt(nConsecAlphaUC * nMultConsecAlphaUC);
		}
		if (nConsecAlphaLC > 0) {  // Consecutive Lowercase Letters exist
			nScore = parseInt(nScore - (nConsecAlphaLC * nMultConsecAlphaLC));
			sConsecAlphaLC = "- " + parseInt(nConsecAlphaLC * nMultConsecAlphaLC);
		}
		if (nConsecNumber > 0) {  // Consecutive Numbers exist
			nScore = parseInt(nScore - (nConsecNumber * nMultConsecNumber));
			sConsecNumber = "- " + parseInt(nConsecNumber * nMultConsecNumber);
		}
		if (nSeqAlpha > 0) {  // Sequential alpha strings exist (3 characters or more)
			nScore = parseInt(nScore - (nSeqAlpha * nMultSeqAlpha));
			sSeqAlpha = "- " + parseInt(nSeqAlpha * nMultSeqAlpha);
		}
		if (nSeqNumber > 0) {  // Sequential numeric strings exist (3 characters or more)
			nScore = parseInt(nScore - (nSeqNumber * nMultSeqNumber));
			sSeqNumber = "- " + parseInt(nSeqNumber * nMultSeqNumber);
		}

		nRequirements = nReqChar;
		if (pwd.length >= nMinPwdLen) { var nMinReqChars = 3; } else { var nMinReqChars = 4; }
		if (nRequirements > nMinReqChars) {  // One or more required characters exist
			nScore = parseInt(nScore + (nRequirements * 2));
			sRequirements = "+ " + parseInt(nRequirements * 2);
		}

		/* Determine complexity based on overall score */
		if (nScore > 100) { nScore = 100; } else if (nScore < 0) { nScore = 0; }
		if (nScore >= 0 && nScore < 20) { sComplexity = "Muito Fraca"; }
		else if (nScore >= 20 && nScore < 40) { sComplexity = "Fraca"; }
		else if (nScore >= 40 && nScore < 60) { sComplexity = "Boa"; }
		else if (nScore >= 60 && nScore < 80) { sComplexity = "Forte"; }
		else if (nScore >= 80 && nScore <= 100) { sComplexity = "Muito Forte"; }

		/* Display updated score criteria to client */
		oScorebar.style.backgroundPosition = "-" + parseInt(nScore * 4) + "px";
		oScore.innerHTML = nScore + "%";
		oComplexity.innerHTML = sComplexity;
	}
	else {
		/* Display default score criteria to client */
		oScorebar.style.backgroundPosition = "0";
		oScore.innerHTML = nScore + "%";
		oComplexity.innerHTML = sComplexity;
	}
}
//-----------------------------------------------------------------------------

/**
 * IAF - 09/06/2010
 * def_classe_css(objeto, classe)
 * Atribui uma classe CSS à um objeto via javascript com verificação de browser
 * @param objeto = Objeto ao qual a classe será atribuída
 * @param classe = Classe CSS a ser atribuída ao objeto
 */
function def_classe_css(objeto, classe)
{
   if(/MSIE (\d+\.\d+);/.test(navigator.userAgent))
   {
      ieversion = new Number(RegExp.$1)

      if(ieversion < 8)
      {
         objeto.setAttribute("className", classe);
      }
      else
      {
         objeto.setAttribute("class", classe);
      }
   }
   else
   {
      objeto.setAttribute("class", classe);
   }
}
//-----------------------------------------------------------------------------

/**
 * IAF - 03/03/2011
 * Função que cria uma "janela" (Div contendo um iframe)
 * A classe CSS janela bem como suas sub-classes devem estar contidas
 * no CSS da página que utiliza este recurso, bem como a imagem ../img/jpg/bt_fechar.jpg
 * deve estar no seu devido lugar...
 */
function mostra_janela(fk, url, largura, altura, titulo)
{
   var janela = document.createElement("div");
   janela.id  = "janela";

   def_classe_css(janela, "janela");

   janela.style.width = largura + "px";
   janela.style.height = altura + "px";

   var esq = Math.abs(document.documentElement.scrollLeft + ((document.documentElement.clientWidth / 2) - (largura / 2)));
   janela.style.left= esq + "px";

   janela.style.top = document.documentElement.scrollTop + 200 + "px";

   var titulo_janela = document.createElement("div");
   def_classe_css(titulo_janela, "titulo");

   titulo_janela.innerHTML = titulo;

   janela.appendChild(titulo_janela);

   var bt_fechar = document.createElement("div");
   def_classe_css(bt_fechar, "bt_fechar");

   bt_fechar.title = "Fechar";

   bt_fechar.onclick = function()
   {
      document.getElementsByTagName("body")[0].removeChild(this.parentNode);
   };

   janela.appendChild(bt_fechar);

   var frame         = document.createElement("iframe");
   frame.frameBorder = "0";
   frame.src         = url + fk;
   
   janela.appendChild(frame);

   document.getElementsByTagName("body")[0].appendChild(janela);
}
//-----------------------------------------------------------------------------


