// Utilizado pela parte de compras...
///////////////////////////
// uso geral 
////////////////////////////
function Trim(str){return str.replace(/^\s+|\s+$/g,"");}

function itemform (f_num,CodIOrc,ref) {
  if (CodIOrc == ref) { var fchg='f';}else{var fchg='t'};
  var target = 'vendas/show_form.php?reload=true&ci='+CodIOrc+'&for='+f_num+'&fchg='+fchg;
  var windowHandle = window.open(target,'prereqWin','menubar=no,status=no,location=no,width=510,height=500,resizable=yes,toolbar=no,scrollbars=yes');
  windowHandle.opener = self;
  windowHandle.window.focus();
	
}
//===========================================================
// Functio: COMPLET
// Input: showline = Referencia para ativar ou não a linha de 
//              pergunta sobre cantos arredondados
//        objID = ID do local onde será carragado o conteudo
//===========================================================
function complet (showline,objID) {
// Usado no formulário de pedido
if (showline == 'S') {
 var str = "<p><span class='select_descri'><b>Cantos arredondados na moldura:</b></span> <span class='select_descri'>Sim <input type='radio' name='rad2' value='S'> N&atilde;o <input type='radio' name='rad2' checked value='N'></span></p>";
}else {
 var str = "";
}
  obj = document.getElementById(objID);
  obj.innerHTML = str;  
}
//--------- final function COMPLET ---------------------------

function buyagain(theform){
 var quant = document.formvenda.quant.value;
 if ((quant != "") && (quant > 0)) {
  var serverPage = 'vendas/salva_item_cesta.php';
  document.selecionar.ach.value = "S";  //Indica utilizando area não cheia
  var objID = "wrkarea";
  var str = getformvalues(theform);
  processajax ("POST",serverPage, objID, str);
 }else {
	alert ("Por favor não deixar a quantidade em branco ou com valor zero!");	
 }
}

function buyagain_old(theform){
 var quant = document.formvenda.quant.value;
 if ((quant != "") && (quant > 0)) {
  var page = 'vendas/salva_item_cesta.php';
  var serverPage = 'wrkarea_ajax.php?reload=true&fi='+page+'&area=ac_id';
  document.selecionar.ach.value = "N";  //Indica utilizando area não cheia
  var objID = "wrkarea";
  var str = getformvalues(theform);
  processajax ("POST",serverPage, objID, str);
 }else {
	alert ("Por favor não deixar a quantidade em branco ou com valor zero!");	
 }
}

function info() {
	alert ("Em breve estaremos com essa opção disponível, favor usar uma de nossas opções de contato: através de nosso e-mail ou pelo atendimento on-line.");
}

function busca_prod () {
 var target = 'vendas/busca.php';
 var windowHandle = window.open(target,'busca','menubar=no,status=no,location=no,width=500,height=300,resizable=yes,toolbar=no,scrollbars=yes');
 windowHandle.opener = self;
 windowHandle.window.focus();
}
function meuspedidos() {
  var areacheia = document.selecionar.ach.value;
  if (areacheia == "S") {
      var page = 'wrkarea_ajax.php?reload=true&fi=includes/meuspedidos1.php&area=ac_id';
      var areaID = "wrkarea";
	  document.selecionar.ach.value = "N";  //Indica area não cheia
      var str = "";
      processajax ("GET",page,areaID, "");
//      conteudo ("includes/meuspedidos1.php");
  }else {
	 cont_acid("includes/meuspedidos.php");
  }
}

function tst_wrkarea(page) {
  var areacheia = document.selecionar.ach.value;
  if (areacheia == "S") {
      var serverpage = page+'&ach=true';
      var areaID = "wrkarea";
	  document.selecionar.ach.value = "N";  //Indica area não cheia
      var str = "";
      processajax ("GET",serverpage,areaID, "");
  }else {
	 cont_acid(page);
  }
}

function busca_go () {
// botão busca do formulário
  var nome = document.selecionar.word.value;
  if (nome != "") {
     var page = 'vendas/lst_prod.php?reload=true&nome='+nome;
//     cont_acid (page);
     tst_wrkarea(page);
  }
}

