// JavaScript Document
                           
                      
 $(document).ready(function()
 {
    $("#target").val('');
    jQuery("#loading_status").val('0');
    var loading_status=0;

//     switch_login_status();
    
    
    var sw=$("#page_name").val();
//     $(".discount_delivery_line, .discount_total_line").hide();
    
    //INITS
    init_buy_forms();
    init_ajax_search_form();
    init_filter_menu();
    
    $(".nyromodal").nyroModal();
    
    if(sw == "delivery")
    {
        init_transport();
    }
    
    if(sw == "pay_meth")
    {
        init_paymeth();
    }
    
    if(sw == "pay_start")
    {
        init_pay();
    }
    
    if(sw == "product_detail")
    {
        init_gal();
        tri_tab();
    }
    
    if(sw == "start_form")
    {
        init_quotation();
        $('#tabs').tabs();
        $('#tabs').bind('tabsselect', function(event, ui) 
        {
            $("#tabindex").val(ui.index);
        });
        
        $("#quotation_previous").hide();
        $("#quotation_suite").click(quotation_next_tab);
        $("#quotation_previous").click(quotation_previous_tab);
    }
    
    //UPDATES IF NEEDED
    if(sw != 'resume_quotation')
    {
      //ajouter_devise(); //ajoute la devise
      update_fields();  //totaux si necessaire
      check_prices_enabled(); //masque les prix si necessaire
    }
    
    update_mini_cart();
    
    //EVENTS LISTNERS
    $(".shop_lnk").click(ajout_panier);
    $(".add_product").click(ajout_qty);
    $(".remove_product").click(retrait_qty);
    $(".shop_table_delete a").click(retrait_panier);
    $("#shop_table_action_total_selection a").click(toggle_select_link);
    $("#check_all").click(toggle_select_input);
    $(".migc_locked").click(bloque_clic);  
    $(".qty").change(edit_qty);
    $(".shop_table_radio input").click(update_fields);
    $("#shop_next_previous_step_table_next button,#shop_next_previous_step_table_prev button").click(redirection);
    $("#shop_steps a").click(check_tab);
    $("#pagination_tab a").click(pagination);
    $(".shop_listing_object_elements_pic a").nyroModal();
    $("#quotation_form input").click(update_quotation);
    
    $("#view_cart_form").submit(view_cart_form_submit)
    $("#submit_add_coupon_disabled").click(set_coupon);
    $("#submit_form_del").click(view_cart_submit_form_del);
    
    $("#tellit a").click(click_tellit);
    //$("#quotation_form select").click(update_quotation_select);
    
    $(".page_suivante_desactivee,.page_precedente_desactivee,.previous_page_grise,.next_page_grise").hide().click(function(){return false;});
    $(".pagination_previous_page_grise a,.pagination_next_page_grise a").hide();
    
    //la catégorie n'est pas prise en compte pour une recherche
    $("#search_form button").click(function()
    {
       $("#cat").val("");
    });
    
    //changement du nbr d'élements lors d'une recherche : modifier nr et resoumettre le formulaire
    $(".page_link").click(function()
    {
         $("#nr").val($(this).attr('id'));
         
         var search_form_type=$("#pagination_tab").attr('class');
         if(search_form_type == "") { search_form_type = 'products';  }
         if(search_form_type == "products")
         {
             $(".search_form_products").submit();
             if($("#search_1").attr("value") == $("#search_1").attr("defaultvalue"))
             {
                $("#search_1").attr("value","");
             }
             return false; 
         }
         if(search_form_type == "datadirs")
         {
             $(".search_form_datadirs").submit();
             if($("#search_1").attr("value") == $("#search_1").attr("defaultvalue"))
             {
                $("#search_1").attr("value","");
             }
             return false; 
         }
        
        return false;
    });
    jQuery("#loading_status").val('1');
    
    var search_default_value=$("#search_1").attr('defaultvalue');
    if($("#search_1").val() == '')
    {
      $("#search_1").val(search_default_value);  
    }
    
    $("#search_1").focus(function()
    {
        if($("#search_1").val() == search_default_value)
        {
          $("#search_1").val('');
        }
    });
    
    $("#search_1").bind('focusout', function()
    {
        if($("#search_1").val() == '')
        {
          $("#search_1").val(search_default_value);
        }
    });
    
    
    
    
    
});


//   function init_coupons_list()
//   {
//     //READ_COOKIE
//     var cookie_coupons_json = $.JSONCookie('migc_shop_coupons');
//     var cookie_coupons_jsontext=JSON.stringify(cookie_coupons_json);
//     var cookie_coupons = eval("(" + cookie_coupons_jsontext + ")");
//     var coupons=cookie_coupons.coupons;
//     
//     //MAKE LIST
//     if(coupons != "")
//     {
//         var coupons_array = coupons.split(',');
//         var list_coupons="";
//         for(i=0;i<coupons_array.length;i++)
//         {
//             if(coupons_array[i] != 'undefined' && coupons_array[i] != '')
//             {
//                 list_coupons+='<div class="suppression_coupon" title="'+coupons_array[i]+'"><img class="del_coupon" src="../gfx/trash.gif"/> '+coupons_array[i]+'</div> ';
//             }
//         }
//         $("#list_coupon").html('<table id="table_coupons_list"><tr><td>Coupons mémorisés:</td><td>'+list_coupons+'</td></tr></table>');
//         
//         $(".suppression_coupon").click(function()
//         {
//             $(this).hide();
//             var coupon_a_supprimer=$(this).attr('title');
//             
//             //read cookie
//             var cookie_coupons_json = $.JSONCookie('migc_shop_coupons');
//             var cookie_coupons_jsontext=JSON.stringify(cookie_coupons_json);
//             var cookie_coupons = eval("(" + cookie_coupons_jsontext + ")");
//             var coupons=cookie_coupons.coupons;
//             if(coupons != '')
//             {
//               var coupons_array = coupons.split(',');
//               var new_list="";
//               
//               for(i=0;i<coupons_array.length;i++)
//               {
//                   if(coupons_array[i] != coupon_a_supprimer)
//                   {
//                       new_list+=','+coupons_array[i];
//                   }
//               }
//               cookie_coupons.coupons=new_list;
//               $.JSONCookie('migc_shop_coupons', cookie_coupons, {path: '/'});
// //               window.location='shop.pl?sw=view_cart';
// 
//               update_fields();
//             }
//         });
//     }
//   }

  function tri_tab()
  {
      
    var test_ordby=$("#product_list_crits_table #ordby_0").attr('class');
    var no_crit=$("#no_crit").val();
//     vérifie si les ordby sont en place
    if(test_ordby == undefined && no_crit !='y')
    {
        var new_tab='';
        var nb_lignes=$("#total_id_product_stocks").val();
        var first_line=$('#product_list_crits_table tr:eq(0)').html();
        
        for(i=1;i<nb_lignes+1;i++)
        {
            var new_line=$('#product_list_crits_table #ordby_'+i).html();
            if(new_line != null)
            {
               new_tab+='<tr>'+new_line+'</tr>';
            }
        }
        
        $("#product_list_crits_table").html('<tr>'+first_line+'</tr>'+new_tab);
    }
    else
    {
//       alert('ordby pas définit partout');
    }
  }
