// Início das Funções de Calendário

var oldLink = null;
// code to change the active stylesheet
function setActiveStyleSheet(link, title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
  if (oldLink) oldLink.style.fontWeight = 'normal';
  oldLink = link;
  link.style.fontWeight = 'bold';
  return false;
}

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
 // if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
 if (cal.dateClicked)
	  cal.callCloseHandler();
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format) {
  var el = document.getElementById(id);
  if (calendar != null) {
    // we already have some calendar created
    calendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(false, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    calendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  calendar.setDateFormat(format);    // set the specified date format
  calendar.parseDate(el.value);      // try to parse the text in field
  calendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  calendar.showAtElement(el.nextSibling, "Br");        // show the calendar

  return false;
}

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

// If this handler returns true then the "date" given as
// parameter will be disabled.  In this example we enable
// only days within a range of 10 days from the current
// date.
// You can use the functions date.getFullYear() -- returns the year
// as 4 digit number, date.getMonth() -- returns the month as 0..11,
// and date.getDate() -- returns the date of the month as 1..31, to
// make heavy calculations here.  However, beware that this function
// should be very fast, as it is called for each day in a month when
// the calendar is (re)constructed.
function isDisabled(date) {
  var today = new Date();
  return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}

function flatSelected(cal, date) {
  var el = document.getElementById("preview");
  el.innerHTML = date;
}

function showFlatCalendar() {
  var parent = document.getElementById("display");

  // construct a calendar giving only the "selected" handler.
  var cal = new Calendar(false, null, flatSelected);

  // hide week numbers
  cal.weekNumbers = false;

  // We want some dates to be disabled; see function isDisabled above
  cal.setDisabledHandler(isDisabled);
  cal.setDateFormat("DD, M d");

  // this call must be the last as it might use data initialized above; if
  // we specify a parent, as opposite to the "showCalendar" function above,
  // then we create a flat calendar -- not popup.  Hidden, though, but...
  cal.create(parent);

  // ... we can show it here.
  cal.show();
}

// Fim das Funções de Calendário

function MM_findObj(n, d) { //v4.0
  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 && document.getElementById) x=document.getElementById(n); return x;
}

function ClicaBotao(paForm,paCampo,paValor) //Funcao utilizada no botam Flash
{ 
	document.forms[paForm].elements[paCampo].value= paValor;
}

function DesclicaBotao(paForm,paCampo) //Funcao utilizada no botam Flash
{
	document.forms[paForm].elements[paCampo].value='';
}
	
function isNum( caractere ) //verifica se o caractere é um numero
{ 
         var strValidos = "0123456789" 
         if ( strValidos.indexOf( caractere ) == -1 ) 
                 return false; 
         return true; 
} 

function validaTecla(campo, event) //verifica a tecla pressionada
{ 
         var BACKSPACE=  8; 
         var key; 
         var tecla; 


         CheckTAB=true; 
         if(navigator.appName.indexOf("Netscape")!= -1) 
                 tecla= event.which; 
         else 
                 tecla= event.keyCode; 


         key = String.fromCharCode( tecla); 
//         alert( 'key: ' + tecla + '  -> campo: ' + campo.value); 


         if ( tecla == 13 ) 
                 return false; 
         if ( tecla == BACKSPACE ) 
                 return true;
		 if ( tecla == 37 ) //seta
                 return true;
		 if ( tecla == 39 ) //seta
                 return true;
		 if ( tecla == 46 ) // del
                 return true;
  		 if ( tecla == 16 ) // shift
                 return true;
         return ( isNum(key)); 
} 

function mask_data( paObj,paEvent ) //Insere Mascara de DATA no campo utlizar "onKeyUp=mascara_data(this,event); onFocus=this.select();"
{ 
	if (!validaTecla(paObj,paEvent))
	{
		data    = paObj.value;
		total   = data.length;
		
		data = converte_numero ( data );
		if (data.length<7)
			paObj.value = data.substring(0,2) + '/' + data.substring(2,6);
		else
			paObj.value = data.substring(0,2) + '/' + data.substring(2,4) + '/' + data.substring(4,8);
	}
}

function mascara_data( paObj,paEvent ) //Essa Tem bug, mas tem soft q ainda usa ela. A mask_data ej melhor
{ 
		data    = paObj.value;
		total   = data.length;
		
		data = converte_numero ( data );
		if (data.length<7)
			paObj.value = data.substring(0,2) + '/' + data.substring(2,6);
		else
			paObj.value = data.substring(0,2) + '/' + data.substring(2,4) + '/' + data.substring(4,8);
}

function tamanhoJanela( paLargura, paAltura)
{
	var winX, winY, vmLar, vmAlt;
	vmLar= paLargura;
	vmAlt= paAltura;
	winX = (screen.Width - vmLar) / 2;
	winY = (screen.availHeight - vmAlt) / 2;
	window.resizeTo( vmLar, vmAlt);
	window.moveTo( winX, winY);
}

function janela(paLink, paNome, paLar, paAlt) // abre uma janela do browser nova
{
	var winX, winY, wind;
	winX = (screen.Width - paLar) / 2;
	winY = (screen.availHeight - paAlt) / 2;
	wind = window.open(paLink,paNome,"width="+paLar+",height="+paAlt+",toolbars=no,status=no,scrollbars=yes,resizable=yes,top="+winY+",left="+winX+"");
	if (parseInt(navigator.appVersion) >= 4) { wind.window.focus(); }
}

function cpf ( paCpf ) // verifica a validação de CPF
{
	var i; 
	s = paCpf; 
	var c = s.substr(0,9); 
	var dv = s.substr(9,2); 
	var d1 = 0; 
	vmRetorno = true;	

	for (i = 0; i < 9; i++) 
	{ 
		d1 += c.charAt(i)*(10-i); 
	} 
	
		if (d1 == 0){ 
			vmRetorno = false; 
		} 
	
	d1 = 11 - (d1 % 11); 
	
	if (d1 > 9) d1 = 0; 
	
	if (dv.charAt(0) != d1) 
	{ 
		vmRetorno = false; 
	} 

	d1 *= 2; 
	
	for (i = 0; i < 9; i++) 
	{ 
		d1 += c.charAt(i)*(11-i); 
	} 
	
	d1 = 11 - (d1 % 11); 
	
	if (d1 > 9) d1 = 0; 
	
	if (dv.charAt(1) != d1) 
	{ 
		vmRetorno = false; 
	} 

	return vmRetorno;
}

function cgc(pcgc) // faz verificação de CNPJ
{
	// verifica o tamanho
	if (pcgc.length != 14) 
	{
		sim=false;
	}
	else 
	{
		sim=true;
	}

	if (sim )  // verifica se e numero
	{
		for (i=0;((i<=(pcgc.length-1))&& sim); i++)
		{
			val = pcgc.charAt(i)
			// alert (val)
			if ( (val!="9") && (val!="0") && (val!="1") && (val!="2") && (val!="3") && (val!="4") && (val!="5") && (val!="6") && (val!="7") && (val!="8") ) 
			{ 
				sim=false;
			}
		}
		if (sim)  // se for numero continua
		{
			m2 = 2
			soma1 = 0
			soma2 = 0
			for (i=11;i>=0;i--)
			{
				val = eval(pcgc.charAt(i))
				// alert ("Valor do Val: "+val)
				m1 = m2
				if (m2<9) 
				{ 
					m2 = m2+1;
				}
				else 
				{
					m2 = 2;
				}
				soma1 = soma1 + (val * m1)
				soma2 = soma2 + (val * m2)
			}  // fim do for de soma

			soma1 = soma1 % 11
			if (soma1 < 2) 
			{
				d1 = 0;
			}
			else 
			{ 
				d1 = 11- soma1;
			}

			soma2 = (soma2 + (2 * d1)) % 11
			if (soma2 < 2) 
			{ 
				d2 = 0;
			}
			else 
			{ 
				d2 = 11- soma2;
			}
			// alert (d1)
			// alert (d2)
			if ((d1==pcgc.charAt(12)) && (d2==pcgc.charAt(13)))
			{ 
				return true; 
			}
			else 
				return false;
		}
	}
}

function CPF_CNPJ( paStr )
{
	valido = false;
	if ( cgc( paStr ) || cpf( paStr ) )
	{
		valido = true;
	}
	return valido;
}

function compara_data(data, data_ant)
{
	 dia = eval(data.substring(0,2));
	 mes = eval(data.substring(3,5));
	 ano = eval(data.substring(6,10));
	 
	 td  = eval(data_ant.substring(0,2));
	 tm  = eval(data_ant.substring(3,5));
	 ta  = eval(data_ant.substring(6,10));

	 if (td >= 0 && td <= 9)
	 {
		 td = '0'+td;
	 }
	 if (tm >= 0 && tm <= 9)
	 {
		 tm = '0'+tm;
	 }
	 if (dia >= 0 && dia <= 9)
	 {
		 dia = '0'+dia;
	 }
	 if (mes >= 0 && mes <= 9)
	 {
		 mes = '0'+mes;
	 }

	 data_anterior = eval(ta+''+tm+''+td);
	 data_atual   = eval(ano+''+mes+''+dia);


	 if (data_anterior <= data_atual)
	 {
		 return false;
	 }
	 else
		 return true;

}

function data_inferior(data, data_ant)
{
	 dia = eval(data.substring(0,2));
	 mes = eval(data.substring(3,5));
	 ano = eval(data.substring(6,10));
	 
	 td  = eval(data_ant.substring(0,2));
	 tm  = eval(data_ant.substring(3,5));
	 ta  = eval(data_ant.substring(6,10));

	 if (td >= 0 && td <= 9)
	 {
		 td = '0'+td;
	 }
	 if (tm >= 0 && tm <= 9)
	 {
		 tm = '0'+tm;
	 }
	 if (dia >= 0 && dia <= 9)
	 {
		 dia = '0'+dia;
	 }
	 if (mes >= 0 && mes <= 9)
	 {
		 mes = '0'+mes;
	 }

	 data_anterior = eval(ta+''+tm+''+td);
	 data_atual   = eval(ano+''+mes+''+dia);


	 if (data_anterior < data_atual)
		 return true;
	 else
		 return false;
}

function checadata(data) // faz verificação de data
{
	retorno = true;

	if (data == '' && data.length!=10 && data.length!=7)
		{
		retorno = false;
		}
	else
		{

		vet_dia    = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
		vet_dia_bi = new Array(31,29,31,30,31,30,31,31,30,31,30,31);
		
		if (data.length==10)
			{
			dia = data.substring(0,2);
			ba1 = data.substring(2,3);
			mes = data.substring(3,5);
			ba2 = data.substring(5,6);
			ano = data.substring(6,10);
			}
		else
			{
			dia = 15;
			ba2 = '/';
			mes = data.substring(0,2);
			ba1 = data.substring(2,3);
			ano = data.substring(3,7);
			}

		if (!sonumero(dia, 'i') || !sonumero(mes, 'i') || !sonumero(ano, 'i'))
			{
			retorno = false;
			}
		else
			{

			if ( (ba1 != '/') || (ba2 != '/'))
				{
				retorno = false;
				}

			if (eval(ano) < 1900)
				{
				retorno = false;
				}

			if ( (eval(mes) < 1) || (eval(mes) > 12))
				{
				retorno = false;
				}

			if ((eval(ano) % 4 ) == 0)
				{
				if ( (eval(dia) < 1) || (eval(dia) > vet_dia_bi[eval(mes)-1]) )
					retorno = false;
				}
			else
				{
				if ( (eval(dia) < 1) || (eval(dia) > vet_dia[eval(mes)-1]) )
					retorno = false;
				}
			}
		}

	return retorno;
}

function converte_numero ( paString ) //Converte uma string em numero
{
	tam		= paString.length;
	indice  = 0;
	vmString= "";

	for (cont=0;cont<tam ;cont++ )
	{
		if (paString.charAt(cont)==",")
		{
			vmString += "." ;
		}
		else
		{
			if (paString.charAt(cont)<=9)
			{
			vmString += paString.charAt(cont);
			}
		}
	}

	return vmString;
}

function retiraPontos( paString ) //Retorna somente os numeros de uma String
{
	tam		= paString.length;
	indice  = 0;
	vmString= "";

	for (cont=0;cont<tam ;cont++ )
	{
		if (paString.charAt(cont)<=9)
		{
			vmString += paString.charAt(cont);
		}
	}

	return vmString;
}

function sonumero(pega, tipo) // faz verificação de número
{
	retorno = true;
	if ( tipo=="m" && qde_chars(pega, ",")>0 && qde_chars(pega, ".")>0 )
		retorno = false;
	else if ( qde_chars(pega, ",")>1 || qde_chars(pega, ".")>1 )
		retorno = false;
	else
	{
		if (tipo=="m")
			tipo="f";

		for (w=0; w<pega.length; w++)
			{
			ponto=0;
			if ( (pega.substring(w,w+1) < '0') || (pega.substring(w,w+1) > '9') )
				{
				if (tipo == 'f' && (pega.substring(w,w+1)=="." || pega.substring(w,w+1)=="," || pega.substring(0,1)=="-") && ponto==0)
					{ponto=1;}
				else
				retorno = false;
				}
			}
	}
	return retorno;
}

function qde_chars(texto, caracter) // faz verificação de quantos carateres caracter tem em pega
{
	qde=0;
	for (ind=0; ind<texto.length; ind++)
		{
		if ( (texto.substring(ind,ind+1) == caracter ) )
			qde++;
		}
	return qde;
}

function formata(num) { 
var sign, cents; 
num = num.toString().replace(/\$|\,/g,''); 
if(isNaN(num)) 
num = "0"; 
sign = (num == (num = Math.abs(num))); 
num = Math.floor(num*100+0.50000000001); 
cents = num%100; 
num = Math.floor(num/100).toString(); 
if(cents<10) 
cents = "0" + cents; 
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) 
num = num.substring(0,num.length-(4*i+3))+'.'+ 
num.substring(num.length-(4*i+3)); 
return (((sign)?'':'-') + num + ',' + cents); 
}

