// source --> https://www.tacto.es/wp-content/plugins/woocommerce/assets/js/frontend/woocommerce.min.js?ver=10.4.4 
function on_keydown_remove_from_cart(e){" "===e.key&&(e.preventDefault(),e.currentTarget.click())}function focus_populate_live_region(){var e=["woocommerce-message","woocommerce-error","wc-block-components-notice-banner"].map(function(e){return"."+e+'[role="alert"]'}).join(", "),o=document.querySelectorAll(e);if(0!==o.length){var t=o[0];t.setAttribute("tabindex","-1");var n=setTimeout(function(){t.focus(),clearTimeout(n)},500)}}function refresh_sorted_by_live_region(){var e=document.querySelector(".woocommerce-result-count");if(e){var o=e.innerHTML;e.setAttribute("aria-hidden","true");var t=setTimeout(function(){e.setAttribute("aria-hidden","false"),e.innerHTML="",e.innerHTML=o,clearTimeout(t)},2e3)}}function on_document_ready(){focus_populate_live_region(),refresh_sorted_by_live_region()}jQuery(function(e){e(".woocommerce-ordering").on("change","select.orderby",function(){e(this).closest("form").trigger("submit")}),e("input.qty:not(.product-quantity input.qty)").each(function(){var o=parseFloat(e(this).attr("min"));o>=0&&parseFloat(e(this).val())<o&&e(this).val(o)});var o="store_notice"+(e(".woocommerce-store-notice").data("noticeId")||"");if("hidden"===Cookies.get(o))e(".woocommerce-store-notice").hide();else{function t(o){["Enter"," "].includes(o.key)&&(o.preventDefault(),e(".woocommerce-store-notice__dismiss-link").click())}e(".woocommerce-store-notice").show(),e(".woocommerce-store-notice__dismiss-link").on("click",function n(r){Cookies.set(o,"hidden",{path:"/"}),e(".woocommerce-store-notice").hide(),r.preventDefault(),e(".woocommerce-store-notice__dismiss-link").off("click",n).off("keydown",t)}).on("keydown",t)}e(".woocommerce-input-wrapper span.description").length&&e(document.body).on("click",function(){e(".woocommerce-input-wrapper span.description:visible").prop("aria-hidden",!0).slideUp(250)}),e(".woocommerce-input-wrapper").on("click",function(e){e.stopPropagation()}),e(".woocommerce-input-wrapper :input").on("keydown",function(o){var t=e(this).parent().find("span.description");if(27===o.which&&t.length&&t.is(":visible"))return t.prop("aria-hidden",!0).slideUp(250),o.preventDefault(),!1}).on("click focus",function(){var o=e(this).parent(),t=o.find("span.description");o.addClass("currentTarget"),e(".woocommerce-input-wrapper:not(.currentTarget) span.description:visible").prop("aria-hidden",!0).slideUp(250),t.length&&t.is(":hidden")&&t.prop("aria-hidden",!1).slideDown(250),o.removeClass("currentTarget")}),e.scroll_to_notices=function(o){o.length&&e("html, body").animate({scrollTop:o.offset().top-100},1e3)},e('.woocommerce form .woocommerce-Input[type="password"]').wrap('<span class="password-input"></span>'),e(".woocommerce form input").filter(":password").parent("span").addClass("password-input"),e(".password-input").each(function(){const o=e(this).find("input").attr("id");e(this).append('<button type="button" class="show-password-input" aria-label="'+woocommerce_params.i18n_password_show+'" aria-describedBy="'+o+'"></button>')}),e(".show-password-input").on("click",function(o){o.preventDefault(),e(this).hasClass("display-password")?(e(this).removeClass("display-password"),e(this).attr("aria-label",woocommerce_params.i18n_password_show)):(e(this).addClass("display-password"),e(this).attr("aria-label",woocommerce_params.i18n_password_hide)),e(this).hasClass("display-password")?e(this).siblings(['input[type="password"]']).prop("type","text"):e(this).siblings('input[type="text"]').prop("type","password"),e(this).siblings("input").focus()}),e("a.coming-soon-footer-banner-dismiss").on("click",function(o){var t=e(o.target);e.ajax({type:"post",url:t.data("rest-url"),data:{woocommerce_meta:{coming_soon_banner_dismissed:"yes"}},beforeSend:function(e){e.setRequestHeader("X-WP-Nonce",t.data("rest-nonce"))},complete:function(){e("#coming-soon-footer-banner").hide()}})}),"undefined"==typeof wc_add_to_cart_params&&e(document.body).on("keydown",".remove_from_cart_button",on_keydown_remove_from_cart),e(document.body).on("item_removed_from_classic_cart updated_wc_div",focus_populate_live_region)}),document.addEventListener("DOMContentLoaded",on_document_ready);
// source --> https://www.tacto.es/wp-content/plugins/duracelltomi-google-tag-manager/dist/js/analytics-talk-content-tracking.js?ver=1.22.3 
"use strict";"undefined"==typeof console&&(window.console={log:function(){}}),function(){var r,a=gtm4wp_scrollerscript_debugmode,t=gtm4wp_scrollerscript_callbacktime,l=gtm4wp_scrollerscript_readerlocation,o=0,i=!1,c=!1,d=!1,m=(new Date).getTime();function n(){var e,t=window.innerHeight+window.scrollY,o=document.body.offsetHeight,n=0;l<t&&!i&&(n=(new Date).getTime(),e=Math.round((n-m)/1e3),a?console.log("Started reading "+e):window[gtm4wp_datalayer_name].push({event:"gtm4wp.reading.startReading",timeToScroll:e}),i=!0),((null==(e=document.querySelector("#"+gtm4wp_scrollerscript_contentelementid))?void 0:e.scrollTop)||0)+((null==(e=document.querySelector("#"+gtm4wp_scrollerscript_contentelementid))?void 0:e.clientHeight)||0)<=t&&!c&&(e=(new Date).getTime(),e=Math.round((e-n)/1e3),a?console.log("End content section "+e):window[gtm4wp_datalayer_name].push({event:"gtm4wp.reading.contentBottom",timeToScroll:e}),c=!0),o<=t&&!d&&(e=(new Date).getTime(),r=Math.round((e-n)/1e3),a?(r<gtm4wp_scrollerscript_scannertime?console.log('The visitor seems to be a "scanner"'):console.log('The visitor seems to be a "reader"'),console.log("Bottom of page "+r)):(r<gtm4wp_scrollerscript_scannertime?window[gtm4wp_datalayer_name].push({event:"gtm4wp.reading.readerType",readerType:"scanner"}):window[gtm4wp_datalayer_name].push({event:"gtm4wp.reading.readerType",readerType:"reader"}),window[gtm4wp_datalayer_name].push({event:"gtm4wp.reading.pagebottom",timeToScroll:r})),d=!0)}a?console.log("Article loaded"):window[gtm4wp_datalayer_name].push({event:"gtm4wp.reading.articleLoaded"}),document.addEventListener("scroll",function(e){o&&clearTimeout(o),o=setTimeout(n,t)})}((window,document));
// source --> https://www.tacto.es/wp-content/plugins/woocommerce-min-max-quantities/assets/js/frontend/validate.min.js?ver=4.1.4 
!function(a){a(function(){var i={init:function(p){p.find(".quantity").each(function(){var n,t,i=a(this).find("input.qty");i.length&&(n=parseInt(i.prop("min"),10),t=""!==i.prop("max")?parseInt(i.prop("max"),10):1/0,1===n&&n===t?(i.prop("type","hidden"),a(this).addClass("hidden")):a(this).hasClass("hidden")&&(i.prop("type","number"),a(this).removeClass("hidden")))}),p.hasClass("variations_form")&&p.on("show_variation",function(n,t){var i=p.find("input.qty"),a=p.find(".quantity"),e=void 0===t.step||t.step.length?1:parseInt(t.step,10),o=parseInt(t.min_qty,10),t=""!==t.max_qty?parseInt(t.max_qty,10):1/0;1<e&&(e<o?o=(remain=o/e)?e*Math.ceil(remain):o:0<o&&(o=Math.max(o,e)),e<t?t=(remain=t/e)?e*Math.floor(remain):t:t<e&&(t=e)),i.prop("step",e).val(o),i.prop("min",o),i.prop("max",t),1===o&&o===t?(i.prop("type","hidden"),a.addClass("hidden")):a.hasClass("hidden")&&(i.prop("type","number"),a.removeClass("hidden"))})},watch:function(){a("body").on("wc-mmq-init-validation",function(n,t){i.init(t)})}},n=a("body").find(".cart:not( .cart_group )");n.length&&(n.each(function(){i.init(a(this))}),i.watch())})}(jQuery,(document,window));
// source --> https://www.tacto.es/wp-content/plugins/pixel-manager-for-woocommerce/admin/pixels/js/pixel-manager.js?ver=2.1 
window.dataLayer = window.dataLayer || [];
class PMW_PixelManagerJS {
  constructor(options = {}, is_Bindings = true, is_woocomerce = true){    
    this.options = {
      esc_tracking: true
    };
    if(options){
      Object.assign(this.options, options);
    }
    if(is_woocomerce){
      this.PixelManagerDataLayer = PixelManagerDataLayer[0]["data"];
      this.PMWEventID = PixelManagerEventOptions.time;
      this.PixelManagerOptions = PixelManagerOptions;
      this.TrackFormSubmissionsBindings();    

      this.LineItemReq = {    
        item_id       : 'item_id',
        item_name     : 'item_name',
        item_category : 'item_category',
        index         : 'index',
        item_brand    : 'item_brand',
        item_variant  : 'item_variant',
        price         : 'price',
        //currency      : "currency",
        //quantity      : 'quantity',
        item_list_name: 'item_list_name'
      };
      this.is_begin_checkout_fired = false;
      this.is_shipping_fired = false;
      this.TrackGoogleAdsConversionFormSubmissionsBindings();
    }else{
      this.PixelManagerOptions = PixelManagerOptions;
      this.TrackFormSubmissionsBindings();
      this.TrackGoogleAdsConversionFormSubmissionsBindings();
    }
    
    /*var variations = jQuery('.variations_form').data( 'product_variations' );
    var variation = this.get_item_form_items_by_key_val(variations, 'variation_id', 132);*/
  }
  TrackFormSubmissionsBindings(){
    if(this.PixelManagerOptions.hasOwnProperty('generate_lead_from') && this.PixelManagerOptions.generate_lead_from != ""){
      let generate_lead_from = this.PixelManagerOptions.generate_lead_from;
      generate_lead_from = generate_lead_from.replace(/,([^ ])/g, ', $1');     
      //var selector_elements = generate_lead_from.split(', ').map(selector => selector.trim());      
      var elements  = document.querySelectorAll(generate_lead_from);
      if(elements.length > 0){ 
        for (var i = 0; i < elements.length; i++) {
          if(elements[i]){
            elements[i].addEventListener("submit", () => this.TrackFormSubmissions(event));
          }
        }
      }
    }
  }

