


////////////////////////////////////////////////////////////////////////////////////////
// Events                                                                             //
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Constants                                                                          //
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Variables                                                                          //
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Constructor                                                                        //
////////////////////////////////////////////////////////////////////////////////////////
jQuery(document).ready(function () {
  var jq_mainForm = jQuery("form[name=wd_shop_main_form]");

  // fields that needs to be checked
  jq_mainForm.find("input[name^=product_count_]").each(function () {
      var jq_field = jQuery(this);
      var jq_productDataContainer = jq_field.closest(".wd_shop_product_data_container");
      var countIsUnlimited = jq_productDataContainer.attr("count_is_unlimited");
      var countAvailable = jq_productDataContainer.attr("count_available");

      jq_field.on("blur", function () {
          var value = jq_field.val();
          if ((value % 1 == 0) && (value > 0) && ((countIsUnlimited == "1") || (value <= parseInt(countAvailable)))) {
            jq_field.closest(".form-group").removeClass("has-error");
          }
          else {
            jq_field.closest(".form-group").addClass("has-error");
          }
      });
  });
  var shipping_calculation = jQuery(".wd_shop_product_containers_list").attr("data-shipping-calculation");
  jQuery(".wd_shop_product_data_container").each(function () {
    onSelectableParameterChange(this, shipping_calculation);
    var that = this;
    jQuery(this).find(".wd_shop_parameter_select, .wd_shop_parameter_radio, .wd_shop_parameter_checkbox, .wd_shop_product_data_count, .wd_shop_product_data_shipping_method_id").each(function () {
      jQuery(this).on("change", function() {onSelectableParameterChange(that, shipping_calculation);});
    });
  });
  if (shipping_calculation == 'per_order') {
    onShippingMethodChange(this);
    jQuery(".wd_shop_product_data_container").each(function () {
      var that = this;
      jQuery(this).find(".wd_shop_product_data_shipping_method_id").each(function () {
        jQuery(this).on("change", function() {onShippingMethodChange(that);});
      });
      jQuery(this).find(".wd_shop_product_data_count").each(function () {
        jQuery(this).on("change", function() {onShippingMethodChange(that);});
      });
    });
  }
});

////////////////////////////////////////////////////////////////////////////////////////
// Public Methods                                                                     //
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Getters & Setters                                                                  //
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Private Methods                                                                    //
////////////////////////////////////////////////////////////////////////////////////////
function wdShop_checkout_getInvalidFields() {
    var jq_mainForm = jQuery("form[name=wd_shop_main_form]");

    var invalidFields = [];
    // check count fields
    jq_mainForm.find("input[name^=product_count_]").each(function () {
        var jq_field = jQuery(this);
        var jq_productDataContainer = jq_field.closest(".wd_shop_product_data_container");
        var countIsUnlimited = jq_productDataContainer.attr("count_is_unlimited");
        var countAvailable = jq_productDataContainer.attr("count_available");

        var value = jq_field.val();
        if ((value % 1 != 0) || (value <= 0) || ((countIsUnlimited == "0") && (value > parseInt(countAvailable)))) {
            invalidFields.push(jq_field);
        }
    });

    return invalidFields;
}


////////////////////////////////////////////////////////////////////////////////////////
// Listeners                                                                          //
////////////////////////////////////////////////////////////////////////////////////////
function onWDShop_pagerBtnClick(event, obj) {
    jQuery("form[name=wd_shop_main_form] .form-group").removeClass("has-error");

    var invalidFields = wdShop_checkout_getInvalidFields();
    if (invalidFields.length > 0) {
        for (var i = 0; i < invalidFields.length; i++) {
            var invalidField = invalidFields[i];
            jQuery(invalidField).closest(".form-group").addClass("has-error");
        }

        var jq_alert = jQuery(".wd_shop_checkout_alert_incorrect_data");
        if (jq_alert.is(":visible") == false) {
            jq_alert
                .removeClass("hidden")
                .slideUp(0)
                .slideDown(250);
        } else {
            jq_alert
                .fadeOut(100)
                .fadeIn(100);
        }
        return;
    }

    wdShop_mainForm_setAction(jQuery(obj).attr("href"));
    wdShop_mainForm_submit();
}