function buscaproduto (ref,id,nome) {
//chamado via opção da lista de busca
  var page = 'vendas/lst_prod.php?reload=true&ref='+ref+'&id='+id+'&nome='+nome;
//  cont_acid (page);
  tst_wrkarea(page);
}

function verif_num(e,quantid,vlunid,vsubtot,vtotal,qt_prod) {
 var keynum;
 var keychar;
 var numcheck;
 if(window.event) { // IE
    keynum = e.keyCode;
 }else if(e.which) {// Netscape/Firefox/Opera
    keynum = e.which;
 }
 keychar = String.fromCharCode(keynum);
 numcheck = /\d/;
 if (keynum == 8) { //backspace
   return !numcheck.test(keychar);
 }else {
   return numcheck.test(keychar);
 }
}

//Converte numero com ponto para string money
// com virgula e duas casas decimais
//exemplo: 58.3 = 58,30
function num_to_strmoney(num){
var result = num;
	result = result.toFixed(2);
	result += ''; // convert para string
	if ((result.lastIndexOf (".",result.length)) == -1 ) {
		// Não tem centavos
		result = result+",00";
	}else {
	  if ( (result.length - (result.lastIndexOf (".",result.length))) == 2) {
		  // tem apenas uma casa depois da virgula
		    result = result +"0";
	  }
	}
	result = result.replace(".",",");
return(result)
}

function cancel_item (itemID,prodID,quantid,vlunid,vsubtot,vtotal,qt_prod) {
  var checked = document.getElementById(itemID).checked;
 if (checked){
  //Colocar 0 no valor total 
	var objsubtot = document.getElementById(vsubtot);
	objsubtot.innerHTML = "0,00";
 }
   //Bloquear ou liberar campo quantidade
    var quant = document.getElementById(quantid);
	quant.disabled = checked;
	quant.style.background = !checked ? "white" : "silver";
//	quant.value = checked ? "" : "1";
    var produto = document.getElementById(prodID);
	produto.disabled = checked;
	produto.style.background = !checked ? "yellow" : "silver";

    recalculacesta (quantid,vlunid,vsubtot,vtotal,qt_prod,itemID);

}

function recalculacesta (quantid,vlunid,vsubtot,vtotal,qt_prod,itemID) {
 //Obtem status do campo se deletar
 var checked = document.getElementById(itemID).checked;
 var quant = document.getElementById(quantid).value;
 if ((quant != "") && (quant > 0)) {
	if (!checked) {
	var objsubtot = document.getElementById(vsubtot);
    var objunid = document.getElementById(vlunid);
    var unid = objunid.innerHTML;
    unid = unid.replace(",",".");
	var result = (parseFloat(quant) * (unid*100))/100;
	result = num_to_strmoney (result);
	objsubtot.innerHTML = result;
	}
    // Acertar o total da compra 
	//imput: ID do campo subtotal (vsubtot) = "vltotal-i";
	var objtot = document.getElementById(vtotal);
	var total = 0;
	for (i=0;i<qt_prod;i++) {
		vsubtotID = "vltotal-"+i;
		vsubtot = document.getElementById(vsubtotID).innerHTML;
        vsubtot = vsubtot.replace(",",".");
		valor = parseFloat(vsubtot);
		total = Number(total + valor);
	}
	total = num_to_strmoney(total);
	objtot.innerHTML = total;
	
 }else {
	alert ("Por favor não deixar a quantidade em branco ou com valor zero!");	
 }
}


function recalculaitem (itemID,vlunid,vltotal) {
 var quant = document.getElementById(itemID).value;
 if ((quant != "") && (quant > 0)) {
	var objtot = document.getElementById(vltotal);
    var objunid = document.getElementById(vlunid);
    var unid = objunid.innerHTML;
    unid = unid.replace(",",".");
	var result = (parseFloat(quant) * (unid*100))/100;
	result += ''; // convert para string
	if ((result.lastIndexOf (".",result.length)) == -1 ) {
		// Não tem centavos
		result = result+",00";
	}else {
	  if ( (result.length - (result.lastIndexOf (".",result.length))) == 2) {
		  // tem apenas uma casa depois da virgula
		    result = result +"0";
	  }
	}
	result = result.replace(".",",");
	objtot.innerHTML = result;
 }else {
	alert ("Por favor não deixar a quantidade em branco ou com valor zero!");	
 }
}