  TrackGoogleAdsConversionFormSubmissionsBindings() {
    const options = this.PixelManagerOptions;

    // Validate required fields for Google Ads form conversion tracking
    const isEnabled = options.google_ads_form_conversion?.is_enable;
    const conversionId = options.google_ads_form_conversion?.id;
    const conversionLabel = options.google_ads_form_conversion?.label;
    const selector = options.google_ads_form_conversion?.selector;

    // Only proceed if tracking is enabled and all required fields are present
    if (isEnabled && conversionId && conversionLabel && selector) {
      // Clean up selector string
      let formSelectors = selector.replace(/,([^ ])/g, ', $1');
      const elements = document.querySelectorAll(formSelectors);

      if (elements.length > 0) {
        elements.forEach(form => {
          if (form) {
            form.addEventListener("submit", (event) => this.TrackFormSubmissionsGoogleAds(event));
          }
        });
      }
    }
  }
  TrackFormSubmissionsGoogleAds(event){
    event.preventDefault();
    var this_var =  event.currentTarget;
    // prevent infinite loop on programmatic submit
    if (this_var && this_var.dataset && this_var.dataset.pmwSubmitted === '1') {
      return;
    }
    var form_name = this_var.getAttribute('aria-label') || this_var.getAttribute('name') || this_var.getAttribute('id');
    var form_id = this_var.getAttribute('id');
    var action_url = this_var.getAttribute('action');
    var page_url = window.location.href;
    var page_title = document.title;
    var PMWEvent = {
        event: "form_conversion",
        conversion_type: "lead_form_submission",
        page_title : page_title,
        form_id: (form_id)?form_id:"",
        form_name: (form_name)?form_name:"",
        action_url: (action_url)?action_url:"",
        page_url: page_url
      };
      dataLayer.push(PMWEvent);
  }

