var panel1;
var panel2;
var panel3;
function show_panel(titulo,html,w) {

  YAHOO.namespace("example.body");
  
  // Instantiate a Panel from markup
  panel1 = YAHOO.example.body.panel1;
  panel2 = YAHOO.example.body.panel2;
  panel3 = YAHOO.example.body.panel3;
  
  panel1 = new YAHOO.widget.Panel("panel1", { width:w+"px", visible:true, constraintoviewport:true } );
  panel1.render();
  
  // Instantiate a Panel from script
  panel2 = new YAHOO.widget.Panel("panel2", { xy:[488,162], width:w, visible:false, draggable:false, close:false } );
  panel2.setHeader(titulo);
  panel2.setBody(html);
  panel2.render("body");
  
  return panel2;
}

function show_panel2(titulo,html,w) {

  YAHOO.namespace("example.body");
  
  // Instantiate a Panel from markup
  panel3 = YAHOO.example.body.panel3;
  
  
  // Instantiate a Panel from script
  panel3 = new YAHOO.widget.Panel("panel3", { xy:[488,162], width:w,zIndex:9999,visible:true, draggable:true, close:false } );
  panel3.setHeader(titulo);
  panel3.setBody(html);
  panel3.render("body");
  
  return panel3;
}
function removeDIV(main_elem,elem) {
  var main = document.getElementById(main_elem);
  var div = document.getElementById(elem);
  
  if(main!=null && div!=null){
    
    main.removeChild(div);
    //div.parentNode.removeChild(div);
  }  
}

function IsNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }

var equivalentes;
//Função de carrinho de compras
function carrinho(form){
  if (xmlhttp)
  {
    // tenta estabelecer ligação
    try
    {
      
      var serverPage="carrinho_actions.php";
      var prods = form.csv_prods.value;
      var marca = form.marca.value;
      var id_cliente = form.id_cliente.value;
      var id_armazem = form.id_armazem.value;
      var id_estado = form.id_estado.value;
      var stock = form.stock.value;
      var QTMIN = 0;
      
      if(form.MINQT != null)
        var QTMIN = form.MINQT.value;
      
      if(form.TESTE != null)
        var TESTE = form.TESTE.value;
      
      
      var refs = prods.split(",");
      var qts = new Array();
     
      for(i=0;i<=refs.length-1;i++){
         var qt = document.getElementById("qt_" + refs[i]);
         qts[i] = qt.value;
         //valida
         if(IsNumeric(qt.value)==false){ alert("Insira um valor numérico para a quantidade");return false;}
         if(qt.value==""){ alert("Insira um valor numérico para a quantidade");return false;}
      }
      
 
      
      
      var opc1 = document.getElementById("opc1");
      var opc2 = document.getElementById("opc2");
      
      if(opc1!=null || opc2!=null){
        var action = "add_split";
      }else{
        var action = "add_multiple";
      }
      
      
      
      var params = "action=" + action + "&csv_prods=" + prods + "&marca=" + marca + "&id_cliente=" + id_cliente + "&id_armazem=" + id_armazem + "&id_estado=" + id_estado + "&stock=" + stock + "&add_ref=" + refs + "&qts=" + qts + "&QTMIN=" + QTMIN;
      //
      
      
      if(opc1!=null || opc2!=null){
        var opc ;
        
        if(form.opc.length!=null){
         
          for (var i=0; i < form.opc.length; i++){
            if (form.opc[i].checked){
                
                opc = form.opc[i].value;
            }
          }
        }else {
           opc = form.opc.value;
        }
        
        params+="&opc="+opc;
        
        //se tiver escolhido ver as referencias equivalentes
        if(opc==3){
          document.getElementById('ref_eqX').style.visibility='visible';
          Effect.Appear("ref_eqX", { duration: 2.0,from:0,to:1,afterFinishInternal:function (){
            //apaga o painel
            removeDIV('body','panel2_c');
          }});
        }
      
        if(opc==1 || opc==2 || opc==4){
          params+="&estado2="+form.selp.value;
        }
      }
     
     
      //alert(params);
      xmlhttp.open("POST", serverPage,true);
      
      //Send the proper header information along with the request
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xmlhttp.setRequestHeader("Content-length", params.length);
      xmlhttp.setRequestHeader("Connection", "close");
      
      xmlhttp.onreadystatechange = function() {//Chama a função quando o estado mudar
        if(xmlhttp.readyState == 1 ) {
              
        }else if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            if(xmlhttp.responseText){
                var resultado = xmlhttp.responseText;
                var panel;
                if(resultado=='1'){ // se tiver sido adicionado com sucesso
                  
                  
                  var  tit = "Produto adicionado com sucesso";
                  var html_panel = "<div><p style='padding:6px 0 0 6px;'>Referência ( <b>"+ refs +"</b> ) adicionada com sucesso a sua encomenda</p></div><div class='div_opc_pop' id=hide2><div class='bt_close' onclick=\"panel2.hide();document.getElementById('fundo_opaco').style.display='none';\" ></div><p class='ou'>ou</p><div class='ver_enc'><a href='index.php?id=69'>Ver a minha Encomenda</a></div><div class='clear'></div></div><div class='clear'></div>";
                  
                  document.getElementById('fundo_opaco').style.display='';
                  	 
                  panel = show_panel(tit,html_panel,416);
                  panel.show();		
                  
                  var mnEncomenda = document.getElementById('mn_encomenda');
                  if(mnEncomenda!=null){
                    
                    
                    //mnEncomenda.style.display='';
                    Effect.Appear("mn_encomenda", { duration: 2.0,from:0.8,to:1,afterFinishInternal:function (){
						         mn_encomenda(id_cliente);
					          }});
                    
                  }
                 
                }else if(resultado=='2'){//se não existir stock
                
                   var  tit = "Quantidade Inexistente";
                  var html_panel = "<form enctype='application/x-www-form-urlencoded' action='index.php?id=55' name='frm_carrinho_split' id='frm_carrinho_split' method='post'   onsubmit='return carrinho(this);' >";
                  html_panel += "<table cellpadding='0' cellspacing='0' border='0'>";
                  html_panel += "<tr><td colspan='3'><div style='padding:6px 0 0 6px;'><p>A Quantidade da Referência ( <b>" + refs + "</b> ) não existe em stock.</b><p></div></td></tr>";
                  html_panel += "<tr><td colspan='3'><div ><p class='p_pop2'>O que pretende fazer ?<p></div>";
                  //se existirem refs equivalentes
                  if(equivalentes==1){
                    html_panel += "<tr><td  width='20'><div class='radio2_pop2'><input type='radio' value='2' onClick=\"trocaRadios('selp');\" name='opc'  id='opc2' width='13' height='13'/></div></td>";
                    html_panel += "<td><div class='p2_rad_pop2'>Desejo encomendar a(s) " + (qts) + " unidade(s) com o estado de</div></td>";
                    html_panel += "<td><div class='p_rad_pop2'><select name='selp' id='selp' disabled='disabled' class='sel_pop2 txt3'>";
                     
                    for(i=0;i<=(t_estados-1);i++){
                      if(estados[i]['cod']!="" && estados[i]['cod']!=undefined){
                       html_panel += "<option value='"+ unescape(estados[i]['cod']) +"'>" + unescape(estados[i]['descpt']) + "</option>";
                      }
                    }
                     html_panel += "</select></div></td></tr>";
                  }else {//se não existirem refs equivalentes
                    html_panel += "<tr><td  width='20'><div class='radio2_pop2'><input type='radio' value='2' checked='true' name='opc'  id='opc2' width='13' height='13'/></div></td>";
                    html_panel += "<td  NOWRAP><div class='p2_rad_pop2'>Desejo encomendar as " + (qts) + " unidades com o estado de</div></td>";
                    html_panel += "<td><div class='p_rad_pop2'><select name='selp' id='selp'  class='sel_pop2 txt3'>";
                     
                    for(i=0;i<=(t_estados-1);i++){
                      if(estados[i]['cod']!="" && estados[i]['cod']!=undefined){
                       html_panel += "<option value='"+ unescape(estados[i]['cod']) +"'>" + unescape(estados[i]['descpt']) + "</option>";
                      }
                    }
                    html_panel += "</select></div></td></tr>";
                  } 
                   
                  //se existirem referencias equivalentes
                  if(equivalentes==1){
                    html_panel += "<tr><td width='20'><div class='radio1_pop2'><input checked='true' type='radio' name='opc' id='opc1' width='13' height='13' value='3' onClick=\"closeRadio('selp');\" /></div></td>";
                    html_panel += "<td ><div class='p_rad_pop2'>Desejo ver as referências equivalentes</div></td></tr>";
                  }
                   
                                    
                   html_panel +="<tr><td><div><input type=\"hidden\" name=\"marca\" value='"+marca+"'>";
                   html_panel +="<input type=\"hidden\" name=\"id_cliente\" value='"+id_cliente+"'>";
                   html_panel +="<input type=\"hidden\" name=\"id_armazem\" value='"+id_armazem+"'>";
                   html_panel +="<input type=\"hidden\" name=\"id_estado\" value='"+id_estado+"'>";
                   html_panel +="<input type=\"hidden\" name=\"MINQT\" value='"+ QTMIN +"'>";
                   html_panel +="<input type=\"hidden\" name=\"stock\" value='0'>";
                   html_panel +="<input type=\"hidden\" name=\"csv_prods\" id=\"csv_prods\" value='"+prods+"'></div></td></tr>";
                   html_panel += "<tr><td colspan='3'><div class='div_opc_pop'><input type='submit' value='' class='bt_add'/></div><div class='ou'>ou</div><div class='ver_enc'><a href='javascript:void(0);' onclick=\"document.getElementById('fundo_opaco').style.display='none';panel2.destroy();\">Fechar janela</a></div></td></tr>";
                   html_panel += "</table></form>";
                  
                  document.getElementById('fundo_opaco').style.display=''; 
                   
                  panel = show_panel(tit,html_panel);
                  panel.show();	
                
                  var obj_qt = document.getElementById('qt_' + refs);
                  
                  if(obj_qt != null){
                    obj_qt.style.border = "1px solid #FF0000";
                  }
                  
                }else if(resultado=='3'){//se não existir stock suficiente
                  
                  var  tit = "Quantidade Inexistente";
                  var html_panel = "<form enctype='application/x-www-form-urlencoded' action='index.php?id=55' name='frm_carrinho_split' id='frm_carrinho_split' method='post'   onsubmit='return carrinho(this);' >";
                  html_panel += "<table cellpadding='0' cellspacing='0' border='0'>";
                  html_panel += "<tr><td colspan='3'><div style='padding:6px 0 0 6px;'><p>A Quantidade da Referência ( <b>" + refs + "</b> ) existente em  stock é de <b>" + stock + " unidades</b><p></div></td></tr>";
                  
                   if(QTMIN>0 && stock<QTMIN){
                      html_panel +="<tr><td colspan='3' height='8'></td></tr>";
                      html_panel +="<tr><td colspan='3'><div style='padding:0px 0px 0px 6px;'><p>No entanto, este artigo está sujeito a uma <b>quantidade mínima</b> de encomenda de múltiplos de <b>" + QTMIN + " unidades</b> .</p></div></td></tr>";
                      html_panel +="<tr><td colspan='3' height='5'></td></tr>";
                   }
                
                  if(QTMIN>0 && stock<QTMIN)
                    html_panel += "<tr><td colspan='3'><div ><p class='p_pop2' style='padding-top:2px;'>O que pretende fazer ?<p></div>";
                  else
                    html_panel += "<tr><td colspan='3'><div ><p class='p_pop2'>O que pretende fazer com as restantes " + (qts-stock) + " unidades?<p></div>";
                    
                    
                    html_panel += "<tr><td width='20'><div ><input checked='true' type='radio' name='opc' id='opc1' width='13' height='13' value='0' onClick=\"closeRadio('selp');\" /></div></td>";
                    html_panel += "<td><p>Apenas desejo encomendar " + stock + " unidades.</p></td></tr>";
                    
                  if(QTMIN>0 && stock<QTMIN)  
                    html_panel += "<tr><td  width='20'><div ><input type='radio' value='4' onClick=\"trocaRadios('selp');\" name='opc'  id='opc2' width='13' height='13'/></div></td>";
                  else  
                    html_panel += "<tr><td  width='20'><div ><input type='radio' value='1' onClick=\"trocaRadios('selp');\" name='opc'  id='opc2' width='13' height='13'/></div></td>";
                    
                    if(QTMIN>0 && stock<QTMIN)
                      html_panel += "<td NOWRAP ><p>Desejo encomendar  " + (((Math.ceil((qts)/QTMIN))*QTMIN)) + " unidades com o estado de</p></td>";
                    else
                      html_panel += "<td NOWRAP ><p>Desejo encomendar as restantes " + (qts-stock) + " com o estado de</p></td>";
                     
                    html_panel += "<td><div><select name='selp' id='selp' disabled='disabled' class='sel_pop2 txt3'>";
                     
                    for(i=0;i<=(t_estados-1);i++){
                      if(estados[i]['cod']!="" && estados[i]['cod']!=undefined){
                       html_panel += "<option value='"+ unescape(estados[i]['cod']) +"'>" + unescape(estados[i]['descpt']) + "</option>";
                      }
                    }
                    html_panel += "</select></div></td></tr>";
                  
                   /*if(QTMIN>0 && stock<QTMIN){
                      html_panel +="<tr><td colspan='3' height='10'></td></tr>";
                      html_panel +="<tr><td colspan='3'><div><p><span style='color:red;'>*</span> Artigo sujeito a quantidade minima.</p></div></td></tr>";
                      html_panel +="<tr><td colspan='3' height='5'></td></tr>";
                   }*/
                   
                   html_panel +="<tr><td><div><input type=\"hidden\" name=\"marca\" value='"+marca+"'>";
                   html_panel +="<input type=\"hidden\" name=\"id_cliente\" value='"+id_cliente+"'>";
                   html_panel +="<input type=\"hidden\" name=\"id_armazem\" value='"+id_armazem+"'>";
                   html_panel +="<input type=\"hidden\" name=\"id_estado\" value='"+id_estado+"'>";
                   html_panel +="<input type=\"hidden\" name=\"stock\" value='"+stock+"'>";
                   html_panel +="<input type=\"hidden\" name=\"MINQT\" value='"+ QTMIN +"'>";
                    
                   html_panel +="<input type=\"hidden\" name=\"csv_prods\" id=\"csv_prods\" value='"+prods+"'></div></td></tr>";
                   html_panel += "<tr><td colspan='3'><div class='div_opc_pop'><input type='submit' value='' class='bt_add'/></div><div class='ou'>ou</div><div class='ver_enc'><a href='javascript:void(0);' onclick=\"document.getElementById('fundo_opaco').style.display='none';panel2.destroy();\">Fechar janela</a></div></td></tr>";
                   html_panel += "</table></form>";
                   
                  document.getElementById('fundo_opaco').style.display=''
                   
                  panel = show_panel(tit,html_panel);
                  panel.show();	
                
                
                }else if(resultado=='4'){ //se a quantidade tiver sido enviada a zero
                  
                  var  tit = "Produto não foi adicionado";
                  var html_panel = "<p style='padding:6px 0 0 6px;'>Referência ( <b>"+ refs +"</b> ) não foi adicionada.<br>Insira a quantidade do produto que pretende adquirir.</p><div class='div_opc_pop' id=hide2><div class='bt_close' onclick=\"removeDIV('body','panel2_c');document.getElementById('fundo_opaco').style.display='none';\" ></div><div class='ver_enc'></div><div class='clear'></div></div>";
                  
                  document.getElementById('fundo_opaco').style.display=''
                                    	 
                  panel = show_panel(tit,html_panel,416);
                  panel.show();		
                  
                  
                  
                }else if(resultado==''){ //se não tiver sido adicionado
                  
                  var  tit = "Produto não foi adicionado";
                  var html_panel = "<p style='padding:6px 0 0 6px;'>Referência ( <b>"+ refs +"</b> ) não foi adicionada.</p><div class='div_opc_pop' id=hide2><div class='bt_close' onclick=\"removeDIV('body','panel2_c');document.getElementById('fundo_opaco').style.display='none';\" ></div><div class='ver_enc'></div><div class='clear'></div></div>";
                  
                  document.getElementById('fundo_opaco').style.display=''
                  	 
                  panel = show_panel(tit,html_panel,416);
                  panel.show();		
                  
                }
                
            }
        }
      }
     
      xmlhttp.send(params);
      return false;
    
    }catch (e){
      alert("Não foi possivel adicionar ao carrinho:\n" + e.toString());
      return false;
    }
  }else {
    return true;
  }
}


