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

jQuery(document).ready(function($) {
  var $cartBtn = $("form.cart").find(".single_add_to_cart_button");
  var $product_div = $('div.product');
  var $selectOptionHolder = $product_div.find(".rental-product-options");

  // single product page related
  // get all options of a product including selected ones
  function get_options_of_single_product() {
    if ($product_div.length) {
      var product_id = 0;

      setTimeout(function() {

        let $isSetOptions = $("div.rental-is-set");
        if ($('form.variations_form').length) {
          product_id = $(".woocommerce-variation-add-to-cart").find('input.variation_id').val();
        } else {
          product_id = $cartBtn.val();
        }
      
        block($selectOptionHolder);
        $.ajax({
          type: 'POST',
          url: rentalObj.url,
          dataType: 'JSON',
          data: {
              action: 'rental_get_all_options_of_product',
              product_id: product_id,
              is_set: $isSetOptions.length // check if it is a SET
          },
          success: function(data) {
          },
          error: function(data) {
            console.log('error:', data )
          },
          complete: function(data) {
            var selectedOptions = [];
            if (data.responseText !== '' && data.responseJSON) {
              selectedOptions = data.responseJSON;
            }
           
            if (selectedOptions.length) {

              $selectOptionHolder.html("");
              for(var i=0; i<selectedOptions.length; i++) {
                if (selectedOptions[i]["once_per_order"] === 1) {
                  var $once_per_order_selected_msg = "<label for='" + selectedOptions[i]["option_id"] + "'> " + selectedOptions[i]["option_title"] + " </label>";
                  $once_per_order_selected_msg += "<small> The Option is a once per order type. </small>";
                  $selectOptionHolder.append($once_per_order_selected_msg);
                  continue;
                }
                var $select = "<label for='" + selectedOptions[i]["option_id"] + "'> " + selectedOptions[i]["option_title"] + " </label>";
                $select += "<select onchange='update_option_data_of_single_product(this)' data-is-set='" + $isSetOptions.length + "' data-product-id='" + selectedOptions[i]["product_id"] + "' id='" + selectedOptions[i]["option_id"] + "' class='rental-product-options-select'>";
                var $option = "";
                var alreadySelectedValue = false;
                for(var v=0; v<selectedOptions[i]['option_values'].length; v++) {
                  var $item = "<option data-selected='0' id='" + selectedOptions[i]['option_values'][v]["id"] + "'  data-value='" + selectedOptions[i]['option_values'][v]["price"] + "' value='" + selectedOptions[i]['option_values'][v]["id"] + "' ";

                    if (selectedOptions[i]['is_selected'] === 1 && selectedOptions[i]['option_values'][v]["id"] === selectedOptions[i]["selected_value_id"]) {
                      $item += " selected='' data-selected='1' ";
                      alreadySelectedValue = true;
                    } else {
                      if (selectedOptions[i]['option_values'][v]["is_default"] === 1 && !alreadySelectedValue) {
                        $item += " selected='' data-selected='1' ";
                        alreadySelectedValue = true;
                      } 
                      // else {
                      //   if (selectedOptions[i]['option_values'][v]["id"] == -1) {
                      //     $item += " selected='' data-selected='1' ";
                      //   }
                      // }
                    }
                  

                  var $price = selectedOptions[i]['option_values'][v]["price"];
                  if ($price !== 0 && $price !== -1) {
                    $item += "> " + selectedOptions[i]['option_values'][v]["title"] + " (" + selectedOptions[i]["currency"] + $price + ")";
                  } else {
                    $item += "> " + selectedOptions[i]['option_values'][v]["title"];
                  }
                  $item += " </option>";
                  $option += $item;
                }
                $select += $option + "</select></div>";
                $selectOptionHolder.append($select);
                
              }
              checkAddToCartPossibility();
            }
            unblock($selectOptionHolder); 
          }
        });
      
      }, 500)
    }
  }

  var $variation_add_cart = $(".woocommerce-variation-add-to-cart");
  if ($variation_add_cart.find('input.variation_id').length) {
      $variation_add_cart.find('input.variation_id').on("change", function() {
      
      if ($(".rental-product-options").length) {
        $cartBtn.addClass('disabled');
        $cartBtn.attr("disabled", true);
        get_options_of_single_product();
      }
      
    });
  } else {

    if ($(".rental-product-options").length) {
      get_options_of_single_product();
    }

  }

  // cart page related
  // get all options of a all cart products including selected ones
  function get_options_of_cart_products() {
    // indicate we are in cart page
    if ($('.woocommerce-cart-form').length) {

      var $productOptionsBlock = $(".woocommerce-cart-form table tbody").find(".cart_item td.product-options");
      block($productOptionsBlock);
      $.ajax({
        type: 'POST',
        url: rentalObj.url,
        dataType: 'JSON',
        data: {
            action: 'rental_get_all_options_of_cart_products'
        },
        success: function(data) {

        },
        error: function(data) {
          console.log('error:', data )
        },
        complete: function(data) {
          var selectedOptions = [];
          if (data.responseText !== '' && data.responseJSON) {
            selectedOptions = data.responseJSON;
          }
         
          if (selectedOptions.length) {
            
              $cartItem = $(".woocommerce-cart-form table tbody").find(".cart_item");
              $cartItem.each(function(){
                var $productOptions = $(this).find("td.product-options");
                $productOptions.each(function(){
                  for(var i=0; i<selectedOptions.length; i++) {
                    if ($productOptions.data("product-id") !== selectedOptions[i]["product_id"]) {
                      continue;
                    }
                    var $selectOptionHolder = $(this);
                    var $select = "<div class='rental-product-options'>"; 
                    if (selectedOptions[i]["once_per_order"] === 1) {
                      var $once_per_order_selected_msg = "<label for='" + selectedOptions[i]["option_id"] + "'> " + selectedOptions[i]["option_title"] + " </label>";
                      $once_per_order_selected_msg += "<small> The Option is a once per order type. </small>";
                      $selectOptionHolder.append($once_per_order_selected_msg);
                      continue;
                    }
                    $select += "<labelfor='" + selectedOptions[i]["option_id"] + "'> " + selectedOptions[i]["option_title"] + " </label>";
                    $select += "<select onchange='update_option_data(this)' data-key='"+ selectedOptions[i]["key"] +"' data-product-id='" + selectedOptions[i]["product_id"] + "' id='" + selectedOptions[i]["option_id"] + "' class='rental-product-options-select'>";
                    var $option = "";
                    var alreadySelectedValue = false;
                    for(var v=0; v<selectedOptions[i]['option_values'].length; v++) {
                      var $item = "<option data-selected='0' id='" + selectedOptions[i]['option_values'][v]["id"] + "'  data-value='" + selectedOptions[i]['option_values'][v]["price"] + "' value='" + selectedOptions[i]['option_values'][v]["id"] + "' ";

                        if (selectedOptions[i]['is_selected'] === 1 && selectedOptions[i]['option_values'][v]["id"] === selectedOptions[i]["selected_value_id"]) {
                          $item += " selected='' data-selected='1' ";
                          alreadySelectedValue = true;
                        } else {
                          if (selectedOptions[i]['option_values'][v]["is_default"] === 1 && !alreadySelectedValue) {
                            $item += " selected='' data-selected='1' ";
                            alreadySelectedValue = true;
                          } 
                          // else {
                          //   if (selectedOptions[i]['option_values'][v]["id"] == -1) {
                          //     $item += " selected='' data-selected='1' ";
                          //   }
                          // }
                        }
                      

                      var $price = selectedOptions[i]['option_values'][v]["price"];
                      if ($price !== 0 && $price !== -1) {
                        $item += "> " + selectedOptions[i]['option_values'][v]["title"] + " (" + selectedOptions[i]["currency"] + $price.toFixed(2) + ")";
                      } else {
                        $item += "> " + selectedOptions[i]['option_values'][v]["title"];
                      }
                      $item += " </option>";
                      $option += $item;
                    }
                    $select += $option + "</select></div>";
                    $selectOptionHolder.append($select);
                    
                  }
                });
              })

            
          }
          unblock($productOptionsBlock);
        }
      });
    }
  }
  get_options_of_cart_products();

  // product specific once per order options (cart page related)
  function get_order_options_of_cart_page() {
    if ($('tr.order-options').length) {

        var $orderOptionsRow =      $("tr.order-options");
        var $orderOptionsBlock =    $orderOptionsRow.find("td.order-options-td");
        var $orderOptionsPrice =    $orderOptionsRow.find("td.order-options-price");
        var $orderOptionsSubtotal = $orderOptionsRow.find("td.order-options-subtotal");

        block($orderOptionsBlock);
        block($orderOptionsPrice);
        block($orderOptionsSubtotal);
        $.ajax({
          type: 'POST',
          url: rentalObj.url,
          dataType: 'JSON',
          data: {
              action: 'rental_get_order_options'
          },
          success: function(data) {
          },
          error: function(data) {
            console.log('error:', data )
          },
          complete: function(data) {
            var selectedOptions = [];
            if (data.responseText !== '' && data.responseJSON) {
              selectedOptions = data.responseJSON;
            }
           
            if (selectedOptions.length) {
              $orderOptionsBlock.html("");
              $orderOptionsPrice.html("");
              $orderOptionsSubtotal.html("");
              var totalPrice = 0;
              var currency = selectedOptions[0]["currency"] || '';
              for(var i=0; i<selectedOptions.length; i++) {
                var $select = "<div class='rental-product-options'>"; 
                $select += "<label> " + selectedOptions[i]["option_title"] + " </label>";
                $select += "<select onchange='update_order_option_data(this)'  id='" + selectedOptions[i]["option_id"] + "' class='rental-order-options-select'>";
                var $option = "";
                var alreadySelectedValue = false;
                for(var v=0; v<selectedOptions[i]['option_values'].length; v++) {
                  var $item = "<option data-selected='0' id='" + selectedOptions[i]['option_values'][v]["id"] + "'  data-value='" + selectedOptions[i]['option_values'][v]["price"] + "' value='" + selectedOptions[i]['option_values'][v]["id"] + "' ";

                  var $price = selectedOptions[i]['option_values'][v]["price"];
                  if (selectedOptions[i]['is_selected'] === 1 && selectedOptions[i]['option_values'][v]["id"] === selectedOptions[i]["selected_value_id"]) {
                    $item += " selected='' data-selected='1' ";
                    alreadySelectedValue = true;

                    // calculating price/subtotal of order specific options
                    totalPrice += $price >= 0 ? $price : 0;
                    currency = selectedOptions[i]["currency"];

                  } else {
                    if (selectedOptions[i]['option_values'][v]["is_default"] === 1 && !alreadySelectedValue) {
                      $item += " selected='' data-selected='1' ";
                      alreadySelectedValue = true;
                    } 
                    // else {
                    //   if (selectedOptions[i]['option_values'][v]["id"] == -1) {
                    //     $item += " selected='' data-selected='1' ";
                    //   }
                    // }
                  }

                  if ($price !== 0 && $price !== -1) {
                    $item += "> " + selectedOptions[i]['option_values'][v]["title"] + " (" + selectedOptions[i]["currency"] + $price.toFixed(2) + ")";
                  } else {
                    $item += "> " + selectedOptions[i]['option_values'][v]["title"];
                  }
                  $item += " </option>";
                  $option += $item;
                }
                $select += $option + "</select></div>";
                $orderOptionsBlock.append($select);
              }
              $orderOptionsPrice.append('<b>'+ currency + totalPrice.toFixed(2) +'</b>');
              $orderOptionsSubtotal.append('<b>'+ currency + totalPrice.toFixed(2) +'</b>');

            }
            unblock($orderOptionsBlock); 
            unblock($orderOptionsPrice);
            unblock($orderOptionsSubtotal);
          }
        });
    }
  }
  get_order_options_of_cart_page();

   // product specific once per order options (cart page related)
  function get_sets_order_options_of_cart_page() {
    if ($('tr.sets-order-options').length) {

        var $orderOptionsRow =      $("tr.sets-order-options");
        var $orderOptionsBlock =    $orderOptionsRow.find("td.order-options-td");
        var $orderOptionsPrice =    $orderOptionsRow.find("td.order-options-price");
        var $orderOptionsSubtotal = $orderOptionsRow.find("td.order-options-subtotal");

        block($orderOptionsBlock);
        block($orderOptionsPrice);
        block($orderOptionsSubtotal);
        $.ajax({
          type: 'POST',
          url: rentalObj.url,
          dataType: 'JSON',
          data: {
              action: 'rental_get_order_options_of_sets'
          },
          success: function(data) {
          },
          error: function(data) {
            console.log('error:', data )
          },
          complete: function(data) {
            var selectedOptions = [];
            if (data.responseText !== '' && data.responseJSON) {
              selectedOptions = data.responseJSON;
            }
           
            if (selectedOptions.length) {
              $orderOptionsBlock.html("");
              $orderOptionsPrice.html("");
              $orderOptionsSubtotal.html("");
              var totalPrice = 0;
              var currency = selectedOptions[0]["currency"] || '';
              for(var i=0; i<selectedOptions.length; i++) {
                var $select = "<div class='rental-product-options'>"; 
                $select += "<label> " + selectedOptions[i]["option_title"] + " </label>";
                $select += "<select onchange='update_order_option_data_of_sets(this)'  id='" + selectedOptions[i]["option_id"] + "' class='rental-order-options-select'>";
                var $option = "";
                var alreadySelectedValue = false;
                for(var v=0; v<selectedOptions[i]['option_values'].length; v++) {
                  var $item = "<option data-selected='0' id='" + selectedOptions[i]['option_values'][v]["id"] + "'  data-value='" + selectedOptions[i]['option_values'][v]["price"] + "' value='" + selectedOptions[i]['option_values'][v]["id"] + "' ";

                  var $price = selectedOptions[i]['option_values'][v]["price"];
                  if (selectedOptions[i]['is_selected'] === 1 && selectedOptions[i]['option_values'][v]["id"] === selectedOptions[i]["selected_value_id"]) {
                    $item += " selected='' data-selected='1' ";
                    alreadySelectedValue = true;

                    // calculating price/subtotal of order specific options
                    totalPrice += $price >= 0 ? $price : 0;
                    currency = selectedOptions[i]["currency"];

                  } else {
                    if (selectedOptions[i]['option_values'][v]["is_default"] === 1 && !alreadySelectedValue) {
                      $item += " selected='' data-selected='1' ";
                      alreadySelectedValue = true;
                    } 
                    // else {
                    //   if (selectedOptions[i]['option_values'][v]["id"] == -1) {
                    //     $item += " selected='' data-selected='1' ";
                    //   }
                    // }
                  }

                  if ($price !== 0 && $price !== -1) {
                    $item += "> " + selectedOptions[i]['option_values'][v]["title"] + " (" + selectedOptions[i]["currency"] + $price.toFixed(2) + ")";
                  } else {
                    $item += "> " + selectedOptions[i]['option_values'][v]["title"];
                  }
                  $item += " </option>";
                  $option += $item;
                }
                $select += $option + "</select></div>";
                $orderOptionsBlock.append($select);
              }
              $orderOptionsPrice.append('<b>'+ currency + totalPrice.toFixed(2) +'</b>');
              $orderOptionsSubtotal.append('<b>'+ currency + totalPrice.toFixed(2) +'</b>');

            }
            unblock($orderOptionsBlock); 
            unblock($orderOptionsPrice);
            unblock($orderOptionsSubtotal);
          }
        });
    }
  }
  get_sets_order_options_of_cart_page();
  
  function get_order_options_effected_subtotal() {
    if ($('tr.order-options').length) {
      var subtotalPriceHolder = jQuery(".cart_totals").find('[data-title="Subtotal"] .woocommerce-Price-amount')
      
        block(subtotalPriceHolder);
        jQuery.ajax({
          type: 'POST',
          url: rentalObj.url,
          dataType: 'JSON',
          data: {
              action: 'rental_get_order_options_effected_subtotal'
          },
          success: function(data) {
          },
          error: function(data) {
            console.log('error:', data )
          },
          complete: function(data) {
            var serverData = data.responseJSON;
    
            if (serverData !== '') {
                if (serverData.subtotal !== undefined && serverData.subtotal !== '' ) {
                  subtotalPriceHolder.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.subtotal+'</bdi>')
                }
            }
    
            unblock(subtotalPriceHolder);
          }
        });
    }
  }
  setTimeout(() => {
    get_order_options_effected_subtotal();
  }, 200);
  
  // cart page related (trigger on cart item quantity update)
  $(document.body).on( 'updated_cart_totals', function(){
      get_options_of_cart_products();
      get_order_options_of_cart_page();
      get_sets_order_options_of_cart_page();
      get_order_options_effected_subtotal();
  });

  $miniCartCheckoutBtn = $(".minicart-dropdown-wrapper .woocommerce-mini-cart__buttons a.checkout")
  $miniCartCheckoutBtn.on("click", function(e) {
    e.preventDefault();

    block($miniCartCheckoutBtn);
    $.ajax({
      type: 'POST',
      url: rentalObj.url,
      dataType: 'JSON',
      data: {
          action: 'rental_check_selected_options'
      },
      success: function(data) {
        // console.log(' check:',  data)
  
        if (data.check !== true) {

          // inside cart page
          if (window.location.href.indexOf("cart") > -1) {
            // customer needs to select a value for each products' options
            errorMsg("Please, review product options before checking out.");
            $([document.documentElement, document.body]).animate({
              scrollTop: $(".rntl-opt-err").offset().top - 120
            }, 1000);
          } else {
            // inside other pages
            window.location = data.url_cart;
          }
         
        } else {
          errorMsg("");
          window.location = data.url;
        }
  
      },
      error: function(data) {
        console.log('error:', data )
      },
      complete: function() {
        unblock($miniCartCheckoutBtn);
        $(".minicart-dropdown-wrapper").find(".close-btn").click()
      }
    });
  })

  
});