// 
  function view_cart_submit_form_del()
  {
  }

  function view_cart_form_submit()
  {
    
    if($("#coupon").val() !='')
    {
        set_coupon();
        return false;
    }
  }

  function set_coupon()
  {
     //get coupon
     var code=$("#shop_new_coupon #coupon").val();
     var lg=$("#shop_new_coupon #coupon_lg").val();
     //check coupon
    $.ajax(
    {
       type: "POST",
       url: "../cgi-bin/shop.pl",
       data: "sw=check_coupon&coupon="+code,
       success: function(msg)
       {
          if(msg == 'ok')
          {
            //add coupon to cookie
            
            //read
            var cookie_json = $.JSONCookie('migc_shop_coupons');
            var cookie_jsontext=JSON.stringify(cookie_json);
            var cookie = eval("(" + cookie_jsontext + ")");
            
            cookie.coupons=cookie.coupons+","+code;
            
            //writ
            $.JSONCookie('migc_shop_coupons', cookie, {path: '/'});   
    
             //set prices
             //set_prices();
             window.location='shop.pl?sw=view_cart';

          }
          else
          {
              alert("Le coupon "+code+" est invalide");
          }
       }
    });
     
     $("#shop_new_coupon input").val("");
     return false;
  }

 //****************************************************************************
  //CHECK TAB
  function check_tab()
  {
     if($(this).hasClass("migc_unlocked"))
     {
     
     }
     else
     {
      return false;
     }    
  }

  //****************************************************************************
  //AJOUT PANIER
  function ajout_panier()
  {
     var res = $(this).attr('id').split('-');    
     var active_form= "#product_list_crits-"+res[1];
     var sw=$("#sw").val();
     $(active_form).unbind('submit');
     $(active_form).submit(function() 
     {
          var product_coche=false;
         
          $("#product_list_crits_table input").each(function(i)
          {
                var est_coche=$("#product_list_crits_table input:eq("+i+")").attr("checked");
                var name=$("#product_list_crits_table input:eq("+i+")").attr("name");
                if(est_coche)
                {
                    product_coche=true;
                }     
          }); 
          
          
          var last_id_product_sheet=$(active_form).children('.id_product_sheet').val();
          $("#last_id_product_sheet").val(last_id_product_sheet);    
          
          var last_id_product_stock=$(active_form).children('.id_product_stock').val();
          $("#last_id_product_stock").val(last_id_product_stock);
          
          
          if(product_coche || sw == 'list')
          {
//               alert(product_coche+' '+sw);
              return true;
          }
          else
          {
              alert("Choisissez un ou plusieurs modèle(s) avant de faire l'ajout au panier");
              return false;
          }
     });
    
    
    $(active_form).submit();         
  }
  
  //****************************************************************************
  //INIT BUY FORMS
  function init_buy_forms()
  {
     
     var sw=$("#sw").val();
    $('.product_list_crits').each(function(i)
    {
        var res = $('.product_list_crits:eq('+i+')').attr('id').split('-');
        
        var active_form= "#product_list_crits-"+res[1];
//         alert(active_form);
        
        $(active_form).ajaxForm(function() 
        { 
//           alert('init ajaxform ('+sw+')');
          var product_coche=false;
         
          $("#product_list_crits_table input").each(function(i)
          {
                var est_coche=$("#product_list_crits_table input:eq("+i+")").attr("checked");
                if(est_coche)
                {
                    product_coche=true;
                }     
          }); 

          if(product_coche || sw == 'list')
          {
               //unckeck checboxes
               $(".crit").attr("checked","");
               
               
               var curr_lg = $("#lg").val();
               if(curr_lg == undefined)
               {
                curr_lg=1;
               }
               
               //init lightbox
               $.nyroModalManual({
               url: '../cgi-bin/shop.pl?sw=add_cart_lightbox&lg='+curr_lg
               });
              
              //save mini cart 
              $.ajax(
              {
                   type: "POST",
                   url: "../cgi-bin/shop.pl",
                   data: "sw=get_total_cart_ajax",
                   success: function(msg)
                   {
                       var res = msg.split('-'); 
                       var total=res[0];
                       var weight=res[1];
                       var qty=res[2];
                       var cookie_json = $.JSONCookie('migc_member');
                       var cookie_jsontext=JSON.stringify(cookie_json);
                       var cookie = eval("(" + cookie_jsontext + ")");
                       var cur='&euro; ';
                       var dlv_method = cookie.active_id_method_delivery;
                      
                      
                       if(!(dlv_method > 0))
                       {
                          dlv_method=jQuery("#default_delivery_method").val();
                       }
                   
                        save_mini_cart(qty,weight,$.sprintf('%.2f', dlv_method),$.sprintf('%.2f', total));
                  }
               });                             
              
               
               
               
          }
          else
          {
  //          alert('Cochez au moins un produit svp');
          }
          
          
        }); 
    });
    
  }
  
  function click_tellit()
  {
    var url=$("#tellit_url").val();
    var title=$("title").html();
    var lg=$("#tellit_lg").val();
    
    if(url != "")
    {
        $.nyroModalManual({
           url: '../cgi-bin/tellit.pl?sw=get_tellit_form&url='+url+'&title='+title+'&lg='+lg
           });                                                                                     
    }
    return false;
    
  }
  
  //****************************************************************************
  //AJOUT QTY
  function ajout_qty()
  {
      var up_tr = $(this).parent().parent();
      var qty = up_tr.find('.qty').val();
      var id_product_stock = up_tr.find('.qty').attr('name');
      qty++;
      if(isNaN(qty))
      {
        qty=1;
      }
      up_tr.find('.qty').val(qty);
      
      update_cookie(id_product_stock,qty);
      update_fields();
      
      return false;
  }
  
  //****************************************************************************
  //retrait QTY
  function retrait_qty()
  {
      var up_tr = $(this).parent().parent();
      var qty = up_tr.find('.qty').val();
      var id_product_stock = up_tr.find('.qty').attr('name');

      qty--;

      if(isNaN(qty))
      {
        qty=1;
      }
      
      if(qty >= 1)
      {
       up_tr.find('.qty').val(qty);
        update_fields();
        update_cookie(id_product_stock,qty);
      }
      
      return false;
  }
  
  
 function check_prices_enabled()
 {
          var no_prices=$("#no_prices").val();
          
          if(no_prices == 'y')
          { 
                 //delete prices headers
                $("#shop_table_pricehtva, #shop_table_pricetvac, #shop_table_tva, #shop_table_totalhtva, #shop_table_totaltvac, #shop_table_action_total_totalhtva, #shop_table_action_total_totaltvac").html("");
                
                //delete prices td
                $(".shop_table_pricehtva, .shop_table_pricetvac, .shop_table_tva, .shop_table_tva,.shop_table_totalhtva,.shop_table_totaltvac").html("");

                $("#shop_table_action_total_col2,.shop_table_delivery, .shop_table_delivery_totalhtva, .shop_table_delivery_totaltvac ").html(" ");
         }
 }
  
  //****************************************************************************
  //UPDATE FIELDS
  function update_fields()
  {
      var cur="&euro; ";
      var transport=$("#transport_total_cart").val();
      var sw=$("#page_name").val();
      
      //DELIVERY
      if(sw == "delivery")
      {
         var id_method=$(this).attr("id");
         $(".shop_table_radio input").each(function(i)
         {       
                if($(".shop_table_radio:eq("+i+") input").attr("checked") == true)
                {
                    var nom_transport=$(".shop_table_meth_delivery_name:eq("+i+")").html();
                    
                    var prix_caddie=$("#transport_total_cart").val();
                    var prix_transport = $(".shop_table_meth_delivery_price:eq("+i+")").html();
                    
                    var reg=new RegExp("&euro; ", "g");
                    prix_caddie=prix_caddie.replace(reg,'');
                    prix_transport=prix_transport.replace(reg,'');
                    
                    var reg=new RegExp("€", "g");
                    prix_caddie=prix_caddie.replace(reg,'');
                    prix_transport=prix_transport.replace(reg,'');
                    
                    var prix_total=parseFloat(prix_caddie)+parseFloat(prix_transport);
                    id_method=$(".shop_table_radio:eq("+i+") input").attr("id");
                    $("#transport_active_name").val(nom_transport);
                                       
                    var prix_total=$.sprintf('%.2f', prix_total);
                    $("#shop_table_action_delivery_price").html(cur+' '+prix_transport);
                    $("#shop_table_action_total_price").html(cur+' '+prix_total);
                    $(".shop_table_meth_delivery_price:eq("+i+")").html(cur+' '+prix_transport);
                }
         });
         
            
          
            //read cookie
            var cookie_json = $.JSONCookie('migc_member');
            var cookie_jsontext=JSON.stringify(cookie_json);
            var cookie = eval("(" + cookie_jsontext + ")");
            
            //unlock next tab
            $("#shop_steps5 a").addClass("migc_unlocked");
            
            //update      
            cookie.active_id_method_delivery=id_method;
            
            //write cookie
            $.JSONCookie('migc_member', cookie, {path: '/'});   
      }   
      
      //PAY_METH
      if(sw == "pay_meth")
      {
         var id_method=$(this).attr("id");
         $(".shop_table_radio input").each(function(i)
          {       
                if($(".shop_table_radio:eq("+i+") input").attr("checked") == true)
                {
                    var prix_caddie=$("#transport_total_cart").val();
                    var nom_transport=$(".shop_table_meth_billing_name:eq("+i+")").html();
                    var prix_transport = $(".shop_table_meth_billing_price:eq("+i+")").html();
                    var prix_total=parseFloat(prix_caddie)+parseFloat(prix_transport);
                    id_method=$(".shop_table_radio:eq("+i+") input").attr("id");
                    $("#billing_active_name").val(nom_transport);
                }
          });
          
            //read cookie
            var cookie_json = $.JSONCookie('migc_member');
            var cookie_jsontext=JSON.stringify(cookie_json);
            var cookie = eval("(" + cookie_jsontext + ")");
            
            //update qty      
            cookie.active_id_method_billing=id_method;
            
            //write cookie
            $.JSONCookie('migc_member', cookie, {path: '/'});   
      }
      
      //PAY_START
      if(sw == "pay_start")
      {
          $(".payment_form").submit();
      }    
    
      //VIEW CART     
      if(sw == "view_cart")
      {
          
          
          var no_prices=$("#no_prices").val();
          
          
          if(no_prices != 'y')
          {    
              set_prices();
          }
          else
          {
               //VIEW CART IF PRICES ARE DISABLED
               //check_prices_enabled(); -> maintenant vérifié à chaque fois
          }
          
          var ref=$("#ref").val();
          if(ref == 'y')
          {
              
              //save mini cart 
              $.ajax(
              {
                   type: "POST",
                   url: "../cgi-bin/shop.pl",
                   data: "sw=get_total_cart_ajax",
                   success: function(msg)
                   {
                       var res = msg.split('-'); 
                       var total=res[0];
                       var weight=res[1];
                       var qty=res[2];
                       var cookie_json = $.JSONCookie('migc_member');
                       var cookie_jsontext=JSON.stringify(cookie_json);
                       var cookie = eval("(" + cookie_jsontext + ")");
                       var cur='&euro; ';
                       var dlv_method = cookie.active_id_method_delivery;
                      
                      
                       if(!(dlv_method > 0))
                       {
                          dlv_method=jQuery("#default_delivery_method").val();
                       }
                   
                        save_mini_cart(qty,weight,$.sprintf('%.2f', dlv_method),$.sprintf('%.2f', total));
                  }
               });   
          }         
       }
  }
  
  
  
  
  
  
  
  function set_prices()
  {
      var id_delivery_identity=0;
      
      var disable_discount_line_if_discount_total=$("#disable_discount_line_if_discount_total").val();
      var disable_discount_line_if_discount_delivery=$("#disable_discount_line_if_discount_delivery").val();
      
      var cookie_json = $.JSONCookie('migc_member');
      var cookie_jsontext=JSON.stringify(cookie_json);
      var cookie = eval("(" + cookie_jsontext + ")");
      var dlv_method = cookie.active_id_method_delivery;
      
      $.ajax(
      {
      type: "POST",
      url: "../cgi-bin/shop.pl",
      data: "sw=ajax_get_id_delivery_identity",
      success: function(msg)
      {
          id_delivery_identity=msg;
          
          if(disable_discount_line_if_discount_total == 'y' || disable_discount_line_if_discount_delivery == 'y')
          {
                 //get total price, qty & weight
                 $.ajax(
                  {
                       type: "POST",
                       url: "../cgi-bin/shop.pl",
                       data: "sw=get_total_cart_ajax",
                       success: function(msg)
                       {
                       var res = msg.split('-'); 
                       
                       var total_tvac=res[0];
                       var total_htva=total_tvac/1.21;
                       var total_weight=weight=res[1];
                       var qty=res[2];
                       
                        //CHECK REMISES/SUPPL POUR LE TOTAL*********************************
                        $.ajax(
                        {
                           type: "POST",
                           url: "../cgi-bin/shop.pl",
                           data: "sw=check_promo_total&render=ajax&condition_target=total&weight="+total_weight+"&dlv_meth="+dlv_method+"&total_htva="+total_htva+"&total_tvac="+total_tvac+"&id_delivery_identity="+id_delivery_identity,
                           success: function(msg_total)
                           {
                              var res = msg_total.split(',');
                              
                              var discount_delivery=res[2];
                              var discount_total_htva=res[7];
                              var discount_lines_enabled='y';
                              
                              if(discount_delivery !=0 && disable_discount_line_if_discount_delivery == 'y')
                              {
                                 discount_lines_enabled='n';                                 
                              }
                              
                              if(discount_total_htva !=0 && disable_discount_line_if_discount_total == 'y')
                              {
                                 discount_lines_enabled='n';                                 
                              }
                              set_discounts_and_total(id_delivery_identity,discount_lines_enabled);
                           }
                         }); 
                        }                  
                    });
          }
          else
          {
              set_discounts_and_total(id_delivery_identity,'y');
          }
      
      } //fin success id identity
    }); //fin ajax id identity
  }
  
  
  function set_discounts_and_total(id_delivery_identity,discount_lines_enabled)
  {
     //TOTAUX
      //retirer_devise();
      var total_htva=0;
      var total_tvac=0;
      var total_weight=0;
      var ajax_count=0;
      
      
      var cookie_json = $.JSONCookie('migc_member');
      var cookie_jsontext=JSON.stringify(cookie_json);
      var cookie = eval("(" + cookie_jsontext + ")");
      var cur='&euro; ';
      var cur2='€';
      
      var dlv_method = cookie.active_id_method_delivery;
      
      
      if(!(dlv_method > 0))
      {
        dlv_method=jQuery("#default_delivery_method").val();
      }
      
      
      var nb_elts=$("#shop_table tr.cart_line").size();
//       nb_elts--;
      
      
      //REMISES POUR CHAQUE LIGNE***********************************************
      $("#shop_table tr.cart_line").each(function(i)
      {
         
         var qty = 0;
         var weight = 0;
         
         qty = $(".shop_table_qty:eq("+i+") .td_qty input.qty").val();
         weight = $(".shop_table_qty:eq("+i+") .td_qty input.prod_weight").val();
         
         var id_product_sheet=$("#shop_table tr.cart_line:eq("+i+")").attr("id");
         id_product_sheet=id_product_sheet.replace("id_product_sheet_","");  
         
         if(qty >= 0)
         {
            var prix_htva=$(".shop_table_pricehtva:visible:eq("+i+")").html();
            var prix_tvac=$(".shop_table_pricetvac:visible:eq("+i+")").html();
            
            if(prix_htva != null)
            {
              prix_htva=prix_htva.replace(cur,"");
              prix_htva=prix_htva.replace(cur2,"");
              prix_htva=prix_htva.replace(' ',"");
              $(".shop_table_pricehtva:visible:eq("+i+")").html("€ "+prix_htva);
            }
            if(prix_tvac != null)
            {
              prix_tvac=prix_tvac.replace(cur,"");
              prix_tvac=prix_tvac.replace(cur2,"");
              rix_tvac=prix_tvac.replace(' ',"");
              $(".shop_table_pricetvac:visible:eq("+i+")").html("€ "+prix_tvac);
            } 
            
            //MULTIPLY BY QTY
            var shop_table_totalhtva=prix_htva*qty;
            var shop_table_totaltvac=prix_tvac*qty;
            
            var sstotal_htva=$.sprintf('%.2f', shop_table_totalhtva);
            var sstotal_tvac=$.sprintf('%.2f', shop_table_totaltvac);
           
            $(".shop_table_totalhtva:visible:eq("+i+")").html(cur+' '+sstotal_htva);
            $(".shop_table_totaltvac:visible:eq("+i+")").html(cur+' '+sstotal_tvac);
         }
         //alert("appel "+i);
         
         //check remise line for this id product sheet
         $.ajax(
         {
           type: "POST",
           url: "../cgi-bin/shop.pl",
           data: "sw=check_promo_line&render=ajax&qty="+qty+"&id_product_sheet="+id_product_sheet+"&condition_target=line&total_htva="+sstotal_htva+"&total_tvac="+sstotal_tvac+"&id_delivery_identity="+id_delivery_identity,
           success: function(msg_line)
           {
                              
                              //alert("recu "+i);
                              ajax_count++;
                              var res_line = msg_line.split(',');

                              var line_raw_total_htva=res_line[0];
                              var line_raw_total_tvac=res_line[1];
                              var line_detail_total=res_line[2];
                              var line_discount_total_htva=res_line[3];
                              var line_discount_total_tvac=res_line[4];
                              var line_total_htva=res_line[5];
                              var line_total_tvac=res_line[6];
                              var coupon=res_line[7];
                              
                              
                              
                               if(qty >= 0)
                               {
                                  sstotal_htva=$.sprintf('%.2f', shop_table_totalhtva);
                                  sstotal_tvac=$.sprintf('%.2f', shop_table_totaltvac);
                                  
                                  line_discount_total_htva=$.sprintf('%.2f', line_discount_total_htva);
                                  line_discount_total_tvac=$.sprintf('%.2f', line_discount_total_tvac);
                                  
                                  $(".shop_table_totalhtva:visible:eq("+i+")").html(cur+' '+sstotal_htva);
                                  $(".shop_table_totaltvac:visible:eq("+i+")").html(cur+' '+sstotal_tvac);
                                  
                                  $(".shop_table_discount_line_label:eq("+i+")").html(line_detail_total);
                                  $(".shop_table_discount_htva:eq("+i+")").html(cur+' '+line_discount_total_htva);
                                  $(".shop_table_discount_tvac:eq("+i+")").html(cur+' '+line_discount_total_tvac);
                                  
                                  $(".shop_table_promo:eq("+i+")").html('<a class="tooltip1" href="shop.pl" title="Supprimer le coupon '+coupon+'"><img alt="'+coupon+'" class="desactive_coupon" src="../usr/sources/shop/delete.png"/>');
                                  $(".shop_table_promo:eq("+i+") a").tooltip({
                                   track: true,
                                   delay: 0,
                                   showURL: false,
                                   extraClass: "right"
                                  }); 
                                  
                                  
                                  if(line_discount_total_htva !=0 && line_discount_total_htva != null && line_discount_total_htva !="" && discount_lines_enabled == 'y')
                                  {
                                    $(".shop_table_discount_line_label:eq("+i+")").parent().show();
                                  }
                                  else
                                  {
                                    $(".shop_table_discount_line_label:eq("+i+")").parent().hide();
                                  }
                                                                    
                                  if(discount_lines_enabled == 'y')
                                  {
                                      total_htva+=parseFloat(line_discount_total_htva);
                                      total_tvac+=parseFloat(line_discount_total_tvac);
                                  }

                                  total_htva+=parseFloat(sstotal_htva);
                                  total_tvac+=parseFloat(sstotal_tvac);
                                  
                                  total_weight+=parseFloat(weight*qty);                    
                               }
//                                var str=ajax_count+" == "+nb_elts+", sstotal_tvac:"+sstotal_tvac+" , total tvac:"+total_tvac;
//                                alert(str);
                               if(ajax_count == nb_elts)
                               {
                                //alert('ok');
                              //CHECK REMISES/SUPPL POUR LE TOTAL*********************************
                              $.ajax(
                              {
                                 type: "POST",
                                 url: "../cgi-bin/shop.pl",
                                 data: "sw=check_promo_total&render=ajax&condition_target=total&weight="+total_weight+"&dlv_meth="+dlv_method+"&total_htva="+total_htva+"&total_tvac="+total_tvac+"&id_delivery_identity="+id_delivery_identity,
                                 success: function(msg_total)
                                 {
                                    var res = msg_total.split(',');
                                    
                                    var raw_delivery=res[0];
                                    var delivery_label=res[1];
                                    var discount_delivery=res[2];
                                    var delivery=res[3];
                                    var raw_total_htva=res[4];
                                    var raw_total_tvac=res[5];
                                    var detail_total=res[6];
                                    var discount_total_htva=res[7];
                                    var discount_total_tvac=res[8];
                                    var total_htva=res[9];
                                    var total_tvac=res[10];  
                                    var coupon=res[11];
                                    
                                    $(".shop_table_delivery_totalhtva").html(cur+' '+$.sprintf('%.2f', delivery));
                                    $(".shop_table_delivery_totaltvac").html(cur+' '+$.sprintf('%.2f', delivery));
                                   
                                    //alert('call total cart');
                                   $.ajax(
                                    {
                                         type: "POST",
                                         url: "../cgi-bin/shop.pl",
                                         data: "sw=get_total_cart_ajax",
                                         success: function(msg)
                                         {
                                         var res = msg.split('-'); 
                                          
                                         var total=res[0];
                                         var weight=res[1];
                                         var qty=res[2];
                                          //alert('total: '+total);
                                          
                                         save_mini_cart(qty,weight,$.sprintf('%.2f', delivery),$.sprintf('%.2f', total_tvac));
//                                          $(".shop_cart_top_qty").html(qty);
//                                          $(".shop_cart_top_weight").html(weight);
//                                          $(".shop_cart_top_price").html(total);
                                         }
                                    });
                                   
                                    
                                   
                                    $("#shop_table_action_total_totalhtva").html(cur+' '+$.sprintf('%.2f', total_htva));
                                    $("#shop_table_action_total_totaltvac").html(cur+' '+$.sprintf('%.2f', total_tvac));
                                    
                                    if(discount_delivery != "" && discount_delivery != "0")
                                    {
                                        //DELIVERY************************************************************************
                                        
                                        //raw delivery;
                                        $("#discount_label_delivery_raw").html("Frais de livraison initiaux");
                                        $("#discount_delivery_raw_htva,#discount_delivery_raw_tvac").html(cur+' '+$.sprintf('%.2f', raw_delivery));
                                        
                                        //discount delivery
                                        $("#discount_label_delivery").html(delivery_label);
                                        $("#discount_delivery_htva,#discount_delivery_tvac").html(cur+' '+$.sprintf('%.2f', discount_delivery));
                                        $(".discount_delivery_line").show();
                                        
                                        
                                        $(".shop_table_delivery_coupon").html('<a class="tooltip1" href="shop.pl" title="Supprimer le coupon '+coupon+'"><img alt="'+coupon+'" class="desactive_coupon" src="../usr/sources/shop/delete.png"/>');
                                        $(".shop_table_delivery_coupon a").tooltip({
                                         track: true,
                                         delay: 0,
                                         showURL: false,
                                         extraClass: "right"
                                        });
                                    }
                                    else
                                    {
                                        $(".discount_delivery_line").hide();
                                    
                                    }
                                    
                                    if(discount_total_htva != "" && discount_total_htva != "0")
                                    {
                                        //TOTAL************************************************************************
                                        
                                        //raw total;
                                        
                                        $("#discount_label_total_raw").html("Total (livraison incluse)");
                                        $("#discount_total_raw_htva").html(cur+' '+$.sprintf('%.2f', raw_total_htva));
                                        $("#discount_total_raw_tvac").html(cur+' '+$.sprintf('%.2f', raw_total_tvac));
                                        
                                        //discount total
                                        $("#discount_label_total").html(detail_total);
                                        $("#discount_total_htva").html(cur+' '+$.sprintf('%.2f', discount_total_htva));
                                        $("#discount_total_tvac").html(cur+' '+$.sprintf('%.2f', discount_total_tvac));
                                        
                                        $(".shop_table_delivery:eq(2)").css("font-weight","bold");
                                        $(".discount_total_line").show();
                                        
                                        $(".shop_table_coupon_total").html('<a class="tooltip1" href="shop.pl" title="Désactiver le coupon '+coupon+'"><img alt="'+coupon+'" class="desactive_coupon" src="../usr/sources/shop/delete.png"/>');
                                        $(".shop_table_coupon_total a").tooltip({
                                         track: true,
                                         delay: 0,
                                         showURL: false,
                                         extraClass: "right"
                                        });
                                    }
                                    else
                                    {
                                        $(".discount_total_line").hide();
                                    }
                                    
                                    //init clic to del coupon
                                    $(".desactive_coupon").click(function()
                                          {
                                             var coupon_a_supprimer=$(this).attr('alt');
                                             if(coupon_a_supprimer != undefined)
                                             {
                                                //read cookie
                                                var cookie_coupons_json = $.JSONCookie('migc_shop_coupons');
                                                var cookie_coupons_jsontext=JSON.stringify(cookie_coupons_json);
                                                var cookie_coupons = eval("(" + cookie_coupons_jsontext + ")");
                                                var coupons=cookie_coupons.coupons;
                                                if(coupons != '')
                                                {
                                                  var coupons_array = coupons.split(',');
                                                  var new_list="";
                                                  
                                                  for(i=0;i<coupons_array.length;i++)
                                                  {
                                                      if(coupons_array[i] != coupon_a_supprimer)
                                                      {
                                                          new_list+=','+coupons_array[i];
                                                      }
                                                  }
                                                  cookie_coupons.coupons=new_list;
                                                  $.JSONCookie('migc_shop_coupons', cookie_coupons, {path: '/'});
                                                  update_fields();
                                                }
                                             }
                                             return false;                                    
                                          }                                     
                                        );
                                    
                                    update_mini_cart();      
                                 }
                               });
                            }
                            
                            
                            
                 } // fin success pour le traitement d'une ligne
             }); //fin ajax 
      }); //fin each
  
  
  }
  
  
  
  //****************************************************************************
  //retrait QTY
  function update_cookie(id_product_stock_r,qty_r)
  {
      //read cookie
      var cookie_json = $.JSONCookie('migc_shop');
      var cookie_jsontext=JSON.stringify(cookie_json);
      var cookie = eval("(" + cookie_jsontext + ")");
      
      var id_product_stock=id_product_stock_r;
      var qty=qty_r;
      
//       alert(id_product_stock+' '+qty);
      
      
      //update qty      
      mavar = eval("cookie."+id_product_stock);
      
//       alert(mavar);
      
      
      mavar.qty=qty;
      
      //write cookie
      $.JSONCookie('migc_shop', cookie, {path: '/'});   
  }
  
  //****************************************************************************
  //retrait panier
  function retrait_panier()
  {
      var id_product_stock=$(this).attr('id');
      
      //update field & cookie
      $(this).parent().parent().html("").hide();
      $(this).parent().parent().next().html("").hide();

      
//       update_fields();
      update_cookie('ips_'+id_product_stock,0);
      window.location = "shop.pl?sw=view_cart&ref=y";
      
      return false;
        
  }
  
  
  //****************************************************************************
  //(de)coche les chechboxes du panier
  function toggle_select_link()
  {
      if($("#check_all").attr("checked") == true)
      {
            $(".cart_line input").attr("checked","");
            $("#check_all").attr("checked","");
      }
      else
      {
            $(".cart_line input").attr("checked","checked");
            $("#check_all").attr("checked","checked");
      }
      
      if($(this).attr('id') != 'check_all')
      {
           return false;
      }
      else
      {
            if($(".cart_line input").attr("checked") == true)
            {
                 $("#check_all").attr("checked","checked");
            }
            else
            {
                $("#check_all").attr("checked","");
            }
      }
  }
  
  //****************************************************************************
  //(de)oche les chechboxes de la lightbox
  function toggle_select_link_lightbox()
  {
      if($("#check_all_lightbox").attr("checked") == true)
      {
            $(".shop_table_checkbox input").attr("checked","");
            $("#check_all_lightbox").attr("checked","");
      }
      else
      {
            $(".shop_table_checkbox input").attr("checked","checked");
            $("#check_all_lightbox").attr("checked","checked");
      }
      
      if($(this).attr('id') != 'check_all_lightbox')
      {
           return false;
      }
      else
      {
            if($(".shop_table_checkbox input").attr("checked") == true)
            {
                 $("#check_all_lightbox").attr("checked","checked");
            }
            else
            {
                $("#check_all_lightbox").attr("checked","");
            }
      }
  }
  //****************************************************************************
  //(de)coche les checkboxes
  function toggle_select_input()
  {
     if($("#check_all").attr("checked") == true)
     {
        $(".cart_line input").attr("checked","checked");
     }
     else
     {
        $(".cart_line input").attr("checked","");
     }
  }
  
  //****************************************************************************
  //(de)coche les chechboxes de la lightbox
  function toggle_select_input_lightbox()
  {
     if($("#check_all_lightbox").attr("checked") == true)
     {
        $(".shop_table_checkbox input").attr("checked","checked");
     }
     else
     {
        $(".shop_table_checkbox input").attr("checked","");
     }
  }
  
  
  //****************************************************************************
  //EDIT QTY
  function edit_qty()
  {
      var id_product_stock=$(this).attr("name");
      var qty=$(this).val();
      
      qty=parseInt(qty);
      $(this).val(qty);
      
      if(isNaN(qty) || qty == 0)
      {
        qty=1;
        $(this).val(qty);
      }
            
     
      update_cookie(id_product_stock,qty);  
      update_fields();
  }
  
  //****************************************************************************
  //Delete saved caert
  function delete_saved_cart()
  {
        var id_order=$(this).attr("id");
        
        $.ajax({
           type: "POST",
           url: "../cgi-bin/shop.pl",
           data: "sw=del_saved_cart&id_order="+id_order,
           success: function(msg){
             $("#menu"+id_order).hide();
             $(".submenu"+id_order).hide();
           }
         });
            
        return false;
  }
  
  //****************************************************************************
  //REDIRECTION
  //****************************************************************************
  
