/*--------------------------------------------------------------
Rentopian Sync Add Ons Modal Functionality Scripts
Author: Rentopian
Website: https://rentopian.com
Copyright 2019, Rentopian Inc. All Rights Reserved.
----------------------------------------------------------------*/

jQuery(document).ready(function($) {

  var $rental_add_ons_modal = $('#rental_add_ons');
  if ($rental_add_ons_modal.length) {
    function addToCartHandler(e) {
      // a sign to know it is a product with variable addons
      setCookie("rental_addon_product", true, 1)
      if ($rental_add_ons_modal.data('modal_is_open')) {
        $rental_add_ons_modal.hide('slow');
        return;
      }
      var variant_id = parseInt($('input[name=variation_id]').val());
      var selected_variants = $rental_add_ons_modal.data('selected_variants');
      if (variant_id && selected_variants && selected_variants.includes(variant_id)) {
        return;
      }
      e.preventDefault();
      e.stopImmediatePropagation();
      $rental_add_ons_modal.data('modal_is_open', 1).show('slow');
    }

    var $att_to_cart_form = $rental_add_ons_modal.closest('form.cart');
    $att_to_cart_form.on('submit', addToCartHandler)
      .on('click', '.single_add_to_cart_button', addToCartHandler);

    $rental_add_ons_modal.on('click', '.rental-modal-cancel', function() {
      // delete the addon cookie
      deleteCookie("rental_addon_product", "/");
      $rental_add_ons_modal.data('modal_is_open', '').hide('slow');
    });
  }


  var $cartBtn = $("form.cart").find(".single_add_to_cart_button");

  if ($('div.product').length) {
      var mainProductId = $cartBtn.val();

      if ($('div#product_has_rental_add_ons').length) {
        
          /* Product with addons' items variant_id fixing 
          * 
          */
          block($cartBtn);
          $.ajax({
              type: 'POST',
              url: rentalObj.url,
              dataType: 'JSON',
              data: {
                  action: 'rental_product_with_addons_fix_variants',
                  product_id: mainProductId
              },
              success: function(data) {
                // console.log(" addons variants fix ", data )
              },
              error: function(data) {
                console.log('error:', data )
              },
              complete: function(data) {
                unblock($cartBtn); 
              }
          });
      }
  }

});


