function setS(S,stForm,campoID){
	if(S == 1){ // abilita
		document.getElementById(campoID).style.display = '';
		document[stForm].user_senha.disabled=false;
		document[stForm].user_senha_verif.disabled = false;
		document[stForm].user_senha.focus();
	}else if(S==0){ // desabilita
		document[stForm].user_senha.disabled=true;
		document[stForm].user_senha_verif.disabled = true;
		document.getElementById(campoID).style.display = 'none';
	}
}

function setComissao(S,campoID){
	if(S == 1){ // habilita
		document.getElementById(campoID).style.display = '';
	}else if(S==0){ // desabilita
		document.getElementById(campoID).style.display = 'none';
	}
}


function checkPASS(T,stForm){
	if(T == 1){ // verifica no campo da senha_verif
		if(document[stForm].user_senha.value != document[stForm].senha_verif.value){
			alert("\n As senhas não estão idênticas.\n Tente novamente!\n");
			document[stForm].user_senha.value="";
			document[stForm].user_senha_verif.value="";
			document[stForm].user_senha.focus();
		}
		return false;
	}else if(T == 0){ // verifica no campo senha
		return true;

	}
}

function SetTipoCadastro(tipo)
{
	switch (tipo)
	{
		case 'cnpj':
		document.getElementById('Xcnpj').style.color = 'red';
		document.getElementById('Xcpf').style.color = '#006699';
		document.getElementById('FISICA').style.display='none';
		document.getElementById('JURIDICA').style.display='';
		break;
		case 'cpf':
		document.getElementById('Xcpf').style.color = 'red';
		document.getElementById('Xcnpj').style.color = '#006699';
		document.getElementById('FISICA').style.display='';
		document.getElementById('JURIDICA').style.display='none';
		break;
	}
}

function descobre(T){
	tamanho = T.value.length;
	V=T.name;
	V = V.replace("nr_","");
	V = V.replace("ds_","");
	V = V.replace("tp_","");

	switch(tamanho){
		case 0:
		T.focus();
		T.style.color = "blue";
		alert( "ERRO: Campo "+V+" está vazio!\n Preencha corretamente." );
		return false;
		break
	}

	//alert(tamanho);
	if( tamanho != 0 && tamanho < 11 ){

		T.focus();
		T.style.color = "red";
		alert( "ERRO: Valor inválido!" );
		T.select();
		return false;
	}
	if( tamanho != 0 && tamanho > 19 ){

		T.focus();
		T.style.color = "red";
		alert( "ERRO: Valor inválido!" );
		T.select();

		return false;
	}

	if( tamanho > 10 && tamanho < 15 ){
		checa_cpf(T.value, T);

	}
	if( tamanho > 14 ){s
	TESTA(T)}

}


function isNUMB(c){
	if((cx=c.indexOf(","))!=-1)
	{
		c = c.substring(0,cx)+"."+c.substring(cx+1);
	}
	if((parseFloat(c) / c != 1))
	{
		if(parseFloat(c) * c == 0)
		{
			return(1);
		}
		else
		{
			return(0);
		}
	}
	else
	{
		return(1);
	}
}

function LIMP(c){
	while((cx=c.indexOf("-"))!=-1)
	{
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf("/"))!=-1)
	{
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf(","))!=-1)
	{
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf("."))!=-1)
	{
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf("("))!=-1)
	{
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf(")"))!=-1)
	{
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf(" "))!=-1)
	{
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	return(c);
}

function VerifyCNPJ(CNPJ){
	CNPJ = LIMP(CNPJ);
	CNPJ = CNPJ.replace("/","");
	CNPJ = CNPJ.replace("-","");
	//alert(CNPJ)
	if(isNUMB(CNPJ) != 1)
	{
		return(0);
	}
	else
	{
		if(CNPJ == 0)
		{
			return(0);
		}
		else
		{
			g=CNPJ.length-2;
			if(RealTestaCNPJ(CNPJ,g) == 1)
			{
				g=CNPJ.length-1;
				if(RealTestaCNPJ(CNPJ,g) == 1)
				{
					return(1);
				}
				else
				{
					return(0);
				}
			}
			else
			{
				return(0);
			}
		}
	}
}
function RealTestaCNPJ(CNPJ,g){
	var VerCNPJ=0;
	var ind=2;
	var tam;
	for(f=g;f>0;f--)
	{
		VerCNPJ+=parseInt(CNPJ.charAt(f-1))*ind;
		if(ind>8)
		{
			ind=2;
		}
		else
		{
			ind++;
		}
	}
	VerCNPJ%=11;

	if(VerCNPJ==0 || VerCNPJ==1)	{
		VerCNPJ=0;
	}else{
		VerCNPJ=11-VerCNPJ;
	}

	if(VerCNPJ!=parseInt(CNPJ.charAt(g))){
		return(0);
	}else{
		return(1);
	}
}


