function deleteRow(i)
{
	var qtd = document.getElementById('txtQtdColaboradores').value;
	
	if(qtd != '')
	{
		document.getElementById('txtQtdColaboradores').value = (parseInt(qtd) - 1);
		
		if(document.getElementById('txtQtdColaboradores').value == 0)
		{
			document.getElementById('txtQtdColaboradores').value = '';
		}
	}
	
    document.getElementById('tabDocumento').deleteRow(i);
}

function addColaboradres(nroColab)
{

if(nroColab != '')
{
	var qtd = document.getElementById('txtQtdColaboradores').value;
	
	if(qtd == '')
	{
		document.getElementById('txtQtdColaboradores').value = nroColab;
	}
	else
	{
		document.getElementById('txtQtdColaboradores').value = (parseInt(qtd) + parseInt(nroColab));
	}
	
	
	var local = document.getElementById('tabDocumento');   
	var tblBody = local.tBodies[0];   
	
	for(i=1;i<=nroColab;i++)
	{
	     var newRow = tblBody.insertRow(-1);
		 
		 var newCel = 'newCel_'+i;
		 newCel = newRow.insertCell(0);
		 newCel.width = "40%";
		 newCel.nowrap = "nowrap";   
		 newCel.innerHTML = '<b>Nome:</b><br><input type="text" id="txtNomeColab_'+i+'" size="40" obrigatorio="true" name="txtNomeColab">';   
		 
		 var newCel2 = 'newCel2'+i;
		 newCel2 = newRow.insertCell(1);
		 newCel2.width = "40%";
		 newCel2.nowrap = "nowrap";   
		 newCel2.innerHTML = '<b>E-mail:</b><br><input type="text" id="txtEmailColab_'+i+'" size="40" obrigatorio="true" name="txtEmailColab">';   
	  
		 var newCel3 = 'newCel3_'+i;
		 newCel3 = newRow.insertCell(2);
		 newCel3.width = "16%";
		 newCel3.nowrap = "nowrap";   
		 newCel3.innerHTML = '<b>Telefone:</b><br><input type="text" id="txtTelColab_'+i+'" size="20" obrigatorio="true" name="txtTelColab" maxlength="11">';
		 
		 var newCel4 = 'newCel4_'+i;
		 newCel4 = newRow.insertCell(3);
		 newCel4.width = "4%";
		 newCel4.nowrap = "nowrap"; 
		 newCel4.align = "center";
		 newCel4.innerHTML = 'Excluir:<br><input type="button" value="X" style="cursor:pointer" class="botao_peq" onclick="deleteRow(this.parentNode.parentNode.rowIndex);">'; 
		
	}
  }
}

function habilitaCadastro(tipo)
{
	if(tipo == 'TipoCPF')
	{
		document.getElementById('TipoCPF').style.display = 'block';
		document.getElementById('TipoCNPJ').style.display = 'none';
		document.getElementById('divColaboradores').style.display = 'none';		
		//frmCadastro.txtTipoPessoa.value = 'PF';
	}
	else
	{
		document.getElementById('TipoCPF').style.display = 'none';
		document.getElementById('TipoCNPJ').style.display = 'block';
		document.getElementById('divColaboradores').style.display = 'block';
		//frmCadastro.txtTipoPessoa.value = 'PJ';
	}
}

//Funçao StringBuilder no JavaScript
function StringBuffer() { this.buffer = []; } 
StringBuffer.prototype.append = function(string) 
{ 
	this.buffer.push(string); 
	return this; 
} 

StringBuffer.prototype.toString = function()
{ 
	return this.buffer.join(""); 
}


// Funcao Responsavel por verificar se os campos obrigatorios foram preenchidos
function validaCamposObrigatorios(formulario)
{
	elementos = document.getElementsByTagName('*');
	var frmAtual = "";
	for(i=0; i < elementos.length; i++)
	{
		if(typeof(elementos[i].name) != "undefined" && elementos[i].name == formulario)
		{
		  frmAtual = 	elementos[i].name;		 
		}
		
		// Verifico se o form e o que deve ser validado
		if(frmAtual == formulario)
		{
			// Verifico se o campo e obrigatorio
			if(typeof(elementos[i].getAttribute('obrigatorio')) != "undefined")
			{
				if(elementos[i].getAttribute('obrigatorio') == "true")
				{
					if(elementos[i].type == 'textarea')
					{
						if(typeof(FCKeditorAPI) != "undefined")
						{
							var inst = FCKeditorAPI.getInstanceById(elementos[i].name);
							valor = inst.getHTML();
						} else {
							valor = elementos[i].value;
						}
					} else {
						valor = elementos[i].value;
					}
					if(valor == "")
					{
						alert("Campo Obrigatório, favor verificar.");
						elementos[i].focus();
						return false;
					}
				}
			}
			// Verifico se o campo deve ser igual a algum outro
			if(typeof(elementos[i].getAttribute('igual')) != "undefined" && elementos[i].getAttribute('igual') != "")
			{
				eleDepende = elementos[i].getAttribute('igual');
				
				// Verifico se o elemento existe
				if(typeof(elementos[eleDepende]) != "undefined")
				{
					// Verifico se os valores sao Diferentes
					if(elementos[i].value != elementos[eleDepende].value)
					{
						alert("O valor da Confirmação deve ser igual, favor verificar.");
						elementos[i].focus();
						return false;
					}
				}
			}
		}
	}
	return true;
}

