function Shop(lang) {
  this.lang = lang;
}

Shop.prototype.changeDelai = function () {
  $(".labelDelai").on("change", function () {
    var val = $(this).val();
    if (val == "J" || val == "S" || val == "M") {
      $(this).prev().animate({ opacity: 1 });
      $(this).prev().removeAttr("readonly");
      $(this).prev().removeClass("disableDelai");
    } else {
      $(this).prev().animate({ opacity: 0 });
      $(this).prev().attr("readonly");
      $(this).prev().addClass("disableDelai");
    }
  });
};

Shop.prototype.addToCart = function () {
  var elem = this;

  $("body").on("click", ".addToCart", function () {
    var idArticle = $(this).attr("ref");
    var stock = $(this).attr("stock");
    var qty = $(this).parent().parent().find(".amountForProduct").val();
    var desc = $(this).attr("desc");
    var code = $(this).attr("code");
    var price = $(this).attr("price");
    var mark = $(this).attr("mark");
    var poids = $(this).attr("poids");
    var unite = $(this).attr("unite");
    var dim = 0;

    if (
      $(this).parent().parent().find(".dimVal").children(".dimForProductSpan")
        .length > 0
    ) {
      dim = $(this)
        .parent()
        .parent()
        .find(".dimVal")
        .children(".dimForProductSpan")
        .children("input")
        .val();
    }
    var element = this;

    $(element).removeClass("fa-cart-plus");
    $(element).addClass("fa-circle-o-notch  fa-spin loadCart ");

    cmson.ajax(
      "admin/action/vermeire/api.php",
      {
        action: "addcart",
        article: idArticle,
        stock: stock,
        quantity: qty,
        description: desc,
        code: code,
        price: price,
        dim: dim,
        mark: mark,
        lang: this.lang,
        poids: poids,
        unite: unite,
      },
      function (response) {
        var result = JSON.parse(response);
        var nbrProducts = Object.keys(result.cart).length;

        $(".amountCart").children("span").html(nbrProducts);

        elem.reloadMinCart();

        if (result[0] === "false") {
          console.log("erreur durant la connexion : URL : " + result.url);
        } else {
          setTimeout(function () {
            $(element).removeClass("fa-circle-o-notch fa-spin loadCart");
            $(element).addClass("fa-check validCart");
          }, 1000);

          setTimeout(function () {
            $(element).removeClass("fa-check validCart");
            $(element).addClass("fa-cart-plus");
          }, 2000);
        }

        var inCart = $(element).parent().find(".inCart");

        if (inCart.length == 0) {
          $(element)
            .parent()
            .append(
              '<div class="inCart"><i class="fa fa-check fa-stack-1x fa-inverse"></i></div>'
            );
        }
      }
    );
  });

  $("body").on("click", ".details_to_cart", function () {
    var idArticle = $("#product_id").val();
    var stock = $("#product_stock").val();
    var qty = $("#product_qty").val();
    var desc = $("#product_desc").val();
    var code = $("#product_code").val();
    var price = $("#product_price").val();
    var mark = $("#product_mark").val();
    var poids = $("#product_weight").val();
    var dim = $("#product_dim").val();
    var unite = $("#product_unite").val();

    cmson.ajax(
      "admin/action/vermeire/api.php",
      {
        action: "addcart",
        article: idArticle,
        stock: stock,
        quantity: qty,
        description: desc,
        code: code,
        price: price,
        dim: dim,
        mark: mark,
        lang: this.lang,
        poids: poids,
        unite: unite,
      },
      function (response) {
        window.location.href = lang + "/cart";
      }
    );
  });
};

Shop.prototype.removeFromCart = function () {
  var elem = this;
  $("body").on("click", ".removeFromCart", function (e) {
    e.preventDefault();
    var idArticle = $(this).attr("ref");

    var parent = $(this).parent().parent();

    cmson.ajax(
      "admin/action/vermeire/api.php",
      {
        action: "removecart",
        article: idArticle,
        lang: this.lang,
      },
      function (response) {
        var result = JSON.parse(response);

        if (result[0] === "false") {
          console.log("erreur durant la connexion : URL : " + result.url);
        } else {
          elem.reloadMinCart();

          var nbrProducts = Object.keys(result.cart).length;
          $(".amountCart").children("span").html(nbrProducts);
          parent.fadeOut(function () {
            $(this).remove();
            var i = 1;
            $(".table_list_prod tr").each(function () {
              if (i % 2 === 0) {
                $(this).css("background", "#ebebeb");
              } else {
                $(this).css("background", "#cbcbcb");
              }
              i++;
            });
            elem.reloadTotal();
          });
        }
      }
    );
  });
};

