function gbi(obj){
	return document.getElementById(obj);
}

function aprova_orcamento(e){
    if(confirm('Você realmente deseja aprovar este orçamento??')){
        window.location = 'index.php?sub=orcamentos&orc_aprovado='+e;
    }
}
function recusa_orcamento(e){
    if(confirm('Você realmente deseja recusar este orçamento??')){
        window.location = 'index.php?sub=orcamentos&orc_recusado='+e;
    }
}

function limpaCampo(){
    if(gbi('query').value == 'Seu Produto aqui...'){
        gbi('query').value = '';
    }
}
function populaCampo(){
    if(gbi('query').value == ''){
        gbi('query').value = 'Seu Produto aqui...';
    }
}

function submitNoEnter(e){  
    if(e.keyCode == 13){
        enviaLogin();
    }
}

function isNumberKey(e) {
		
	if( e.keyCode ) charCode = e.keyCode;
	else if( e.which ) charCode = e.which; // Netscape 4.*
	else if( e.charCode ) charCode = e.charCode; // Mozilla
	
	if( charCode > 31 && (charCode < 48 || charCode > 57) ) return false;

	return true;
}
function Limpar(valor, validos) {
// retira caracteres invalidos da string
var result = "";
var aux;
for (var i=0; i < valor.length; i++) {
aux = validos.indexOf(valor.substring(i, i+1));
if (aux>=0) {
result += aux;
}
}
return result;
}