//--- valida campo
function ValidaCampo(PObj, PRegExp)
{		
		var VRegExp = new RegExp (PRegExp);			
		var VOK = VRegExp.exec(PObj.value);			
		if (!VOK)
		{
				alert('Dados inválido.');
				PObj.value = '';
				PObj.focus();
				return false;
		}
}
	
// Funcao só numeros
function somenteNumeros(e)
{
  var keynum = returnKeyCode(e);
  var keychar = returnKeyChar(e);
  var numcheck = /\d/;
	
	icValido = true;
	if(typeof(keynum) != "undefined" && !numcheck.test(keychar) && keynum != 8)
	{
	  icValido = false;
	}
  return icValido;
}

// Funcao e retorna o codigo da tecla pressionada
function returnKeyCode(e)
{
	if(window.event) // IE
	{
		keynum = e.keyCode
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which
	}
	return keynum;
}

// Funcao que retorna o caracter digitado
function returnKeyChar(e)
{
	keynum = returnKeyCode(e);
	keychar = String.fromCharCode(keynum);	
	return keychar;
}

// Funcao que formata o valor da forma 9999,99
function formataValor(valor)
{
	valor = "" + valor;
  valor = valor.replace(".", ",");
	
	if(valor.indexOf(",") == -1)
	{
		valor += ",00";
	} else {
		casasDecimais = valor.substring(valor.indexOf(",")+1);
		if(casasDecimais.length == 0)
		{
			valor += "00";				
		} else if(casasDecimais.length == 1)
		{
			valor += "0";
		}
	}

	return valor;
}

// Funcao que valida o valor
function validaValor(campo)
{
	  // Verifico se o campo nao esta vazio
		if(campo.value.length == 0)
		{
			campo.value = "0,00";
		}
		else
		{
			qtVirgulas = returnQtCaracteres(campo.value, ",");
			valor = campo.value;
			
			// Verifico se possui mais de uma virgulas
			if(qtVirgulas > 1)
			{
				alert("Valor Incorreto, o valor deve estar no formato 9999,99");
				campo.focus();
				return false;
			}
			
			// Verifico se nao possui virgula
			if(valor.indexOf(",") == -1)
			{
				campo.value += ",00"	;
			} else {
				casasDecimais = valor.substring(valor.indexOf(",")+1);
				if(casasDecimais.length == 0)
				{
					campo.value += "00";				
				} else if(casasDecimais.length == 1)
				{
					campo.value += "0";
				} else if(casasDecimais.length != 2) {
					alert("Valor Incorreto, informe apenas 2 casas decimais.");
					campo.value = "0,00";
					campo.focus();
					return false;
				}
			}
			
			valor = campo.value;
			valor = valor.replace(",","");
			var numcheck = /\d/;
			while(valor.length > 0)
			{
				caracter = valor.substring(0,1);
				valor = valor.substring(1);
				if(!numcheck.test(caracter))
				{
					alert("Valor Incorreto, o valor deve estar no formato 9999,99");
					campo.value = "";
					campo.focus();
					return false;
				}
			}
		}
		return true;
}

//Funcao que valida a data
function valida_data(campo) {
	if(campo.value != "")
	{
		var date = campo.value;
		var array_data = new Array;
		var ExpReg = new RegExp("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/[12][0-9]{3}");
		//vetor que contem o dia o mes e o ano
		array_data = date.split("/");
		erro = false;
		//Valido se a data esta no formato dd/mm/yyyy e se o dia tem 2 digitos e esta entre 01 e 31
		//se o mes tem d2 digitos e esta entre 01 e 12 e o ano se tem 4 digitos e esta entre 1000 e 2999
		if ( date.search(ExpReg) == -1 )
			erro = true;
		//Valido os meses que nao tem 31 dias com execao de fevereiro
		else if ( ( ( array_data[1] == 4 ) || ( array_data[1] == 6 ) || ( array_data[1] == 9 ) || ( array_data[1] == 11 ) ) && ( array_data[0] > 30 ) )
			erro = true;
		//Valido o mes de fevereiro
		else if ( array_data[1] == 2 ) {
			//Valido ano que nao e bissexto
			if ( ( array_data[0] > 28 ) && ( ( array_data[2] % 4 ) != 0 ) )
				erro = true;
			//Valido ano bissexto
			if ( ( array_data[0] > 29 ) && ( ( array_data[2] % 4 ) == 0 ) )
				erro = true;
		}
		if ( erro ) {
			alert("Data Inválida");
			campo.value = "";
			campo.focus();
		}
	}
}