Shop.prototype.updateCart = function () {
  var elem = this;

  $("body").on("click", ".updateCart", function (e) {
    e.preventDefault();
    e.stopPropagation();

    var input = $(this).parent().children(".amountForProductInCart");
    var val = parseInt(input.val());

    if ($(this).attr("data-type") == "more") {
      input.val(val + 1);
    } else if (val > 1) {
      input.val(val - 1);
    }
    updateCart(input);
    updateValidity(input);
  });

  $("body").on("change", ".amountForProduct", function () {
    updateValidity(this);
  });

  $("body").on("change", ".amountForProductInCart", function () {
    updateCart(this);
    updateValidity(this);
  });

  $("body").on("change", ".dimForProductInCart", function () {
    var input = $(this).parent().prev().children(".amountForProductInCart");

    //console.log("change dim width : "+$(this).val() );

    input.attr("dim", $(this).val());

    updateCart(input);
    updateValidity(input);
  });

  function updateCart(input) {
    var idArticle = $(input).attr("ref");
    var stock = $(input).attr("stock");
    var qty = parseInt($(input).val());
    var desc = $(input).attr("desc");
    var code = $(input).attr("code");
    var price = $(input).attr("price");
    var unityPrice = $(input).attr("price");
    var dim = $(input).attr("dim");
    var poids = $(input).attr("poids");

    var priceSplit = price.split(" ");
    var priceFloat = parseFloat(priceSplit[0].replace(",", "."));

    // calcul du prix en tenant compte de la dimension si elle est définie ( > 0 )
    var price = (priceFloat * qty).toFixed(2);
    var poidsTot = (parseFloat(poids) * qty).toFixed(2);
    if (parseFloat(dim) > 0) {
      //console.log("ok, dim > 0 : " + parseFloat(dim));
      price = (parseFloat(dim) * price).toFixed(2);
      poidsTot = (parseFloat(dim) * poidsTot).toFixed(2);
    }

    if (price > 0) {
      $(input)
        .parent()
        .parent()
        .children(".totalPrice")
        .html("<span>" + price + " €</span>");
    }
    $(input)
      .parent()
      .parent()
      .children(".poids")
      .html(poidsTot + " kg");

    cmson.ajax(
      "admin/action/vermeire/api.php",
      {
        action: "addcart",
        article: idArticle,
        stock: stock,
        quantity: qty,
        description: desc,
        code: code,
        price: unityPrice,
        lang: this.lang,
        dim: dim,
        mark: "",
        poids: poids,
      },
      function (response) {
        var result = JSON.parse(response);

        if (result[0] === "false") {
          console.log("erreur durant la connexion : URL : " + result.url);
        } else {
          $(input).css("transition", "all ease .2s");
          $(input).css("border-color", "#72d627");
          setTimeout(function () {
            $(input).css("border-color", "#e1e1e1");
          }, 1000);
        }
      }
    );

    elem.reloadTotal();

    // update transport

    $("#tableProd")
      .find("li")
      .each(function () {
        console.log(this);
      });

    //window.location.reload();
  }

  function updateValidity(input) {
    if ($(input).val() != "") {
      var value = parseInt($(input).val());
      var stock = parseInt($(input).next().attr("stock"));

      if (isNaN(stock)) {
        stock = parseInt($(input).attr("stock"));
      }
      if (stock == 0) {
        $(input).css("background", "#ff2b21c2");
      } else if (stock - value >= 0) {
        $(input).css("background", "#8ca71f");
      } else if (stock - value < 0) {
        $(input).css("background", "#ffc107");
      } else {
        $(input).css("background", "#ff2b21c2");
      }
      $(input).css("color", "#FFF");
    } else {
      $(input).css("background", "#FFF");
      $(input).css("color", "#212121");
    }
  }
};

Shop.prototype.handleCartView = function () {
  $("#backBtn").on("click", function (e) {
    e.preventDefault();

    window.history.back();
  });
};

Shop.prototype.handleOrder = function () {
  var elem = this;
  $("#confirmOrder").on("click", function (e) {
    e.preventDefault();
    $(this).after('<input type="hidden" name="offre" value="true"  />');

    if (elem.checkRequiredFields()) {
      $("#cart").children("form").submit();
    }
  });

  $("#confirmCart").on("click", function (e) {
    e.preventDefault();
    e.stopPropagation();
    if (!$(this).hasClass("disabled")) {
      if (elem.checkRequiredFields()) {
        $("#cart").children("form").submit();
      }
    }
  });
};

Shop.prototype.checkRequiredFields = function () {
  var elem = this;
  var returnMsg = false;
  var error = 0;

  $("#cartForm")
    .find("input,select")
    .each(function () {
      if (this.hasAttribute("required")) {
        if ($(this).val() == "" && error == 0) {
          $(this).focus();
          $(this).addClass("required");
          var message = elem.getTranslation("required", lang);

          $("#msg")
            .html('<div class="notification  error ">' + message + "</div>")
            .fadeIn()
            .delay(3000)
            .fadeOut("slow");
          error++;
        } else {
          $(this).removeClass("required");
        }

        if (error == 0) {
          returnMsg = true;
        }
      }
    });

  return returnMsg;
};