function block($node) {
  if ( !$node.is('.processing') && !$node.parents('.processing').length) {
    $node.addClass('processing').block({
      message: null,
      overlayCSS: {
        background: '#fff',
        opacity: 0.6
      }
    });
  }
}

function unblock($node) {
  $node.removeClass('processing').unblock();
}

$checkoutBtn = jQuery(".wc-proceed-to-checkout").find(".checkout-button")
function update_option_data(element) {
  var target = jQuery(element);
  var key = target.data('key');
  var product_id = target.data('product-id');
  var value_id = target.find('option:selected').attr('id');
  var price = target.find('option:selected').data('value');
  var option_id = target.attr('id');

  var $cartTotals = jQuery(".cart_totals");

  var productTotalPriceHolder = jQuery("#"+key+"_subtotal").find('.woocommerce-Price-amount');
  var productTotalPriceHolder_alternative = jQuery("#"+product_id+"_subtotal").find('.woocommerce-Price-amount');

  var subtotalPriceHolder = $cartTotals.find('[data-title="Subtotal"] .woocommerce-Price-amount');
  var subtotalPriceHolder_alternative = $cartTotals.find('.cart-subtotal .cart-totals-value .woocommerce-Price-amount');

  var totalPriceHolder = $cartTotals.find('[data-title="Total"] .woocommerce-Price-amount');
  var totalPriceHolder_alternative = $cartTotals.find('.order-total .cart-totals-value .woocommerce-Price-amount');
  
    block($checkoutBtn);
    block(productTotalPriceHolder);
    block(productTotalPriceHolder_alternative);
    block(subtotalPriceHolder);
    block(subtotalPriceHolder_alternative);
    block(totalPriceHolder);
    block(totalPriceHolder_alternative);

    jQuery.ajax({
      type: 'POST',
      url: rentalObj.url,
      dataType: 'JSON',
      data: {
          action: 'rental_update_product_option',
          product_id: product_id,
          option_id: option_id,
          value_id: value_id,
          price: price,
      },
      success: function(data) {
      },
      error: function(data) {
        console.log('error:', data )
      },
      complete: function(data) {
        var serverData="";
        if (data.responseText !== '' &&  data.responseJSON) {
          serverData = data.responseJSON;
        }

        if (serverData !== '') {
            if (serverData.total !== undefined 
              && serverData.subtotal !== undefined 
              && serverData.price_total !== undefined 
            ) {
              totalPriceHolder.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.total+'</bdi>')
              totalPriceHolder_alternative.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.total+'</bdi>')
              subtotalPriceHolder.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.subtotal+'</bdi>')
              subtotalPriceHolder_alternative.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.subtotal+'</bdi>')
              productTotalPriceHolder.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.price_total+'</bdi>')
              productTotalPriceHolder_alternative.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.price_total+'</bdi>')
            }

            var $cartTotals = jQuery(".cart_totals");

            if (serverData.security_deposit_title !== undefined && serverData.security_deposit_title.trim() !== '') {
              $cartTotals.find('[data-title="'+serverData.security_deposit_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.security_deposit_value+'</bdi>')
            }
    
            if ( serverData.is_auto_tax === 1) {
              if (serverData.tax_title !== undefined && serverData.tax_title.trim() !== '') {
                $cartTotals.find('tr.auto-tax-key').html('<th>' + serverData.tax_title.trim() + '</th><td class="auto-tax-value"></td>')
                $cartTotals.find('td.auto-tax-value').html(serverData.currency+serverData.tax_value)
              }
            } else {
              if (serverData.tax_title !== undefined && serverData.tax_title.trim() !== '') {
                $cartTotals.find('[data-title="'+serverData.tax_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.tax_value+'</bdi>')
              }
            }
            
            
            if (serverData.damage_waiver_title !== undefined && serverData.damage_waiver_title.trim() !== '') {
              $cartTotals.find('[data-title="'+serverData.damage_waiver_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.damage_waiver_value+'</bdi>')
            }
    
            if (serverData.damage_waiver_tax_title !== undefined && serverData.damage_waiver_tax_title.trim() !== '') {
              $cartTotals.find('[data-title="'+serverData.damage_waiver_tax_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.damage_waiver_tax_value+'</bdi>')
            }
    
            if (serverData.rush_fee_title !== undefined && serverData.rush_fee_title.trim() !== '') {
              $cartTotals.find('[data-title="'+serverData.rush_fee_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.rush_fee_value+'</bdi>')
            }

            if (serverData.auto_applied_fees !== undefined && serverData.auto_applied_fees.length > 0) {
              for(var i=0; i < serverData.auto_applied_fees.length; i++) {
                $cartTotals.find('[data-title="'+serverData.auto_applied_fees[i]["title"].trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.auto_applied_fees[i]["amount"]+'</bdi>')
              }
            }
        }

        unblock(productTotalPriceHolder_alternative);
        unblock(productTotalPriceHolder);
        unblock(subtotalPriceHolder);
        unblock(subtotalPriceHolder_alternative);
        unblock(totalPriceHolder);
        unblock(totalPriceHolder_alternative);
        unblock($checkoutBtn);
      }
    });
}