// Formato a Data
function formataData(campo, e)
{
	if(somenteNumeros(e))
	{
		if(campo.value.length == 2)
		{
			if(campo.value.substring(2,3) != "/" && returnKeyChar(e) != "/")
			{
					campo.value += "/";
			}
		}
		if(campo.value.length == 5)
		{
			if(campo.value.substring(5,6) != "/" && returnKeyChar(e) != "/")
			{
					campo.value += "/";
			}
		}
	} else {
	  return false;	
	}
	return true;
}

// Funcao que limpa a string
function ApenasNum(strParm)
{
  strParm = String(strParm);
  var chrPrt = "0";
  var strRet = "";
  var j=0;
  for(var i=0; i < strParm.length; i++)
  {
    chrPrt = strParm.substring(i, i+1);
    if(chrPrt.match(/\d/))
    {
      if(j==0)
      {
        strRet = chrPrt;
        j=1;
      }
      else
      {
        strRet = strRet.concat(chrPrt);
      }
    }
  }
  return strRet;
}


// Funcao que calcula os digitos
function digitoCPFCNPJ(prNumero)
{
  var numLim;
  var numDois = prNumero.substring( prNumero.length - 2, prNumero.length);
  var novoCPF = prNumero.substring( 0, prNumero.length - 2);
  if(prNumero.length == 11)
  {
    numLim = 11;
  }
  else if(prNumero.length == 14)
  {
    numLim = 9;
  }
  else
  {
    return false;
  }
  var Fator = 1;
  var numSoma = 0;
  for (var i = novoCPF.length-1; i >= 0; i--)
  {
    Fator = Fator + 1;
    if (Fator > numLim)
    {
      Fator = 2;
    }
    numSoma = numSoma + ( Fator * Number( novoCPF.substring( i, i + 1)));
  }
  numSoma = numSoma/11;
  var numResto = Math.round( 11 * ( numSoma - Math.floor( numSoma)));
  if (numResto > 1)
  {
    numResto = 11 - numResto;
  }
  else
  {
    numResto = 0;
  }
 
  var numDigito = String(numResto);
  novoCPF = novoCPF.concat(numResto);

  numSoma = 0;
  Fator = 1;
  for (var i = novoCPF.length - 1; i >= 0; i--)
  {
    Fator = Fator + 1;
    if (Fator > numLim)
    {
      Fator = 2;
    }
    numSoma = numSoma + (Fator * Number( novoCPF.substring( i, i + 1)));
  }
  numSoma = numSoma / 11;
  numResto = numResto = Math.round( 11 * (numSoma - Math.floor( numSoma)));
  if (numResto > 1)
  {
    numResto = 11 - numResto;
  }
  else
  {
    numResto = 0;
  }
  numDigito = numDigito.concat(numResto);
  if (numDigito == numDois)
  {
    return true;
  }
  else
  {
    return false;
  }
}

// Funcao que valida e formata CPF ou CNPJ
function validaCPFCNPJ(objCPFCNPJ)
{
	if(objCPFCNPJ.value != "")
	{
		if(objCPFCNPJ.value == null)
		{
			alert("ATENÇÃO!!!\nPor favor digite o CPF ou CNPJ");
			return false;
		}
		numCPFCNPJ = ApenasNum(objCPFCNPJ.value);
		if(parseFloat(numCPFCNPJ) == 0)
		{
			alert("ATENÇÃO!!!\nO CPF informado é inválido!");
			objCPFCNPJ.value = "";
			return false;		
		}
		if(!digitoCPFCNPJ(numCPFCNPJ))
		{
			alert("ATENÇÃO!!!\nO dígito verificador do CPF ou CNPJ é inválido!");
			objCPFCNPJ.value = "";
			return false;
		}
	}
}

function FormataCpf(Campo,ptecla)
{
	var tam = Campo.value.length;
	var vtecla
 if (ptecla.keyCode) vtecla = ptecla.keyCode;
  else if (ptecla.which) vtecla = ptecla.which; // Netscape 4.?		
	if (((vtecla) >= 48 ) && ((vtecla) <= 57 ))
	{
		if ((tam == 3 ) || (tam == 7))
		{
			Campo.value = Campo.value + ".";
		}		
		if ((tam == 11 ))
		{
			Campo.value = Campo.value + "-";
		}
	}
	
}

