////////////////////////////////////////////////////////////////////
////////////// FUNÇÕES JAVASCRIPT DE GPANIZ ////////////////////////
////////////////////////////////////////////////////////////////////

function voltar(){
	history.go(-1);	
}

function irParaLinha(url){ 
  document.location.href = "produtos.php?linha="+url.options[url.selectedIndex].value+"";
}

function irParaReceita(url){ 
  document.location.href = "index.php?ir=receitas&id_receita="+url.options[url.selectedIndex].value+"";
}

function abreFoto(foto, larg, altu, rolagem){
	window.open("foto.php?foto="+foto+"", "Foto", "width="+larg+",height="+altu+",top=90,left=90,menubar=no,location=no,resizable=no,scrollbars="+rolagem+",status=no");
}

function abrePesquisa(){
	window.open("pesquisa.html", "Pesquisa", "width=500,height=500,top=90,left=90,menubar=no,location=no,resizable=no,scrollbars=yes,status=no");
}

function abreVideo(idprod){
	window.open("video.php?id_produto="+idprod+"", "Video", "width=500,height=500,top=90,left=90,menubar=no,location=no,resizable=no,scrollbars=no,status=no");
}

function abreDetalhesPedido(pedido){
	window.open("representantes_detalhes.php?id_pedido="+pedido+"", "DetalhesPedido", "width=600,height=550,top=20,left=20,menubar=no,location=no,resizable=no,scrollbars=yes,status=no");
}

function mostraVisProduto(div, foto, categoria, nome, id_produto){
	document.getElementById(div).innerHTML = "<div id=destaque><a href=produtos.php?id_produto="+id_produto+" title=\"Conferir mais detalhes deste produto\"><img src=\"thumb/thumb.php?src=../gfx/produtos/"+foto+"&w=90&h=90\" style=\"border:13px solid #FFF\" /></a>\r<br /><h3>"+nome+"</h3><br /></div>";
}

function mostraFlash(src, larg, alt, vars){
	var flash = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="'+ larg +'" height="'+ alt +'">';
	flash += '<param name="movie" value="'+ src +'" />';	
	flash += '<param name="menu" value="false" />';	
	flash += '<param name="wmode" value="transparent" />';	
	flash += '<embed src="'+ src +'" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="'+ larg +'" height="'+ alt +'" menu = "false" wmode="transparent"></embed>';
	flash += '</object>';	
	
	document.write(flash);
}

function emailCheck (emailStr) {
var emailPat=/^(.+)@(.+)$/
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
	alert("O endereço de email "+emailStr+" não está correto.")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

if (user.match(userPat)==null) {
    // user is not valid
    alert("O nome do usuário do e-mail "+emailStr+" não parece ser válido.")
    return false
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("O número do IP não é válido no e-mai "+emailStr+" !")
		return false
	    }
    }
    return true
}

var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("O domínio do e-mail "+emailStr+" não parece estar correto.")
    return false
}

var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   alert("O endereço precisa terminar com 3 letras do domínio ou 2 letras do país.")
   return false
}

if (len<2) {
   var errStr="O endereço "+emailStr+" não contém o domínio. Revise o endereço que digitaste."
   alert(errStr)
   return false
}

return true;
}

function verificaContato(){
	
	var formulario = document.envia_contato;
	
	if(formulario.nome.value==""){
		return false;
		formulario.nome.focus();
	}
	if(formulario.email.value==""){
		return false;
		formulario.email.focus();
	}
	if(formulario.telefone.value==""){
		return false;
		formulario.telefone.focus();
	}
	if(formulario.assunto.value==""){
		return false;
		formulario.assunto.focus();
	}
	if(formulario.mensagem.value==""){
		return false;
		formulario.mensagem.focus();
	}
	return true;
}

function verificaNewsletter(){
	
	var formulario = document.envia_news;
	
	if(formulario.nome.value==""){
		return false;
		formulario.nome.focus();
	}
	if(!emailCheck(formulario.email.value)){
		return false;
		formulario.email.focus();
	}
	if(formulario.pais.value==""){
		return false;
		formulario.pais.focus();
	}
	return true;
}

function verificaRemoveNewsletter(){
	
	var formulario = document.remove_news;
	
	if(!emailCheck(formulario.email.value)){
		return false;
		formulario.email.focus();
	}
	return true;
}