function cesta (page) {
  document.selecionar.ach.value = "S";  //Indica utilizando area cheia
  var areaID = "wrkarea";
  var str = "";
  processajax ("GET",page,areaID, "");
}

function venda (page){
  document.selecionar.ach.value = "S";  //Indica utilizando area cheia
  var page = "vendas/"+page;
  var areaID = "wrkarea";
  var str = "";
  processajax ("GET",page,areaID, "");
}

//==========================================================
// Function: CONF_PEDIDO
// Utilizado na confirmação e na atualização da cesta.
//==========================================================
function conf_pedido (formID, page){
  var qt_prod = document.formcesta.qt_prod.value	
  if (qt_prod > 0) {
  document.selecionar.ach.value = "S";  //Indica utilizando area cheia
  var page = "vendas/"+page;
  var areaID = "wrkarea";
  var theform = document.getElementById(formID)
  var str = getformvalues(theform);
  processajax ("POST",page,areaID, str);
  }
}
//----------------------------------------------------------
function sub_pedido_OLD (formID, file){
  var qt_prod = document.submitcesta.qt_prod.value	
  if (qt_prod > 0) {
     var page = "vendas/"+file;
     var serverpage = 'wrkarea_div.php?reload=true&fi='+page+'&area=ac_id';
     var areaID = "wrkarea";
	 document.selecionar.ach.value = "N";  //Indica area não cheia	  
     var theform = document.getElementById(formID)
     var str = getformvalues(theform);
     processajax ("POST",serverpage,areaID, str);
  }
}


function sub_pedido (formID, file){
var erro = false;
var msg_err = "POR FAVOR CORRIR OS ERROS..\n";
  var qt_prod = document.submitcesta.qt_prod.value	
  if (qt_prod <= 0){erro = true; msg_err = msg_err + ">> Pedido está vazio ... \n";}
  var email = Trim(document.formcontato.email_compra.value);
  if (!(email_valido = is_email(email))) {
	 //Email inválido
     erro = true;
     msg_err = msg_err + ">> Email incorreto ... \n"; 
  }
  var phone = Trim(document.formcontato.phone_compra.value);
  if (phone == "") {erro = true; msg_err = msg_err + ">> Faltou definir telefone ... \n"; }

if (!erro){
     var page = "vendas/"+file;
     var serverpage = 'wrkarea_div.php?reload=true&fi='+page+'&area=ac_id';
     var areaID = "wrkarea";
	 document.selecionar.ach.value = "N";  //Indica area não cheia	  
     var theform = document.getElementById(formID)
     var str1 = getformvalues(theform);
     var theform = document.getElementById('fcontatoID')
     var str2 = getformvalues(theform);
	 var str = str1 + str2;
     processajax ("POST",serverpage,areaID, str);
}else {
  alert (msg_err);
}

}


function logout () {
  var obj = document.getElementById('log_id');
  obj.innerHTML = "Agradecemos por sua preferência!!";
  conteudo('logout.php');	
}

function call_page (page) {
  var areaID = "ac_id";
  var pg = "includes/"+page;
  var str = "";
  processajax ("GET",pg,areaID, "");
}
function validfpedidos(theform, serverPage, objID) {
	var serverPage = "includes/"+serverPage;
	var str = getformvalues(theform);
	processajax ("POST",serverPage, objID, str);
}

function validformforgpss(theform, serverPage, objID) {
  var email = document.forgpss.email_field.value;
  email = review_Email(email);
  if (!(email_valido = is_email(email))) {
	 //Email inválido
	 alert ("Email não válido");
  }else {
	var file = serverPage;
	var str = getformvalues(theform);
	processajax ("POST",serverPage, objID, str);
  }
}