function decimal(pega)
{
	var string;
	string = "";
	for (x=0; x<pega.length; x++)
	{
		if (pega.substring(x,x+1) == ",")
		{
			string = string + ".";
		}
		else
		{
			string = string + pega.substring(x,x+1);				
		}
	}
	return string;
}

function num_real( num )
{
	tam = num.length;
	ret	= '';
	str = '';

	if (tam>0)
	{
		for (z=0;z<tam ;z++ )
		{
			str = num.substring(z,z+1);
			if (num.substring(z,z+1)==".")
				str = "";
			else
			{
				if (num.substring(z,z+1)==",")
					str = ".";
			}
			ret = ret + str;				
		}
	}

	return ret;
}


function valida_email(paCampo) // verifica a validade do e-mail
{
	erros = false;
	if (paCampo == "")
	{
		erros = true;
	}
	else
		{
		prim = paCampo.indexOf("@")
		if(prim < 2)
			{
				erros = true;
			}
		if(paCampo.indexOf("@",prim + 1) != -1)
			{
				erros = true;
			}
		if(paCampo.indexOf(".") < 1)
			{
				erros = true;
			}
		if(paCampo.indexOf(" ") != -1)
			{
				erros = true;
			}
		if(paCampo.indexOf(".@") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf("@.") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf(".com.br.") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf("/") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf("[") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf("]") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf("(") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf(")") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf("..") > 0)
			{
				erros = true;
			}
	}
	if (!erros)
	{
		return false;
	}
	else
	{
		return true;
	}
}