Shop.prototype.handleTotalPrice = function () {
  $("#tableProd .totalPrice").each(function () {
    var price = $(this).parent().children(".price").html();
    var qty = $(this)
      .parent()
      .children("td")
      .children(".amountForProductInCart")
      .val();
    var dim = $(this)
      .parent()
      .children("td")
      .children(".dimForProductInCart")
      .val();

    if (price != undefined) {
      var priceSplit = price.trim().split(" ");
      var priceFloat = parseFloat(priceSplit[0].replace(",", "."));

      if (priceFloat > 0) {
        var priceSplit = price.trim().split(" ");
        var priceFloat = parseFloat(priceSplit[0].replace(",", "."));

        var priceValue = priceFloat * qty;

        if (dim > 0) {
          priceValue = priceValue * dim;
        }
        $(this).html("<span>" + priceValue.toFixed(2) + " €</span>");
      }
    }
  });
};

Shop.prototype.reloadMinCart = function () {
  var url = baseUrl + lang + "?ajaxpart=true";

  var datasParts = {
    part: "parts/mincart",
    params: {},
  };

  if (typeof call !== "undefined") {
    call.abort();
  }
  call = $.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify(datasParts),
    success: function (data) {
      $("#minCart").html(data);
    },
    failure: function (errMsg) {
      console.log(errMsg);
      $("#wimmAlertTop").triggerAlert(
        "Une erreur s'est produite.!",
        "error",
        3000
      );
    },
  });
};

Shop.prototype.reloadTotal = function () {
  var self = this;

  var totalPrice = 0;
  $("#tableProd")
    .find(".totalPrice")
    .each(function () {
      var thisPrice = $(this).children("span").html();
      totalPrice += parseFloat(thisPrice);
    });

  totalPrice = totalPrice.toFixed(2);

  if (totalPrice > 0) {
    $("#TotalCart")
      .find(".totalPrice")
      .children("span")
      .html(totalPrice + " €");
    $("#totalToPay")
      .find(".totalPrice")
      .children("span")
      .html(totalPrice + " €");
    $("#contentLivPart").attr("data-price", totalPrice);
  }

  var totalPoids = 0;
  var maxWeight = 0;
  $("#tableProd")
    .find(".poids")
    .each(function () {
      var thisPoids = $(this).html();
      totalPoids += parseFloat(thisPoids);
      maxWeight =
        parseFloat($(this).attr("unit")) > maxWeight
          ? parseFloat($(this).attr("unit"))
          : maxWeight;
    });

  totalPoids = totalPoids.toFixed(2);

  $("#TotalCart")
    .find(".totalPoids")
    .children("span")
    .html(totalPoids + " kg");
  $("#totalToPay")
    .find(".totalPoids")
    .children("span")
    .html(totalPoids + " kg");
  $("#contentLivPart").attr("data-weight", parseFloat(totalPoids));
  $("#contentLivPart").attr("data-maxweight", parseFloat(maxWeight));

  self.reloadTransport();
};