function FormataRG(Campo,ptecla)
{
	var tam = Campo.value.length;
	var vtecla
if (ptecla.keyCode) vtecla = ptecla.keyCode;
  else if (ptecla.which) vtecla = ptecla.which; // Netscape 4.?		
	if (((vtecla) >= 48 ) && ((vtecla) <= 57 )|| ((vtecla) == 120 ))
	{
		if ((tam == 2 ) || (tam == 6))
		{
			Campo.value = Campo.value + ".";
		}
	
		if ((tam == 10 ))
		{
			Campo.value = Campo.value + "-";
		}
	}
	
}	
	//funcao formata cnpj	
function FormataCNPJ(campo,tammax,teclapres)
{
	var tecla = teclapres.keyCode;
	var vr = campo.value;
	vr = vr.replace( "-", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;
	if (tam < tammax && tecla != 13){ tam = vr.length + 1 ; }
	if (tecla == 13 ){ tam = tam - 1 ; }
	if ( tecla == 13 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105) ){
	if ( tam <= 2 ){
	campo.value = vr ; }
	tam = tam - 1;
	if ( (tam > 2) && (tam <= 5) ){
	campo.value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
	if ( (tam >= 6) && (tam <= 8) ){
	campo.value = vr.substr( 0, tam - 6 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	if ( (tam >= 9) && (tam <= 11) ){
	campo.value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	if ( (tam >= 12) && (tam <= 14) ){
	campo.value = vr.substr( 0, tam - 12 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	} 
}

	//Função FomartCurrency (Formata valores como 12,000.32)
function formatCurrency(num)
{
 num = num.toString().replace(/\R$|\,/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)?'':'-') + 'R$ ' + num + '.' + cents);
}


//Função retona soma de valores (Peso e Valor total)
function somaValores(campo, totalSeq)
{
	var somaTotal = 0;
	
	for (var i=1; i < parseInt(totalSeq); i++)
	{
		somaTotal = (parseFloat(somaTotal) + parseFloat(document.getElementById(campo+i).value));
	}
	
	return somaTotal;
	
}


//login Cabeçalho	
function ajaxValidaLoginCabecalho(caminho)
{
	try
		{
				login = document.getElementById('txtLoginEmailCabecalho').value;
				pwd   = document.getElementById('txtSenhaLoginCabecalho').value;

				XmlHttp.open('POST', caminho+'ajax/ajaxValidaLogin.asp?email='+login+'&pwd='+pwd, true);
				
				XmlHttp.onreadystatechange = function()
				{
					if (XmlHttp.readyState == 4)
					{
						var strRetorno = XmlHttp.responseText.toString();
						if (strRetorno == 'True')
						{
							location.href = 'http://www.planad.com.br/paginas/usuario/';						
						}						
						else
						{
							alert('Desculpe, login ou senha incorretos!');
							return false;
						}							
					}
				}
			
				XmlHttp.send (null)
	  }
	  catch (e)
	  {
		alert('Erro ajax: ' + e.description);
	  }
	  
}

function ShowLoginSenha(nro)
{
	if(nro == 2)
	{
		document.getElementById('tbSenha').style.display = 'block';
		document.getElementById('tbLogin').style.display = 'none';
		document.getElementById('spLink').innerHTML = '<a class="a2" href="javascript:ShowLoginSenha(1);">Login</a>';		
	}
	else
	{
		document.getElementById('tbSenha').style.display = 'none';
		document.getElementById('tbLogin').style.display = 'block';
		document.getElementById('spLink').innerHTML = '<a class="a2" href="javascript:ShowLoginSenha(2);">Esqueci minha senha</a>';	
	}
}

//recupera senha
function ajaxRecuperaSenhaCabecalho(caminho)
{
	var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
	var email = document.getElementById('txtSenhaEmail').value;

	if (er.test(email))
	{
		try
			{
				XmlHttp.open('POST', caminho+'ajax/ajaxRecuperaSenha.asp?email=' + email, true);
				
				XmlHttp.onreadystatechange = function()
				{
					if (XmlHttp.readyState == 4)
					{
						var strRetorno = XmlHttp.responseText.toString();
						
						if (strRetorno == "True")
						{
							alert('Dentro de instantes você receberá sua senha no e-mail informado.');						
						}
						else if(strRetorno == "Erro")
						{
							alert('Falha ao tentar enviar e-mail, por favor entre em contato com a Planad.');
						}
						else if(strRetorno == "False")
						{
							alert('E-mail não encontrado.');	
						}
					}
				}
			
				XmlHttp.send (null)
			}
			catch (e)
			{
				alert('Erro ajax: ' + e.description);
			}
	}
	else
	{
		alert('E-mail inválido.');
		}
}