//Função de carrinho de compras
function carrinho_split(form){
  if (xmlhttp)
  {
    // tenta estabelecer ligação
    try
    {
      /*
      var serverPage="carrinho_actions.php";
     
      var params = "action=add_split&prod=" + prod + "&marca=" + marca + "&id_cliente=" + id_cliente + "&id_armazem=" + id_armazem + "&id_estado=" + id_estado + "&stock=" + stock + "&add_ref=" + refs + "&qts=" + qts;
      
      xmlhttp.open("POST", serverPage,true);
      
      //Send the proper header information along with the request
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xmlhttp.setRequestHeader("Content-length", params.length);
      xmlhttp.setRequestHeader("Connection", "close");
      
      xmlhttp.onreadystatechange = function() {//Chama a função quando o estado mudar
        if(xmlhttp.readyState == 1 ) {
                //
        }else if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            if(xmlhttp.responseText){
                var resultado = xmlhttp.responseText;
                
                
            }
        }
      }
      xmlhttp.send(params);*/
      return false;
    
    }catch (e){
      alert("Não foi possivel adicionar ao carrinho:\n" + e.toString());
      return false;
    }
  }else {
    return true;
  }
}


//Função de carrinho de compras
function remove_carrinho(ref,id_estado,id_cliente,marca){
  if (xmlhttp)
  {
    // tenta estabelecer ligação
    try
    {
      
      var confirmacao = window.confirm("Tem a certeza que deseja remover produto do carrinho de compras?", "");
      
      if(confirmacao){
      
      
        var serverPage="carrinho_actions.php";
        
        var params = "action=remove&ref=" + ref + "&marca=" + marca + "&id_cliente=" + id_cliente + "&id_estado=" + id_estado;
        
        xmlhttp.open("POST", serverPage,true);
        
        //Send the proper header information along with the request
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.setRequestHeader("Content-length", params.length);
        xmlhttp.setRequestHeader("Connection", "close");
        
        xmlhttp.onreadystatechange = function() {//Chama a função quando o estado mudar
          if(xmlhttp.readyState == 1 ) {
                
          }else if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
              
              if(xmlhttp.responseText){
                  var resultado = xmlhttp.responseText;
                  var panel;
                  if(parseInt(resultado)==1){
                    
                    var  tit = "Produto removido com sucesso";
                    var html_panel = "<p style='padding:6px 0 0 6px;'>Referência ( <b>"+ ref +"</b> ) removida com sucesso da sua encomenda</p><div class='div_opc_pop' id=hide2><div class='bt_close' onclick=\"removeDIV('body','panel2_c')\" ></div><div class='clear'></div></div>";
                    	 
                    panel = show_panel(tit,html_panel);
                    //panel.show();		
                    
                    var mnEncomenda = document.getElementById('mn_encomenda');
                    if(mnEncomenda!=null){
                      //mnEncomenda.style.display='';
                      //mn_encomenda(id_cliente);
                      Effect.Appear("mn_encomenda", { duration: 2.0,from:0.8,to:1,afterFinishInternal:function (){
          						  mn_encomenda(id_cliente);
          						 
          					  }});
                    }
                    
                    var linha_carrinho = document.getElementById('refC_' + ref + "_" + id_estado);
                    if(linha_carrinho!=null){
                      removeDIV('frm_carrinho','refC_' + ref + "_" + id_estado);
                    }
                    
                     //actuliza dados (total)
                    actualiza_dados(id_cliente);
                    
                  }else if(parseInt(resultado)==2){
                    
                    window.location='index.php?id=55';
                   
                  } else if(parseInt(resultado)==0){
                    var  tit = "Produto não foi removido";
                    var html_panel = "<p style='padding:6px 0 0 6px;'>Referência ( <b>"+ ref +"</b> ) não foi removida da sua encomenda.Por favor tente novamente.</p><div class='div_opc_pop' id=hide2><div class='bt_close' onclick=\"removeDIV('body','panel2_c')\" ></div><div class='clear'></div></div>";
                    	 
                    panel = show_panel(tit,html_panel);
                    panel.show();	
                  }
                 
                  
              }
          }
        }
        xmlhttp.send(params);
        return false;
      }else {
        return false;
      }
    
    }catch (e){
      alert("Não foi possivel adicionar ao carrinho:\n" + e.toString());
      return false;
    }
  }else {
    return true;
  }
}