function validformpass(theform, serverPage, objID) {
  if (document.passform.newpass.value == document.passform.passconf.value) {
	var file = serverPage;
	var str = getformvalues(theform);
	processajax ("POST",serverPage, objID, str);
  } else {
     alert("Erra na confirmação da nova senha!");
  }
}

function validformemail(theform, serverPage, objID) {
  if (document.emailform.email_field.value == document.emailform.conf_email.value) {
  //----- confirmar formato do email -------------
      var email = document.emailform.email_field.value;
	  email = review_Email(email);
	  if (!(email_valido = is_email(email))) {
		 //Email inválido
		 alert ("Novo email não tem um valor válido.");
	  }else {
 	     var file = serverPage;
	     var str = getformvalues(theform);
	     processajax ("POST",serverPage, objID, str);
	  }
  } else {
     alert("Erra na confirmação do novo Email!");
  }
}



function cad_complement(page,areaID){
  var page1 = "includes/"+page;
  var str = "";
  processajax ("GET",page1,areaID, "");
}

function review_Email(email_in){
var email_out = email_in;
  if (email_out.indexOf("@hotmail.com.br") >= 0) {
     // O E-mail HOTMAIL não termina com .BR
	email_out = email_out.replace("hotmail.com.br", "hotmail.com");
  }

  if (email_out.indexOf("@aol.com.br") >= 0) {
		// O E-mail AOL não termina com .BR
		email_out = email_out.replace("aol.com.br", "aol.com");
  }
  
  if (email_out.indexOf(" ") >= 0){
		// E-mail não deve conter espaços em branco
 		while(email_out.indexOf(" ") >= 0) 
			email_out = email_out.replace(" ", "");
  }
  email_out = email_out.replace("/", "");
  email_out = email_out.replace("@.", "@");
  email_out = email_out.replace(".@", "@");
  email_out = email_out.replace(",", ".");
  email_out = email_out.replace(";", ".");
  
  return email_out;
}

function cadconcl(theform,serverPage, objID) {
//senha tem que ser iguais
if (!document.fcadadd.newCL.value) {
	/* se não for cliente novo não tem senha para checar */
      var str = getformvalues(theform);
      processajax ("POST",serverPage, objID, str);
}else {
    if ((document.fcadadd.senha.value) != (document.fcadadd.senhaconf.value)) {
	 alert ("Erro na confirmação da senha.");
    }else {
  
//  Apenas para teste
/*  
  if (document.fcadadd.opt[0].checked) { 

  alert ("Pessoa Física \n"+
		 "nome = "+document.fcadadd.nome.value+"\n"+
		 "sobrenome = "+document.fcadadd.sobrenome.value+"\n"+
		 "C.P.F = "+document.fcadadd.cpf.value+"\n"+
		 "R.G = "+document.fcadadd.rg.value+"\n"+
		 "Nasc = "+document.fcadadd.nasc.value+"\n"+
		 "Genero = "+document.fcadadd.sexo.value+"\n");
  }else {
	alert ("Pessoa Jurídica  \n"+
		 "Razão Social = "+document.fcadadd.RazaoSocial.value+"\n"+
		 "Contato = "+document.fcadadd.Contato.value+"\n"+
		 "C.N.P.J = "+document.fcadadd.CNPJ.value+"\n"+
		 "InscEst = "+document.fcadadd.InscEst.value+"\n");
		   
  }
	alert ("Informações complementares \n"+
		   "ender = "+document.fcadadd.ender.value+"\n"+
		 "numero =  = "+document.fcadadd.num.value+"\n"+
		 "Complemento = "+document.fcadadd.comp.value+"\n"+
		 "Tipo endereço =" +document.fcadadd.tpend.value+"\n"+
		 "C.E.P = "+document.fcadadd.cep.value+"\n"+
		 "bairro = "+document.fcadadd.bairro.value+"\n"+
		 "cidade = "+document.fcadadd.cidade.value+"\n"+
		 "estado = "+document.fcadadd.estado.value+"\n"+
		 "pais = "+document.fcadadd.pais.value+"\n"+
		 "phone1 = "+document.fcadadd.phone1.value+"\n"+
		 "phone2 = "+document.fcadadd.phone2.value+"\n"+
		 "Referencia = "+document.fcadadd.ref.value+"\n");

*/
// final do teste 
      if ( ((document.fcadadd.senha.value) == "") || ((document.fcadadd.senhaconf.value) == "")) {
		 alert ("Senha deve ser preenchida");
	  }else {
         var str = getformvalues(theform);
         processajax ("POST",serverPage, objID, str);
	  }
   }
}
}

