jQuery(document).ready(function () {

  jQuery('button[data-bs-toggle="tab"]').on("shown.bs.tab", function (e) {
    //update progress
    var step = jQuery(e.target).data("step");
    var percent = (parseInt(step) / 5.5) * 100;

    jQuery(".elex-multi-vendor-for-woocommerce-product-progress").css({ width: percent + "%" });
    //e.relatedTarget // previous tab
  });

  jQuery("#clear-filter-for-vendor-product-btn").click(function (e) {
    e.preventDefault();

    const u = new URL(location);
    let params = new URLSearchParams(u.search);
    u.searchParams.delete("search_term");
    u.searchParams.delete("status");
    u.searchParams.delete("stock");
    u.searchParams.delete("enabled");
    u.searchParams.delete("sort_by");
    u.searchParams.delete("order_by");
    u.searchParams.delete("from_date");
    u.searchParams.delete("to_date");
    u.searchParams.delete("elex-advance-filter");

    window.location.replace(u);
  });

  jQuery("#elex-search-product-vendor-button").click(function () {
    search_val = jQuery("#elex-search-product-vendor").val();
    const u = new URL(location);
    let params = new URLSearchParams(u.search);
    if (params.has("search_term")) {
      u.searchParams.set("search_term", search_val);
    } else {
      u.searchParams.append("search_term", search_val);
    }

    if (params.has("nonce")) {
      u.searchParams.set("nonce", elex_mv_coupon_ajaxurl_object.nonce);
    } else {
      u.searchParams.append("nonce", elex_mv_coupon_ajaxurl_object.nonce);
    }

    window.location.replace(u);
    jQuery("#elex-search-product-vendor").val(search_val);
  });

  jQuery("#elex-search-product-vendor-button-cross").click(function () {
    const u = new URL(location);
    let params = new URLSearchParams(u.search);

    if (params.has("search_term")) {
      u.searchParams.delete("search_term");
    }
    window.location.replace(u);
  });

  jQuery("#elex-multi-vendor-for-woocommerce-add-product-vendor-side").removeClass("active");

  jQuery(".elex-multi-vendor-for-woocommerce-add-product-btn").click(function () {
    jQuery("#elex-multi-vendor-for-woocommerce-add-product-vendor-side").addClass("active");

    jQuery('#elex-multi-vendor-for-woocommerce-add-ac-variations-tab').closest('li').addClass('d-none');

		jQuery('#elex-multi-vendor-for-woocommerce-add-ac-variations').addClass('d-none');
    jQuery('body').css('overflow', 'hidden');

  });

  jQuery(".elex-multi-vendor-for-woocommerce-close-cross-product-btn").click(function () {
    window.location.reload();

    // var additem = document.getElementById("wsdesk_additem_toast");

    // // jQuery("#toast_message_mv").html("All your details will be saved as draft");
    // var toast = new bootstrap.Toast(additem);
    // toast.show();

    // jQuery("#elex-multi-vendor-for-woocommerce-add-product-vendor-side").removeClass("active");
    // jQuery("#elex-multi-vendor-for-woocommerce-detail-form")[0].reset();
    // jQuery("#elex-multi-vendor-for-woocommerce-price-form")[0].reset();
    // jQuery("#elex-multi-vendor-for-woocommerce-shipping-form")[0].reset();
    // jQuery("#elex-multi-vendor-for-woocommerce-carrier-form")[0].reset();

    // jQuery("#elexPreviewImageUpload").attr(
    //   "src",
    //   elex_mv_coupon_ajaxurl_object.plugin_path + "images/default.jpg"
    // );

    // setTimeout(function () {
    //   window.location.reload();
    // }, 3000);
  });

  jQuery(document).on("change", "#elex-multi-vendor-for-woocommerce-filetag", function () {
    changeImage(this);
  });

  function changeImage(input) {
    var reader;
    if (input.files && input.files[0]) {
      reader = new FileReader();
      reader.onload = function (e) {
        jQuery("#elexPreviewImageUpload").attr("src", e.target.result);
        jQuery(".elex-multi-vendor-for-woocommerce-prod-img-name-div").removeClass("d-none");
        jQuery(".elex-multi-vendor-for-woocommerce-prod-img-name").html(input.files[0].name);
      };
      reader.readAsDataURL(input.files[0]);
    }
  }

  jQuery(".elex-multi-vendor-for-woocommerce-product-form-remove-image").click(function () {
    jQuery("#elexPreviewImageUpload").attr(
      "src",
      elex_mv_coupon_ajaxurl_object.plugin_path + "images/default.jpg"
    );
    jQuery(".elex-multi-vendor-for-woocommerce-prod-img-name-div").addClass("d-none");
    jQuery("#elex-multi-vendor-for-woocommerce-filetag").val("");
  });

  jQuery(".elex-multi-vendor-for-woocommerce-add-vendor-product-form-prev-btn").click(function () {
    jQuery(".nav-tabs > .nav-item > .active")
      .parent()
      .prev("li")
      .find("button")
      .trigger("click");
  });

  validation_for_forms_func(
    "#elex_multivendor_new_product_name",
    /^[A-Za-z][ A-Za-z0-9_]{0,29}$/,
    "#elex_mv_show_error_new_product_name",
    "Enter Proper Name"
  );
  validation_for_forms_func(
    "#elex_multivendor_new_product_description",
    /.*/,
    "#elex_mv_show_error_new_product_description",
    "Enter Proper description"
  );

  validation_for_forms_func(
    "#elex_multivendor_regular_price",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_regular_price_error",
    "Enter Regular Price in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_sale_price",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_sale_price_error",
    "Enter Sale Price in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_stock_value",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_stock_value_error",
    "Enter Stock Value in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_lower_threshold",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_lower_threshold_error",
    "Enter Lower Threshold in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_product_weight",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_product_weight_error",
    "Enter Product Weight in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_product_length",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_product_length_error",
    "Enter Product Length in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_product_width",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_product_width_error",
    "Enter Product Width in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_product_height",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_product_height_error",
    "Enter Product Height in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_hs_tariff",
    /[a-zA-Z0-9]{2,10}/,
    "#elex_multivendor_hs_tariff_error",
    "Enter HS Tariff Number in Alphanumerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_custom_declared_value",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_custom_declared_value_error",
    "Enter Custom declared value in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_country_of_manufacture",
    /[A-Z]{2,3}/,
    "#elex_multivendor_country_of_manufacture_error",
    "Enter country in Capital"
  );
  validation_for_forms_func(
    "#elex_multivendor_commodity_name",
    /^[A-Za-z][ A-Za-z0-9_]{0,29}$/,
    "#elex_multivendor_commodity_name_error",
    "Enter Commodity Name"
  );
  validation_for_forms_func(
    "#elex_multivendor_waybill_description",
    /.*/,
    "#elex_multivendor_waybill_description_error",
    "Enter description in waybill"
  );
  validation_for_forms_func(
    "#elex_multivendor_special_service",
    /.*/,
    "elex_multivendor_special_service",
    "Enter Special Service"
  );

  
  jQuery(".elex-multi-vendor-for-woocommerce-add-product-form-next-btn").click(function (e) {
    jQuery("#elex_multivendor_regular_price_error").html("");
    jQuery("#elex_multivendor_sale_price_error").html("");
    jQuery("#elex_multivendor_new_product_image_error").html("");
    e.preventDefault();
    var dis = this;
    var link = elex_mv_admin_ajaxurl_object.ajax_url;
    var formData;
    let prod_id = jQuery(".elex-multi-vendor-for-woocommerce-add-product-form-next-btn").attr("elex_mv_id_prod");
    if(!prod_id){
      prod_id = jQuery(".elex-save-attributes").attr("elex_mv_id_prod");
    }
    link += "?action=elex_mv_add_product_details";
    var formData = new FormData(
      document.getElementById("elex-multi-vendor-for-woocommerce-product-form")
    );
    if (prod_id) {
      formData.append("elex_prod_id", prod_id);
    }
    formData.append("form-step", jQuery(this).data('step'));
    // formData.append("product_category", JSON.stringify(selectedarrayele));
    if (jQuery(this).hasClass("save-as-draft")) {
      formData.append("save-as-draft", true);
    }

    if (jQuery(this).data("send-for-approval")) {
      formData.append("send_for_approval", "yes");
    }
    if (jQuery(this).data("publish")) {
      formData.append("publish", "yes");
    }

    jQuery(".elex_mv_product_schedule_btn").click(function(){
      jQuery(".elex_mv_product_schedule_sec").removeClass("d-none");
      jQuery(this).addClass("d-none");
      jQuery(".elex_mv_product_schedule_cancel_btn").removeClass("d-none");
    });
    jQuery(".elex_mv_product_schedule_cancel_btn").click(function(){
      jQuery(".elex_mv_product_schedule_sec").addClass("d-none");
      jQuery(".elex_mv_product_schedule_btn").addClass("d-none");
      jQuery(this).addClass("d-none");
    })


    jQuery.ajax({
      url: link,
      type: "POST",
      data: formData,
      enctype: "multipart/form-data",
      processData: false,
      contentType: false,
      success: function (result) {
        if (result.success) {
          jQuery(".elex-multi-vendor-for-woocommerce-add-product-form-next-btn").attr(
            "elex_mv_id_prod",
            result.data
          );
          jQuery(".elex-save-attributes").attr(
            "elex_mv_id_prod",
            result.data
          );
       
	
	  
          jQuery(".elex-multi-vendor-for-woocommerce-close-product-btn").attr(
            "elex_mv_id_prod",
            result.data
          );
         

        
      
          var additem = document.getElementById("wsdesk_additem_toast");

       
            if (
              jQuery( dis ).data('step') == "1" ||
              jQuery( dis ).data('step') == "2" ||
              jQuery( dis ).data('step') == "3"
            ) {
              jQuery("#toast_message_mv").html("Saved as a draft");
            } else {
              jQuery("#toast_message_mv").html("New Product Added");
            }
          var toast = new bootstrap.Toast(additem);
          toast.show();

          if ( jQuery(dis).data("move")=='next') {
            next_page_iterate(jQuery(".nav-tabs > .nav-item > .active")
            .parent()
            .next("li"));
          }

          if (jQuery(dis).data('step') == "4") {
            setTimeout(function () {
              window.location.reload();
            }, 3000);
          }
        }
      },
      error: function (status, errorThrown) {
        add_product_error_obj = status.responseJSON.data;
        for (const key in add_product_error_obj) {
          function loop_for_html_error(obj) {
            string = "";
            for (var i = 0; i < obj.length; i++) {
              string += ` ${obj[i]}`;
            }
            return string;
          }

          if (add_product_error_obj[key] == null) {
            continue;
          } else if (key == "regular_price" || key == "sale_price") {
            jQuery("#elex_multivendor_" + key + "_error").html(
              '<div style="color:red;"  >' +
                loop_for_html_error(add_product_error_obj[key]) +
                "</div>"
            );
          } else if (key == "product_image") {
            jQuery("#elex_multivendor_new_product_image_error").html(
              '<div style="color:red;"  >' +
                loop_for_html_error(add_product_error_obj[key]) +
                "</div>"
            );
          } else {
            jQuery("#" + key).after(
              '<div style="color:red;"  >' +
                loop_for_html_error(add_product_error_obj[key]) +
                "</div>"
            );
          }
        }
      },
    });
  });

  jQuery(".elex-multi-vendor-for-woocommerce-delete-product-btn").on("click", function () {
    var id = jQuery(this).attr("data-attr-id");
    var additem = document.getElementById("wsdesk_delete_item_toast");
    jQuery("#elex-multi-vendor-for-woocommerce-delete-prod-confirm-btn").val(id);
    var toast = new bootstrap.Toast(additem);
    toast.show();
    setTimeout(function () {
      window.location.reload();
    }, 3000);
  });

  jQuery("#elex-multi-vendor-for-woocommerce-delete-prod-confirm-btn").click(function () {
    var form;
    var delete_product_link = elex_mv_admin_ajaxurl_object.ajax_url;
    delete_product_link =
      delete_product_link + "?action=elex_mv_delete_product";
    id = jQuery("#elex-multi-vendor-for-woocommerce-delete-prod-confirm-btn").val();

    form = {
      id: id,
      nonce: elex_mv_coupon_ajaxurl_object.nonce,
    };

    jQuery.ajax({
      url: delete_product_link,
      type: "POST",
      data: form,
      enctype: "text/plain",
      success: function () {
        location.reload();
      },
    });
  });

	let variation_index = 0;
	let last_variation_id = 0;

  function isJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return JSON.parse(str);
}

  dwn_index = 0;


  jQuery(document).on('mouseover click', '.elex_mv_edit_product_emblem', function(){
    
    const popover = bootstrap.Popover.getInstance(jQuery(this));
    popover.tip.querySelectorAll(".popover-body")[0].innerHTML = jQuery(this).attr('data-bs-content');
    popover.update();


  })

  jQuery(".elex-multi-vendor-for-woocommerce-edit-product-btn").on("click", function () {

    selectedarrayele = [];
    
    jQuery("#elex-multi-vendor-for-woocommerce-edit-product").addClass("active");
    jQuery('body').css('overflow', 'hidden');

    var id = jQuery(this).attr("data-attr-id");
    jQuery(".elex-save-attributes_edit").attr(
      	"elex_mv_id_prod",
      	id
    );
    jQuery(".variable_parent_post_id_edit").attr(
      "value",
      id
    );
   
    var edit_page_link = elex_mv_admin_ajaxurl_object.ajax_url;
    edit_page_link = edit_page_link + "?action=elex_mv_edit_product_display";
    var form = {
      id: id,
      nonce: jQuery("#elex-page-nonce").val(),
    };
    jQuery.ajax({
      url: edit_page_link,
      type: "POST",
      data: form,
      enctype: "multipart/form-data",
      success: function (result) {
        jQuery.each(result.data, function (key, value) {
          if (jQuery("#" + key).length) {
            jQuery("#" + key).val(value);
          }
        });

	

    

    	attributes_p = isJsonString( result.data.attributes );

    	variations_parsed = isJsonString( result.data.variation_data.variations );
    	attributes_parsed = (result.data.variation_data.product_attributes)?isJsonString( result.data.variation_data.product_attributes ):isJsonString( result.data.product_attribute );


      if(attributes_parsed){

      	Object.keys( attributes_parsed ).forEach(function(curr_key){

      		result_option=[];
      		json_data = attributes_parsed[curr_key];
      		result_option = Object.values(json_data);
          
        

        	attribute_number_edit =  jQuery('.elex_mv_add_attribute_parent_edit').attr('attribute_curr_index') ? jQuery('.elex_mv_add_attribute_parent_edit').attr('attribute_curr_index') : 0;
      		value =jQuery('.elex_mv_add_attribute_parent_edit').append( jQuery( '#template-for-attributes_edit' ).html() );

      		jQuery('.elex_mv_mini_max_sec_parent_template_edit').removeClass('d-none');  

      		jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex_mv_mini_max_sec_parent_template_edit").attr('data-position', attribute_number_edit );

      		first_letter = curr_key.split("_");

   

          var name_attribute ;

          if( Object.keys( attributes_p ).length > 0 ){

            name_attribute = attributes_p[curr_key]['name'];

          }

      		vlaue2 = jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-name-of-attribute-input_edit").val(name_attribute);
      		vlaue2 =  jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-attribute-title_edit").html( name_attribute.replace('pa_','')  );


      	        jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-remove-button-attribute-template_edit").data( 'attribute_name', curr_key );


      	        jQuery('.elex_mv_add_attribute_parent_edit').children().last().data( 'attribute-id', curr_key.id );
      		

      		if( first_letter[0] == 'pa'  ){

      			jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-attribute-values-label_edit").after().html("<select id=\"elex-attribute-edit-" + attribute_number_edit + "\" name=\"attribute_values[" + attribute_number_edit + "][]\" class=\"elex-attribute-values-select_edit\" style=\"width:200px;\" class='attribute-select' ></select>");

            jQuery('.elex_mv_add_attribute_parent_edit').children().first().find(".elex_mv_select_all_attribute_values_edit").removeClass('d-none');
            jQuery('.elex_mv_add_attribute_parent_edit').children().first().find(".elex_mv_select_all_attribute_values_edit").attr('id', 'elex_mv_select_all_attribute_values_edit_id-'+ attribute_number_edit );
        
            jQuery('.elex_mv_add_attribute_parent_edit').children().first().find(".elex_mv_select_create_attribute_values_edit").removeClass('d-none');
            jQuery('.elex_mv_add_attribute_parent_edit').children().first().find(".elex_mv_select_create_attribute_values_edit").attr('id', 'elex_mv_select_create_attribute_values_edit_id-'+ attribute_number_edit );
        
        
        
            jQuery(document).on( 'click', "#elex_mv_select_create_attribute_values_edit_id-" + attribute_number_edit , function(){
        
              var attribute_number_edit = this.id.split('-').pop();
        
              var attribute = curr_key ;
        
              var new_attribute_name = window.prompt(
                'Enter a name for the new attribute term:'
              );
        
              if ( new_attribute_name ) {
                var data = {
                  action: 'elex_mv_add_new_attributes',
                  taxonomy: attribute.toLowerCase().replace(' ', '-'),
                  term: new_attribute_name,
                  nonce: elex_mv_coupon_ajaxurl_object.nonce
                };
        
                jQuery.post(
                  elex_mv_coupon_ajaxurl_object.ajax_url,
                  data,
                  function ( response ) {
                    if ( response.error ) {
                      // Error.
                      window.alert( response.error );
                    } else if ( response.slug ) {
                      // Success.
                      jQuery( '#elex-attribute-edit-' + attribute_number_edit ).append(
                          '<option value="' +
                            response.term_id +
                            '" selected="selected">' +
                            response.name +
                            '</option>'
                        );
                        jQuery( '#elex-attribute-edit-' + attribute_number_edit ).trigger( 'change' );
                    }
        
                  }
                );
              }	
            });
        
            jQuery(document).on( 'click', "#elex_mv_select_all_attribute_values_edit_id-" + attribute_number_edit , function(){
        
              var attribute_number_edit = this.id.split('-').pop();
        
              var attribute = curr_key ;
        
              var data = {
                action: 'elex_mv_json_search_taxonomy_terms',
                taxonomy: attribute.toLowerCase().replace(' ', '-'),
                nonce: elex_mv_coupon_ajaxurl_object.nonce
        
              };
           
              jQuery.get(
                elex_mv_coupon_ajaxurl_object.ajax_url,
                data,
                function ( response ) {
                  if ( response.errors ) {
                    // Error.
                    window.alert( response.errors );
                  } else if ( response && response.length > 0 ) {
                    // Success.
        
                    response.forEach( function ( term ) {
                      const currentItem = jQuery( '#elex-attribute-edit-' + attribute_number_edit ).find(
                        'option[value="' +
                          term.term_id +
                          '"]'
                      );
                      if ( currentItem && currentItem.length > 0 ) {
                        currentItem.prop( 'selected', 'selected' );
                      } else {
                        
                          jQuery( '#elex-attribute-edit-' + attribute_number_edit )
                          .append(
                            '<option value="' +
                              term.term_id +
                              '" selected="selected">' +
                              term.name +
                              '</option>'
                          );
                      }
                    } );
                    jQuery( '#elex-attribute-edit-' + attribute_number_edit ).trigger( 'change' );
                  }
        
                }
              );
            } ) 

      			jQuery("#elex-attribute-edit-" + attribute_number_edit ).select2({

      				allowClear:true,
      				placeholder: "",
      				dataType: 'json',
      				multiple: true,
      				closeOnSelect: true,
      		    
      				ajax: {
      					url:         elex_mv_coupon_ajaxurl_object.ajax_url,
      					dataType:    'json',
      					delay:       250,
      					data:        function( params ) {
      					    return {
      						taxonomy: curr_key.toLowerCase().replace(' ', '-'),
      						limit:    '50',
      						orderby:  'menu_order',
      						term:     params.term,
      						action:   'elex_mv_json_search_taxonomy_terms',
                  nonce: elex_mv_coupon_ajaxurl_object.nonce

      					    };
      					},
      					processResults: function( data ) {
      					    var terms = [];
      					    if ( data ) {
      					
      						jQuery.each( data, function( id, term ) {
      						    terms.push({
      							id:   term.term_id,
      							text: term.name
      						    });
      						});
      					    }
      					    return {
      						results: terms
      					    };
      					},
      					cache: true
      				}    
      			});

            

            var data = {
              action: 'elex_mv_json_search_taxonomy_terms',
              taxonomy: curr_key.toLowerCase().replace(' ', '-'),
              nonce: elex_mv_coupon_ajaxurl_object.nonce
      
            };
          
            jQuery.get(
              elex_mv_coupon_ajaxurl_object.ajax_url,
              data,
              function ( response ) {
                if ( response.errors ) {
                  // Error.
                  window.alert( response.errors );
                } else if ( response && response.length > 0 ) {
                  // Success.
      
                  response.forEach( function ( term ) {
                  
                      
                        jQuery( '#elex-attribute-edit-' + attribute_number_edit )
                        .append(
                          '<option value="' +
                            term.term_id +
                            '">' +
                            term.name +
                            '</option>'
                        );
                  } );
                  jQuery( '#elex-attribute-edit-' + attribute_number_edit ).trigger( 'change' );
                }
      
              }
            );
      			vlaue2 = jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-name-of-attribute-input_edit").addClass('d-none');
      			jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-name-of-attribute_edit").html("Name:" + curr_key.replace('pa_','')  );


      			var newOption = '';
      				
      			Object.keys( json_data ).forEach(function(val_key){
      				 newOption += "<option  selected='selected' value='" + val_key  + "'>"+ json_data[val_key] +"</option>";

      			});

      	 
      			jQuery("#elex-attribute-edit-" + attribute_number_edit).append(newOption).trigger('change');

      			jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-attribute-values-textarea_edit").remove();

      		}else{

      			vlaue2 = jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-name-of-attribute-input_edit").removeClass('d-none');
      			jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-name-of-attribute_edit").addClass('d-none');
      			
      			jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-attribute-values-textarea_edit").val(result_option.join('|'));
      			jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-attribute-values-textarea_edit").prop('name', 'attribute_values[' + attribute_number_edit + ']');

      			
      			

      		}
      		
          
      		    jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-name-of-attribute-input_edit").prop( 'name','attribute_names[' + attribute_number_edit + ']'  );
      		  
      		    jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-visibile-product_edit").prop( 'name','attribute_visibility[' + attribute_number_edit + ']'  );
      		    



      		    if( attributes_p[curr_key].is_visible ){
      			    jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-visibile-product_edit").attr('checked', true);

      		    }

      		    jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-use-for-variations_edit").prop( 'name','attribute_variation[' + attribute_number_edit + ']'  );
      		  
      		    if( attributes_p[curr_key].is_variation ){
      			    jQuery('.elex_mv_add_attribute_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-use-for-variations_edit").attr('checked', true);

      		    }

              if(result.data.type == 'simple' ){
                parent = jQuery('.elex_mv_add_attribute_parent_edit').children().first().find(".elex-multi-vendor-for-woocommerce-use-for-variations_edit").parent();
                parent.addClass('d-none');
          
              }

      		    attribute_number_edit++;
      	    

              jQuery('.elex_mv_add_attribute_parent_edit').attr('attribute_curr_index', attribute_number_edit );
              jQuery(".elex_mv_edit_attribute_expand_close_div").removeClass('d-none')

      	})
        if(variations_parsed){

      	  load_variations(id);
        }
      }

	// variations_parsed.forEach(functions( instant_value, ins_index ){})    ; 

        jQuery.each(result.data, function (key, value) {
          if (
            jQuery("#" + key).length &&
            jQuery("#" + key).is(":checkbox") &&
            value == "yes"
          ) {
            jQuery("#" + key).attr("checked", true);
          } else if (
            jQuery("#" + key).length &&
            jQuery("#" + key).is(":checkbox")
          ) {
            jQuery("#" + key).attr("checked", false);
          }
        });

        jQuery("#elex_multivendor_edit_new_product_id").attr("value", id);
        jQuery("#elex_multivendor_edit_new_product_name").val(
          result.data.product_name
        );
        jQuery("#elex_multivendor_edit_new_product_description").val(
          result.data.product_description
        );
        jQuery('#elex-vendor-edit-product-category').html('').val(null).trigger("change");

        jQuery.each(result.data.product_category, function (index, item) {
          var option = new Option(item.cat_name, item.cat_id, true, true);
          jQuery('#elex-vendor-edit-product-category').append(option).trigger('change');
        });
     

        jQuery("#elexEditPreviewImageUpload").attr(
          "src",
          result.data.product_image[0]
        );
        // jQuery('.elex-multi-vendor-for-woocommerce-edit-product-form-submit-btn').attr('elex-multi-vendor-for-woocommerce-edit-prod-id', result.data.prod_id);
        
        jQuery("#elex_multivendor_edit_new_product_type").val(result.data.type);

       

        if(result.data.type && result.data.type == 'simple' ){

          jQuery('#elex-multi-vendor-for-woocommerce-edit-prod-variations-tab').closest('li').addClass('d-none');      
          jQuery('#elex-multi-vendor-for-woocommerce-edit-prod-variations').addClass('d-none');
          jQuery('#elex-multi-vendor-for-woocommerce-edit-virtual-product-switch-div').removeClass('d-none');
          jQuery('#elex-multi-vendor-for-woocommerce-edit-dwn-product-switch-div').removeClass('d-none');
      
        }else{
          jQuery('#elex-multi-vendor-for-woocommerce-edit-prod-variations-tab').closest('li').removeClass('d-none');
          jQuery('#elex-multi-vendor-for-woocommerce-edit-prod-variations').removeClass('d-none');
          jQuery('#elex-multi-vendor-for-woocommerce-edit-virtual-product-switch-div').addClass('d-none');
          jQuery('#elex-multi-vendor-for-woocommerce-edit-dwn-product-switch-div').addClass('d-none');
        }

      

        if(result.data.is_virtual ) {
          jQuery("#elex-multi-vendor-for-woocommerce-edit-virtual-product-switch").attr('checked', true);
          jQuery('#elex-multi-vendor-for-woocommerce-edit-ship-tab').closest('li').addClass('d-none');

    			jQuery('#elex-multi-vendor-for-woocommerce-edit-ship').addClass('d-none');
        }else{
          jQuery("#elex-multi-vendor-for-woocommerce-edit-virtual-product-switch").attr('checked', false);
          jQuery('#elex-multi-vendor-for-woocommerce-edit-ship-tab').closest('li').removeClass('d-none');

			    jQuery('#elex-multi-vendor-for-woocommerce-edit-ship').removeClass('d-none');

        }
         if(result.data.is_downloadable ) {
          jQuery("#elex-multi-vendor-for-woocommerce-edit-dwn-product-switch").attr('checked', true);
          jQuery(".elex-multi-vendor-for-woocommerce-edit-download-file-div").removeClass('d-none');
          jQuery(".elex-multi-vendor-for-woocommerce-dwm-limit-expiry-div").removeClass('d-none');


        }else{
          jQuery("#elex-multi-vendor-for-woocommerce-edit-dwn-product-switch").attr('checked', false);
          jQuery(".elex-multi-vendor-for-woocommerce-edit-download-file-div").addClass('d-none');
          jQuery(".elex-multi-vendor-for-woocommerce-dwm-limit-expiry-div").addClass('d-none');

        }
        jQuery("#elex_multivendor_edit_weight").val(result.data.product_weight);
        jQuery("#elex_multivendor_edit_length").val(result.data.product_length);
        jQuery("#elex_multivendor_edit_width").val(result.data.product_width);
        jQuery("#elex_multivendor_edit_height").val(result.data.product_height);

          if(result.data.sale_start_date && result.data.sale_start_date != 'null' ){

            var date = new Date( JSON.parse( result.data.sale_start_date ).date);

            // Extract year, month, and day components
            var year = date.getFullYear();
            var month = (date.getMonth() + 1).toString().padStart(2, "0"); // Months are zero-based, so add 1
            var day = date.getDate().toString().padStart(2, "0");
    
            // Create the new formatted date string in "yyyy-MM-dd" format
            var formattedDateString = `${year}-${month}-${day}`;

            jQuery("#elex_mv_edit_sale_start_date").val(formattedDateString);

          }

          if(result.data.sale_end_date && result.data.sale_end_date != 'null' ){

            var date = new Date( JSON.parse( result.data.sale_end_date ).date);

            // Extract year, month, and day components
            var year = date.getFullYear();
            var month = (date.getMonth() + 1).toString().padStart(2, "0"); // Months are zero-based, so add 1
            var day = date.getDate().toString().padStart(2, "0");
    
            // Create the new formatted date string in "yyyy-MM-dd" format
            var formattedDateStringe = `${year}-${month}-${day}`;

            jQuery("#elex_mv_edit_sale_end_date").val(formattedDateStringe);

          }
    


       
        if(result.data.product_downloads ) {
          prod_dwnlds = result.data.product_downloads
          dwn_index=0;
          Object.keys( prod_dwnlds ).forEach(function(dwnload_val){

         
            
              jQuery('#elex_mv_edit_table_download_file').find('tbody').prepend(jQuery('#template-for-product-file-download').html());
              jQuery('#elex_mv_edit_table_download_file').find('tbody').children('tr:first').find( ".elex_mv_name_file_download" ).attr('id', 'elex_mv_name_file_download_id-' + dwn_index );
              jQuery('#elex_mv_edit_table_download_file').find('tbody').children('tr:first').find( ".elex_mv_hash_file_download" ).attr('id', 'elex_mv_hash_file_download_id-' + dwn_index );
              jQuery('#elex_mv_edit_table_download_file').find('tbody').children('tr:first').find( ".elex_mv_url_file_download" ).attr('id', 'elex_mv_url_file_download_id-' + dwn_index );
              jQuery('#elex_mv_edit_table_download_file').find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-remove-dowload-tr-simple-product" ).attr('id', 'elex-multi-vendor-for-woocommerce-remove-dowload-tr-simple-product-id-' + dwn_index );


              jQuery('#elex_mv_edit_table_download_file').find('tbody').children('tr:first').find( ".elex_mv_url_file_download" ).attr('value', prod_dwnlds[dwnload_val].file );
              jQuery('#elex_mv_edit_table_download_file').find('tbody').children('tr:first').find( ".elex_mv_hash_file_download" ).attr('value',prod_dwnlds[dwnload_val].id  );
              jQuery('#elex_mv_edit_table_download_file').find('tbody').children('tr:first').find( ".elex_mv_name_file_download" ).attr('value', prod_dwnlds[dwnload_val].name );

              jQuery('#elex_mv_edit_table_download_file').find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-edit-upload-download-file-btn" ).attr('id', 'elex-multi-vendor-for-woocommerce-edit-upload-download-file-btn-id-' + dwn_index );
              jQuery('#elex_mv_edit_table_download_file').find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-file-download" ).attr('id', 'elex-multi-vendor-for-woocommerce-file-download-id-' + dwn_index );
          
              dwn_index++;

          });
        }

        jQuery("#elex_multivendor_edit_regular_price").val(
          result.data.product_regular_price
        );
        jQuery("#elex_multivendor_edit_sale_price").val(
          result.data.product_sale_price
        );


        if(result.data.manage_stock ) {
          jQuery("#elex_multivendor_edit_manage_stock_value").attr('checked', true);

          jQuery(".elex-multi-vendor-for-woocommerce-low-stock-value-div").removeClass('d-none');
          jQuery(".elex-multi-vendor-for-woocommerce-low-stock-threshold-div").removeClass('d-none');
          jQuery(".elex-multi-vendor-for-woocommerce-backorders-div").removeClass('d-none');
          
          jQuery(".elex-multi-vendor-for-woocommerce-stock-status-div").addClass('d-none');

        }else{
          jQuery("#elex_multivendor_edit_manage_stock_value").attr('checked', false);

        	  jQuery(".elex-multi-vendor-for-woocommerce-low-stock-value-div").addClass('d-none');
        		jQuery(".elex-multi-vendor-for-woocommerce-low-stock-threshold-div").addClass('d-none');
        		jQuery(".elex-multi-vendor-for-woocommerce-backorders-div").addClass('d-none');
        		
        		jQuery(".elex-multi-vendor-for-woocommerce-stock-status-div").removeClass('d-none');

        }
        jQuery("#elex_multivendor_edit_stock_value").val(
          result.data.stock_value
        );

     

        jQuery(".elex_mv_product_shipping_class_edit").val(
          result.data.shipping_class
        );
        jQuery("#elex_multivendor_edit_lower_threshold").val(
          result.data.lower_threshold
        );
        if(result.data.download_expiry > 0){
            jQuery("#elex_multivendor_edit_download_expiry").val(
              result.data.download_expiry
            );  
          }
       
          if(result.data.download_limit > 0){
            jQuery("#elex_multivendor_edit_download_limit").val(
              result.data.download_limit
            );  
          }
        jQuery("#elex_multivendor_edit_stock_status").val(
          result.data.stock_status
        );
        jQuery("#elex_multivendor_edit_sku").val(
          result.data.sku
        );

        if (result.data.allow_back_orders) {
          jQuery("#elex_multivendor_edit_allow_back_orders").val(result.data.allow_back_orders);
        }
     
        if (result.data.sold_individually == true) {
          jQuery("#elex_multivendor_edit_sold_individual_item").attr(
            "checked",
            true
          );
        } else {
          jQuery("#elex_multivendor_edit_sold_individual_item").attr(
            "checked",
            false
          );
        }

        if (result.data.status == "reject") {
          jQuery(".elex-multi-vendor-for-woocommerce-edit-resend-for-approval-btn").show();
          jQuery(".elex_mv_rejected_product_title_text").removeClass('d-none');

      

          if(result.data.rejected_message){
            jQuery(".elex_mv_edit_product_emblem").attr('data-bs-content', result.data.rejected_message);
          }
          jQuery(".elex-multi-vendor-for-woocommerce-edit-product-form-submit-btn").show();
          jQuery(".elex-multi-vendor-for-woocommerce-edit-product-form-submit-btn").text("Save");

          jQuery(".elex-multi-vendor-for-woocommerce-edit-product-form-next-btn").show();


        } else if (result.data.status == "draft") {
          jQuery(".elex-multi-vendor-for-woocommerce-edit-resend-for-approval-btn").show();
          jQuery(".elex-multi-vendor-for-woocommerce-edit-resend-for-approval-btn").text("Send For Approval");

          jQuery(".elex-multi-vendor-for-woocommerce-edit-product-form-submit-btn").show();
          jQuery(".elex-multi-vendor-for-woocommerce-edit-product-form-submit-btn").text("Save As Draft");

          jQuery(".elex-multi-vendor-for-woocommerce-edit-product-form-next-btn").show();

          
        } else if (result.data.status == "pending") { 
          
       

          jQuery(".elex-multi-vendor-for-woocommerce-edit-resend-for-approval-btn").hide();

          jQuery(".elex-multi-vendor-for-woocommerce-edit-product-form-submit-btn").show();
        } else if (result.data.status == "publish") { 

          jQuery('#elex-multi-vendor-for-woocommerce-edit-carrier-tab').closest('li').addClass('d-none');      
          jQuery("#elex-multi-vendor-for-woocommerce-edit-carrier-tab").addClass('d-none');
          jQuery("#elex-multi-vendor-for-woocommerce-edit-carrier").addClass('d-none');

          jQuery(".elex-multi-vendor-for-woocommerce-edit-resend-for-approval-btn").hide();

          jQuery(".elex-multi-vendor-for-woocommerce-edit-product-form-submit-btn").show();
        }
        jQuery("#elex_multivendor_edit_hs_tariff").val(
          result.data.product_hs_tariff
        );
        jQuery("#elex_multivendor_edit_custom_declared_value").val(
          result.data.product_sale_price
        );
        jQuery("#elex_multivendor_edit_country_of_manufacture").val(
          result.data.product_sale_price
        );


      },
    });
  });

  function load_variations(post_id){


        var data = {
            action: 'elex_mv_load_variations',
            post_id: post_id,
            nonce: elex_mv_coupon_ajaxurl_object.nonce

        };
        jQuery.post(
			elex_mv_coupon_ajaxurl_object.ajax_url,
            data,
            function ( response ) {
                if(response.success){
                    data = JSON.parse( response.data )

                    jQuery('.elex_mv_add_variations_parent_edit').html('');

                  
                    ship_class_data =  JSON.parse( data.shipping_class);
                    variation_data =  JSON.parse( data.variation_data);
                    product_attributes =  JSON.parse( data.product_attributes);
                    default_attribute =  JSON.parse( data.default_attribute);


                    default_check=0;
                    if(variation_data.length === 0){
                      jQuery('.elex_mv_expand_close_edit_variation').addClass('d-none');
                        return;
                      }else{
                        jQuery('.elex_mv_expand_close_edit_variation').removeClass('d-none');
            
                      }
                    variation_data.forEach(function (current_value, curr_index, arr){


                        jQuery('.elex_mv_add_variations_parent_edit').append( jQuery( '#template-for-variations_edit' ).html() );
                        variation_index = jQuery('.elex_mv_add_variations_parent_edit').attr('variation_curr_index') ? jQuery('.elex_mv_add_variations_parent_edit').attr('variation_curr_index') : 0;

                        jQuery('.variable_parent_post_id_edit').attr('value', current_value.parent_id);

                        object_atribute =  current_value.attributes
                        Object.keys( object_atribute ).forEach(function( curr_key ){

                            options_jquery ='';
                            options_jquery += ' <option value=""> any ' + curr_key + '</option>';

                            pro_atribute =   product_attributes[curr_key];

                            Object.keys( pro_atribute ).forEach(function(attr_value){

                                if( object_atribute[curr_key] == pro_atribute[attr_value] ){
                                    options_jquery += ' <option selected value="'+pro_atribute[attr_value]+'">' + pro_atribute[attr_value] + '</option>';

                                }else{
                                    options_jquery += ' <option value="'+pro_atribute[attr_value]+'">' + pro_atribute[attr_value] + '</option>';

                                }
                            })

                         
                            jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_attribute_variation_values_select_edit").append(' <select name= \"attribute_' + curr_key + '[' + variation_index + ']' +'\" >'+options_jquery+ '</select>' );
                        

                        });


                        if( jQuery(".default-form-values_edit").html() == '' ){

                          jQuery(".default-form-values_edit").append( '<div class="fs-6 mb-1">Default form Values:</div>' );

                          Object.keys( object_atribute ).forEach(function( curr_key ){

                              if(default_check == 0 ){

                                  opt_jquery ='';
                                  opt_jquery += ' <option value=""> any ' + curr_key + '</option>';

                                  pro_atribute =   product_attributes[curr_key];
                                 
                                 

                                  Object.keys( pro_atribute ).forEach(function(attr_value){
                                  
                                  

                                      if( default_attribute[curr_key] == pro_atribute[attr_value] ){
                                        opt_jquery += ' <option selected value="'+pro_atribute[attr_value]+'">' + pro_atribute[attr_value] + '</option>';

                                      }else{
                                        opt_jquery += ' <option value="'+pro_atribute[attr_value]+'">' + pro_atribute[attr_value] + '</option>';

                                      }


                                  })

                                  

                                  jQuery(".default-form-values_edit").append( ' <select name= \"default_attribute_' + curr_key  +'\" >'+opt_jquery+ '</select>' );
                                  jQuery(".default-form-values_edit").removeClass('d-none');

                              }

                          });
                          default_check=1;       

                        }
                          shipping_option = '';

                        ship_class_data.forEach(function (cu_value, curr_index, arr){

                          if(cu_value.term_id == current_value.shipping_class_id){
                            shipping_option += '<option selected value="' + cu_value.term_id +'"> '+ cu_value.name +' </option>' 

                          }else{
                            shipping_option += '<option value="' + cu_value.term_id +'"> '+ cu_value.name +' </option>' 

                          }

                        })


                          
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_variation_id_edit").html( current_value.id );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_variation_id_edit").attr( 'data-id', current_value.id );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".variable_post_id_edit").attr('name', 'variable_post_id[' + variation_index + ']' );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".variable_post_id_edit").attr('value', current_value.id ) ;

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".variable_post_id_edit").val(current_value.id);

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_sku_edit").attr('name', 'variable_sku[' + variation_index + ']' );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_sku_edit").attr('value', current_value.sku);

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_regular_price_edit").attr('name', 'variable_regular_price[' + variation_index + ']' );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_regular_price_edit").attr('value', current_value.regular_price );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_sale_price_edit").attr('name', 'variable_sale_price[' + variation_index + ']' );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_sale_price_edit").attr('value', current_value.sale_price );
                        
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_variation_product_schedule_btn").attr('id', 'elex_mv_variation_product_schedule_btn_id-' + variation_index  );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_variation_product_schedule_sec").attr('id', 'elex_mv_variation_product_schedule_sec_id-' + variation_index  );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_schedule_cancel_btn").attr('id', 'elex_mv_product_schedule_cancel_btn_id-' + variation_index );             
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_sale_start_date").attr('name', 'variable_sale_price_dates_from[' + variation_index + ']' );                       
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_sale_end_date").attr('name', 'variable_sale_price_dates_to[' + variation_index + ']' );
              

                        if( (current_value.date_on_sale_from && current_value.date_on_sale_from != 'null') || (current_value.date_on_sale_to && current_value.date_on_sale_to != 'null' ) )
                        {
                          jQuery('#elex_mv_variation_product_schedule_sec_id-' + variation_index).removeClass('d-none')

                        }
                      if(current_value.date_on_sale_from && current_value.date_on_sale_from != 'null' ){

                        var date = new Date( current_value.date_on_sale_from.date);

                        // Extract year, month, and day components
                        var year = date.getFullYear();
                        var month = (date.getMonth() + 1).toString().padStart(2, "0"); // Months are zero-based, so add 1
                        var day = date.getDate().toString().padStart(2, "0");
                
                        // Create the new formatted date string in "yyyy-MM-dd" format
                        var formattedDateString = `${year}-${month}-${day}`;

                        jQuery("[name='variable_sale_price_dates_from["+ variation_index +"]']").val(formattedDateString);

                      }
                      if(current_value.date_on_sale_to && current_value.date_on_sale_to != 'null' ){

                        var date = new Date( current_value.date_on_sale_to.date);

                        // Extract year, month, and day components
                        var year = date.getFullYear();
                        var month = (date.getMonth() + 1).toString().padStart(2, "0"); // Months are zero-based, so add 1
                        var day = date.getDate().toString().padStart(2, "0");
                
                        // Create the new formatted date string in "yyyy-MM-dd" format
                        var formattedDateString = `${year}-${month}-${day}`;

                        jQuery("[name='variable_sale_price_dates_to["+ variation_index +"]']").val(formattedDateString);

                      }
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_stock_quantity_edit").attr('name', 'variable_stock[' + variation_index + ']' );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_stock_quantity_edit").attr('value', current_value.stock_quantity );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_enabled_edit").attr('id', 'elex_mv_variation_enabled_edit-' + variation_index );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_enabled_edit").attr('name', 'variable_enabled[' + variation_index + ']' );
                        if( current_value.status == 'publish' ){
                          jQuery('#elex_mv_variation_enabled_edit-' + variation_index).attr('checked', true)
                        }else{
                          jQuery('#elex_mv_variation_enabled_edit-' + variation_index).attr('checked', false)

                        }

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_allow_backorders_edit").attr('name', 'variable_backorders[' + variation_index + ']' );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_allow_backorders_edit").attr('value', current_value.backorder );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_low_stock_threshold_edit").attr('name', 'variable_low_stock_amount[' + variation_index + ']' );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_low_stock_threshold_edit").attr('value', current_value.low_stock_amount );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_stock_status_edit").attr('name', 'variable_stock_status[' + variation_index + ']' );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_stock_status_edit").attr('value', current_value.stock_status );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_weight_edit").attr('name', 'variable_weight[' + variation_index + ']' );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_weight_edit").attr('value', current_value.weight );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_length_edit").attr('name', 'variable_length[' + variation_index + ']' );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_length_edit").attr('value', current_value.length );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_width_edit").attr('name', 'variable_width[' + variation_index + ']' );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_width_edit").attr('value', current_value.width );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_height_edit").attr('name', 'variable_height[' + variation_index + ']' );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_height_edit").attr('value', current_value.height );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_shipping_class_edit").attr('name', 'variable_shipping_class[' + variation_index + ']' );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_shipping_class_edit").append(shipping_option);
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_shipping_class_edit").attr('value', current_value.shipping_class_id);

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_description_edit").attr('name', 'variable_description[' + variation_index + ']' );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_description_edit").attr('value', current_value.description );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-filetag-variation").attr('name', 'upload_image_id[' + variation_index + ']' );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-filetag-variation").attr('id', 'elex-multi-vendor-for-woocommerce-filetag-variation-' + variation_index );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elexPreviewImageUploadVariation").attr('id', 'elexPreviewImageUploadVariation_' + variation_index  );
                        
                     
                        

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-remove-image-btn-variation").attr('id', 'elex-multi-vendor-for-woocommerce-remove-image-variation-' + variation_index  );
                        if(current_value.image_id){
                          jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elexPreviewImageUploadVariation").attr('src', current_value.image_id );

                          jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-remove-image-btn-variation").removeClass('d-none');

                        }

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_download_limit_variation_edit").attr('id', 'elex_mv_download_limit_variation_edit-' + variation_index );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_download_limit_variation_edit").attr('name', 'variable_download_limit[' + variation_index + ']' );
                      
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_download_expiry_variation_edit").attr('id', 'elex_mv_download_expiry_variation_edit-' + variation_index );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_download_expiry_variation_edit").attr('name', 'variable_download_expiry[' + variation_index + ']' );
                      

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_manage_stock_check_edit").attr('name', 'variable_manage_stock[' + variation_index + ']' );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_manage_stock_check_edit").attr('id', 'elex_mv_variation_manage_stock_check_edit-' + variation_index );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_stock_sec").attr('id', 'elex_mv_stock_sec-' + variation_index );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_stock_status_sec").attr('id', 'elex_mv_stock_status_sec-' + variation_index );

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_downloadable_check_edit").attr('id', 'elex_mv_product_variation_downloadable_check_edit-' + variation_index );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_downloadable_check_edit").attr('name', 'variable_is_downloadable[' + variation_index + ']' );
            
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_virtual_edit").attr('id', 'elex_mv_product_variation_virtual_edit-' + variation_index );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_product_variation_virtual_edit").attr('name', 'variable_is_virtual[' + variation_index + ']' );
            
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-edit-variable-download-file-div").attr('id', 'elex-multi-vendor-for-woocommerce-edit-variable-download-file-div-' + variation_index );
            
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_shipping_variation_section").attr('id', 'elex_mv_shipping_variation_section-' + variation_index );
            

                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_edit_variable_table_download_file").attr('id', 'elex_mv_edit_variable_table_download_file_id-' + variation_index );
                        jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-add-variable-download-file-row").attr('id', 'elex-multi-vendor-for-woocommerce-add-download-file-row_id-' + variation_index );

                        if(current_value.download_limit > 0){
                          jQuery("#elex_mv_download_limit_variation_edit-" + variation_index).val(current_value.download_limit)
                        }

                        if(current_value.download_expiry > 0){
                          jQuery("#elex_mv_download_expiry_variation_edit-" + variation_index).val(current_value.download_expiry)

                        }
                    
                        if(current_value.manage_stock){
                          jQuery('#elex_mv_variation_manage_stock_check_edit-' + variation_index ).attr('checked', true);
                          jQuery('#elex_mv_stock_sec-'+variation_index).removeClass('d-none');
                          jQuery('#elex_mv_stock_status_sec-'+variation_index).addClass('d-none');

                        }else{
                          jQuery('#elex_mv_variation_manage_stock_check_edit-' + variation_index ).attr('checked', false);
                          jQuery('#elex_mv_stock_sec-'+variation_index).addClass('d-none');
                          jQuery('#elex_mv_stock_status_sec-'+variation_index).removeClass('d-none');
                        }
                        jQuery("#elex-multi-vendor-for-woocommerce-edit-variable-download-file-div-" + variation_index ).addClass('d-none');


                        if( current_value.downloadable == true ) {

                          jQuery("#elex-multi-vendor-for-woocommerce-edit-variable-download-file-div-" + variation_index ).removeClass('d-none');
                          jQuery("#elex_mv_product_variation_downloadable_check_edit-" + variation_index ).attr('checked', true);
                        }else{
                  
                          jQuery("#elex_mv_product_variation_downloadable_check_edit-" + variation_index ).attr('checked', false);

                          jQuery("#elex-multi-vendor-for-woocommerce-edit-variable-download-file-div-" + variation_index ).addClass('d-none');

                        }

                        if( current_value.virtual == true ) {
                          jQuery("#elex_mv_shipping_variation_section-" + variation_index ).addClass('d-none');
                          jQuery("#elex_mv_product_variation_virtual_edit-" + variation_index ).attr('checked', true);
                        }else{
                          jQuery("#elex_mv_shipping_variation_section-" + variation_index ).removeClass('d-none');
                          jQuery("#elex_mv_product_variation_virtual_edit-" + variation_index ).attr('checked', false);

                        }

                        jQuery(document.body).on( 'click', "#elex_mv_variation_product_schedule_btn_id-" + variation_index , function(){
                          var variat_index = this.id.split('-').pop();
            
                          jQuery('#elex_mv_variation_product_schedule_sec_id-' + variat_index).removeClass('d-none')
                        
                        })
                        jQuery(document.body).on( 'click', "#elex_mv_product_schedule_cancel_btn_id-" + variation_index , function(){
                          var variat_index = this.id.split('-').pop();
            
                          jQuery('#elex_mv_variation_product_schedule_sec_id-' + variat_index).addClass('d-none')
                        
                        })
            
                        jQuery(document.body).on( 'change', "#elex_mv_product_variation_downloadable_check_edit-" + variation_index , function(){
                          var variat_index = this.id.split('-').pop();
            
                          if( jQuery(this).is(":checked") ){
                            jQuery("#elex-multi-vendor-for-woocommerce-edit-variable-download-file-div-" + variat_index ).removeClass('d-none');
                          } else{
                            jQuery("#elex-multi-vendor-for-woocommerce-edit-variable-download-file-div-" + variat_index ).addClass('d-none');
            
                          }
                        })
            
                        jQuery(document.body).on( 'change', "#elex_mv_product_variation_virtual_edit-" + variation_index , function(){
                          var variat_index = this.id.split('-').pop();
            
                          if( jQuery(this).is(":checked") ){
                            jQuery("#elex_mv_shipping_variation_section-" + variat_index ).addClass('d-none');
                          } else{
                            jQuery("#elex_mv_shipping_variation_section-" + variat_index ).removeClass('d-none');
            
                          }
                        })

                        if( current_value.downloads ) {
                        

                          prod_dwnlds = current_value.downloads
                          Object.keys( prod_dwnlds ).forEach(function(dwnload_val){

                            curr_dwn_index = jQuery("#elex-multi-vendor-for-woocommerce-add-download-file-row_id-" + variation_index).attr('curr_dwn_index') ? jQuery("#elex-multi-vendor-for-woocommerce-add-download-file-row_id-" + variation_index).attr('curr_dwn_index') : 0 ;
                
                           
                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').prepend(jQuery('#template-for-var-product-file-download').html());
                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex_mv_name_file_download" ).attr('id', 'elex_mv_name_file_download_id-' + curr_dwn_index );
                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex_mv_name_file_download" ).attr('name', '_wc_files_names[' + variation_index + '][' + curr_dwn_index + ']' );
                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex_mv_name_file_download" ).attr('value', prod_dwnlds[dwnload_val].name );

                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex_mv_hash_file_download" ).attr('id', 'elex_mv_hash_file_download_id-' + curr_dwn_index );
                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex_mv_hash_file_download" ).attr('name', '_wc_files_hashes[' + variation_index + '][' + curr_dwn_index + ']' );
                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex_mv_hash_file_download" ).attr('value', prod_dwnlds[dwnload_val].id );

                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex_mv_url_file_download" ).attr('id', 'elex_mv_url_file_download_id-' + curr_dwn_index );
                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex_mv_url_file_download" ).attr('name', '_wc_files_urls[' + variation_index + '][' + curr_dwn_index + ']' );
                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex_mv_url_file_download" ).attr('value', prod_dwnlds[dwnload_val].file );

                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-edit-upload-download-file-btn" ).attr('id', 'elex-multi-vendor-for-woocommerce-edit-upload-download-file-btn-id-' + curr_dwn_index );
                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-edit-upload-download-file-btn" ).attr('data-variat', variation_index );

                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-file-download" ).attr('id', 'elex-multi-vendor-for-woocommerce-file-download-id-' + curr_dwn_index );
                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-file-download" ).attr('data-variat', variation_index );

                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-remove-dowload-tr-simple-product" ).attr('id', 'elex-multi-vendor-for-woocommerce-remove-dowload-tr-simple-product-id-' + curr_dwn_index );
                            jQuery('#elex_mv_edit_variable_table_download_file_id-' + variation_index ).find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-remove-dowload-tr-simple-product" ).attr('data-variat', variation_index );

                            
                            curr_dwn_index++;
                            jQuery("#elex-multi-vendor-for-woocommerce-add-download-file-row_id-" + variation_index).attr('curr_dwn_index', curr_dwn_index);
              
                          });
                        }

			// jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex-multi-vendor-for-woocommerce-remove-image-btn-variation").attr('id', 'elex-multi-vendor-for-woocommerce-remove-image-variation-' + variation_index  );

                            // req_table = jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elex_mv_edit_variable_table_download_file");
                           
                            jQuery(document).on('click', '#elex-multi-vendor-for-woocommerce-add-download-file-row_id-' + variation_index , function(){
                              var curr_dwn_index = 0;
                              var variat_index = this.id.split('-').pop();

                              curr_dwn_index = jQuery("#elex-multi-vendor-for-woocommerce-add-download-file-row_id-" + variat_index).attr('curr_dwn_index') ;
                            

                              jQuery('#elex_mv_edit_variable_table_download_file_id-' + variat_index ).find('tbody').prepend(jQuery('#template-for-var-product-file-download').html());
                              jQuery('#elex_mv_edit_variable_table_download_file_id-' + variat_index ).find('tbody').children('tr:first').find( ".elex_mv_name_file_download" ).attr('id', 'elex_mv_name_file_download_id-' + curr_dwn_index );
                              jQuery('#elex_mv_edit_variable_table_download_file_id-' + variat_index ).find('tbody').children('tr:first').find( ".elex_mv_name_file_download" ).attr('name', '_wc_files_names[' + variat_index + '][' + curr_dwn_index + ']' );

                              jQuery('#elex_mv_edit_variable_table_download_file_id-' + variat_index ).find('tbody').children('tr:first').find( ".elex_mv_hash_file_download" ).attr('id', 'elex_mv_hash_file_download_id-' + curr_dwn_index );
                              jQuery('#elex_mv_edit_variable_table_download_file_id-' + variat_index ).find('tbody').children('tr:first').find( ".elex_mv_hash_file_download" ).attr('name', '_wc_files_hashes[' + variat_index + '][' + curr_dwn_index + ']' );

                              jQuery('#elex_mv_edit_variable_table_download_file_id-' + variat_index ).find('tbody').children('tr:first').find( ".elex_mv_url_file_download" ).attr('id', 'elex_mv_url_file_download_id-' + curr_dwn_index );
                              jQuery('#elex_mv_edit_variable_table_download_file_id-' + variat_index ).find('tbody').children('tr:first').find( ".elex_mv_url_file_download" ).attr('name', '_wc_files_urls[' + variat_index + '][' + curr_dwn_index + ']' );

                              jQuery('#elex_mv_edit_variable_table_download_file_id-' + variat_index ).find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-edit-upload-download-file-btn" ).attr('id', 'elex-multi-vendor-for-woocommerce-edit-upload-download-file-btn-id-' + curr_dwn_index );
                              jQuery('#elex_mv_edit_variable_table_download_file_id-' + variat_index ).find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-edit-upload-download-file-btn" ).attr('data-variat', variat_index );

                              jQuery('#elex_mv_edit_variable_table_download_file_id-' + variat_index ).find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-file-download" ).attr('id', 'elex-multi-vendor-for-woocommerce-file-download-id-' + curr_dwn_index );
                              jQuery('#elex_mv_edit_variable_table_download_file_id-' + variat_index ).find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-file-download" ).attr('data-variat', variat_index );

                              jQuery('#elex_mv_edit_variable_table_download_file_id-' + variat_index ).find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-remove-dowload-tr-simple-product" ).attr('id', 'elex-multi-vendor-for-woocommerce-remove-dowload-tr-simple-product-id-' + curr_dwn_index );
                              jQuery('#elex_mv_edit_variable_table_download_file_id-' + variat_index ).find('tbody').children('tr:first').find( ".elex-multi-vendor-for-woocommerce-remove-dowload-tr-simple-product" ).attr('data-variat', variat_index );

                              
                              curr_dwn_index++;
                              jQuery("#elex-multi-vendor-for-woocommerce-add-download-file-row_id-" + variat_index).attr('curr_dwn_index', parseInt( curr_dwn_index ));
                
                            });


                            jQuery( document.body ).on( 'change', '#elex-multi-vendor-for-woocommerce-file-download-id-' + variation_index, function ( event ) {
		
                              var reader;
                          
                              var dwn_no_index = this.id.split('-').pop();
                              var variat_index = jQuery(this).data('variat');

                              var formData = new FormData();
                          
                              if (this.files && this.files[0]) {
                                reader = new FileReader();
                                reader.onload = function (e) {
                          
                          
                                // jQuery("#elexPreviewImageUploadVariation_" + variat_index).attr("src", e.target.result);
                          
                          
                                // jQuery("#elex-multi-vendor-for-woocommerce-remove-image-variation-"+ dwn_no_index).removeClass("d-none");
                          
                          
                                };
                          
                                reader.readAsDataURL(this.files[0]);
                          
                                formData.append('file',this.files[0] ); 
                                formData.append('nonce',elex_mv_coupon_ajaxurl_object.nonce); 

                                jQuery.ajax({
                                url : elex_mv_coupon_ajaxurl_object.ajax_url + "?action=elex_mv_save_image_wordpress",
                                method: "post",
                                encType: 'multipart/form-data',
                                processData: false,
                                contentType: false,
                                data: formData,
                                success: function ( response ) {
                            
                                  jQuery('[name="_wc_files_urls['+ variat_index +']['+ dwn_no_index +']"]').val(response.data)
                                },
                          
                              });
                          
                              }
                            
                            })





                        jQuery(document).on('change', "[id^='elex_mv_variation_manage_stock_check_edit-']", function () {
                              var variat_index = this.id.split('-').pop();


                           
              							if(jQuery(this).is(":checked")){
              								jQuery('#elex_mv_stock_sec-'+variat_index).removeClass('d-none');
              								jQuery('#elex_mv_stock_status_sec-'+variat_index).addClass('d-none');

              							}else{
              								jQuery('#elex_mv_stock_sec-'+variat_index).addClass('d-none');
              								jQuery('#elex_mv_stock_status_sec-'+variat_index).removeClass('d-none');

              							}


                        })

                        jQuery(document).on('change', "[id^='elex-multi-vendor-for-woocommerce-filetag-variation-']", function () {
                            var reader;

                            var variat_index = this.id.split('-').pop();

                            if (this.files && this.files[0]) {
                              reader = new FileReader();
                              reader.onload = function (e) {

                                // jQuery('.elex_mv_add_variations_parent_edit').children().last().find(".elexPreviewImageUploadVariation").attr('src', e.target.result  );

                                jQuery("#elexPreviewImageUploadVariation_" + variat_index).attr("src", e.target.result);


                                jQuery("#elex-multi-vendor-for-woocommerce-remove-image-variation-"+ variat_index).removeClass("d-none");

                              };
                              reader.readAsDataURL(this.files[0]);
                            }
                        } )

                        jQuery(document).on('click', "[id^='elex-multi-vendor-for-woocommerce-remove-image-variation-']", function(){


                          var vari_index = this.id.split('-').pop();

                          jQuery("#elexPreviewImageUploadVariation_"+ vari_index).attr(
                            "src",
                            elex_mv_coupon_ajaxurl_object.plugin_path + "images/default.jpg"
                          );
                          jQuery("#elex-multi-vendor-for-woocommerce-filetag-variation-"+ vari_index).val(""); 
                          jQuery("#elex-multi-vendor-for-woocommerce-remove-image-variation-"+ vari_index).addClass("d-none");
    
                      } )


                        variation_index++;
                        jQuery('.elex_mv_add_variations_parent_edit').attr('variation_curr_index', variation_index);
                        jQuery('.elex_mv_edit_number_of_variation').html(jQuery('.elex_mv_add_variations_parent_edit').children().size());
                         
                         
                    })

        

                }
              


            }
        );


    }


  jQuery(".elex-multi-vendor-for-woocommerce-add-filter-open-btn").click(function () {
    jQuery("#elex-multi-vendor-for-woocommerce-add-filter").addClass("active");
    jQuery('body').css('overflow', 'hidden');

  });
  jQuery(".elex-multi-vendor-for-woocommerce-add-filter-close-btn").click(function () {
    jQuery("#elex-multi-vendor-for-woocommerce-add-filter").removeClass("active");
    location.reload();

  });

  jQuery(".elex-multi-vendor-for-woocommerce-add-export-open-btn").click(function () {
    jQuery("#elex-multi-vendor-for-woocommerce-add-export").addClass("active");
    jQuery('body').css('overflow', 'hidden');

  });
  jQuery(".elex-multi-vendor-for-woocommerce-add-export-close-btn").click(function () {
    jQuery("#elex-multi-vendor-for-woocommerce-add-export").removeClass("active");
    location.reload();

  });
  jQuery("#elex-export-csv-button-submit").click(function (e) {
    jQuery("#elex-multi-vendor-for-woocommerce-add-export").removeClass("active");
  });

  var selectedarrayele = [];



  jQuery(".elex-vendor-add-edit-product-category").select2({
		minimumInputLength: 2,
		placeholder: 'Select Categories',

		ajax: {
			url: elex_mv_admin_ajaxurl_object.ajax_url,
			type: 'POST',

			data: function (params) {
				var query = {
					search_val: params.term,
					action: 'elex_mv_cat_search_with_entered_val',
					nonce: elex_mv_admin_ajaxurl_object.nonce,
				}
				return query;
			},
			processResults: function (response) {
				return {
          
					results: response.data.map(function (cat) {
						return {
							text: cat.name,
							id: cat.term_id,
						}
					}),

				};
			}

		}

	});

 

  function funcClickSelectCategory(id, name) {
    enter_cat_id = {
      id: id,
      name: name,
    };

    selectedarrayele.push(enter_cat_id);
    jQuery("#selected-options-div-category").html("");
    selectedarrayele = [
      ...new Map(selectedarrayele.map((item) => [item["id"], item])).values(),
    ];
    selectedarrayele.forEach(function (resi) {
      jQuery("#selected-options-div-category").append(
        "<div data-select-id='" +
          resi.id +
          "' class='btn-primary elex-category-multivendor-div p-1'><p class='mb-1'>" +
          resi.name +
          "</p><button class='delete-category-button' data-id='" +
          resi.id +
          "' data-name='" +
          resi.name +
          "' type='button'>-</button></div>"
      );
    });

    // Attaching click event to the button using event delegation
    jQuery("#selected-options-div-category").on(
      "click",
      ".delete-category-button",
      function () {
        var catID = jQuery(this).data("id");
        var catName = jQuery(this).data("name");
        funcClickDeleteCategory(catID, catName);
      }
    );
    jQuery("#select-options-for-div-category").hide();
  }

  function funcClickDeleteCategory(id, name) {
    jQuery("#selected-options-div-category").html("");
    selectedarrayele = selectedarrayele.filter(function (obj) {
      if (obj.id == 0) {
        return obj.name !== name;
      }
      return obj.id !== id;
    });
    selectedarrayele = [
      ...new Map(selectedarrayele.map((item) => [item["name"], item])).values(),
    ];
    selectedarrayele.forEach(function (resi) {
      jQuery("#selected-options-div-category").append(
        "<div data-select-id='" +
          resi.id +
          "' class='btn-primary elex-category-multivendor-div p-1'><p class='mb-1'>" +
          resi.name +
          "</p><button class='delete-category-button' data-id='" +
          resi.id +
          "' data-name='" +
          resi.name +
          "' type='button'>-</button></div>"
      );
      // Attaching click event to the button using event delegation
      jQuery("#selected-options-div-category").on(
        "click",
        ".delete-category-button",
        function () {
          var catID = jQuery(this).data("id");
          var catName = jQuery(this).data("name");
          funcClickDeleteCategory(catID, catName);
        }
      );
    });
  }

  // edit page ====
  jQuery(".elex-multi-vendor-for-woocommerce-edit-product-close-btn").click(function () {
    location.reload();
    jQuery("#elex-multi-vendor-for-woocommerce-edit-product").removeClass("active");
  });

  jQuery(".elex-multi-vendor-for-woocommerce-edit-product-form-prev-btn").click(function () {
    jQuery(".nav-tabs > .nav-item > .active")
      .parent()
      .prev("li")
      .find("button")
      .trigger("click");
  });

  jQuery("#elex-multi-vendor-for-woocommerce-filetag").change(function () {
    editchangeImage(this);
  });

  function editchangeImage(input) {
    var reader;
    if (input.files && input.files[0]) {
      reader = new FileReader();

      reader.onload = function (e) {
        elexEditPreviewImageUpload.setAttribute("src", e.target.result);
      };
      reader.readAsDataURL(input.files[0]);
    }
  }

  validation_for_forms_func(
    "#elex_multivendor_edit_new_product_name",
    /^[A-Za-z][ A-Za-z0-9_]{0,29}$/,
    "#elex_multivendor_edit_new_product_name_error",
    "Enter Proper Name"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_new_product_description",
    /.*/,
    "#elex_multivendor_edit_new_product_description_error",
    "Enter Proper description"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_new_product_category",
    /^[A-Za-z][ A-Za-z0-9_]{0,29}$/,
    "#elex_multivendor_edit_new_product_category_error",
    "Enter Proper category"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_regular_price",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_edit_regular_price_error",
    "Enter Regular Price in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_sale_price",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_edit_sale_price_error",
    "Enter Sale Price in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_stock_value",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_edit_stock_value_error",
    "Enter Stock Value in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_lower_threshold",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_edit_lower_threshold_error",
    "Enter Lower Threshold in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_weight",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_edit_weight_error",
    "Enter Product Weight in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_length",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_edit_length_error",
    "Enter Product Length in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_width",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_edit_width_error",
    "Enter Product Width in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_height",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_edit_height_error",
    "Enter Product Height in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_hs_tariff",
    /[a-zA-Z0-9]{2,10}/,
    "#elex_multivendor_edit_hs_tariff_error",
    "Enter HS Tariff Number in Alphanumerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_custom_declared_value",
    /^\d{0,8}(\.\d{1,4})?$/,
    "#elex_multivendor_edit_custom_declared_value_error",
    "Enter Custom declared value in numerics"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_country_of_manufacture",
    /[A-Z]{2,3}/,
    "#elex_multivendor_edit_country_of_manufacture_error",
    "Enter country in Capital"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_commodity_name",
    /^[A-Za-z][ A-Za-z0-9_]{0,29}$/,
    "#elex_multivendor_edit_commodity_name_error",
    "Enter Commodity Name"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_waybill_description",
    /.*/,
    "#elex_multivendor_edit_waybill_description_error",
    "Enter description in waybill"
  );
  validation_for_forms_func(
    "#elex_multivendor_edit_special_service",
    /.*/,
    "elex_multivendor_edit_special_service",
    "Enter Special Service"
  );

  function validation_for_forms_func(
    id_for_input_element,
    regex_for_string,
    id_for_error_element,
    error_string
  ) {
    jQuery(id_for_input_element).keyup(function () {
      const regex = regex_for_string;

      if (!regex.test(this.value)) {
        jQuery(id_for_error_element).html(
          `<div class="text-danger">${error_string}</div>`
        );
      } else {
        jQuery(id_for_error_element).html("");
      }
    });
  }

  jQuery(".elex-multi-vendor-for-woocommerce-edit-product-form-submit-btn-req").click(function () {
    jQuery("#elex_multivendor_edit_regular_price_error").html("");
    jQuery("#elex_multivendor_edit_sale_price_error").html("");
    jQuery("#elex_multivendor_edit_new_product_image_error").html("");
    var formData;
    dis=this;
    var edit_page_save_link = elex_mv_admin_ajaxurl_object.ajax_url;
    var id_prod = jQuery("#elex_multivendor_edit_new_product_id").attr("value");

    edit_page_save_link += "?action=elex_mv_edit_product";
    formData = new FormData(
      document.getElementById("elex-multi-vendor-for-woocommerce-edit-form-details")
    );

    // formData.append("product_category", JSON.stringify(selectedarrayele));
    formData.append("form-step", jQuery(this).data('step') );

    if (jQuery(this).data("send-for-approval")) {
      formData.append("send_for_approval", "yes");
    }

    jQuery.ajax({
      url: edit_page_save_link,
      type: "POST",
      data: formData,
      enctype: "multipart/form-data",
      processData: false,
      contentType: false,
      success: function (result) {
        if (result.success && result.success !== false) {
          var additem = document.getElementById("wsdesk_additem_toast-edit");
          jQuery("#toast_message_mv-edit").html("Changes are saved");
          var toast = new bootstrap.Toast(additem);
          toast.show();
        }
        if(!jQuery(dis).hasClass('save-as-draft')){
          next_page_iterate(jQuery(".nav-tabs > .nav-item > .active")
				  .parent()
				  .next("li"));
        }
        
        // jQuery("#elex-multi-vendor-for-woocommerce-edit-product").removeClass("active");
      },
      error: function (status, errorThrown) {
        add_product_error_obj = status.responseJSON.data;
        for (const key in add_product_error_obj) {
          function loop_for_html_error(obj) {
            string = "";
            for (var i = 0; i < obj.length; i++) {
              string += ` ${obj[i]}`;
            }
            return string;
          }

          if (add_product_error_obj[key] == null) {
            continue;
          } else if (
            key == "regular_price" ||
            key == "sale_price"
          ) {
            jQuery("#elex_multivendor_edit_" + key + "_error").html(
              '<div style="color:red;"  >' +
              loop_for_html_error(add_product_error_obj[key]) +
              "</div>"
            );
          } else if (key == "product_image") {
            jQuery("#elex_multivendor_edit_new_product_image_error").html(
              '<div style="color:red;"  >' +
              loop_for_html_error(add_product_error_obj[key]) +
              "</div>"
            );
          } else {
            jQuery("#" + key).after(
              "<div >" +
                loop_for_html_error(add_product_error_obj[key]) +
                "</div>"
            );
          }
        }
      },
    });
  });

  function next_page_iterate(elem){

    if( elem.hasClass('d-none') ){
      next_page_iterate(elem.next('li'));
    }else{
        elem.find("button")
        .trigger("click");
    }
  }
  var selectedarrayele = [];

  function funcClickEditSelectCategory(id, name) {
    enter_cat_id = {
      id: id,
      name: name,
    };

    selectedarrayele.push(enter_cat_id);
    jQuery("#selected-options-for-edit-div-category").html("");
    selectedarrayele = [
      ...new Map(selectedarrayele.map((item) => [item["id"], item])).values(),
    ];
    selectedarrayele.forEach(function (resi) {
      var htmlContent = `<div data-select-id='${resi.id}' class='btn-primary elex-edit-category-multivendor-div p-1'>
              <p class='mb-1'>${resi.name}</p>
              <button class='edit-delete-category-button' data-id='${resi.id}' data-name='${resi.name}' type='button'>-</button>
          </div>`;

      jQuery("#selected-options-for-edit-div-category").append(htmlContent);
      // Attaching click event to the button using event delegation
      jQuery("#selected-options-for-edit-div-category").on(
        "click",
        ".edit-delete-category-button",
        function () {
          var catID = jQuery(this).data("id");
          var catName = jQuery(this).data("name");
          funcClickEditDeleteCategory(catID, catName);
        }
      );
    });

    jQuery("#select-options-for-edit-div-category").hide();
  }

  function funcClickEditDeleteCategory(id, name) {
    jQuery("#selected-options-for-edit-div-category").html("");
    selectedarrayele = selectedarrayele.filter(function (obj) {
      if (obj.id == 0) {
        return obj.name !== name;
      }
      return obj.id !== id;
    });
    selectedarrayele = [
      ...new Map(selectedarrayele.map((item) => [item["name"], item])).values(),
    ];
    selectedarrayele.forEach(function (resi) {
      var htmlContent = `<div data-select-id='${resi.id}' class='btn-primary elex-edit-category-multivendor-div p-1'>
              <p class='mb-1'>${resi.name}</p>
              <button class='edit-delete-category-button' data-id='${resi.id}' data-name='${resi.name}' type='button'>-</button>
          </div>`;

      jQuery("#selected-options-for-edit-div-category").append(htmlContent);
      // Attaching click event to the button using event delegation
      jQuery("#selected-options-for-edit-div-category").on(
        "click",
        ".edit-delete-category-button",
        function () {
          var catID = jQuery(this).data("id");
          var catName = jQuery(this).data("name");
          funcClickEditDeleteCategory(catID, catName);
        }
      );
    });
  }

  // advanced filters =========

  jQuery("#elex-multi-vendor-for-woocommerce-advanced-filter-submit-button").click(function () {
    var additem = document.getElementById("wsdesk_additem_toast");
    jQuery("#toast_message_mv").html("Filters Applied Successfully");
    var toast = new bootstrap.Toast(additem);
    toast.show();
  });

  // categories =========

  jQuery(".elex-multi-vendor-for-woocommerce-add-category-btn").click(function () {
    jQuery("#elex-multi-vendor-for-woocommerce-add-category").addClass("active");
  });

  jQuery(".elex-multi-vendor-for-woocommerce-close-cross-category-btn").click(function () {
    jQuery("#elex-multi-vendor-for-woocommerce-add-category").removeClass("active");
  });

  jQuery(".elex-multi-vendor-for-woocommerce-rename-close-btn").click(function () {
    jQuery("#elex-multi-vendor-for-woocommerce-add-rename").removeClass("active");
  });

  jQuery("#elex-search-category-vendor-button").click(function () {
    search_val = jQuery("#elex-search-category-vendor").val();
    // url_for_search = window.location.href.split('?')[0] + '?search_term=' + search_val;
    const u = new URL(location);
    let params = new URLSearchParams(u.search);
    if (params.has("category_search")) {
      u.searchParams.set("category_search", search_val);
    } else {
      u.searchParams.append("category_search", search_val);
    }
    window.location.replace(u);
    jQuery("#elex-search-category-vendor").val(search_val);
  });
  jQuery(".elex-multi-vendor-for-woocommerce-add-category-wp-btn").click(function (e) {
    // e.preventDefault();
    var link = elex_mv_admin_ajaxurl_object.ajax_url;
    var formData;

    link += "?action=elex_mv_add_category_name";
    var formData = new FormData(
      document.getElementById("elex-multi-vendor-for-woocommerce-category-detail-form")
    );

    jQuery.ajax({
      url: link,
      type: "POST",
      data: formData,
      enctype: "multipart/form-data",
      processData: false,
      contentType: false,
      success: function (result) {
        if (result.success) {
          var additem = jQuery(".elex_new_category_toast");

          jQuery("#toast_message_cat_mv").html("Category Added Sucessfully");
          var toast = new bootstrap.Toast(additem);
          toast.show();
          setTimeout(function () {
            location.reload();
          }, 3000);
        }
      },
    });
  });

  jQuery("#elex-multi-vendor-for-woocommerce-category-rename-save-changes").click(function () {
    var formData;
    cat_id = jQuery("#category-current-id").val();
    var edit_page_save_link = elex_mv_admin_ajaxurl_object.ajax_url;
    edit_page_save_link += "?action=elex_mv_category_rename_form";
    formData = new FormData(
      document.getElementById("elex-multi-vendor-for-woocommerce-category-rename-form")
    );
    formData.append("category-current-id", cat_id);
    jQuery.ajax({
      url: edit_page_save_link,
      type: "POST",
      data: formData,
      enctype: "multipart/form-data",
      processData: false,
      contentType: false,
      success: function (result) {
        var additem = jQuery(".elex_new_category_toast");

        jQuery("#toast_message_cat_mv").html("Category Renamed Sucessfully");
        var toast = new bootstrap.Toast(additem);
        toast.show();
        setTimeout(function () {
          location.reload();
        }, 3000);
      },
    });
  });

  function renameCategoryFunc(id) {
    jQuery("#elex-multi-vendor-for-woocommerce-add-rename").addClass("active");

    var edit_page_link = elex_mv_admin_ajaxurl_object.ajax_url;
    edit_page_link = edit_page_link + "?action=elex_mv_rename_display";
    var form = {
      id: id,
      nonce: jQuery("#elex-page-nonce").val(),
    };
    jQuery.ajax({
      url: edit_page_link,
      type: "POST",
      data: form,
      enctype: "multipart/form-data",
      success: function (result) {
        jQuery("#category-current-id").attr("value", id);
        jQuery("#category-current-name").val(result.data.category_name);
      },
    });
  }

  function deleteCategoryFunc(id) {
    var additem = document.getElementById("wsdesk_delete_category_toast");
    jQuery("#elex-multi-vendor-for-woocommerce-delete-cat-confirm-btn").val(id);
    var toast = new bootstrap.Toast(additem);
    toast.show();
  }

  jQuery("#elex-multi-vendor-for-woocommerce-delete-cat-confirm-btn").click(function () {
    var form;
    var delete_category_link = elex_mv_admin_ajaxurl_object.ajax_url;
    delete_category_link =
      delete_category_link + "?action=elex_mv_delete_category";
    id = jQuery("#elex-multi-vendor-for-woocommerce-delete-cat-confirm-btn").val();
    form = {
      id: id,
      nonce: jQuery("#elex-page-nonce").val(),
    };
    jQuery.ajax({
      url: delete_category_link,
      type: "POST",
      data: form,
      enctype: "text/plain",
      success: function () {
        location.reload();
      },
    });
  });

  jQuery(".elex-export-csv-button-submit").click(function () {
    alert("Do you want to download csv");

    jQuery("#export-form-for-vendor-product").submit();
  });
});