//Função de remoção do carrinho de compras
function remove_all(){
  if (xmlhttp)
  {
    // tenta estabelecer ligação
    try
    {
      
      var confirmacao = window.confirm("Tem a certeza que deseja remover todos os produtos do carrinho de compras?", "");
      
      if(confirmacao){
      
      
        var serverPage="carrinho_actions.php";
        
        //var params = "action=remove_all&id_cliente=" + id_cliente;
        var params = "action=remove_all";
        
        xmlhttp.open("POST", serverPage,true);
        
        //Send the proper header information along with the request
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.setRequestHeader("Content-length", params.length);
        xmlhttp.setRequestHeader("Connection", "close");
        
        xmlhttp.onreadystatechange = function() {//Chama a função quando o estado mudar
          if(xmlhttp.readyState == 1 ) {
                
          }else if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
              
              if(xmlhttp.responseText){
                  var resultado = xmlhttp.responseText;
                  var panel;
                  if(resultado=='1'){
                    
                    window.location='index.php?id=55';
                    
                  }else {
                    var  tit = "Produtos não foram removidos";
                    var html_panel = "<p style='padding:6px 0 0 6px;'>Os produtos não foram removidos da sua encomenda.Por favor tente novamente.</p><div class='div_opc_pop' id=hide2><div class='bt_close' onclick=\"removeDIV('body','panel2_c')\" ></div><div class='clear'></div></div>";
                    	 
                    panel = show_panel(tit,html_panel);
                    panel.show();	
                  }
                 
                  
              }
          }
        }
        xmlhttp.send(params);
        return false;
      }else {
        return false;
      }
    
    }catch (e){
      alert("Não foi possivel adicionar ao carrinho:\n" + e.toString());
      return false;
    }
  }else {
    return true;
  }
}
var total_items ;
//Função de remoção do carrinho de compras
function convertOrcamento(form){
  
    // tenta estabelecer ligação
    try
    {
      
      if(total_items>0){
      
        var confirmacao = window.confirm("Todos os produtos que se encontram actualmente no seu carrinho de compras serão eliminados?\n Confirma que deseja converter o orçamento seleccionado numa encomenda?", "");
        
        if(confirmacao){
        
          form.submit();
          
          return true;
        }else {
          return false;
        }
      }else {
         form.submit();
      }
    }catch (e){
      alert("Não foi possivel adicionar ao carrinho:\n" + e.toString());
      return false;
    }
 
}

