function getHTTPObject(){
  var xmlHttp = "";
  try{
    xmlHttp = new XMLHttpRequest();
  }catch(ee){
    try{
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            xmlHttp = false;
        }
    }
  }
  return xmlHttp;
}



function getMetodo() {
	var metoto;
	// Mozilla, Firefox, Safari, e Netscape
	if (window.XMLHttpRequest){
		try {
			metodo = "GET";
		} catch(e) {
			metodo = false;
		}
		return metodo;
	}
	// Internet Explorer
	if (window.ActiveXObject) {
		try {
			metodo = "POST"; 
		} catch(e) {
			try {
				metodo = "POST"; 
			} catch(e) {
				try {
					metodo = "POST";
				} catch(e) {
					try {
						metodo = "POST"; 
					} catch(e) {
						metodo = false;
					}
				}
			}
		}
		return metodo;
	}
	alert("Objeto XMLHTTP nao e suportado pelo navegador.");
  }
  
  function carregaCidades(){
  	vSel = document.getElementById('estado');
  	if (parseFloat(vSel.value) != ""){
    	var vRetorno = "";
  	  url = "ajax_consultas.php?controle=1&estado="+vSel.value;
  	  ometodo = getMetodo();
  	  xmlhttp = getHTTPObject();
  	  xmlhttp.open(ometodo,url,true);
  	  xmlhttp.onreadystatechange=function(){
    		if(xmlhttp.readyState == 4) {
    		  vRetorno = xmlhttp.responseText;
    		  MontaSelect(vRetorno,'cidade');
    		}
  	  }
  	  xmlhttp.send(null);
  	}
  }
  
  function Remove_Subitens(vSelect){
	  var vSubitens = vSelect.length;
	  for (x=0; x<vSubitens; x++){
		  vSelect.options[x] = null;
	  }
	  vSubitens = vSelect.length;
	  if (vSubitens>0){
		  return Remove_Subitens(vSelect);
	  }
  }
  
  function MontaSelect(vStr,vSel){
	  var vSelectItem = document.getElementById(vSel);
	  var optn = document.createElement("option");
	  var vOptions = new String;
	  var vMT_Options = new Array;
	  var vMT_KeyVal = new Array;
	  var vSubitens = vSelectItem.length;
	  
	  if (vSubitens>0){
		  Remove_Subitens(vSelectItem);
	  }
	  
	  vOptions = vStr;
	  vMT_Options = vOptions.split("#");
	  if (vMT_Options.length>1){
		  for (y=0; y<vMT_Options.length; y++){
			  optn = document.createElement("option");
			  vMT_KeyVal[y] = vMT_Options[y].split("|");
			  vSelectItem.options[y] = optn;
			  optn.value = vMT_KeyVal[y][0];
			  optn.text = vMT_KeyVal[y][1];
		  }
	  } else {
		  if (vMT_Options.length==1){
			  optn = document.createElement("option");
			  vMT_KeyVal = vOptions.split("|");
			  optn.value = vMT_KeyVal[0];
			  optn.text = vMT_KeyVal[1];
			  vSelectItem.options.add(optn);
		  }
	  }
  }
    