function onSelectableParameterChange(obj, shipping_calculation) {
  var parameters_price = JSON.parse(jQuery(obj).attr("parameters_price"));
  var tax_rate = jQuery(obj).attr("tax_rate");
  var discount_rate = jQuery(obj).attr("discount_rate");
  var product_price = wde_parseFloat(jQuery(obj).attr("product_price"), 2);

  jQuery(obj).find(".wd_shop_parameter_select, .wd_shop_parameter_radio, .wd_shop_parameter_checkbox, .wd_shop_product_data_count").each(function () {
    var type_id = jQuery(this).attr('data-type');
    var name = jQuery(this).attr('name');
    var new_price = 0;
    switch (type_id) {
      // Select.
      case '3':
        var param_price_text = jQuery(this).find(':selected').attr('data-price');
        new_price = param_price_text;
        break;
      // Radio.
      case '4':
        if (this.checked) {
          var param_price_text = jQuery(this).attr('data-price');
          new_price = param_price_text;
        }
        break;
      // Checkbox.
      case '5':
        var checked_prices = 0;
        checked_param_price = this.checked ? jQuery(this).attr('data-price') : "";
        
        var price_sign = checked_param_price.substr(0, 1);
        var param_price = checked_param_price.substr(1, checked_param_price.length);
        if (param_price) {
          if (price_sign == '+') {
            checked_prices = (wde_parseFloat(checked_prices, 2) + wde_parseFloat(param_price, 2)).toFixed(2);
          }
          else {
            checked_prices = (wde_parseFloat(checked_prices, 2) - wde_parseFloat(param_price, 2)).toFixed(2);
          }
        }
        if (checked_prices > 0) {
          checked_prices = "+" + checked_prices;
        }
        new_price = checked_prices;
        break;
    }
    
    var parameters_price_sum = 0;
    if (new_price) {
      var price_sign = new_price.substr(0, 1);
      var param_price = new_price.substr(1, new_price.length);
      if (param_price) {
        if (price_sign == '+') {
          parameters_price_sum = (wde_parseFloat(parameters_price_sum, decimals) + wde_parseFloat(param_price, decimals)).toFixed(decimals);
        }
        else {
          parameters_price_sum = (wde_parseFloat(parameters_price_sum, decimals) - wde_parseFloat(param_price, decimals)).toFixed(decimals);
        }
      }
    }
    product_price = wde_parseFloat(parameters_price_sum, decimals) + product_price;
  });
  var shipping_price = jQuery(obj).find(".wd_shop_product_data_shipping_method_id:checked").attr("data-price");
  var shipping_type = jQuery(obj).find(".wd_shop_product_data_shipping_method_id:checked").attr("data-shipping-type");
  shipping_price = wde_parseFloat(shipping_price, decimals);
  var free_shipping = jQuery(obj).find(".wd_shop_product_data_shipping_method_id:checked").attr("data-free-shipping");
  var free_shipping_start_price = jQuery(obj).find(".wd_shop_product_data_shipping_method_id:checked").attr("data-free-shipping-start-price");
  var discount_price = product_price * (1 - (discount_rate === null ? 0 : discount_rate) / 100);
  var tax = discount_price * ((tax_rate === null ? 0 : tax_rate) / 100);
  var product_updated_price = (tax + discount_price);
  if (product_price) {
    product_updated_price = Math.floor(product_updated_price * 100) / 100;
    product_updated_price *= jQuery(obj).find(".wd_shop_product_data_count").val();
    if (shipping_calculation != 'per_order') {
      if (free_shipping == 0 || (free_shipping == 2 && product_updated_price < free_shipping_start_price)) {
        if (shipping_type == 'per_unit') {
          shipping_price *= jQuery(obj).find(".wd_shop_product_data_count").val();
        }
        product_updated_price += shipping_price;
      }
    }
    jQuery(obj).find('.wd_shop_product_price_text').attr("data-price", product_updated_price.toFixed(decimals));
    if (wdShop_currency_position == 1) {
      jQuery(obj).find('.wd_shop_product_price_text').html(product_updated_price.toFixed(decimals) + wdShop_currency_code);
    }
    else {
      jQuery(obj).find('.wd_shop_product_price_text').html(wdShop_currency_code + product_updated_price.toFixed(decimals));
    }
  }
}

function onShippingMethodChange(obj) {
  var shipping_price_total = 0;
  var shippings_list = [];
  jQuery(".wd_shop_product_data_container").each(function () {
    var shipping = [];
    var shipping_id = jQuery(this).find(".wd_shop_product_data_shipping_method_id:checked").attr("value");
    var shipping_price = jQuery(this).find(".wd_shop_product_data_shipping_method_id:checked").attr("data-price");
    var shipping_type = jQuery(this).find(".wd_shop_product_data_shipping_method_id:checked").attr("data-shipping-type");
    var free_shipping = jQuery(this).find(".wd_shop_product_data_shipping_method_id:checked").attr("data-free-shipping");
    var free_shipping_start_price = jQuery(this).find(".wd_shop_product_data_shipping_method_id:checked").attr("data-free-shipping-start-price");
    shipping_price = wde_parseFloat(shipping_price, decimals);
    var count = 1;
    var products_price = 0;
    if (shipping_type == 'per_unit') {
      jQuery(this).find(".wd_shop_product_data_count").each(function () {
        count = parseInt(jQuery(this).val());
      });
      jQuery(this).find(".wd_shop_product_price_text").each(function () {
        products_price = parseFloat(jQuery(this).attr("data-price"));
      });
    }
    shipping['price'] = shipping_price;
    shipping['type'] = shipping_type;
    shipping['free_shipping'] = free_shipping;
    shipping['free_shipping_start_price'] = free_shipping_start_price;
    shipping['count'] = count;
    shipping['products_price'] = products_price;
    if (typeof(shippings_list[shipping_id]) == 'undefined') {
      shippings_list[shipping_id] = shipping;
    }
    else {
      if (shipping_type == 'per_unit') {
        shippings_list[shipping_id]['count'] += count;
      }
      shippings_list[shipping_id]['products_price'] += products_price;
    }
  });
  for (var i in shippings_list) {
    if (shippings_list[i]['free_shipping'] == 0 || (shippings_list[i]['free_shipping'] == 2 && shippings_list[i]['products_price'] < shippings_list[i]['free_shipping_start_price'])) {
      shipping_price_total += shippings_list[i]['count'] * shippings_list[i]['price'];
    }
  }
  if (wdShop_currency_position == 1) {
    jQuery('.wd_shop_shipping_method_container').find('.wd_shop_product_price_text').html(shipping_price_total.toFixed(decimals) + wdShop_currency_code);
  }
  else {
    jQuery('.wd_shop_shipping_method_container').find('.wd_shop_product_price_text').html(wdShop_currency_code + shipping_price_total.toFixed(decimals));
  }
}