function TESTA(LOCAL,tipo){
	switch (tipo){
		case "CNPJ":
		if(LOCAL.value != "")	{
			if(VerifyCNPJ(LOCAL.value) != 1)		{
				alert("CNPJ inserido não é válido!");
				LOCAL.focus();
				LOCAL.style.color = "red";
				LOCAL.select();
				return false;
			}
		}
		break;
		case "CPF":
		if(LOCAL.value != ""){
			if(checa_cpf(LOCAL.value,LOCAL) != 1){
				alert("CPF inserido não é válido!");
				LOCAL.focus();
				LOCAL.style.color = "red";
				LOCAL.select();
				return false;
			}
		}
		break;
	}

}

//end CPF


function checa_cpf(pcpf,local){
	pcpf = pcpf.replace( ".", "" );
	pcpf = pcpf.replace( ".", "" );
	pcpf = pcpf.replace( ".", "" );
	pcpf = pcpf.replace( "-", "" );

	if (pcpf.length != 11) {sim=false}
	else {sim=true}

	if (sim )
	{
		for (i=0;((i<=(pcpf.length-1))&& sim); i++)
		{
			val = pcpf.charAt(i)
			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)
		{
			soma = 0
			for (i=0;i<=8;i++)
			{
				val = eval(pcpf.charAt(i))
				soma = soma + (val*(i+1))
			}
			resto = soma % 11
			if (resto>9) dig = resto -10
			else  dig = resto
			if (dig != eval(pcpf.charAt(9))) { sim=false }
			else
			{
				soma = 0
				for (i=0;i<=7;i++)
				{
					val = eval(pcpf.charAt(i+1))
					soma = soma + (val*(i+1))
				}
				soma = soma + (dig * 9)
				resto = soma % 11
				if (resto>9) dig = resto -10
				else  dig = resto
				if (dig != eval(pcpf.charAt(10))) { sim = false }
				else sim = true
			}
		}
	}
/*
	var CPFcnpj = local;
	if((CPFcnpj.value == '000.000.000-00')||
	(CPFcnpj.value == '111.111.111-11')||
	(CPFcnpj.value == "222.222.222-22")||
	(CPFcnpj.value == "333.333.333-33")||
	(CPFcnpj.value == "444.444.444-44")||
	(CPFcnpj.value == "555.555.555-55")||
	(CPFcnpj.value == "666.666.666-66")||
	(CPFcnpj.value == "777.777.777-77")||
	(CPFcnpj.value == "999.999.999-99"))
	{ sim = false }

	if(CPFcnpj.value != "")
	{
		if (!sim)
		{
			//alert(CPF.value);
			local.focus();
			local.style.color='red';
			local.select();
			alert("Valor inválido!");
			return false;
		}
	}*/
	return sim;
}

function checaESTADO(uf,nome){
	if(uf.value == ""){
		alert("\n Campo UF é obrigatório!\n");
		uf.value="";
		uf.focus();
		uf.style.border=" 1px #666666 solid";
		uf.style.background="#FFFFEC"
		uf.style.fontWeight='bold';
		return false;
	}
	if(nome.value == ""){
		alert("\n Campo Nome é obrigatório!\n");
		nome.value="";
		nome.focus();
		nome.style.border=" 1px #666666 solid";
		nome.style.fontWeight='bold';
		nome.style.background="#FFFFEC"
		return false;
	}


}


function formataFone(keypress, objeto)
{
	campo = eval(objeto);
	caracteres = '01234567890';
	separacao1 = '-';
	conjunto1 = 2;
	conjunto2 = 5;
	conjunto3 = 8;

	//alert(keypress);
	if(event.keyCode < 48 || event.keyCode > 57)
	{
		event.returnValue = false;
	}
	
	//if ((caracteres.search(String.fromCharCode (keypress))!= -1) && campo.value.length < (conjunto1 + conjunto2 + conjunto3)) 
	if (campo.value.length < (conjunto1 + conjunto2 + conjunto3)) 
	{
		if (campo.value.length == conjunto1)
		   campo.value = '(' + campo.value + ')';
		if (campo.value.length == conjunto3)
		   campo.value = campo.value + separacao1;
	} else
		event.returnValue = false;
}