function ValidaCPF(CPF)
  {
    dig_1 = 0;
    dig_2 = 0;
    controle_1 = 10;
    controle_2 = 11;
    lsucesso = 1;
    numero = CPF;
    if (
         numero == "000000000-00" ||
         numero == "111111111-11" ||
         numero == "222222222-22" ||
         numero == "333333333-33" ||
         numero == "444444444-44" ||
         numero == "555555555-55" ||
         numero == "666666666-66" ||
         numero == "777777777-77" ||
         numero == "888888888-88" ||
         numero == "99999999-99" 
        )
    {
      return false;
    }    
    if ((numero.length != 12) || (numero.substring(9, 10) != "-"))
    {
      return false;
    }
    else
    {
      for (i=0 ; i < 9 ; i++)
      {
        dig_1 = dig_1 + parseInt(numero.substring(i, i+1) * controle_1);
        controle_1 = controle_1 - 1;
      }
      resto = dig_1 % 11;
      dig_1 = 11 - resto;
      if ((resto == 0) || (resto == 1))
        dig_1 = 0;
      for ( i=0 ; i < 9 ; i++)
      {
        dig_2 = dig_2 + parseInt(numero.substring(i, i + 1) * controle_2);
        controle_2 = controle_2 - 1;
      }
      dig_2 = dig_2 + 2 * dig_1;
      resto = dig_2 % 11;
      dig_2 = 11 - resto;

      if ((resto == 0) || (resto == 1))
        dig_2 = 0;

      dig_ver = (dig_1 * 10) + dig_2;

      if (dig_ver != parseFloat(numero.substring(numero.length-2,numero.length)))
      {
        return false;
      }
    }
    return true;
  }       
  function ValidaCNPJ(NroCNPJ) 
  {

    NroCNPJ = replace(NroCNPJ,"/","");
    NroCNPJ = replace(NroCNPJ,".","");
    NroCNPJ = replace(NroCNPJ,"-","");

    var dig1=0;
    var dig2=0;
    var x;
    var Mult1 = '543298765432';
    var Mult2 = '6543298765432';

    for(x=0; x<=11; x++) 
    {
      dig1 = dig1 +(parseInt(NroCNPJ.slice(x,x+1)) * parseInt(Mult1.slice(x,x+1)) ) ;
    }
    for(x=0; x<=12; x++) 
    {
      dig2 = dig2 + (parseInt(NroCNPJ.slice(x, x+1)) * parseInt(Mult2.slice(x,x+1)) );
    }


    dig1 = (dig1 * 10)%11;
    dig2 = (dig2 * 10)%11;

    if (dig1 == 10) {dig1 = 0;}
    if (dig2 == 10) {dig2 = 0;}

    if (dig1 != parseInt(NroCNPJ.slice(12, 13))) 
    {
      return false;
    } 
    else 
    {
      if (dig2 != parseInt(NroCNPJ.slice(13, 14))) 
      {
        return false;
      } 
      else 
      {
        return true;
      }
    }
  }
  function replace(string,text,by) 
  {
    // Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);

    if ((!i) && (text != string.substring(0,txtLength))) return string;
        if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
  }
  function FormataReais(fld, milSep, decSep, e) 
  {
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (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 = fld.value.length;
    for(i = 0; i < len; i++)
      if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) 
        break;
    aux = '';
    for(; i < len; i++)
      if (strCheck.indexOf(fld.value.charAt(i))!=-1) 
        aux += fld.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) 
      fld.value = '';
    if (len == 1) 
      fld.value = '0'+ decSep + '0' + aux;
    if (len == 2) 
      fld.value = '0'+ decSep + aux;
    if (len > 2) 
    {
      aux2 = '';
      for (j = 0, i = len - 3; i >= 0; i--) 
      {
        if (j == 3) 
        {
          aux2 += milSep;
          j = 0;
        }
        aux2 += aux.charAt(i);
        j++;
      }
      fld.value = '';
      len2 = aux2.length;
      for (i = len2 - 1; i >= 0; i--)
        fld.value += aux2.charAt(i);
      fld.value += decSep + aux.substr(len - 2, len);
    }
    return false;
  }  

function fValidaNumerico(oEvento) 
{
	oEvento = (oEvento) ? oEvento : event;
    var charCode = (oEvento.charCode) ? oEvento.charCode : ((oEvento.keyCode) ? oEvento.keyCode : ((oEvento.which) ? oEvento.which : 0));
	if (charCode == 44) return true;	
    if (charCode > 31 && (charCode < 48 || charCode > 57)) 
    {
        return false;
    }
    return true;
}
function flash(arquivo, largura, altura, parametro){
    document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+largura+'" height="'+altura+'" id="teste" align="middle">');
    document.write('<param name="allowScriptAccess" value="sameDomain" /><param name="wmode" value="transparent" />');
    document.write('<PARAM NAME=FlashVars VALUE="'+parametro+'" />');
    document.write('<param name="movie" value="'+arquivo+'" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><embed src="'+arquivo+'" flashvars="'+parametro+'" wmode="transparent" quality="best" width="'+largura+'" height="'+altura+'" name="teste" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
    document.write('</object>');
}

function criaMascara(_RefObjeto, _Modelo){
  var valorAtual = _RefObjeto.value;
  var valorNumerico = '';
  var nIndexModelo = 0;
  var nIndexString = 0;
  var valorFinal = '';
  var adicionarValor = true;
  for (i=0;i<_Modelo.length;i++){
    if (_Modelo.substr(i,1) != '#'){
      valorAtual = valorAtual.replace(_Modelo.substr(i,1),'');
    }
  }
  for (i=0;i<valorAtual.length;i++){
    if (!isNaN(parseFloat(valorAtual.substr(i,1)))){
      valorNumerico = valorNumerico + valorAtual.substr(i,1);
    }
  }
  for (i=0;i<_Modelo.length;i++){
    if (_Modelo.substr(i,1) == '#'){
      if (valorNumerico.substr(nIndexModelo,1) != ''){
        valorFinal = valorFinal + valorNumerico.substr(nIndexModelo,1);
        nIndexModelo++;nIndexString++;
      } else {
        adicionarValor = false;
      }
    } else {
      if (adicionarValor && valorNumerico.substr(nIndexModelo,1) != ''){
        valorFinal = valorFinal + _Modelo.substr(nIndexString,1)
        nIndexString++;
      }
    }
  }
  _RefObjeto.value = valorFinal
}