function seleciona_todos( paForm, paMarca, paCampo, paQde )
{
	form = document.getElementById(paForm);
	if (form.elements[paMarca+"[0]"].checked)
	{
		for ( z=0; z<(paQde);z++ )
		{
			form.elements[paCampo+"["+z+"]"].checked=true;
		}
	}
	else
	{
		for ( z=0; z<(paQde);z++ )
		{
			form.elements[paCampo+"["+z+"]"].checked=false;
		}
	}
}

function ver_seleciona_todos( paForm, paMarca, paCampo, paQde, paInd )
{
	form = document.getElementById(paForm);
	if (form.elements[paCampo+"["+paInd+"]"].checked==false)
		form.elements[paMarca+"[0]"].checked=false;
	else
	{
		check = true;
		for ( z=0; z<(paQde);z++ )
		{
			if ( check && form.elements[paCampo+"["+z+"]"].checked==false)
			{
				check=false;
			}
		}
		if (check==false)
		{
			form.elements[paMarca+"[0]"].checked=false;
		}
		else
		{
			form.elements[paMarca+"[0]"].checked=true;
		}
	}
}

//Esta Função eu alterei os campos de entrada e melhorei algumas coisas. Manter esta
    function mascara(obj, 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 = obj.value;

      if (sMask == '(99) 999-9999') {
	     if (sValue.length > 12) {
		    sMask = '(99) 9999-9999';
		 }
	  }

      // 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( " ", "" );
      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) == " "))

        if (bolMask) {
          sCod += sMask.charAt(i);
          mskLen++; }
        else {
          sCod += sValue.charAt(nCount);
          nCount++;
        }

        i++;
      }

      obj.value = sCod;

      if (nTecla != 8) { // backspace
        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;
      }
    }