function SetValue(item){
	var campo = "&nbsp;";
	var jss    = "";

	switch(item.value){
		case "select":
		campo += "<font color='red'>Separe as opções por virgula(,)</font>&nbsp;&nbsp;";
		campo += "<input type='text' class='input' name='select_value'> <br><b>EX.:</b> opcao 1, opcao2";

		break;
		case "checkbox":
		campo += "<font color='red'>Valor:</font>&nbsp;&nbsp;";
		campo += "<input type='text' class='input' name='select_value'> <br>";

		break;

	}
	document.getElementById('INselect').innerHTML = campo;

	// move o cursor ate o campo criado
	if(item.value == 'select') {
		document.cadastro.select_value.focus();
	}
	if(item.value == 'checkbox') {
		document.cadastro.select_value.focus();
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//inicio função formata reais
	documentall = document.all;
	/*
	* função para formatação de valores monetários retirada de
	*/

	function formatamoney(c) {
		var t = this; if(c == undefined) c = 2;		
		var p, d = (t=t.split("."))[1].substr(0, c);
		for(p = (t=t[0]).length; (p-=3) >= 1;) {
				t = t.substr(0,p) + "." + t.substr(p);
		}
		return t+","+d+Array(c+1-d.length).join(0);
	}
	
	String.prototype.formatCurrency=formatamoney
	
	function demaskvalue(valor, currency)
	{
		//
		// Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as 
		//casas decimais
	
		var qtd_dig = 12;
		var val2 = '';
		var strCheck = '0123456789';
		var len = valor.length;

		if (len > qtd_dig)
		{
			valor = valor.substring(0,len-1);
		}


		if (len== 0)
		{
			return 0.00;
		}

	if (currency ==true)
	{	
		// Elimina os zeros à esquerda 
		//a variável  <i> passa a ser a localização do primeiro caractere após os zeros e 
		//val2 contém os caracteres (descontando os zeros à esquerda)
		
		
		for(var i = 0; i < len; i++)
			if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;
		
		for(; i < len; i++)
		{
			if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);
		}

		if(val2.length==0) return "0.00";
		if (val2.length==1)return "0.0" + val2;
		if (val2.length==2)return "0." + val2;
		
		var parte1 = val2.substring(0,val2.length-2);
		var parte2 = val2.substring(val2.length-2);
		var returnvalue = parte1 + "." + parte2;
		return returnvalue;
		
	}
	else
	{
			// currency é false: retornamos os valores COM os zeros à esquerda, 
			// sem considerar os últimos 2 algarismos como casas decimais 

			val3 ="";
			for(var k=0; k < len; k++)
			{
				if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);
			}			
	return val3;
	}
}

	function reais(obj,event)
	{
	var whichCode = (window.Event) ? event.which : event.keyCode;
	/*
	Executa a formatação após o backspace nos navegadores !document.all
	*/
	if (whichCode == 8 && !documentall) {	
	/*
	Previne a ação padrão nos navegadores
	*/
		if (event.preventDefault){ //standart browsers
				event.preventDefault();
			}else{ // internet explorer
				event.returnValue = false;
		}
		var valor = obj.value;
		var x = valor.substring(0,valor.length-1);
		obj.value= demaskvalue(x,true).formatCurrency();
		return false;
	}
	/*
	Executa o Formata Reais e faz o format currency novamente após o backspace
	*/
	FormataReais(obj,'.',',',event);
	} // end reais
	
	
	function backspace(obj,event){
	/*
	Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.
	O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
	Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.
	*/

	var whichCode = (window.Event) ? event.which : event.keyCode;
	if (whichCode == 8 && documentall) {	
		var valor = obj.value;
		var x = valor.substring(0,valor.length-1);
		var y = demaskvalue(x,true).formatCurrency();
	
		obj.value =""; //necessário para o opera
		obj.value += y;
		
		if (event.preventDefault){ //standart browsers
				event.preventDefault();
			}else{ // internet explorer
				event.returnValue = false;
		}
		return false;
	
		}// end if		
	}// end backspace

	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 == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown
	if (whichCode == 0 ) return true;
	if (whichCode == 9 ) return true; //tecla tab
	if (whichCode == 13) return true; //tecla enter
	if (whichCode == 16) return true; //shift internet explorer
	if (whichCode == 17) return true; //control no internet explorer
	if (whichCode == 27 ) return true; //tecla esc
	if (whichCode == 34 ) return true; //tecla end
	if (whichCode == 35 ) return true;//tecla end
	if (whichCode == 36 ) return true; //tecla home

	/*
	O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script
	*/
	
	if (e.preventDefault){ //standart browsers
			e.preventDefault()
		}else{ // internet explorer
			e.returnValue = false
	}

	var key = String.fromCharCode(whichCode);  // Valor para o código da Chave
	if (strCheck.indexOf(key) == -1) return false;  // Chave inválida
	
	/*
	Concatenamos ao value o keycode de key, se esse for um número
	*/
	fld.value += key;
	
	var len = fld.value.length;
	var bodeaux = demaskvalue(fld.value,true).formatCurrency();
	fld.value=bodeaux;

	/*
	Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror.
	*/
  if (fld.createTextRange) {
	var range = fld.createTextRange();
	range.collapse(false);
	range.select();
  }
  else if (fld.setSelectionRange) {
	fld.focus();
	var length = fld.value.length;
	fld.setSelectionRange(length, length);
  }
  return false;

}
//fim formata reais
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//onKeyPress="return MM_formtCep(event,this,'#####-###');"
//mascara do CEP 
function MM_formtCep(e,src,mask) 
{
	if(window.event) { _TXT = e.keyCode; } 
	else if(e.which) { _TXT = e.which; }
	if(_TXT > 47 && _TXT < 58) { 
	 var i = src.value.length; var saida = mask.substring(0,1); var texto = mask.substring(i)
	 if (texto.substring(0,1) != saida) { src.value += texto.substring(0,1); } 
		return true; } else { if (_TXT != 8) { return false; } 
	 else { return true; }
	}
}