  TrackFormSubmissions(event){
    event.preventDefault();
    var this_var =  event.currentTarget;
    // prevent infinite loop on programmatic submit
    if (this_var && this_var.dataset && this_var.dataset.pmwSubmitted === '1') {
      return;
    }
    var form_name = this_var.getAttribute('aria-label') || this_var.getAttribute('name') || this_var.getAttribute('id');
    var form_id = this_var.getAttribute('id');
    var action_url = this_var.getAttribute('action');
    var page_url = window.location.href;
    var page_title = document.title;
    var PMWEvent = {
        event: "form_submit",
        page_title : page_title,
        form_id: (form_id)?form_id:"",
        form_name: (form_name)?form_name:"",
        action_url: (action_url)?action_url:"",
        page_url: page_url
      };
      dataLayer.push(PMWEvent);
      // continue with normal form submission
      if (this_var) {
        this_var.dataset.pmwSubmitted = '1';
        this_var.submit();
      }
  }

  Purchase(){
    if(this.PixelManagerDataLayer.hasOwnProperty('checkout') && this.PixelManagerDataLayer.checkout.hasOwnProperty('cart_product_list')){
      this.LineItemReq["quantity"]="quantity";
      var Items = this.GetLineItems(this.PixelManagerDataLayer.checkout.cart_product_list, this.LineItemReq);
      var PMWEvent = {
        event: "purchase",
        ecommerce: {
          transaction_id: this.PixelManagerDataLayer.checkout.id,
          currency: this.PixelManagerDataLayer.currency,
          value: this.PixelManagerDataLayer.checkout.total,
          tax: this.PixelManagerDataLayer.checkout.tax,
          shipping: this.PixelManagerDataLayer.checkout.shipping,
          coupon: this.PixelManagerDataLayer.checkout.coupon,
          items: Items
        }
      };
      dataLayer.push(PMWEvent);
    }
  }