Shop.prototype.handleReloadAjaxFilters = function () {
  $("body").on("click", "#dispo_list", function () {
    $("#dispo").click();
  });

  $("body").on("click", "#ordered_list", function () {
    $("#ordered").click();
  });

  var element = this;

  reloadProducts = function (relauchZParams) {
    $("#productsPart").animate({ opacity: 0.5 });
    //$('#loadingFilters').fadeIn();

    $("#loadingProducts").fadeIn();

    var paramsFilters = {};

    var isChecked = $("#dispo").is(":checked");
    var isOrdered = $("#ordered").is(":checked");

    paramsFilters["parent"] = $("#parent").val();
    paramsFilters["famweb"] = $("#famweb").val();
    paramsFilters["niveau"] = $("#niveau").val();
    paramsFilters["search"] = $("#searchVal").val();

    if (isChecked) {
      paramsFilters["dispo"] = isChecked.toString();
    }

    if (isOrdered) {
      paramsFilters["ordered"] = isOrdered.toString();
    }

    var urlRewrite =
      baseUrl +
      "/" +
      lang +
      "/shop?niveau=product&famweb=" +
      paramsFilters["famweb"] +
      "&parent=" +
      paramsFilters["parent"];

    if (!relauchZParams) {
      $("body .select2Field").each(function () {
        var value = $(this).val();
        var name = $(this).attr("name");

        name = name.substring(0, name.length - 2);

        paramsFilters[name] = value;

        if (typeof value == "object") {
          $(value).each(function () {
            urlRewrite += "&" + name + "[]=" + this;
          });
        } else {
          urlRewrite += "&" + name + "[]=" + value;
        }
      });

      $("body .checkboxField").each(function () {
        if ($(this).prop("checked")) {
          var value = $(this).val();
          var name = $(this).attr("name");

          name = name.substring(0, name.length - 2);

          if (paramsFilters[name] != undefined) {
            paramsFilters[name].push(value);
          } else {
            paramsFilters[name] = [value];
          }

          if (typeof value == "object") {
            $(value).each(function () {
              urlRewrite += "&" + name + "[]=" + this;
            });
          } else {
            urlRewrite += "&" + name + "[]=" + value;
          }
        }
      });

      if ($("#searchFieldGlobal").length > 0) {
        var search = $("#searchFieldGlobal");
        urlRewrite += "&" + search.attr("name") + "=" + search.val();
      }

      $("#fiche_prod_filtres")
        .find(".imgBox")
        .each(function () {
          if ($(this).hasClass("selected")) {
            var name = "Z1";
            var value = $(this).children("img").attr("title");
            if (paramsFilters[name] != undefined) {
              paramsFilters[name].push(value);
            } else {
              paramsFilters[name] = [value];
            }

            if (typeof value == "object") {
              $(value).each(function () {
                urlRewrite += "&" + name + "[]=" + this;
              });
            } else {
              urlRewrite += "&" + name + "[]=" + value;
            }
          }
        });
    }

    /* reload de l'url pour prendre en compte tous les get */

    //urlRewrite +="#menu_famille";

    history.pushState({}, null, urlRewrite);

    /* reload ajax */

    var url = baseUrl + lang + "?ajaxpart=true";

    var datas = {
      part: "parts/shop/products",
      params: {
        currentUrl: $("#currentUrl").val(),
        filters: paramsFilters,
      },
    };

    if (typeof call !== "undefined") {
      call.abort();
    }
    call = $.ajax({
      type: "POST",
      url: url,
      data: JSON.stringify(datas),
      success: function (data) {
        $("#productsPart").html(data);
        $("#productsPart").animate({ opacity: 1 });
        $("#loadingProducts").fadeOut();
        element.adaptePageLayout();

        $(".detailsCol,.infoCol").addClass("show");

        var toggleDetails = $("#toggleDetails");

        if (toggleDetails.attr("data-status") === "hide") {
          toggleDetails.attr("data-status", "show");
          var currentLabel = $(toggleDetails).children("span").html();
          $(toggleDetails)
            .children("span")
            .html($(toggleDetails).attr("data-label"));
          $(toggleDetails).attr("data-label", currentLabel);
        }

        /*

                var url = baseUrl+lang+'?ajaxpart=true';


                var datas = {
                    part : "parts/shop/filters",
                    params : {
                        currentUrl : $('#currentUrl').val(),
                        filters  : paramsFilters
                    }
                };
                if (typeof call !== 'undefined') {
                    call.abort();
                }
                call = $.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify(datas),
                    success: function (data) {
                        $('#filter_reload_content').html(data);
                        $('#loadingFilters').fadeOut();

                        $('.select2Field').each(function(){
                            $(this).select2({
                                allowClear: true,
                                matcher: function (params, data) {
                                    params.term = params.term || '';
                                    params.term = params.term.toUpperCase();
                                    var regex = new RegExp('^' + params.term);
                                    if (regex.test(data.text.toUpperCase())) {
                                        return data;
                                    }
                                    return false;
                                }
                            });
                        });



                    },
                    failure: function (errMsg) {
                        console.log(error);
                        $('#wimmAlertTop').triggerAlert('Une erreur s\'est produite.!','error',3000);

                    }
                });

                */
      },
      failure: function (errMsg) {
        console.log(error);
        $("#wimmAlertTop").triggerAlert(
          "Une erreur s'est produite.!",
          "error",
          3000
        );
      },
    });

    if (false) {
      // reload mark logo

      var logo_options = {
        part: "parts/shop/mark_logo",
        params: {
          currentUrl: $("#currentUrl").val(),
          filters: paramsFilters,
        },
      };
      $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(logo_options),
        success: function (data) {
          $("#markLogoReloadBox").html(data);

          vermeire.markLogo($("#categories_prod_logo"));
        },
        failure: function (errMsg) {
          $("#wimmAlertTop").triggerAlert(
            "Une erreur s'est produite.!",
            "error",
            3000
          );
        },
      });
    }
    $("#footer").fadeOut();
    setTimeout(function () {
      fixFooter();
    }, 1200);
  };

  $("body").on("click", "#reloadBtn", function (e) {
    e.preventDefault();
    $(".checkboxField").prop("checked", false);
    $(".select2Field").val([]).trigger("change");
    reloadProducts();
  });

  $("body").on("change", ".select2Field", function () {
    reloadProducts();
  });

  $("body").on("change", ".checkboxField", function () {
    reloadProducts();
  });

  setTimeout(function () {
    $("#searchVal").on("change", function () {
      reloadProducts();
    });
    $("#famweb").on("change", function () {
      reloadProducts(true);
    });
  }, 1000);

  $("#dispo").on("change", function () {
    reloadProducts();
  });

  $("#ordered").on("change", function () {
    reloadProducts();
  });

  $("#fiche_prod_filtres").on("click", ".imgBox", function (e) {
    e.preventDefault();
    e.stopPropagation();

    $(this).toggleClass("selected");

    reloadProducts();
  });
};

Shop.prototype.handleAddressLiv = function () {
  $(".selectAddress").on("click", function () {
    $(".selectAddress").each(function () {
      $(this).removeClass("selected");
    });

    $(this).addClass("selected");

    if ($(this).attr("id") == "otherAdd") {
      $("#externalAdd").fadeIn();
      $("#externalAdd").find("input").attr("type", "text");
    } else {
      $("#externalAdd").fadeOut();
      $("#externalAdd").find("input").attr("type", "text");

      $("#nameLiv").val($(this).find(".nameLiv").html());
      $("#adresse1Liv").val($(this).find(".adresse1Liv").html());
      $("#adresse2Liv").val($(this).find(".adresse2Liv").html());
      $("#cpostalLiv").val($(this).find(".cpostalLiv").html());
      $("#locLiv").val($(this).find(".locLiv").html());
      $("#paysLiv").val($(this).find(".paysLiv").html());

      document.getElementById("paysLiv").value = $.trim(
        $(this).find(".paysLiv").html()
      );
      document.getElementById("paysLiv").dispatchEvent(new Event("change"));
    }
  });
};