function redirection()
  {
      var page=$(this).attr('id');
      var lg=$("#lg").val();
      
      if(lg == undefined)
      {
        lg=$("#current_language").val();
      }

//       alert(page);
      if(page == "view_cart")
      {
          window.location = "shop.pl?sw=view_cart&lg="+lg;
          return false;          
      }
            
      if(page == "view_sub_forms")
      {
          window.location = "subscriptions.pl?&lg="+lg;
          return false;          
      }
      if(page == "view_forms")
      {
          window.location = "bill_and_delivery.pl?&lg="+lg;
          return false;          
      }
      if(page == "delivery")
      {
          window.location = "shop.pl?sw=delivery&lg="+lg;
          return false;          
      }
      if(page == "pay_meth")
      {
          window.location = "shop.pl?sw=pay_meth&lg="+lg;
          return false;          
      }
      if(page == "recap_cart")
      {
          window.location = "shop.pl?sw=recap_cart&lg="+lg;
          return false;          
      }
      if(page == "pay_start" || page == "INUTILISE_pay_start")
      {
          window.location = "shop.pl?sw=make_order_db&lg="+lg;
          return false;          
      }
      if(page == "finish_order")
      {
          //read cookie MEMBER
          var cookie_json = $.JSONCookie('migc_member');
          var cookie_jsontext=JSON.stringify(cookie_json);
          var cookie = eval("(" + cookie_jsontext + ")");
          var id_method_billing=cookie.active_id_method_billing;
          
          //read cookie ORDER
          var cookie_json = $.JSONCookie('migc_shop_order');
          var cookie_jsontext=JSON.stringify(cookie_json);
          var cookie_order = eval("(" + cookie_jsontext + ")");
          
          var id_method_billing=cookie.active_id_method_billing;
          var id_order=cookie_order.id_order;
          
          if(id_order >0)
          {
          
          }
          else
          {
              id_order=$("#id_order").val();
          }
          
          
          //record id method submit
          $.ajax({
           type: "POST",
           url: "../cgi-bin/shop.pl",
           data: "sw=meth&id_order="+id_order+"&id_meth="+id_method_billing+"&lg="+lg,
           success: function(msg)
           {
              //alert(msg);
              if(msg == 'ok')
              {
              //submit form
              $("#payment_method_"+id_method_billing).submit();
              }
           }
         });
      }
  }
   
  
  
  //****************************************************************************
  //INITS
  //****************************************************************************
  
  
  //****************************************************************************
  //init_transport
  function init_transport()
  {
    var active_id=$("#active_id_method_delivery").val();
    if(active_id == undefined || active_id=="") 
    { 
        $(".shop_table_radio:first input").attr("checked","checked");
    }
    else
    {
       $(".shop_table_radio #"+active_id).attr("checked","checked");
    }
  }
  
  //****************************************************************************
  //init_transport
  function init_paymeth()
  {
    var active_id=$("#active_id_method_billing").val();
    if(active_id == undefined || active_id=="") 
    { 
        $(".shop_table_radio:first input").attr("checked","checked");
    }
    else
    {
       $(".shop_table_radio #"+active_id).attr("checked","checked");
    }
  }
  
  //****************************************************************************
  //init pay start
  function init_pay()
  {
    var active_id=$("#active_id_method_billing").val();
    if(active_id == undefined || active_id=="") 
    { 
        $(".shop_table_radio:first input").attr("checked","checked");
    }
    else
    {
       $(".shop_table_radio #"+active_id).attr("checked","checked");
    }
  }
  
   function bloque_clic()
  {
    return false;
  }
  
  
  //****************************************************************************
  //INIT QUOTATION
  function init_quotation()
  {
    $("#tabindex").val('0');
    
    var quotation_values_width=$("#quotation_values_width").val();
    var quotation_values_height=$("#quotation_values_height").val();
    var quotation_values=$("#quotation_values").val();
    var quotation_nbelt_width=$("#quotation_nbelt_width").val();
    var quotation_nbelt_height=$("#quotation_nbelt_height").val();
    $("#quotation_zone_button").append('<div id="msg_quotation" style="text-align:right; color:red; padding-right:18px;">Message</div>');
    
    var labels_line1="";
    var labels_line2="";

    var labels1 = $("#labels1").html().split(',');
    var labels2 = $("#labels2").html().split(',');
    
    for ( var i=0, len=labels1.length; i<len; ++i )
    {
        labels_line1+=mes1_indices[labels1[i]]+', ';
    }
    for ( var i=0, len=labels2.length; i<len; ++i )
    {
        labels_line2+=mes2_indices[labels2[i]]+', ';
    }
    $("#labels1").html(labels_line1);
    $("#labels2").html(labels_line2);
    
    quotation_nbelt_width--;
    quotation_nbelt_height--;
    
    var quotation_array_heights = eval("new Array("+quotation_values_height+")");
    var quotation_array_widths = eval("new Array("+quotation_values_width+")");
    var quotation_array_values = eval("new Array("+quotation_values+")");                
    var default_mes1=$("#measure_1_default").val();
    
    // Init Sliders
    $('#slider_height').slider({
      min:0,
      max:quotation_nbelt_height,
			change: function(event, ui) 
      {
          $("#amount_height").val(mes2_indices[quotation_array_heights[ui.value]]);
          $("#quotation_height").html(mes2_indices[quotation_array_heights[ui.value]]);
          
          var step_height=quotation_array_heights[$("#slider_height").slider("value")];
     	    var step_width=quotation_array_widths[$("#slider_width").slider("value")];
          
          edit_base_price(step_width,step_height);
          update_quotation();
      
			},
			slide: function(event, ui)
      {
          $("#amount_height").val(mes2_indices[quotation_array_heights[ui.value]]);
          $("#quotation_height").html(mes2_indices[quotation_array_heights[ui.value]]);
  		}
		});
		
		$('#slider_width').slider({
      min:0,
      max:quotation_nbelt_width,
      value: default_mes1,
			change: function(event, ui) 
      {
          $("#amount_width").val(mes1_indices[quotation_array_widths[ui.value]]);
          $("#quotation_width").html(mes1_indices[quotation_array_widths[ui.value]]);
          
          var step_height=quotation_array_heights[$("#slider_height").slider("value")];
    	    var step_width=quotation_array_widths[$("#slider_width").slider("value")];
          
          edit_base_price(step_width,step_height);
          update_quotation();  
			},
			slide: function(event, ui) 
      {
          $("#amount_width").val(mes1_indices[quotation_array_widths[ui.value]]);
          $("#quotation_width").html(mes1_indices[quotation_array_widths[ui.value]]);
			}
		});
		
		var step_height=quotation_array_heights[$("#slider_height").slider("value")];
	  var step_width=quotation_array_widths[$("#slider_width").slider("value")];
    edit_base_price(step_width,step_height);
    update_quotation();
   
    $("#amount_height").val(mes2_indices[step_height]);
		$("#quotation_height").html(mes2_indices[step_height]);
		
		$("#quotation_width").html(mes1_indices[step_width]);
		//$("#amount_width").val(mes1_indices[step_width]);
		
		
    update_quotation(); 
    $("#quotation_end").hide();
  }
  
  //****************************************************************************
  //UPDATE QUOTATION SELECT HIDDEN VALUE FROM OPTION
 // function update_quotation_select()
 // {
 //     var cet_id=$(this).attr('id');
 //     var cette_option=$("#"+cet_id+" option:selected").attr('id');
 //     $("#"+cet_id).attr('title',cette_option);
 //     
 //     update_quotation();
 //    
 // }
  
  //****************************************************************************
  //PAGINATION
  function pagination()
  {
    var num=$(this).html();
    
    if(num>0)
    {
      
    }
    else
    {
        var num=$(this).attr('id');
    }
    //check search form presence
    var test=$("#search_form").attr('id');
    if(test)
    { 
        $(".num_page").val(num);
        $("#search_mode").val("pagination");
        
        var search_form_type=$("#pagination_tab").attr('class');
        if(search_form_type)
        {
             if(search_form_type == "products")
             {
                 if($("#search_1").attr("value") == $("#search_1").attr("defaultvalue"))
                 {
                    $("#search_1").attr("value","");
                 }
                 $(".search_form_products").submit();
                 return false; 
             }
             if(search_form_type == "datadirs")
             {
                 if($("#search_1").attr("value") == $("#search_1").attr("defaultvalue"))
                 {
                    $("#search_1").attr("value","");
                 }
                 $(".search_form_datadirs").submit();
                 return false; 
             }
        }
        else
        {
             $("#search_form").submit();
            return false;
        }
    }   
    else
    {
      return true;
    }
 }
 

  //****************************************************************************
  //update quotation
  function update_quotation()
  {
      var total_base=parseFloat($("#quotation_total_base").html());
      var total_money=0;
      var total_perc=0;
      
      //total money
//       $('.elt_money').each(function(i)
//       {
//           var elt_money = $('.elt_money:eq('+i+')').attr('title');
//           var est_coche = $('.elt_money:eq('+i+')').attr('checked');
//           if(est_coche)
//           {
//             total_money=total_money+parseFloat(elt_money);
//           }
//       });

      
      var count=$("#count").val();
      for(var u=0;u<count;u++)
      {
          var elt=$('#elt_money'+u);
          var elt_money = elt.attr('title');
          var est_coche = elt.attr('checked');
          if(est_coche)
          {
            total_money=total_money+parseFloat(elt_money);
          }
      }      
      
      //total perc
      $('.elt_perc').each(function(i)
      {
          var elt_perc = $('.elt_perc:eq('+i+')').attr('title');
          var est_coche = $('.elt_perc:eq('+i+')').attr('checked');
          if(est_coche)
          {
              total_perc=total_perc+parseFloat(elt_perc);
          }
      });
      
      
      total_net=$.sprintf('%.2f',(total_base+total_money)*(1+parseFloat(total_perc)/100));
      total_money=$.sprintf('%.2f', total_money);
      total_perc=$.sprintf('%.2f', total_perc);
      
      $("#quotation_total_money").html(total_money);
      $("#quotation_total_perc").html(total_perc); 
      $("#quotation_total_net").html(total_net);
      
      
      
  }
  
  function quotation_next_tab()
  {
      var index=$("#tabindex").val();
      var maxtabindex=$("#maxtabindex").val();
      
//       alert(index+' / '+maxtabindex);
      
      
      
      index++;
      
      if(index == maxtabindex)
      {
        $("#quotation_previous").show();
        $("#quotation_suite").hide();
        $("#quotation_end").show();
      }
      else
      { 
        $("#quotation_previous").show();
        $("#quotation_suite").show();
        $("#quotation_end").hide();
      }
      
      //alert(index+' / '+maxtabindex);
      
      if(index > maxtabindex)
      {
        index=0;
      }
      
      //alert(index+' / '+maxtabindex);
      
      $("#tabindex").val(index);
      $("#tabs").tabs( 'select' , index);  
      return false;
  }
  
  
 
  function init_gal()
  {
          $("#gal_next,#gal_prev").hover(function(){$('.jquery_gal_1').cycle("pause")},function(){$('.jquery_gal_1').cycle("resume")}); 
          
          
          $('.jquery_gal_1').cycle(
          { 
          fx:    'fade', 
          speed:  2000,
          pause : 1,
          pager: "#nav",
          next:   '#gal_next', 
          prev:   '#gal_prev',
          pauseOnPagerHover: 1,
          fit:1
          }
          );
          
          var nb_img=0;
           $('.jquery_gal_1 .pic_detail').each(function(i)
           {
              nb_img++;
           });
         if(nb_img < 2)
         {
            $('#gal_next, #gal_prev').hide();
         } 
        
 }
    
  
  function quotation_previous_tab()
  {
      var index=$("#tabindex").val();
      var maxtabindex=$("#maxtabindex").val();
      
//       alert(index+' / '+maxtabindex);
      
      index--;
      
//       alert(index+' / '+maxtabindex);
      
      
      if(index == 0)
      {
        $("#quotation_suite").show();
        $("#quotation_previous").hide();
        $("#quotation_end").hide();
      }
      else
      { 
        $("#quotation_suite").show();
        $("#quotation_previous").show();
        $("#quotation_end").hide();
      }
      
      
      if(index < 0 )
      {
        index=maxtabindex;                   
      }
      
//       alert(index+' / '+maxtabindex);
      $("#tabindex").val(index);
      $("#tabs").tabs( 'select' , index);  
      return false;
  }
  
  
  function save_mini_cart(qty,weight,delivery,total_tvac)
  {
      //read cookie
      var cookie_json = $.JSONCookie('migc_shop_minicart');
      var cookie_jsontext=JSON.stringify(cookie_json);
      var cookie = eval("(" + cookie_jsontext + ")");
      
      cookie.qty=qty;
      cookie.weight=weight;
      cookie.delivery=delivery;
      cookie.total_tvac=total_tvac;
      
      //write cookie
      $.JSONCookie('migc_shop_minicart', cookie, {path: '/'});  
      
      update_mini_cart();
  }                                       
  
  function update_mini_cart()
  {
      //read cookie
      var cookie_json = $.JSONCookie('migc_shop_minicart');
      var cookie_jsontext=JSON.stringify(cookie_json);
      var cookie = eval("(" + cookie_jsontext + ")");
      
      $(".shop_cart_top_qty").html(cookie.qty);
      $(".shop_cart_top_weight").html(cookie.weight);
      $(".shop_cart_top_price").html(cookie.total_tvac);
//       alert('updating mini cart');

//       $.ajax(
//       {
//            type: "POST",
//            url: "../cgi-bin/shop.pl",
//            data: "sw=get_total_cart_ajax",
//            success: function(msg)
//            {
//            var res = msg.split('-'); 
//            
//            var total=res[0];
//            var weight=res[1];
//            var qty=res[2];
//            
//            $(".shop_cart_top_qty").html(qty);
//            $(".shop_cart_top_weight").html(weight);
//            $(".shop_cart_top_price").html(total);
//            }
//       });
  }
  
  
  