  TrackPurchase() {
    if (!this.PixelManagerDataLayer?.checkout?.cart_product_list) {
      return;
    }

    const { id: order_id, cart_product_list: items, total } = this.PixelManagerDataLayer.checkout;
    const { currency } = this.PixelManagerDataLayer;
    const itemsArray = Object.values(items);

    // Prepare platforms data
    const platformsData = {
      facebook: this.PixelManagerOptions.fb_conversion_api?.is_enable || false,
      tiktok: this.PixelManagerOptions.tiktok_conversion_api?.is_enable || false,
      pinterest: this.PixelManagerOptions.pinterest_conversion_api?.is_enable || false,
      //twitter: this.PixelManagerOptions.twitter_conversion_api?.is_enable || false,
      //snapchat: this.PixelManagerOptions.snapchat_conversion_api?.is_enable || false
    };

    // Prepare common data
    const eventData = {
      event_id: this.PMWEventID,
      order_id,
      currency,
      total,
      items: JSON.stringify(itemsArray.map(item => ({
        id: item.id,
        name: item.item_name,
        price: item.price,
        quantity: item.quantity,
        category: item.category?.[0]
      }))),
      platforms: JSON.stringify(platformsData) // Stringify the platforms object
    };

    // Only proceed if any platform is enabled
    if (!Object.values(platformsData).some(Boolean)) {
      return;
    }

    // Single AJAX call for all platforms
    jQuery.ajax({
      type: 'POST',
      url: pmw_f_ajax_url,
      data: {
          action: 'pmw_process_conversion_events',
          ...eventData
      },
      success: (response) => {
          console.log('Conversion events processed:', response);
      },
      error: (xhr, status, error) => {
          console.error('Error processing conversions:', error);
      }
    });
  }
  