function SohNumeros(valor){
  chars= "0123456789,.";
  e = String.fromCharCode(window.event.keyCode);
  if (e == ""){
    if (valor.indexOf(e)==-1){
      return;
    }
    window.event.keyCode=0;
  }
  if(chars.indexOf(e)==-1){
    window.event.keyCode=0;
  }
}
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
function GM_Verifica_Data(vAno, vMes, vDia)
  {
	  vOk = false;
	  //Cria uma data
		vData = new Date(vAno, vMes-1, vDia);
		vDia1 = vData.getDate();
		if(vDia1<10)
		{
		vDia1 = '0'+vDia1
		}
		
		vMes1 = vData.getMonth();
		vAno1 = vData.getFullYear();  
		//alert(vDia + ' - ' + vDia1) 
		//alert(vMes-1 + ' - ' + vMes1)
		//alert(vAno + ' - ' + vAno1)
    vOk = isDateJS(vAno,vMes,vDia) && (vDia == vDia1) && ((vMes -1) == vMes1) && (vAno == vAno1);	
    return vOk;
  }

function isDateJS (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.
    //alert(year)
    //alert(month)
    //alert(day)
	if(parseInt(month.substring(0,1))==0)
	{
		month = parseInt(month.substring(1,2))
	}
	if(parseInt(day.substring(0,1))==0)
	{
		day = parseInt(day.substring(1,2))
	}
    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;
    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

function fVoltar()
{
	history.go(-1);
}

function onBlurData(campo_obj_data)
{
	var erro = 0;
	var Data = campo_obj_data.value;
	var ArrayData = Data.split("/");
	if(Data != '')
	{
	vAnoOriginal = ArrayData[2]
		if(vAnoOriginal<1900)
		{
			erro = erro + 1;
		}
		if(Data.length!=10) // Valida o len do campo
		{
			erro = erro + 1;
		}
		if(ArrayData.length!=3) // valida o tamanho do array de barras (/) DD/MM/YYYY
		{
			erro = erro + 1;
		}
		else
		{
			biSexto(Data,campo_obj_data);
		}
		if(erro>0)
		{
			campo_obj_data.value = '';
			alert('Data inválida')	
			return false;
		}
	}
}

function biSexto(data_valor, nome_campo)
{
var sData = data_valor.split("/");
var entrou;
	sDia = sData[0];
	sMes = sData[1];
	sAno=(sData[2]%4);
	sAnoOriginal=sData[2];
	entrou = 0;
	
	if((sData[1] == 2) && (sData[0] > 27))
	{
		if(sAno==0)
		{//ano bisexto (Fev tem 29 dias)
			if(sDia>29)
			{
				alert('O mês de Fevereiro ocorre variação em ano bisexto.\nVocê escolheu uma data de ano bisexto. \nEstamos corrigindo a data.');
				nome_campo.value = '29'+'/'+sData[1]+'/'+sData[2];
				entrou = 1;
			}
		}
		else
		{//nao eh ano bisexto, fev tem 28 dias
			if(sDia>28)
			{
				alert('O mês de Fevereiro ocorre variação em ano bisexto.\n A Data escolhida não é valida. \nEstamos corrigindo a data.');
				nome_campo.value = '28'+'/'+sData[1]+'/'+sData[2];
				entrou = 1;
			}
		}
	}
	if(entrou == 0)
	{
		if(GM_Verifica_Data(sAnoOriginal, sMes, sDia)==false)
		{
			nome_campo.value = '';
		}
	}
}

function mascara_data(data_valor,nome_campo, evento)
{
	CharCode = evento.keyCode;
	var sData = data_valor.split("/");
	var ano;
	ano = sData[2];
	if((sData[0]>31) || (sData[1]>12))
	{
		nome_campo.value='';
		alert('Data Inválida');
	}
	else
	{
		if(CharCode!=8)//verificacao do BACKSPACE, so entra qnd nao for backspace
		{
			var mydata = '';
			mydata = mydata + data_valor;
			if (mydata.length == 2) {
				mydata = mydata + '/';
				nome_campo.value = mydata;
			}
			if (mydata.length == 5) {
				mydata = mydata + '/';
				nome_campo.value = mydata;
			}
		}
	}
}

function ValidarEmail(valor)
{
	email = valor;
	if(email.indexOf("@") > 0 && email.indexOf(".") > 0 ) 
	{
		return true;
	}
	else
	{
		return false;
  }
}

function fValidarEmail(valor)
{
	email = valor.value;
	if (email != '')
	{
		if(email.indexOf("@") > 0 && email.indexOf(".") > 0 ) 
		{
			return true;
		}
		else
		{
			valor.focus();
			valor.select();
			alert('O campo e-mail deve contar um endereco eletrônico válido.');
			return false;
		}
	}
}


function mascara_hora(hora_valor,nome_campo)
{
var sHora = hora_valor.split(":");
	if((sHora[0]>23) || (sHora[1]>59))
	{
	alert('Hora Inválida')
	nome_campo.value=''
	nome_campo.focus()
	}
	else
	{
		var myHora = '';
		myHora = myHora + hora_valor;
		if (myHora.length == 2) {
			myHora = myHora + ':';
			nome_campo.value = myHora;
		}
	}
}

function fValidaNumerico(oEvento) 
{
	oEvento = (oEvento) ? oEvento : event;
    var charCode = (oEvento.charCode) ? oEvento.charCode : ((oEvento.keyCode) ? oEvento.keyCode : ((oEvento.which) ? oEvento.which : 0));
	if (charCode == 44) return true;	
    if (charCode > 31 && (charCode < 48 || charCode > 57)) 
    {
        return false;
    }
    return true;
}

function excluiReg(id,nome){
  var excluir = confirm("Tem certeza que deseja excluir " + nome + "?")
  if (excluir == true){
    document.form_excluir.codigo.value = id;
    document.form_excluir.submit();
  }
}

function gotoPage(pag)
{
  window.location.href=pag;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function hide(lyr)
{
  var x = document.getElementById(lyr);
  x.style.visibility = (hide) ? 'hidden' : 'visible';
}

function setLyrDetalheAutor(obj,lyr, vTop, vLeft, vID_Autor){
  var coors = findPos(obj);
  var x = document.getElementById(lyr);
  x.style.top = eval(coors[1]+vTop) + 'px';
  x.style.left = eval(coors[0]+vLeft) + 'px';
  P7_autoLayers(0,lyr);
  P7_autoHide(lyr); // apaga div
  GM_MostraDetalheAutorAJAX(vID_Autor);
  return false;
}

function setLyrErros(obj,lyr, vTop, vLeft, vErro)
{
  var coors = findPos(obj);
  var x = document.getElementById(lyr);
  x.style.top = eval(coors[1]+vTop) + 'px';
  x.style.left = eval(coors[0]+vLeft) + 'px';
  P7_autoLayers(0,lyr);
  P7_autoHide(lyr); // apaga div
  GM_MostraErrosAJAX(vErro);
  return false;
}

function findPos(obj)
{
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    curleft = obj.offsetLeft
    curtop = obj.offsetTop
    while (obj = obj.offsetParent) {
      curleft += obj.offsetLeft
      curtop += obj.offsetTop
    }
  }
  return [curleft,curtop];
}

function P7_autoHide() { //v1.3 by PVII
 var i,g,args=P7_autoHide.arguments;
 for(i=0;i<args.length;i++){if((g=MM_findObj(args[i]))!=null){
  g.p7aHide=true;if(document.layers){
  g.captureEvents(Event.MOUSEOUT);}g.onmouseout=P7_hideDiv;g.p7ahD=true;}}
}

function P7_hideDiv(evt) { //v1.3 by PVII
 var b,relT,mT=false; 
 if(document.layers){b=evt.target;if(b.p7aHide){
  b.visibility="hidden";}else{routeEvent(evt);}
 }else if(document.all&&!window.opera){b=event.srcElement;
  while(b!=null){if(b.tagName=="DIV" && b.p7ahD){mT=true;break;}b=b.parentElement;}
  if(!b.contains(event.toElement)){b.style.visibility="hidden";}
 }else if(document.getElementById){b=evt.currentTarget;relT=evt.relatedTarget;
  while(relT!=null){if(b==relT){mT=true;break;}
  relT=relT.parentNode;}if(!mT){b.style.visibility="hidden";}}
}

function P7_autoLayers() { //v1.4 by PVII
 var g,b,k,f,args=P7_autoLayers.arguments;a=parseInt(args[0]);if(isNaN(a))a=0;
 if(!document.p7setc){p7c=new Array();document.p7setc=true;for(var u=0;u<10;u++){
 p7c[u]=new Array();}}for(k=0;k<p7c[a].length;k++){if((g=MM_findObj(p7c[a][k]))!=null){
 b=(document.layers)?g:g.style;b.visibility="hidden";}}for(k=1;k<args.length;k++){
 if((g=MM_findObj(args[k]))!=null){b=(document.layers)?g:g.style;b.visibility="visible";f=false;
 for(var j=0;j<p7c[a].length;j++){if(args[k]==p7c[a][j]) {f=true;}}
 if(!f){p7c[a][p7c[a].length++]=args[k];}}}
}

function OcultaForm(form){
  document.getElementById(form).style.visibility="hidden";
}