// product specific order options - cart page related
function update_order_option_data(element) {
  var target = jQuery(element);
  var value_id = target.find('option:selected').attr('id');
  var price = target.find('option:selected').data('value');
  var option_id = target.attr('id');
  var $cart_totals = jQuery(".cart_totals");

  var orderOptionPriceHolder = jQuery(".order-options td.order-options-price")
  var orderOptionTotalPriceHolder = jQuery(".order-options td.order-options-subtotal")
  var subtotalPriceHolder = $cart_totals.find('[data-title="Subtotal"] .woocommerce-Price-amount')
  var totalPriceHolder = $cart_totals.find('[data-title="Total"] .woocommerce-Price-amount')
  
    block($checkoutBtn);
    block(orderOptionPriceHolder);
    block(orderOptionTotalPriceHolder);
    block(subtotalPriceHolder);
    block(totalPriceHolder);
    jQuery.ajax({
      type: 'POST',
      url: rentalObj.url,
      dataType: 'JSON',
      data: {
          action: 'rental_update_order_option',
          option_id: option_id,
          value_id: value_id,
          price: price,
      },
      success: function(data) {
      },
      error: function(data) {
        console.log('error:', data )
      },
      complete: function(data) {
        // console.log(' update order option dataaaaa:',  data)
        var serverData = data.responseJSON;
        var $cart_totals = jQuery(".cart_totals");

        if (serverData !== '') {
            if (serverData.total !== undefined 
              && serverData.subtotal !== undefined 
              && serverData.price_total !== undefined 
            ) {
              totalPriceHolder.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.total+'</bdi>')
              subtotalPriceHolder.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.subtotal+'</bdi>')
              orderOptionPriceHolder.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.price_total+'</bdi>')
              orderOptionTotalPriceHolder.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.price_total+'</bdi>')
            }

            if (serverData.security_deposit_title !== undefined && serverData.security_deposit_title.trim() !== '') {
              $cart_totals.find('[data-title="'+serverData.security_deposit_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.security_deposit_value+'</bdi>')
            }
    
            if (serverData.tax_title !== undefined && serverData.tax_title.trim() !== '') {
              $cart_totals.find('[data-title="'+serverData.tax_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.tax_value+'</bdi>')
            }
            
            if (serverData.damage_waiver_title !== undefined && serverData.damage_waiver_title.trim() !== '') {
              $cart_totals.find('[data-title="'+serverData.damage_waiver_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.damage_waiver_value+'</bdi>')
            }
    
            if (serverData.damage_waiver_tax_title !== undefined && serverData.damage_waiver_tax_title.trim() !== '') {
              $cart_totals.find('[data-title="'+serverData.damage_waiver_tax_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.damage_waiver_tax_value+'</bdi>')
            }

            if (serverData.rush_fee_title !== undefined && serverData.rush_fee_title.trim() !== '') {
              $cart_totals.find('[data-title="'+serverData.rush_fee_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.rush_fee_value+'</bdi>')
            }
    
            if (serverData.auto_applied_fees !== undefined && serverData.auto_applied_fees.length > 0) {
              for(var i=0; i < serverData.auto_applied_fees.length; i++) {
                $cart_totals.find('[data-title="'+serverData.auto_applied_fees[i]["title"].trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.auto_applied_fees[i]["amount"]+'</bdi>')
              }
            }
        }

        unblock(orderOptionPriceHolder);
        unblock(orderOptionTotalPriceHolder);
        unblock(subtotalPriceHolder);
        unblock(totalPriceHolder);
        unblock($checkoutBtn);
      }
    });
}
// sets specific order options - cart page related
function update_order_option_data_of_sets(element) {
  var target = jQuery(element);
  var value_id = target.find('option:selected').attr('id');
  var price = target.find('option:selected').data('value');
  var option_id = target.attr('id');
  var $cart_totals = jQuery(".cart_totals");

  var orderOptionPriceHolder = jQuery(".sets-order-options td.order-options-price")
  var orderOptionTotalPriceHolder = jQuery(".sets-order-options td.order-options-subtotal")
  // var subtotalPriceHolder = $cart_totals.find('[data-title="Subtotal"] .woocommerce-Price-amount')
  var subtotalPriceHolder = $cart_totals.find('.cart-subtotal .cart-totals-value .woocommerce-Price-amount')
  // var totalPriceHolder = $cart_totals.find('[data-title="Total"] .woocommerce-Price-amount')
  var totalPriceHolder = $cart_totals.find('.order-total .cart-totals-value .woocommerce-Price-amount')
  
    block($checkoutBtn);
    block(orderOptionPriceHolder);
    block(orderOptionTotalPriceHolder);
    block(subtotalPriceHolder);
    block(totalPriceHolder);
    jQuery.ajax({
      type: 'POST',
      url: rentalObj.url,
      dataType: 'JSON',
      data: {
          action: 'rental_update_order_option_of_set',
          option_id: option_id,
          value_id: value_id,
          price: price,
      },
      success: function(data) {
      },
      error: function(data) {
        console.log('error:', data )
      },
      complete: function(data) {
        // console.log(' update order option dataaaaa:',  data)
        var serverData = data.responseJSON;
        var $cart_totals = jQuery(".cart_totals");

        if (serverData !== '') {
            if (serverData.total !== undefined 
              && serverData.subtotal !== undefined 
              && serverData.price_total !== undefined 
            ) {
              totalPriceHolder.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.total+'</bdi>')
              subtotalPriceHolder.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.subtotal+'</bdi>')
              orderOptionPriceHolder.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.price_total+'</bdi>')
              orderOptionTotalPriceHolder.html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.price_total+'</bdi>')
            }

            if (serverData.security_deposit_title !== undefined && serverData.security_deposit_title.trim() !== '') {
              $cart_totals.find('[data-title="'+serverData.security_deposit_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.security_deposit_value+'</bdi>')
            }
    
            if (serverData.tax_title !== undefined && serverData.tax_title.trim() !== '') {
              $cart_totals.find('[data-title="'+serverData.tax_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.tax_value+'</bdi>')
            }
            
            if (serverData.damage_waiver_title !== undefined && serverData.damage_waiver_title.trim() !== '') {
              $cart_totals.find('[data-title="'+serverData.damage_waiver_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.damage_waiver_value+'</bdi>')
            }
    
            if (serverData.damage_waiver_tax_title !== undefined && serverData.damage_waiver_tax_title.trim() !== '') {
              $cart_totals.find('[data-title="'+serverData.damage_waiver_tax_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.damage_waiver_tax_value+'</bdi>')
            }

            if (serverData.rush_fee_title !== undefined && serverData.rush_fee_title.trim() !== '') {
              $cart_totals.find('[data-title="'+serverData.rush_fee_title.trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.rush_fee_value+'</bdi>')
            }
    
            if (serverData.auto_applied_fees !== undefined && serverData.auto_applied_fees.length > 0) {
              for(var i=0; i < serverData.auto_applied_fees.length; i++) {
                $cart_totals.find('[data-title="'+serverData.auto_applied_fees[i]["title"].trim()+'"] .woocommerce-Price-amount').html('<bdi><span class="woocommerce-Price-currencySymbol">'+serverData.currency+'</span>'+serverData.auto_applied_fees[i]["amount"]+'</bdi>')
              }
            }
        }

        unblock(orderOptionPriceHolder);
        unblock(orderOptionTotalPriceHolder);
        unblock(subtotalPriceHolder);
        unblock(totalPriceHolder);
        unblock($checkoutBtn);
      }
    });
}