function limpaCampo(formulario, op) {

	if(formulario.value == 'dd/mm/aaaa' && op==1) {
		formulario.value = '';
	}else if(formulario.value == '' && op==1) {
	   formulario.value = 'dd/mm/aaaa';
	}else if(formulario.value == '0,00' && op==0) {
		formulario.value = '';
	}else if(formulario.value == '' && op==0) {
		formulario.value = '0,00';
	}
}


function getkey(e)
{
	if (window.event){return window.event.keyCode;}
	else if (e){return e.which;}
	else{return null;}
}

function goodchars(e, goods)
{
	var key, keychar;
	key = getkey(e);
	if (key == null) {return true;}
	// get character
	keychar = String.fromCharCode(key);
	keychar = keychar.toLowerCase();
	goods = goods.toLowerCase();
	// check goodkeys
	if (goods.indexOf(keychar) != -1){return true;}
	
	// control keys
	if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 ){return true;}
	
	// else return false
	return false;
	
}

var slot=new Array(50);
function addLinhaItem()
{
	for(i=1;i<=50;i++)
	{
		if(!slot[i]){break;}
	}
	if(i>=50){return;}
	slot[i]=1;
	if(i==0){
		document.getElementById("linhaItem"+(i+2)).style.display="";
	}else{
		document.getElementById("linhaItem"+(i+1)).style.display="";
	}
	document.getElementById("habilitado_"+(i+1)).value="1";
}

function delLinhaItem(slotnumber)
{
	slot[(slotnumber-1)]=0;  //free the slot
	document.getElementById("linhaItem"+slotnumber).style.display="none";
	document.getElementById("habilitado_"+slotnumber).value="0";
	document.getElementById("produto"+slotnumber).value="";
	document.getElementById("quantidade"+slotnumber).value="";
	document.getElementById("tensao"+slotnumber).value="";
	document.getElementById("valor_unitario"+slotnumber).value="";
	document.getElementById("ipi"+slotnumber).value="";
	calculo(slotnumber)
}


function resultadosFinais(){

	var total_geral = document.getElementById("total_geral");
	var total_geral_h4 = document.getElementById("total_geral_h4");
	var total_liquido = document.getElementById("total_liquido");
	var total_liquido_h4 = document.getElementById("total_liquido_h4");
	var total_temp = 0;
	var total_final = 0;
	var total_liquido_final = 0;
	for(i=1; i<=50; i++){
		if(document.getElementById("total_liquido_linha"+i).value!=''){
			total_liquido_final+=parseFloat(document.getElementById("total_liquido_linha"+i).value);
		}
	}
	for(i=1; i<=50; i++){
		if(document.getElementById("total_linha"+i).value!=''){
			total_final+=parseFloat(document.getElementById("total_linha"+i).value);
		}
	}
	
	total_liquido.value = total_liquido_final.toFixed(2);
	total_liquido_h4.innerHTML = "R$ "+total_liquido_final.toFixed(2).replace(".",",");
	
	//CALCULA O IPI, SE O CAMPO FOR PREENCHIDO
	//CASO CONTRÁRIO, SOMENTE ALTERA O VALOR FINAL SEM O IPI
	/*if(valor_ipi!=''){
		valor_ipi = valor_ipi.replace(",",".");
		//total_final+=parseFloat(valor_ipi);
		
		total_temp = parseFloat(total_liquido.value/100*valor_ipi);
		total_final = parseFloat(total_liquido.value)+parseFloat(total_temp);
		
		total_geral.value = total_final.toFixed(2);
		total_geral_h4.innerHTML = "R$ "+total_final.toFixed(2).replace(".",",");
	}else{
	*/
		total_geral.value = total_final.toFixed(2);
		total_geral_h4.innerHTML = "R$ "+total_final.toFixed(2).replace(".",",");
	//}
	
}