function FormataMoeda(campo,tammax,teclapres,decimal) {
	var tecla = teclapres.keyCode;
	vr = Limpar(campo.value,"0123456789");
	tam = vr.length;
	dec=decimal

	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 )
	{ tam = tam - 1 ; }

	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
	{

	if ( tam <= dec )
	{ campo.value = vr ; }

	if ( (tam > dec) && (tam <= 5) ){
	campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; }
	if ( (tam >= 6) && (tam <= 8) ){
	campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
	}
	if ( (tam >= 9) && (tam <= 11) ){
	campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
	if ( (tam >= 12) && (tam <= 14) ){
	campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
	if ( (tam >= 15) && (tam <= 17) ){
	campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;}
	} 
} 




function FormataMoedaFFW(fld, milSep, decSep, e,precisionm,sizem) {
  
  precision = 2;
  size = 10;
  
  var sign = "";
  var i,j = 0;
  var key = '';
  var len = len2 = 0;
  var strCheck = new Array();
  var aux = aux2 = '';
  var whichCode = (window.Event) ? e.which : e.keyCode;
  strCheck[48] = strCheck[96] = 0;
  strCheck[49] = strCheck[97] = 1;
  strCheck[50] = strCheck[98] = 2;
  strCheck[51] = strCheck[99] = 3;
  strCheck[52] = strCheck[100] = 4;
  strCheck[53] = strCheck[101] = 5;
  strCheck[54] = strCheck[102] = 6;
  strCheck[55] = strCheck[103] = 7;
  strCheck[56] = strCheck[104] = 8;
  strCheck[57] = strCheck[105] = 9;
  if (!(whichCode < 48 || whichCode > 57) || !(whichCode < 96 || whichCode > 105) || whichCode == 8 || whichCode == 45 || whichCode == 43 ) {
	  key = strCheck[whichCode];
	  aux = fld.value;
	  if (whichCode == 43 || whichCode == 45) {
		  if (whichCode == 45) {
			  if (aux.charAt(0) == "-") {
				  sign = "";
			  } else {
				  sign = "-";
			  }
		  } else {
			  sign = "";
		  }
	  } else if (aux.charAt(0) == "" || aux.charAt(0) == "-") {
		sign = aux.charAt(0); 
	  }
	  aux = cleanNotAllowed(aux, '0123456789');
	  if (whichCode != 8 && whichCode != 43 && whichCode != 45) {
	     if (aux.length >= fld.maxLength && fld.maxLength>0) return false;
		 else aux += key;
	  } else if (whichCode == 8 && aux.length > 1) {
	  	aux = aux.substr(0,aux.length-1);
	  }
	  while (aux != "0" && aux.charAt(0) == '0') {
		  aux = aux.replace(/0([0-9]+)/,'$1')
	  }
	  if (aux.length > 0) {
		  if (aux.length == 1) {
			  aux2 = "0,0"+aux;
		  } else if (aux.length == precision) {
			  aux2 = "0,"+aux;
		  } else {
			  for (j = 0,i = aux.length; i >= 0; i--) {
				  if (j == 3 && aux2.length > precision) {
					  aux2 = milSep + aux2;
					  j = 1;
				  } else if (aux2.length > precision) {
					  j++;
				  }
				  aux2 = aux.charAt(i) + aux2;
				  if (aux2.length == precision) {
					  aux2 = decSep + aux2;
				  }
			  }
		  }
	  } else {
		aux2 = "0,00";
	  }
	  fld.value = sign+aux2;
  }
  return false;
}


function cleanNotAllowed(old,valids){
    var i, n="";
    for(i=0;i<old.length;i++) 
        if(valids.indexOf(old.charAt(i))>=0) 
            n += old.charAt(i);
    return n;
}


function parseReal(valor){
	var val = valor.replace('.','');
	val = val.replace(',','.');
	return isNaN(parseFloat(val))?0:parseFloat(val);
}
function valorsonumero(valor){
	var val = valor.replace(/[^0-9]/i,'');
	return parseInt(val);
}

function refreshtotal(){
    var cont = 0,comissao=0;
    var i, t;
	var valor_frete = gbi('valor_frete').value;
	valor_frete = valor_frete.replace("R$ ","").replace(",",".");
	valor_frete = parseFloat(valor_frete);
	
    for(i=0;i<n_linhas;i++){
      t = gbi('campo_total'+i).innerHTML;
      t = t.replace("R$ ","").replace(",",".");
      cont += parseFloat(t);
    }
	cont = cont + valor_frete;
    gbi('prodtot').innerHTML = "<strong>R$ "+ ((Math.round(cont*100)/100).toString().replace(".",","))+"</strong>";
	gbi('total_orcamento').value = ((Math.round(cont*100)/100).toString().replace(".",","));
}

function refreshvalor(id_linha){

	var unidade = valorsonumero(gbi('quant_prod'+id_linha).value);	
	var valor_unitario = parseReal(gbi('valor_unitario'+id_linha).value);
	var cor_extra = parseReal(gbi('valor_cor_extra'+id_linha).value);
	var ccf = parseReal(gbi('valor_ccf'+id_linha).value);
	var fotolito_arte = parseReal(gbi('valor_fotolito_arte'+id_linha).value);
	var outros = parseReal(gbi('valor_outros'+id_linha).value);
	
    var calc = (unidade*valor_unitario)+cor_extra+ccf+fotolito_arte+outros;
    calc = Math.round(calc*100)/100;
    calc = calc.toString();
    calc = calc.replace(".",",");
    gbi('campo_total'+id_linha).innerHTML = "R$ " + calc;
    refreshtotal();
}

function refreshTodosValores(n_linhas){

    for(id_linha=0;n_linhas>id_linha;id_linha++){
        var unidade = valorsonumero(gbi('quant_prod'+id_linha).value);	
    	var valor_unitario = parseReal(gbi('valor_unitario'+id_linha).value) + 0;
        
    	var cor_extra = parseReal(gbi('valor_cor_extra'+id_linha).value) + 0;
    	var ccf = parseReal(gbi('valor_ccf'+id_linha).value) + 0;
    	var fotolito_arte = parseReal(gbi('valor_fotolito_arte'+id_linha).value) + 0;
    	var outros = parseReal(gbi('valor_outros'+id_linha).value) + 0;
    	
        var calc = (unidade*valor_unitario)+cor_extra+ccf+fotolito_arte+outros;
        calc = Math.round(calc*100)/100;
        calc = calc.toString();
        calc = calc.replace(".",",");
        gbi('campo_total'+id_linha).innerHTML = "R$ " + calc;
    }
    
}

function corrigeComissao(campo){

	if(campo.value>100){
		campo.value = 100;
		return;
	}
	if(campo.value<0){
		campo.value=0;
		return;
	}
}
function valida_form_orc_pend(){
gbi('orcamento_pendente').submit();

}
function overMenu(id){ gbi(id).style.display = "block"; }
function outMenu(id){ gbi(id).style.display = "none"; }

function visualiza_login(){
	gbi('nlogin').focus();gbi('nlogin').style.border='2px solid #f00';
}

function envia_arquivo(){
	gbi('form_arquivo').submit();
}
function enviaLogin(){
	if(gbi('nlogin').value.length<6){
		alert("Digite seu usuário corretamente!");
		gbi('nlogin').focus();
	}else if(gbi('slogin').value.length<6){
		alert("Digite sua senha corretamente!");
		gbi('slogin').focus();
	}else{
		gbi('formLogin').submit();
	}
}

function enviaFormularioContato(){
	if(gbi('nome').value==""){
	   alert("Digite seu nome completo.");
	   gbi('nome').focus();
	   return false;
	}
	if(gbi('email').value=="")
	{
		alert("ATENÇÃO \nDIGITE O SEU EMAIL");
		return false;
	}

	if(gbi('email').value=="" || gbi('email').value.indexOf('@', 0) == -1 
	|| gbi('email').value.indexOf('.', 0)  ==- 1)
	{
		alert("ATENÇÃO \nE-MAIL INVÁLIDO");
		return false;
	}
	if(gbi('departamento').value==""){
	   alert("Selecione um departamento.");
	   gbi('departamento').focus();
	   return false;
	}
	if(gbi('mensagem').value==""){
	   alert("Digite sua mensagem");
	   gbi('departamento').focus();
	   return false;
	}

 gbi('formContato').submit();

}


// Função Troca Miniatura dos produtos
function trocaMiniatura(nome){
		 gbi('miniatura_produto').innerHTML = '<a href="javascript:imgProduto(\''+nome+'\');"><img src="./iss/mini.php?sup=sim&f='+nome+'.jpg" id="imgampliada" ></a>';
         //gbi('miniatura_produto').innerHTML = '<a href="javascript:imgProduto(\''+nome+'\');"><img src="./iss/m_'+nome+'.jpg" id="imgampliada" ></a>';
}

function imgProduto(imagem_produto){		 
	window.open('iss/popup_produtos.php?nome_imagem='+imagem_produto,'Produto','width=400,height=400,scrolling=auto,top=200,left=200');
}

// Newsletter::ISS 
function newsletterHandler(o){
    if (o.readyState == "4") {
        var result = o.responseText.split("#");
        if(result[0]=="OK"){
            alert(result[1]);
        }else{
            alert("Não foi possível realizar a ação do newsletter!");
        }
    }
}
var newsletterAjse = new Ajse("iss/newsletter.php",newsletterHandler,"UTF-8");
function registerNewsletter(){         
	email = document.getElementById('campoNewsletter').value;
    acao = true;	        
	if(!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))){ 
		alert("Preencha o campo de E-Mail com um e-mail válido e tente novamente!");
		return ;
    }            
	newsletterAjse.query("email="+email+"&acao="+acao,"POST");		        
	document.getElementById('campoNewsletter').value = "";      
} 