function update_option_data_of_single_product(element) {
  var $cartBtn = jQuery("form.cart").find(".single_add_to_cart_button");
  if ($cartBtn) {
    $cartBtn.attr("disabled", true);
    $cartBtn.addClass("disabled");
  }

  var target = jQuery(element);
  var product_id;
  var variation_id = jQuery('input.variation_id');
  if (variation_id.length) {
    product_id = variation_id.val();
  } else {
    product_id = target.data('product-id');
  }
  var is_set = target.data('is-set');
  var value_id = target.find('option:selected').attr('id');
  var price = target.find('option:selected').data('value');
  var option_id = target.attr('id');
  
  jQuery.ajax({
    type: 'POST',
    url: rentalObj.url,
    dataType: 'JSON',
    data: {
        action: 'rental_update_product_option',
        product_id: product_id,
        option_id: option_id,
        value_id: value_id,
        price: price,
        single_product: 1,
        is_set: is_set
    },
    success: function(data) {
      // console.log('single product option update back:',  data)
    },
    error: function(data) {
      console.log('error:', data )
    },
    complete: function() {
      block($cartBtn);
      checkAddToCartPossibility(is_set);
    }
  });
}

function checkAddToCartPossibility(is_set = 0) {
  var $selectOptionHolder = jQuery('div.product').find(".rental-product-options");
  var $cartBtn = jQuery("form.cart").find(".single_add_to_cart_button");
  if ($selectOptionHolder.length) {
      block($cartBtn);
      $cartBtn.addClass('disabled');
      $cartBtn.attr("disabled", true);
      var product_id = $cartBtn.val();
      if (jQuery('form.variations_form').length) {
        product_id = jQuery(".woocommerce-variation-add-to-cart").find('input.variation_id').val();
      }
    
      jQuery.ajax({
        type: 'POST',
        url: rentalObj.url,
        dataType: 'JSON',
        data: {
            action: 'rental_check_selected_options_of_product',
            product_id: product_id,
            is_set: is_set
        },
        success: function(data) {
        },
        error: function(data) {
          console.log('error:', data )
        },
        complete: function(data) {
          var serverData = '';
          if (data.responseText !== '' && data.responseJSON) {
            serverData = data.responseJSON;
          }
         
          if (serverData !== '') {
            
            if (serverData["check"] === true) {
              $cartBtn.removeClass('disabled');
              $cartBtn.attr("disabled", false);
            } else {
              $cartBtn.addClass('disabled');
              $cartBtn.attr("disabled", true);
            }
           
          } else {
            $cartBtn.addClass('disabled');
            $cartBtn.attr("disabled", true);
          }
          unblock($cartBtn); 
        }
      });
    
  }
}
setTimeout(function() {
  checkAddToCartPossibility();
}, 500);