function init_update_qty_lightbox()
{
$("#lightbox_qty").blur(function()
{
   var last_id_product_sheet=$("#last_id_product_sheet").val(); 
   var last_id_product_stock=$("#last_id_product_stock").val();
   var qty=$("#lightbox_qty").val();
   //alert('last id product sheet: ['+last_id_product_sheet+'],last id product stock: ['+last_id_product_stock+'], qty: ['+qty+']');
   if(qty >= 0)
   {
    update_cookie('ips_'+last_id_product_stock,qty);
    
    $.ajax(
   {
         type: "POST",
         url: "../cgi-bin/shop.pl",
         data: "sw=get_total_cart_ajax",
         success: function(msg)
         {
             var res = msg.split('-'); 
             
             var total_tvac=res[0];
             var total_htva=total_tvac/1.21;
             var total_weight=weight=res[1];
             var qty=res[2];
             
             $("#shop_menu_addtocart_total1").html(qty);
         }
   });
    
   }
});	
}
  
function init_ajax_search_form()
{
//   alert('init ajax search form');
  $("#ajax_search_form").submit(function()
  {
//      alert('ajax search form submitted');
     var href=$(this).attr('action');
     var method=$(this).attr('method');
     var lg='1';
     var sw='list';
     var render='ajax';
     var page='1';
     var cat='0';
     var extlink='0';
     var search_total=$("#search_total").val();
     var search_type1=$("#search_type1").val();
     var search_fieldtype1=$("#search_fieldtype1").val();
     var search_fieldname1=$("#search_fieldname1").val();
     var search_strict1=$("#search_strict1").val();
     var search_1=$(".search_zone_input input").val();
          
     $.ajax
     (
     {
           type: method,
           url: href,
           data: "lg="+lg+"&sw="+sw+"&render="+render+"&search_1="+search_1+"&page="+page+"&cat="+cat+"&extlink="+extlink+"&search_total="+search_total+"&search_type1="+search_type1+"&search_fieldtype1="+search_fieldtype1+"&search_fieldname1="+search_fieldname1+"&search_strict1="+search_strict1,
           success: function(msg)
           {
                $("#mycarousel2").html(msg); 
              
                 jQuery("#mycarousel2").jcarousel({
                    scroll: 1,
                    initCallback: mycarousel_initCallback2
                 });
              
              
           }
     }
     );
// alert('submit');
  
  
      return false;
  });

}  