Shop.prototype.handleAssocProduct = function () {
  $("body").on("click", ".linkedProduct", function (e) {
    // load ajax linked products
    var url = baseUrl + lang + "?ajaxpart=true";

    var datas = {
      part: "parts/shop/sub_products",
      params: {
        currentUrl: $("#currentUrl").val(),
        parent: $(this).attr("data-parent"),
      },
    };
    $("#linkedProducts .content").html(
      '<div style="width:100%;text-align: center;padding:30px 0px;"><i style="color: grey;font-size=14px;" class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i></div>'
    );

    $("#linkedProductsWrapper").css("opacity", "0");
    $("#linkedProductsWrapper").css("display", "flex");
    $("#linkedProductsWrapper").animate({ opacity: 1 });

    $.ajax({
      type: "POST",
      url: url,
      data: JSON.stringify(datas),
      success: function (data) {
        $("#linkedProducts .content").html(data);
      },
      failure: function (errMsg) {
        $("#wimmAlertTop").triggerAlert(
          "Une erreur s'est produite.!",
          "error",
          3000
        );
      },
    });
  });

  $("body").on("click", "#closeWrapper", function () {
    $("#linkedProductsWrapper").fadeOut();
  });
};

Shop.prototype.demandePrice = function () {
  $("body").on("click", ".price_to_cart", function (e) {
    e.preventDefault();

    var target = $(this).attr("href");
    var btnAdd = $(this)
      .parent()
      .parent()
      .children("td")
      .last()
      .children(".addToCart");

    btnAdd.click();
    setTimeout(function () {
      window.location.href = target;
    }, 1500);
  });
};

Shop.prototype.getTranslation = function (id, lang) {
  var translations = {
    fr: {
      required: "Veuillez remplir tous les champs requis.",
    },
    en: {
      required: "Please fill in all required fields.",
    },
    nl: {
      required: "Vul alle verplichte velden in.",
    },
    de: {
      required: "Bitte füllen Sie alle erforderlichen Felder aus.",
    },
  };

  return translations[lang][id];
};

Shop.prototype.switchGlobalSearch = function () {
  $("#categorySearch").on("click", function () {
    var alt = $("#searchVal").attr("data-alt");
    $("#searchVal").attr("data-alt", $("#searchVal").attr("placeholder"));
    $("#searchVal").attr("placeholder", alt);

    var famweb =
      $("#famwebSearch").val() == ""
        ? $("#famwebSearch").attr("data-famweb")
        : "";
    $("#famwebSearch").val(famweb);

    var parent =
      $("#parentSearch").val() == ""
        ? $("#parentSearch").attr("data-parent")
        : "";
    $("#parentSearch").val(parent);
  });
};

Shop.prototype.adaptePageLayout = function () {
  var amountProducts = $("#amountProductsFound").clone();

  if (amountProducts.length > 0) {
    $("#amountContent").remove();
    $("#amountProductsFound").remove();
    $(amountProducts).attr("id", "");
    $("#filterPart").append(
      "<div id='amountContent'>" + amountProducts.html() + "</div>"
    );
  }
};

Shop.prototype.handleTransport = function () {
  var self = this;

  // livraison

  $("body").on("click", "#livList li", function () {
    $("#livList .selected").removeClass("selected");
    $(this).toggleClass("selected");

    $(this)
      .find("input")
      .each(function () {
        this.checked = true;
      });

    $("#livTotalPrice").html($(this).attr("data-price"));

    if (parseFloat($("#calcTotalPrice").html()) > 0) {
      var livPrice = isNaN(parseInt($(this).attr("data-price")))
        ? 0
        : parseInt($(this).attr("data-price"));
      var roundAmount = Number(
        Math.round(parseFloat($("#calcTotalPrice").html()) + livPrice + "e2") +
          "e-2"
      );

      $("#livCalcTotal").html(roundAmount + "€");
    }
  });

  $("#paysLiv").on("change", function () {
    self.reloadTransport();
  });
};

Shop.prototype.reloadTransport = function () {
  var self = this;
  /* reload ajax */
  var url = baseUrl + lang + "/cart?ajaxpart=true";
  console.log(url);
  var datas = {
    part: "parts/cart/livraison",
    params: {
      code: $("#paysLiv").val(),
      weight: $("#contentLivPart").attr("data-weight"),
      htva: $("#contentLivPart").attr("data-price"),
      maxWeight: $("#contentLivPart").attr("data-maxweight"),
    },
  };
  $.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify(datas),
    success: function (data) {
      $("#contentLivPart").html(data);
      $("body").find("#firstLiv").trigger("click");
    },
    failure: function (errMsg) {
      console.log(error);
      $("#wimmAlertTop").triggerAlert(
        "Une erreur s'est produite.!",
        "error",
        3000
      );
    },
  });
};

