var panel1;
var panel2;
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;
  
  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 removeDIV(main_elem,elem) {
  var main = document.getElementById(main_elem);
  var div = document.getElementById(elem);
  main.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;
   }


//Função de carrinho de compras
function carrinho(prod,qt,preco){



  if (xmlhttp)
  {
    // tenta estabelecer ligação
    try
    {
      
      var serverPage="carrinho_actions.php";
      
      
      var action = "add";
      
      var params = "action=" + action + "&prod_id=" + prod + "&qt=" + qt;
      
      
     
      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;
                resultado = resultado.split("|*|");
                
                var obj1 = document.getElementById("subtotal");
                var obj2 = document.getElementById("preco");
                var obj3 = document.getElementById("portes");
                var obj4 = document.getElementById("total_c");
                var obj5 = document.getElementById("taxa");
                
                obj1.innerHTML = resultado[0] + " &euro;";
                obj2.innerHTML = resultado[1] + " &euro;";
                if(obj5!=null)
                  obj5.innerHTML = resultado[2] ;
                  
                obj3.innerHTML = resultado[3] + " &euro;";
                obj4.innerHTML = resultado[4] + " &euro;";
                //alert(resultado);
                
                 var obj = document.getElementById("total_p" + prod);
                 if(obj!=null){
                    Number.prototype.formatMoney = function(c, d, t){
                    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
                       return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
                     };
                 
                    preco2 = parseFloat(qt*preco);
                    //preco2 = preco2.toFixed(2);
                    //alert(preco2);
                    //preco2 = preco2.replace(".",",");
                    preco3 =  preco2.formatMoney(2, ',', '.');

                    
                    obj.innerHTML = preco3 + " &euro;";
                 }
                
            }    
        }
      }
     
      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(prod_id){
  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&prod_id=" + prod_id;
        
        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'){
                    
                    alert("Produto removido com sucesso");	
                    window.location = window.location.href;
                    
                    
                    
                  }else {
                    alert("Não foi possivel remover o produto que solicitou.");		
                  }
                 
                  
              }
          }
        }
        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 remover do carrinho:\n" + e.toString());
      return false;
    }
  }else {
    return true;
  }
}