function telefone(objeto)
{
	mascaralimpa=objeto.value.replace("(","");
	mascaralimpa=mascaralimpa.replace(")","");
	mascaralimpa=mascaralimpa.replace("-","");
	suber=0;
	if((mascaralimpa.length == 9) && (mascaralimpa.substr(0,2)!='45'))
	{
		mascaralimpa='XX'+mascaralimpa; suber=1; 
	}
	if((mascaralimpa.length < 9) && (mascaralimpa.length > 5)  && (mascaralimpa.substr(0,2)!='45')) 
		mascaralimpa='XX'+mascaralimpa;
	mascara='('+mascaralimpa.substr(0,2)+')'+mascaralimpa.substr((2+suber),4)+'-'+mascaralimpa.substr((6+suber),4);
	
	if(mascara == '()-' || mascara == '(XX)-')
		mascara = '';	
	objeto.value=mascara;
}

function imprime_div(div_imprimir)
{
 var prtContent = document.getElementById(div_imprimir);
 var WinPrint = window.open('','','letf=0,top=0,width=650,height=400,toolbar=0,scrollbars=1,status=0');
 WinPrint.document.write(prtContent.innerHTML);
 WinPrint.document.close();
 WinPrint.focus();
 WinPrint.print();
 WinPrint.close();
 //prtContent.innerHTML=strOldOne;
}

//DESABILITADA PARA UTILI|AR A FUNCAO ABAIXO

function formata_peso(val,len,evento)
{
	n='__0123456789';
	tam_variavel = val.value;
	leng = tam_variavel.length;

	s = '';
	a = 2;
	for (i=0; i < leng; i++)
	{
		c=tam_variavel.charAt(i);
		if (n.indexOf(c) > a)
		{
			a=1;
			s+=c;
		};
	};
	leng = s.length;
	t=len-1;
	if (leng > t)
	{
		leng=t;
		s=s.substr(0,t);
	};
	r='';
	if (leng > 3)
	{
		r = s.substr(0,leng-3)+'.'+s.substr(leng-3,3);
	}
	else
	{
		if (leng == 3)
		{
			r='0.'+s;
		}
		else
		{
			if (leng == 2)
			{
				r='0.0'+s;
			}
			else
			{
				if (leng == 1)
				{
					r='0.00'+s;
				};
			};
		};
	};
	if (r == '')
	{
		r='0.000';
	};
	val.value=r;
	return 'ok';
};


////////////////////////////////////////////////////

function dasabilitarEVENT(event) 
{
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if(keyCode == 13 )
	{ 
		return false;
	}
	if(keyCode == 32 )
	{ 
		return false;
	}
	return keyCode;
}


function trSetColor(linha,cor,ipt_id)
{
	//linha.style.cursor='pointer'; //CURSOR MAO FUNCIONA NO FIREFOX
//	linha.style.cursor='hand';
	if (linha != null) {
		if ( cor == '' || typeof(linha.style) == 'undefined') {
	        return false;
	    }
	    if (typeof(document.getElementsByTagName) != 'undefined') {
	        var celulas = linha.getElementsByTagName('td');
	    }
	    else if (typeof(linha.cells) != 'undefined') {
	        var celulas = linha.cells;
	    }
	    else {
	        return false;
	    }

	    var celulas_count  = celulas.length;
	    for (var c = 0; c < celulas_count; c++) {
	        celulas[c].style.backgroundColor = cor;
	    }
	}	
		
	if (ipt_id!='') {
		if (linha != null) {
			if(document.getElementById(ipt_id).checked)
				trSetColor(linha,'#E2E6A6','');		
		}
		
	}		
		
			
	
    return true;
}

function check_radio(radio){	
	if(document.getElementById(radio)) {
		document.getElementById(radio).checked = "true";	
		window.location = 'index.php?pg=finalizar.htm&forma_pagamento='+document.getElementById(radio).value;			
	}
		
}


function verifica_setado (forma_pagamento) {

	if (forma_pagamento!=''){
		var tr_id = 'tr_'+forma_pagamento;
		trSetColor(document.getElementById(tr_id),'#E2E6A6','');	
	}	
}


function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