Shop.prototype.handleProductDetails = function () {
  $(".productSlider").flexslider({
    animation: "slide",
    controlsContainer: $(".custom-controls-container"),
    customDirectionNav: $(".custom-navigation a"),
  });
};

Shop.prototype.handleGuide = function () {
  var self = this;
  var cookie_guide = this.getCookie("hide_tour_guide");

  if (!cookie_guide) {
    $("#guide_tour").removeClass("closed");
  }

  $("#guide_tour")
    .find(".close_tour")
    .on("click", function (e) {
      e.preventDefault();
      e.stopPropagation();

      self.setCookie("hide_tour_guide", true, 360);

      $("#guide_tour").addClass("closed");
    });

  var labels = {
    next: "Next",
    previous: "Previous",
    done: "Done",
    step1: "Access filters by clicking this button",
    step2_1: "You can hide or reset filters by clicking on these buttons",
    step2_2: "You can also only filter available products.",
    step3_1: "Search for a product by reference/keyword",
    step3_2: "The search starts automatically",
    step4: "Search for a product by brand",
    step5: "Here is the number of products found for the ongoing research.",
    step6: "Filter on products you've already ordered in the past.",
    step7: "Find your orders, view order status and download PDF confirmation",
    step8: "Switch to another category",
    step9_1: "Search for a product by VB article code, reference or keyword",
    step9_2: "Bearing example: 6204ZZ C3",
    step9_3: "Pulley example: 3SPB400",
    step9_4: "Belt example belt: SPC2000",
    step9_5: "Motor example: 0.75 1500 B3 IE3",
    step9_6:
      "Siemens article example: 1LE1003-0DA22-2AA4 (or part of the reference)",
    step10_1: "View articles associated with the selected article",
    step10_2: "Example: taperbush for pulley",
    step11: "Get more information about a column data",
    step12: "Click on the product description to access the product data sheet",
    step13: "Click on the web subfamily to go back in the product selection",
  };

  if (lang == "fr") {
    labels.next = "Suivant";
    labels.previous = "Précédent";
    labels.done = "Terminer";

    labels.step1 = "Accédez aux filtres en cliquant sur ce bouton";
    labels.step2_1 =
      "Vous pouvez masquer ou réinitiialiser les filtres en cliquant sur ces boutons";
    labels.step2_2 =
      "Vous pouvez aussi filtrer uniquement les produits disponibles.";
    labels.step3_1 = "Rechercher un produit par référence / mot-clé";
    labels.step3_2 = "La recherche se lance automatiquement.";
    labels.step4 = "Rechercher un produit par marque";
    labels.step5 =
      "Voici le nombre de produits trouvés pour la recherche en cours.";
    labels.step6 =
      "Filtrer sur les produits que vous avez déjà commandés par le passé.";
    labels.step7 =
      "Rechercher vos commandes, visualiser le statut de la commande et télécharger la confirmation PDF";
    labels.step8 = "Basculer vers une autre famille de produit";
    labels.step9_1 =
      "Rechercher un produit par code article VB, par référence ou par mot-clé";
    labels.step9_2 = "Exemple roulement : 6204ZZ C3";
    labels.step9_3 = "Exemple poulie : 3SPB400";
    labels.step9_4 = "Exemple courroie : SPC2000";
    labels.step9_5 = "Exemple moteur : 0,75 1500 B3 IE3";
    labels.step9_6 =
      "Exemple article Siemens : 1LE1003-0DA22-2AA4 (ou partie de la référence)";
    labels.step10_1 = "Afficher les articles associés à l’article sélectionné";
    labels.step10_2 = "Exemple : moyeu amovible pour poulie";
    labels.step11 =
      "Obtenir des informations complémentaires sur une donnée colonne";
    labels.step12 =
      "Cliquer sur le libellé descriptif produit pour accéder à la fiche produit";
    labels.step13 =
      "Cliquer sur la sous famille web pour remonter en arrière dans la sélection produit";
  } else if (lang == "nl") {
    labels.next = "Volgende";
    labels.previous = "Vorige";
    labels.done = "Beëindigen";

    labels.step1 = "Hier klikken voor de filters";
    labels.step2_1 =
      "U kunt filters verbergen of resetten door op deze knoppen te klikken";
    labels.step2_2 = "U kunt ook alleen de beschikbare producten filteren.";
    labels.step3_1 = "Zoek een product op basis van referentie / trefwoord";
    labels.step3_2 = "Het zoeken begint automatisch";
    labels.step4 = "Zoek een product op merk";
    labels.step5 =
      "Hier is het aantal producten dat is gevonden voor de huidige zoekopdracht.";
    labels.step6 =
      "Filter op de producten die u in het verleden heeft besteld.";
    labels.step7 =
      "Zoek uw bestellingen, bekijk de bestelstatus en download de pdf-bevestiging";
    labels.step8 = "Schakel over naar een andere productfamilie";
    labels.step9_1 =
      "Zoek naar een product op VB-artikelcode, op referentie of op trefwoord";
    labels.step9_2 = "Lager voorbeeld: 6204ZZ C3";
    labels.step9_3 = "Voorbeeld katrol: 3SPB400";
    labels.step9_4 = "Riemvoorbeeld: SPC2000";
    labels.step9_5 = "Motor voorbeeld: 0,75 1500 B3 IE3";
    labels.step9_6 =
      "Voorbeeld Siemens-artikel: 1LE1003-0DA22-2AA4 (of een deel van de referentie)";
    labels.step10_1 =
      "Geef de artikelen weer, die bij het geselecteerde artikel horen";
    labels.step10_2 = "Voorbeeld: klembus voor schijf";
    labels.step11 = "Verkrijg aanvullende informatie over een kolomgegevens";
    labels.step12 =
      "Klik op het productbeschrijvingslabel om het productblad te openen";
    labels.step13 =
      "Klik op de websubfamilie om terug te gaan naar de productselectie";
  } else if (lang == "de") {
    labels.next = "Weiter";
    labels.previous = "Zurück";
    labels.done = "Beenden";

    labels.step1 =
      "Greifen Sie auf die Filter zu, indem Sie auf diese Schaltfläche klicken";
    labels.step2_1 =
      "Sie können Filter ausblenden oder zurücksetzen, indem Sie auf diese Schaltflächen klicken";
    labels.step2_2 = "Sie können auch nur die verfügbaren Produkte filtern.";
    labels.step3_1 =
      "Suchen Sie nach einem Produkt anhand der Referenz / des Schlüsselworts";
    labels.step3_2 = "Die Suche startet automatisch.";
    labels.step4 = "Finden Sie ein Produkt nach Marke";
    labels.step5 =
      "Hier ist die Anzahl der Produkte, die für die aktuelle Suche gefunden wurden.";
    labels.step6 =
      "Filtern Sie nach den Produkten, die Sie in der Vergangenheit bestellt haben.";
    labels.step7 =
      "Durchsuchen Sie Ihre Bestellungen, zeigen Sie den Bestellstatus an und laden Sie die PDF-Bestätigung herunter";
    labels.step8 = "Wechseln Sie zu einer anderen Produktfamilie";
    labels.step9_1 =
      "Suchen Sie nach einem Produkt anhand des VB-Artikelcodes, der Referenz oder des Schlüsselworts";
    labels.step9_2 = "Lagerbeispiel: 6204ZZ C3";
    labels.step9_3 = "Beispielscheibe: 3SPB400";
    labels.step9_4 = "Riemenbeispiel: SPC2000";
    labels.step9_5 = "Motorbeispiel: 0,75 1500 B3 IE3";
    labels.step9_6 =
      "Beispiel Siemens Artikel: 1LE1003-0DA22-2AA4 (oder Teil der Referenz)";
    labels.step10_1 =
      "Zeigen Sie die Artikel an, die dem ausgewählten Artikel zugeordnet sind";
    labels.step10_2 = "Beispiel: Buchse für Riemenscheibe";
    labels.step11 =
      "Erhalten Sie zusätzliche Informationen zu den Daten dieser Kolonne";
    labels.step12 =
      "Klicken Sie auf das Produktbeschreibungsetikett, um auf das Produktblatt zuzugreifen";
    labels.step13 =
      "Klicken Sie auf die Web-Unterfamilie, um zur Produktauswahl zurückzukehren";
  }

  var intro = introJs();

  var steps = [];

  // Step 1
  steps.push({
    element: "#amountContent",
    intro: "<strong>" + labels.step5 + "</strong>",
    position: "left",
  });

  // Step 2
  steps.push({
    element: "#ordered_list",
    intro: "<strong>" + labels.step6 + "</strong>",
    position: "right",
  });

  if ($("#headOrderButton").length > 0) {
    // Step 3
    steps.push({
      element: "#headOrderButton",
      intro: "<strong>" + labels.step7 + "</strong>",
      position: "left",
    });
  }

  // step 4
  steps.push({
    element: "#menu_famille",
    intro: "<strong>" + labels.step8 + "</strong>",
    position: "bottom",
  });

  if (
    $("#list_breadcrumb").length > 0 &&
    $("#list_breadcrumb").html().trim() !== ""
  ) {
    // step 9
    steps.push({
      element: "#list_breadcrumb",
      intro: "<strong>" + labels.step13 + "</strong>",
      position: "bottom",
    });
  }

  // step 5
  steps.push({
    element: "#head_search",
    intro:
      "<strong>" +
      labels.step9_1 +
      "</strong><br /><br /><span>" +
      labels.step9_2 +
      "</span><br /><span>" +
      labels.step9_3 +
      "</span><br /><span>" +
      labels.step9_4 +
      "</span><br /><span>" +
      labels.step9_5 +
      "</span><br /><span>" +
      labels.step9_6 +
      "</span>",
    position: "bottom",
  });

  // step 6
  steps.push({
    element: "#art_assoc",
    intro:
      "<strong>" +
      labels.step10_1 +
      "</strong><br /><br /><span>" +
      labels.step10_2 +
      "</span>",
    position: "bottom",
  });

  if ($(".filterImg").length > 0) {
    // step 8
    steps.push({
      element: ".filterImg",
      intro: "<strong>" + labels.step11 + "</strong>",
      position: "bottom",
    });
  }

  if ($(".desc_td").length > 0) {
    // step 9
    steps.push({
      element: ".desc_td",
      intro: "<strong>" + labels.step12 + "</strong>",
      position: "bottom",
    });
  }

  // Step 10
  steps.push({
    element: "#toggleFilters",
    intro: "<span>" + labels.step1 + "</span>",
    position: "right",
  });

  // Step 2
  steps.push({
    element: "#headFilters",
    intro:
      "<strong>" +
      labels.step2_1 +
      "</strong><br /><br /><span>" +
      labels.step2_2 +
      "</span>",
    position: "right",
  });

  // Step 3
  steps.push({
    element: ".searchField",
    intro:
      "<strong>" +
      labels.step3_1 +
      "</strong><br /><br /><span>" +
      labels.step3_2 +
      "</span>",
    position: "right",
  });

  if ($("#select_Z1").length > 0) {
    // step 4
    steps.push({
      element: "#select_Z1",
      intro: "<strong>" + labels.step4 + "</strong>",
      position: "right",
    });
  }

  intro.setOptions({
    nextLabel: labels.next,
    prevLabel: labels.previous,
    doneLabel: labels.done,
    steps: steps,
  });

  intro.onbeforeexit(function () {
    //self.setCookie('hide_tour_guide',true,360);
  });

  intro.onbeforechange(function () {
    var element = this._introItems[this._currentStep].element;

    if (element == document.getElementById("headFilters")) {
      if (!$("#productContainer").hasClass("open")) {
        $("#toggleFilters").click();
      }
    }
  });

  intro.onafterchange(function () {});

  $("#proceed_tour").on("click", function (e) {
    e.preventDefault();
    e.stopPropagation();
    $("#guide_tour").addClass("closed");
    intro.start();
  });
};