  IsEmpty(List){
    if(List != undefined && Object.keys(List).length > 0 ){
      return false;
    }
    return true;
  }
  ConvertArrayToString(value){
    if(Object.keys(value).length > 0){
      return value.join(", ");
    }else{
      return value;
    }
  }
  GetProductFromProductList(product_id){    
     if(this.PixelManagerDataLayer.hasOwnProperty('product_list') && product_id != ""){
      var ProductList = this.PixelManagerDataLayer.product_list;
      if(!this.IsEmpty(ProductList) ){        
        for(var dataLayer_item in ProductList){
          if(ProductList[dataLayer_item].hasOwnProperty('id')){
            var id = ProductList[dataLayer_item].id;
            if(product_id == id){
              return ProductList[dataLayer_item];
            }
          }
        }
      }
    }
  }
  GetProductFromCartProductList(product_id){
    if(this.PixelManagerDataLayer.hasOwnProperty('checkout') && this.PixelManagerDataLayer.checkout.hasOwnProperty('cart_product_list')){
      var ProductList = this.PixelManagerDataLayer.checkout.cart_product_list;
      if(!this.IsEmpty(ProductList) ){        
        for(var dataLayer_item in ProductList){
          if(ProductList[dataLayer_item].hasOwnProperty('id')){
            var id = ProductList[dataLayer_item].id;
            if(product_id == id){
              return ProductList[dataLayer_item];
            }
          }
        }
      }
    }
  }
  /*get_variation_data(obj){
    var p_v_title = "";
    var variation_data = [];
    if(Object.keys(obj).length >0 ){
      for(var dataLayer_item in obj) {
        if(obj[dataLayer_item].hasOwnProperty("attributes")){
          for(var p_attributes in obj[dataLayer_item]) {
            if(obj[dataLayer_item].hasOwnProperty(p_attributes)){
              p_v_title+=(p_v_title=="")?p_attributes[index]:' | '+p_attributes[index]; 
            }      
          }
          variation_data.push(p_v_title);
        }      
      }
      return variation_data;
    }
  }
  get_item_form_items_by_key_val(obj, key, val){
    if(val != ""){
      if(Object.keys(obj).length >0 ){
        for(var dataLayer_item in obj){
          if(obj[dataLayer_item].hasOwnProperty(key)){
            var map_val = obj[dataLayer_item][key]; 
            if(val == map_val){
              return obj[dataLayer_item];
            }
          }
        }
      }
    }
  }*/

  GetProductFromProductListByURL(prod_obj, key, product_url){
    if(this.IsEmpty(prod_obj)){
      return [];
    }
    if(product_url != ""){      
      for(var dataLayer_item in prod_obj){
        if(prod_obj[dataLayer_item].hasOwnProperty(key)){
          var map_val = prod_obj[dataLayer_item][key]; 
          if(product_url == map_val){
            return prod_obj[dataLayer_item];
          }
        }
      }      
    }
  }
  GetLineItems( ProductList, LineItemReq, PixelName = null ){
    if(this.IsEmpty(ProductList)){
      return [];
    }
    var this_var = this;
    var ProductItems = [];
    if(Object.keys(ProductList).length > 0){
      Object.keys(ProductList).forEach(function(KeyVal, index){        
        if(ProductList.hasOwnProperty(KeyVal)){
          var Item = ProductList[KeyVal];
          var NewItem = this_var.GetLineItem(Item, LineItemReq, PixelName);
          if(Object.keys(NewItem).length > 0){
            ProductItems.push( NewItem );
          }
        }        
      });      
    }
    return ProductItems;
  }
  GetLineItem( Product, LineItemReq, PixelName = null){
    if(this.IsEmpty(Product)){
      return [];
    }
    var ProductItem = {};
    if(Object.keys(LineItemReq).length > 0){
      Object.keys(LineItemReq).forEach(function(KeyVal, index){
        var ItemKey = LineItemReq[KeyVal];
        if(Product.hasOwnProperty(ItemKey)){
          if(KeyVal == "item_category"){
            Object.keys(Product[ItemKey]).forEach(function(c_KeyVal, c_index){
              if(c_KeyVal == 0 ){
                ProductItem[KeyVal] = Product[ItemKey][c_index];
              }else{
                ProductItem[KeyVal+(c_index+1)] = Product[ItemKey][c_index];
              }
            });
          }else if(Product[ItemKey] != '' && Product[ItemKey] != null && Product[ItemKey] != 'undefined' ){
            ProductItem[KeyVal] = Product[ItemKey];
          }
        }
      });
      /*if(PixelName == "Tiktok"){
        ProductItem['currency'] = DataLayer.currency;
      }*/
    }
    return ProductItem;    
  }
  getParameterByName(name, url = window.location.href){
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
  }
  isFacebookConversionAPIEnable(){
    if(this.PixelManagerOptions.hasOwnProperty("fb_conversion_api") && this.PixelManagerOptions.fb_conversion_api.is_enable){
      return true;
    }else{
      return false;
    }
  }
  isGA4Enable(){
    if(this.PixelManagerOptions.hasOwnProperty("google_analytics_4_pixel") && this.PixelManagerOptions.google_analytics_4_pixel.is_enable ){
      return true;
    }else{
      return false;
    }
  }
  isTikTokConversionAPIEnable(){
    if(this.PixelManagerOptions.hasOwnProperty("tiktok_conversion_api") && this.PixelManagerOptions.tiktok_conversion_api.is_enable){
      return true;
    }else{
      return false;
    }
  }
};