function mn_encomenda(cod_quiter){
  if (xmlhttp)
  {
    // tenta estabelecer ligação
    try
    {
    var serverPage="mn_encomenda.php";
    var obj = document.getElementById('mn_enc');
    
    var params = "ajx=1&cod_quiter=" + cod_quiter;
      
      xmlhttp.open("POST", serverPage,true);
      
      //Send the proper header information along with the request
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xmlhttp.setRequestHeader("Content-length", params.length);
      xmlhttp.setRequestHeader("Connection", "close");
      
      xmlhttp.onreadystatechange = function() {//Chama a função quando o estado mudar
        if(xmlhttp.readyState == 1 ) {
            obj.innerHTML="<div class='encomenda' id='mn_encomenda'><h1><img border='0' title='ENCOMENDA' alt='ENCOMENDA' src='sysimages/tit_encomenda.gif'></h1><div class='linemenu2'></div><div class='caixa_encomenda' align='center' ><div style='padding-top:25px;'><img src='./sysimages/ajax-loader.gif' border='0' ></div></div></div>";
        }else if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            if(xmlhttp.responseText){
                var resultado = xmlhttp.responseText;
                if(obj!=null){
                	obj.innerHTML = resultado;
				        }
            }
        }
      }
      xmlhttp.send(params);
      return false;
    
    }catch (e){
      alert("Não foi possivel adicionar ao carrinho:\n" + e.toString());
      return false;
    }
  }
}
//actualiza dados referentes ao total,subtotal,descontos,etc quando é feita uma remoção de um produto do carrinho
function actualiza_dados(cod_quiter){
  if (xmlhttp)
  {
    // tenta estabelecer ligação
    try
    {
    var serverPage="actualiza_dados.php";
    
    var obj0 = document.getElementById('loader_actualizar1');
    var obj1 = document.getElementById('total_carrinho1');
    var obj2 = document.getElementById('subtotal1');
    var obj3 = document.getElementById('total_portes1');
    var obj4 = document.getElementById('total_descontos1');
    var obj5 = document.getElementById('total_taxas1');
    var obj6 = document.getElementById('total_iva1');
    
    
    var params = "cod_quiter=" + cod_quiter;
      
      xmlhttp.open("POST", serverPage,true);
      
      //Send the proper header information along with the request
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xmlhttp.setRequestHeader("Content-length", params.length);
      xmlhttp.setRequestHeader("Connection", "close");
      
      xmlhttp.onreadystatechange = function() {//Chama a função quando o estado mudar
        if(xmlhttp.readyState == 1 ) {
            if(obj0!=null){
              obj0.style.display='';
              obj0.innerHTML="<div ><img src='./sysimages/ajax-loader.gif' border='0' ></div>";
            }
            
        }else if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            if(xmlhttp.responseText){
                var resultado = xmlhttp.responseText;
                
                if(obj1!=null && obj2!=null && obj3!=null && obj4!=null && obj5!=null && obj6!=null){
                  obj0.style.display='none';
                  
                  resultado = resultado.split("|**|");
                  //alert(resultado);
                	obj1.innerHTML = resultado[0]+ " €";
                	obj6.innerHTML = resultado[1]+ " €";
                	obj2.innerHTML = resultado[2]+ " €";
                	obj3.innerHTML = resultado[3]+ " €";
                	obj4.innerHTML = resultado[4]+ " €";
                	obj5.innerHTML = resultado[5]+ " €";
				        }
            }
        }
      }
      xmlhttp.send(params);
      return false;
    
    }catch (e){
      alert("Não foi possivel actualizar valores do carrinho:\n" + e.toString());
      return false;
    }
  }
}

function confirma_devolucao(){
  //verifica quantidade máxima (5) e minima(1) antes de permitir submeter
  var max = 5;
  var min = 1;
  
  var qt = 0;
  
  var form = document.getElementById('frm_dev');
  var t_elem = form.elements.length;
  var elem = form.elements;
  
  for(i=0;i<t_elem;i++){
    if(elem[i].className=='txt1'){
      if(elem[i].value>0){
        //qt+=elem[i].value;
        qt++;
      }
      
    }
  }
  if(qt<min){ alert('O seu número de pedidos de devolução deverá ter um minimo (' + min + ') de produtos.');return false;}
  
  if(qt>max){ alert('O seu número de pedidos de devolução (' + qt + ') excede o máximo (' + max + ') permitido.');return false;}
  
  var confirmacao = window.confirm("Tem a certeza que pretende pedir a devolução dos seguintes produtos?", "");
  if(confirmacao){
    return true;
  }else {
    return false;
  }
  
}