//CALCULA OS VALORES
function calculo(linha){

	var campo_qtde = document.getElementById("quantidade"+linha);
	var campo_valor = document.getElementById("valor_unitario"+linha);
	var campo_ipi = document.getElementById("ipi"+linha);
	var span_total = document.getElementById("valor_total"+linha);
	var total_liquido_linha = document.getElementById("total_liquido_linha"+linha);
	var total_linha = document.getElementById("total_linha"+linha);
	
	//TROCA VIRGULA POR PONTO, PARA PODER SOMAR
	valor = campo_valor.value.replace(",",".");
	ipi = campo_ipi.value.replace(",",".");
	qtde = campo_qtde.value;
	
	//FAZ O TOTAL
	var total = valor*qtde;
	
	var total_temp = parseFloat(total/100*ipi);
	var totalOK = parseFloat(total)+parseFloat(total_temp);
	

	//COLOCA O TOTAL EM UM INPUT HIDDEN
	total_linha.value = totalOK;
	//CADA LINHA AGORA CONTA COM 2 TOTAIS: TOTAL GERAL (QUE INCLUI O IPI) E TOTAL LÍQUIDO (SEM IPI), O TOTAL LIQUIDO TEM INPUT HIDDEN PRÓPRIO, PARA SOMAR NO FINAL
	total_liquido_linha.value = total;
	//FORMATA O TOTAL PRA MOSTRAR NA TELA
	totalOK=totalOK.toFixed(2).replace(".",",");
	//MOSTRA O TOTAL DA LINHA NA TELA
	//span_total.innerHTML = total;
	span_total.innerHTML = totalOK;
	//PEGA O VALOR DO IPI
	//var ipi = document.getElementById("ipi").value;
	//CHAMA A FUNÇÃO PARA MOSTRAR O RESULTADO FINAL
	resultadosFinais();
	
}


function calcularValorLinha(linha){

	if(document.getElementById("quantidade"+linha).value==''){
		alert("Atenção: Preencha o campo referente à quantidade na "+linha+"ª linha");
		document.getElementById("quantidade"+linha).focus();
		document.getElementById("quantidade"+linha).value='';
		document.getElementById("valor_unitario"+linha).value='';
	}else{
		calculo(linha)
	}
	
}

function atualizaValorLinha(linha){

	if(document.getElementById("valor_unitario"+linha).value!=''){
		calculo(linha)	
	}
	
}