// Envio de form de login

function enviaLogin(){
	if(gbi('nlogin').value.length<6){
		alert("Digite seu usuário corretamente!");
		gbi('nlogin').focus();
	}else if(gbi('slogin').value.length<6){
		alert("Digite sua senha corretamente!");
		gbi('slogin').focus();
	}else{
		gbi('formLogin').submit();
	}
}

// Validação do formulário de contato

function enviaFormularioCadastro(editando){
     
	 if(!editando && !(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(gbi('cad_email').value))){
	      alert("E-Mail informado é inválido!");
		  gbi('cad_email').focus();	      
		  return;
	 }
     if(gbi('cad_nome').value.length<3){
          alert("Informe seu nome!");
		  gbi('cad_nome').focus();
          return;
     }
     if(gbi('cad_telconv').value.length<3){
          alert("Informe seu telefone convencional!");
		  gbi('cad_telconv').focus();
          return;
     }
	 if(!editando){
		if(!formataCPFCNPJ(gbi('cpfcnpj'))){
		  gbi('cpfcnpj').focus();
          return;
		}	
	 }
     if(gbi('cad_cep').value.length<5){
          alert("Informe seu cep corretamente");
		  gbi('cad_cep').focus();
          return;	 
	 }if(gbi('cad_cep2').value.length<3){
          alert("Informe seu cep corretamente!");
		  gbi('cad_cep2').focus();
          return;	 
	 }
	 	 
	 gbi('formCadastro').submit();
}

function enviaFormularioCadastroCliente(editando){
     
	 if(!editando && !(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(gbi('cad_email').value))){
	      alert("E-Mail informado é inválido!");
		  gbi('cad_email').focus();	      
		  return;
	 }
     if(gbi('cad_nome').value.length<3){
          alert("Informe seu nome!");
		  gbi('cad_nome').focus();
          return;
     }
     if(gbi('cad_telconv').value.length<3){
          alert("Informe seu telefone convencional!");
		  gbi('cad_telconv').focus();
          return;
     }
	 if(gbi('cpfcnpj').value.length<3){
          alert('Atenção: Para ir para o próximo passo você deve informar o cpf/cnpj do seu cliente!');
		  gbi('cpfcnpj').focus();
          return;
     }
	if(!formataCPFCNPJ(gbi('cpfcnpj'))){
		  gbi('cpfcnpj').focus();
          return;
     } 
	 gbi('formCadastro').submit();
}