// product options selection check on cart page checkout btn 
$checkoutBtn.on("click", function(e) {
  e.preventDefault();
  
  block($checkoutBtn);
  jQuery.ajax({
    type: 'POST',
    url: rentalObj.url,
    dataType: 'JSON',
    data: {
        action: 'rental_check_selected_options'
    },
    success: function(data) {
      // console.log(' check order/non order options:',  data)
      
      if (data.check !== true) {
        // customer needs to select a value for each products' options
        errorMsg("Please review the product options before checking out.");
        jQuery([document.documentElement, document.body]).animate({
          scrollTop: jQuery(".rntl-opt-err").offset().top - 120
        }, 1000);
      } else {
        errorMsg("");
        window.location = data.url;
      }

    },
    error: function(data) {
      // console.log('error:', data )
    }, complete: function() {
      unblock($checkoutBtn);
    }
  });

})



var errorMsg = function (msg) {
  var $div = jQuery("div.woocommerce-notices-wrapper")
  var errorBox = "";
  if (msg !== "") {
    errorBox = '<div class="rntp-notification rntp-notification--error rntl-opt-err" style="margin-top:1rem">' +
      // '<a href class="rntp-notification__close color--error">×</a>' +
      '<div class="rntp-notification__status rntp-bg--gradient-red">' +
        ' &times;' +
      '</div>' +
      '<div class="rntp-notification__content">' +
          '<h4 class="rntp-notification__title"> Product Options </h4>' +
          '<p class="rntp-notification__text"> '+ msg +' </p>' +
      '</div>' +
    '</div>';
    
    if (!(jQuery(".rntl-opt-err").length > 0)) {
      $div.append(errorBox)
    }
   
  } else {
    $div.append(errorBox)
  }
  
};

if (window.location.href.indexOf("rntp_opt_err") > -1) {
  errorMsg("Please review the product options before checking out.");
  jQuery([document.documentElement, document.body]).animate({
    scrollTop: jQuery(".rntl-opt-err").offset().top - 120
  }, 1000);
}