Shop.prototype.handleRestoreCart = function () {
  $("#restore_cart_action").on("click", function () {
    cmson.ajax(
      "admin/action/vermeire/api.php",
      { action: "restoreCart" },
      function (response) {
        window.location.reload();
      }
    );
  });
  $("#no_restore_cart_action").on("click", function () {
    cmson.ajax(
      "admin/action/vermeire/api.php",
      { action: "overrideSavedCart" },
      function (response) {
        window.location.reload();
      }
    );
  });
};

Shop.prototype.setCookie = function (c_name, value, exdays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var c_value =
    escape(value) + (exdays == null ? "" : "; expires=" + exdate.toUTCString());
  document.cookie = c_name + "=" + c_value;
};

Shop.prototype.getCookie = function (c_name) {
  var _cookies = document.cookie.split(";");
  for (var i = 0; i < _cookies.length; i++) {
    var x = _cookies[i].substr(0, _cookies[i].indexOf("="));
    var y = _cookies[i].substr(_cookies[i].indexOf("=") + 1);
    x = x.replace(/^\s+|\s+$/g, "");
    if (x == c_name) return unescape(y);
  }

  return null;
};

Shop.prototype.handleTableDetails = function () {
  $("body").on("click", "#toggleDetails", function () {
    $(".detailsCol,.infoCol").toggleClass("show");

    var currentLabel = $(this).children("span").html();
    $(this).children("span").html($(this).attr("data-label"));
    $(this).attr("data-label", currentLabel);

    if ($(this).attr("data-status") === "hide") {
      $(this).attr("data-status", "show");
    } else {
      $(this).attr("data-status", "hide");
    }
  });
};