/* NSA() */
function nsa(){
	if(gbi('satual').value.length<5){
		alert('Digite sua senha atual!');
	}else if(gbi('snova').value!=gbi('rnova').value){
		alert('A nova senha e a repetição de nova senha são diferentes!');
	}else if(gbi('snova').value.length<5){
		alert('A nova senha deve conter pelo menos 5 caracteres!');
	}else{
		gbi('formSenha').submit();
	}
}
function nsa2(){
	if(gbi('snova').value!=gbi('rnova').value){
		alert('A nova senha e a repetição de nova senha são diferentes!');
	}else if(gbi('snova').value.length<6){
		alert('A nova senha deve conter pelo menos 6 caracteres!');
	}else{
		gbi('formSenha').submit();
	}
}
function nsa3(){
	if(!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(gbi('nlogin').value))){
		alert('Digite seu e-mail e mantenha a senha vazia, então clique em "esqueci minha senha" novamente!');
	}else if(gbi('slogin').value.length!=0){
		alert('Digite seu e-mail e mantenha a senha vazia, então clique em "esqueci minha senha" novamente!');
	}else{
		gbi('slogin').value = "rescuepass!!!";
		gbi('formLogin').submit();
	}
}

// Aplica máscara
function applyMask(string,mask){
    var i=0;
    var j=0;
    var masked="";
    for(;string.length>i && mask.length>j;j++){
       if(mask.charAt(j)=='0'){
           masked += string.charAt(i);
           i++;
       }else{
           masked += mask.charAt(j);
       }
    }
    return masked;
}
function envia_form(){
	 if(gbi('cpfcnpj').value.length<3){
          alert('Atenção: Para ir para o próximo passo você deve informar o cpf/cnpj do seu cliente!');
		  gbi('cpfcnpj').focus();
          return;
     }
	if(!formataCPFCNPJ(gbi('cpfcnpj'))){
		  gbi('cpfcnpj').focus();
          return;
     } 
	gbi('form_cpf_orcamentos').submit();
}

function formataCPFCNPJ(obj){
    var old = obj.value;
    var n = "",valids = "0123456789",cpf="000.000.000-00",cnpj="00.000.000/0000-00";
    var i = 0,valid = false;
    for(i=0;i<old.length;i++) {
        if(valids.indexOf(old.charAt(i))>=0) n += old.charAt(i);
    }
    if(n.length==11){
        valid = validacpf(n);
        n = applyMask(n,cpf);
    }else if(n.length==14){
        valid = validacnpj(n);
        n = applyMask(n,cnpj);
    }
    if(valid==false && n!="") alert('O valor digitado não parece ser um CPF ou CNPJ válido!');
    obj.value = n;
    return valid;
}


// Valida CPF e CNPJ
function validacpf(s){
	var i,digitos_iguais=1;
	if (s.length != 11) return false;
    for (i = 0; i < s.length - 1; i++) if (s.charAt(i) != s.charAt(i + 1)) { digitos_iguais = 0; break; }
	if(digitos_iguais==1) return false;
 	var c = s.substr(0,9);
  	var dv = s.substr(9,2);
  	var d1 = 0;
  	for (i = 0; i < 9; i++)	d1 += c.charAt(i)*(10-i);
	if (d1 == 0) return false;
    d1 = 11 - (d1 % 11);
  	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1)	return 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)	return false;
  	return true;
}
function validacnpj(cnpj) {
	var numeros, digitos, soma, i, resultado, pos, tamanho;
	if (cnpj.length != 14) return false;
    var digitos_iguais = 1;
    for (i = 0; i < cnpj.length - 1; i++) if (cnpj.charAt(i) != cnpj.charAt(i + 1)){ digitos_iguais = 0; break;}
    if (digitos_iguais==1) return false;
    tamanho = cnpj.length - 2
	numeros = cnpj.substring(0,tamanho);
	digitos = cnpj.substring(tamanho);
	soma = 0;
	pos = tamanho - 7;
	for (i = tamanho; i >= 1; i--){ soma += numeros.charAt(tamanho - i) * pos--; if (pos < 2) pos = 9; }
	resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
	if (resultado != digitos.charAt(0))	return false;
	tamanho = tamanho + 1;
	numeros = cnpj.substring(0,tamanho);
	soma = 0;
	pos = tamanho - 7;
	for (i = tamanho; i >= 1; i--){ soma += numeros.charAt(tamanho - i) * pos--; if (pos < 2) pos = 9; }
    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
    if (resultado != digitos.charAt(1))	return false;
    return true;
}