function is_email(email_in){
var email = email_in;
 if (   (email.indexOf("@") <= 0) || 
		(email.indexOf(".") <=0)  || 
	  ( (email.length) == (email.indexOf(".")+1) ) ){
	 return false;
 }else {
  return true;
 }
}


function cadlogin (theform,serverPage, objID) {
	var vsim = document.fcadaccess.opt[0].checked; 
	var vnao = document.fcadaccess.opt[1].checked; 
	var senha = document.fcadaccess.senha.value;
	var email = document.fcadaccess.email_field.value;
	email = review_Email(email);
	if (!(email_valido = is_email(email))) {
		alert ("Email inválido");
	}else { 
	  if (email != "") {
		if (senha != "") {
			// Forneceu email e senha logo campo Vsim e Vnão é desconsiderado			
  		  var str = getformvalues(theform);
			processajax ("POST",serverPage, objID, str);
			
		}else {
  	       if (vsim) {
			 //Não forneceu senha mas indicou como primeira compra
			 var str = getformvalues(theform);
					processajax ("POST",serverPage, objID, str);
	       }else {
		      if (vnao){
	  	        alert ("Favor inserir a senha de acesso.....email="+email);
		      }
	       }
	    }
	 }else {
	  alert ("Por favor preencher campo E-mail");
     }
    }
}

function esquecisenha () {
	var email = document.fcadaccess.email_field.value;
	if (email != "") {
   	    alert ("Senha sendo enviada por email..."+email);
	}else{
	  alert("Por favor preencher campo E-mail");
    }
}

function not_able () {
	alert ("Esta função não está habilitada ainda. Favor não alterar valor original.");
}

function chkFirstData (){
var erro  = false;
var temvalor = false;
var msg_err = "Por favor, corrigir os erros a seguir \n";
var email = Trim(document.formentry.email_contact.value);
var codigoproduto = Trim(document.formentry.codigoproduto.value);
var ddd = Trim(document.formentry.ddd.value);
var phone = Trim(document.formentry.phone.value);
var codigocliente = Trim(document.formentry.codigocliente.value);

if (codigocliente != "") {erro = true; msg_err=msg_err + "<< Codigo de cliente incorreto >> \n";}

if (email != "") {
  if (!is_email(email)){erro = true; msg_err=msg_err + "<< Email incorreto >> \n";}else {temvalor=true;}
}
if ((ddd != "") || (phone != "")) {
 if (isNaN(ddd)){erro = true; msg_err=msg_err + "<< DDD deve ser numerico >> \n";}
 if (ddd.length <2) {erro = true; msg_err=msg_err + "<< DDD deve ter 2 digitos >> \n";}
 if (phone == "") {erro = true; msg_err=msg_err + "<< Faltou preencher telefone >> \n";}
 else { if (phone.length < 8) {erro = true; msg_err=msg_err + "<< Telefone incorreto >> \n";}
      }
 if (!erro) {temvalor=true;}
}

if (erro) {
  alert (msg_err);
}else {
   if (temvalor) {
//      alert("email = "+email +"\n ddd ="+ddd+"\n phone = "+phone+"\n codigocliente ="+codigocliente+"\n codigoproduto = "+codigoproduto);
      var page = "vendas/venda_first_item.php"; 
      var areaID = "wrkarea";
      var theform = document.getElementById('formentryID')
      var str = getformvalues(theform);
      processajax ("POST",page,areaID, str);
   }else {
      alert ("Por favor entrar com dados para contato");
   }
}

}