function init_filter_menu()
{
    var list_cat=$("#list_cat").val();
    var filter=$("#filter").val();
     
    if(filter == 'y')
    {
        $("#left_content .level_2").hide();
        $("#left_content .level_3").parent().parent().show();
    }
   
    if(list_cat != undefined)
    { 
        var list_cat_array = list_cat.split(',');  
        $("#filters_menu").prepend('<ul id="filter_list"><li class="selections" id="selections"><a href="#"><span>Votre sélection</span><div class="submenu_indic"></div></a><ul id="selections_list"></ul></li><li class="kill_all_filters">Supprimer mes sélections</ul>');          
        for(i=0;i<list_cat_array.length;i++)
        {
            if(list_cat_array[i] != 'undefined' && list_cat_array[i] != '')
            {
//                 alert("#filters_menu .menuid_"+list_cat_array[i]);
                $("#filters_menu .menuid_"+list_cat_array[i]).parent().parent().hide();
                var titre=$("#filters_menu .menuid_"+list_cat_array[i]+" a span").html();
                if(titre != null)
                {
                    titre='<li class="filter_element" name="'+list_cat_array[i]+'">'+titre+'<a href="#" class="cancel_category"></a></li>'; 
                    $("#selections_list").append(titre);
                }
            }
        }
//         if(i == 0)
//         {
// //             alert('show');
// //             $(".migc_selitem_last").parent().parent().show();
//         }
    }
    
    $(".filter_element").click(function()
    {
        var id=$(this).attr('name');
        var list_cat=$("#list_cat").val();
        
        list_cat=list_cat.replace(','+id,"");
        list_cat=list_cat.replace(id,"");
        
        var ajax_self=$("#ajax_self").val();
        var url=ajax_self+"&lvl=3&list_cat="+list_cat;
        window.location = url;
        return false;      
    });
    
    $(".kill_all_filters").click(function()
    {
        var ajax_self=$("#ajax_self").val();
        var url=ajax_self;
        window.location = url;
        return false;      
    });
    
    
    $("#filters_menu .non_cliquable").click(function(){return false;});
    
    if($("#selections_list").html() == "")
    {
       $("#filter_list").hide();
    }
    
    
//     alert($(".migc_selitem_last").parent().hasClass('level_3'));
//      alert($('#list_cat').val());
    if($(".migc_selitem_last").parent().hasClass('level_3') && $('#list_cat').val() != "")
    {
      
//       alert("destroy");
      $(".migc_selitem_last").parent().parent().html("").hide().css("top","5000px");
//       $(".migc_selitem_last").parent().parent().hide();
    }
    else
    {
//       alert("show");
      $(".migc_selitem_last").parent().parent().show();
    }
    
//     $(".migc_selitem_last").parent().parent().hide();   



     
     $("#filters_menu #submenuid_0 #submenuid_1 li").each(function(i)
     {
        var lvl2=$(this);
        var select_genere=false;
        var lvl2_vide=true;
        var liste="";
        lvl2.children("ul").children("li").each(function(j)
        {
             var lvl3=$(this);
             lvl2_vide=false;
             if(j > 3)
             {
                  if(!select_genere)
                  {
                    liste='<select name="filter_select_links" class="filter_select_links"><option value="" name=""> > Plus de choix...</option>';
                    select_genere=true;
                  }
                  var content=lvl3.html();
                  var href=lvl3.children('a').attr('href');
                  if(content != '')
                  {
                    liste+='<option name="'+href+'" value="">'+content+'</option>';
                  }
                  lvl3.hide();           
             }
        });
        if(select_genere)
        {
           liste+='</select>';
        }
        lvl2.append(liste);
     }); 
     
     $(".filter_select_links").change(function()
     {
          var href=$(this).children('option:selected').attr('name');
          if(href != '')
          {
            window.location=href;
          }
     });  
     
//      alert('test');
    
}

// function switch_login_status()
// {
//   //read cookie
//   var cookie_json = $.JSONCookie('migc_member');
//   var cookie_jsontext=JSON.stringify(cookie_json);
//   var cookie = eval("(" + cookie_jsontext + ")");
//   
//   var logged=(cookie.id > 0);
//   if(logged)
//   {
//     var href=$("#top_bar ul li:eq(0) a").attr('href');
//     if(href != '')
//     {
//         href=href+'&amp;sw=logout';
//         $("#top_bar ul li:eq(0) a").attr('href',href);
//         $("#top_bar ul li:eq(0) a span").html('<img src="../gfx/logout.png" alt="logout" />');
//         
//     }  
//   }
// }