function Mascara(objeto, evt, mask) {
 
var LetrasU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var LetrasL = 'abcdefghijklmnopqrstuvwxyz';
var Letras  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var Numeros = '0123456789';
var Fixos  = '().-:/ '; 
var Charset = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_/`abcdefghijklmnopqrstuvwxyz{|}~";

evt = (evt) ? evt : (window.event) ? window.event : "";
var value = objeto.value;
if (evt) {
	 var ntecla = (evt.which) ? evt.which : evt.keyCode;
	 tecla = Charset.substr(ntecla - 32, 1);
	 if (ntecla < 32) return true;
	
	 var tamanho = value.length;
	 if (tamanho >= mask.length) return false;
	
	 var pos = mask.substr(tamanho,1); 
	 while (Fixos.indexOf(pos) != -1) {
	  value += pos;
	  tamanho = value.length;
	  if (tamanho >= mask.length) return false;
	  pos = mask.substr(tamanho,1);
	 }
	
	 switch (pos) {
	   case '#' : if (Numeros.indexOf(tecla) == -1) return false; break;
	   case 'A' : if (LetrasU.indexOf(tecla) == -1) return false; break;
	   case 'a' : if (LetrasL.indexOf(tecla) == -1) return false; break;
	   case 'Z' : if (Letras.indexOf(tecla) == -1) return false; break;
	   case '*' : objeto.value = value; return true; break;
	   default : return false; break;
	 }
	}
	objeto.value = value; 
	return true;
}

function MaskCep(objeto, evt) { 
	return Mascara(objeto, evt, '#####-###');
}

function MaskData(objeto, evt) { 
	return Mascara(objeto, evt, '##/##/####');
}

function MaskTelefone(objeto, evt) { 
	return Mascara(objeto, evt, '(##) ####-####');
}

function MaskCnpj(objeto, evt) { 
	return Mascara(objeto, evt, '##.###.###/####-## ');
}

function checkCamposProdutos(form)
{
	for(i=1;i<=50;i++)
	{
		if(document.getElementById("habilitado_"+i).value=="1")
		{
			if(document.getElementById("produto"+i).value.length<1){alert("Por favor, selecione o produto");document.getElementById("produto"+i).focus();return false;}
			else if(document.getElementById("quantidade"+i).value.length<1){alert("Por favor, preencha a quantidade");document.getElementById("quantidade"+i).focus();return false;}
			else if(document.getElementById("tensao"+i).value.length<1){alert("Por favor selecione a tensão");document.getElementById("tensao"+i).focus();return false;}
			else if(document.getElementById("valor_unitario"+i).value.length<1){alert("Por favor, preencha o valor unitário para o produto escolhido");document.getElementById("valor_unitario"+i).focus();return false;}
			else if(document.getElementById("ipi"+i).value.length<1){alert("Por favor, preencha o campo referente ao IPI.");document.getElementById("ipi"+i).focus();return false;}
		}
	}
	form.submit();
	return true;

}

function checkCampos(form){
	if((form.idAprovado.value != '000000')&&(form.idAprovado.value == '1')){
		for(i=0;i<form.elements.length;i++)
		{
			if(form.elements[i].name=="habilitado[]"){return checkCamposProdutos(form);}
			if(form.elements[i].name=="ordem_compra" || form.elements[i].name=="ipi" || form.elements[i].name=="obs"){continue;}
			if(form.elements[i].value.length<=0)
			{
				alert("Por favor, preencha todos os campos, exceto IPI e OBS.");
				form.elements[i].focus();
				return false;
			}
		}
	}else{
		alert("Por favor, insira um número de formulário válido.");
		form.id_pedido.focus();
	}
}

function nexttab(form,e,me){
	var key,lucky,you;
	key = getkey(e);
	if(key==13)  //enter pressed, move to next element
	{
		for(i=0;i<form.elements.length;i++)
		{
			you=form.elements[i];

			if(you.type=='hidden'){ continue;} 
			
			//pula elementos consecutivos com mesmo nome (por exemplo, 2 ou + radios, checkboxes, etc...)
			if(lucky && (you.name==lucky.name)){lucky=null;me=you;}
			if(lucky)
			{
				//you.select();
				you.focus();
				return true;
			}
			if(me==you){lucky=you;}
		}
	}
	return false;
}

function testarData(data, id){
	window.frames.testaData.location.href  = "testardata.php?data="+data+"&campo="+id;
}

function chamaOutros(linha, valor, form){
	
	if(document.getElementById("produto"+linha).value=='O'){
		document.getElementById("produto"+linha).style.display='none';
		document.getElementById("produto_temp"+linha).style.display='';
		document.getElementById("imgTroca"+linha).style.display='';
		
		document.getElementById("produto"+linha).name="produto_old[]";
		document.getElementById("produto"+linha).id="produto_old"+linha;
		
		document.getElementById("produto_temp"+linha).name="produto[]";
		document.getElementById("produto_temp"+linha).id="produto"+linha;
		
		document.getElementById("tensao"+linha).selectedIndex = 5;
		document.getElementById("produto"+linha).focus();
	}
}

function chamaSelect(linha, valor, form){
	
	document.getElementById("imgTroca"+linha).style.display='none';
	
	document.getElementById("produto"+linha).name="produto_temp[]";
	document.getElementById("produto"+linha).id="produto_temp"+linha;
	
	document.getElementById("produto_old"+linha).name="produto[]";
	document.getElementById("produto_old"+linha).id="produto"+linha;
	
	document.getElementById("produto"+linha).style.display='';
	document.getElementById("produto_temp"+linha).style.display='none';
	
	document.getElementById("produto"+linha).selectedIndex = 0;
	document.getElementById("tensao"+linha).selectedIndex = 0;
	document.getElementById("produto"+linha).focus();
	
}

function zeraCampo(campo, form){
	if(campo.value=='000000'){
		campo.value = '';
	}
}

function verificaId(campo){
	var id_pedido = campo.value;
	if(id_pedido=='000000' || id_pedido=='' || id_pedido.length<5){ 
		document.getElementById('id_pedido').style.color = "#c5000a";
		document.getElementById('idAprovado').value = "0";
		document.getElementById('idAprovadoLabel').style.display = "none";
		document.getElementById('idAprovadoLabel').innerHTML = "";
		alert('Digite um número de formulário válido ou aceite a sugestão de número.');
		campo.focus();
	}else{ 
		window.frames.testaId.location.href = 'representantes_testaid.php?id_pedido='+id_pedido;
	}
}

function aceitarSugestao(idOK){
	document.getElementById('id_pedido').value = idOK;
	document.getElementById('id_pedido').style.color="#006600";
	document.getElementById('idAprovado').value = "1";
	document.getElementById('idAprovadoLabel').style.display = "";
	document.getElementById('idAprovadoLabel').innerHTML = "<b>Número OK!</b> Preencha agora os campos do formulário:";
	document.getElementById('id_pedido').readonly = "readonly";
	document.getElementById('aceitaSugestao').style.display = "none";
}