Shop.prototype.handleProfilePrice = function () {
  $("#selectProfile").on("change", function (e) {
    var lang = $(this).attr("data-lang");
    var code = $(this).attr("data-code");
    var cltno = $(this).attr("data-client");
    var profile = e.target.value.trim();

    cmson.ajax(
      "admin/action/vermeire/api.php",
      {
        action: "getProfilePrice",
        profile: profile,
        code: code,
        lang: lang,
        cltno: cltno,
      },
      function (response) {
        const result = JSON.parse(response);
        const recommendedPrice = document.getElementById('recommended_price');
        const recommendedPriceSpan = document.querySelector('#recommended_price span');

        if(recommendedPrice && recommendedPriceSpan){
          if(result.status === 'success'){
            recommendedPrice.classList.add('active');    
            recommendedPriceSpan.innerText = result.price;     
          }else{
            recommendedPrice.classList.remove('active');    
            recommendedPriceSpan.innerText = '';
          }
        }else{
          console.log('missing recommended_price element');
        }
       
      }
    );
  });
};

$(function () {
  var shop = new Shop();

  shop.handleAddressLiv();

  shop.addToCart();
  shop.removeFromCart();
  shop.updateCart();
  shop.changeDelai();
  shop.handleCartView();
  shop.handleTotalPrice();
  shop.handleOrder();
  shop.handleReloadAjaxFilters();
  shop.handleAssocProduct();
  shop.demandePrice();
  shop.switchGlobalSearch();
  shop.adaptePageLayout();
  shop.handleTransport();
  shop.handleProductDetails();
  shop.handleGuide();
  shop.handleRestoreCart();
  shop.handleTableDetails();
  shop.handleProfilePrice();
});
