    var
    token = $('body').data('token'),
    info  = $('[data-info]').data('info'),
    productInfo = JSON.parse(document.querySelector('[data-productinfo]').getAttribute('data-productinfo')),
    typeMarketplace = productInfo.type_marketplace,
    productId = productInfo.product_id,
    typeProduct = productInfo.type_product,
    productCatalogId = document.getElementById('js-catalog-product-id'),
    urlFilter = productInfo.urlFilter,
    isGrid = productInfo.is_grid,
    btnSyncronize = $('.js-modal-syncronize').get(0),
    btnSave = $('.js-modal-save').get(0),
    btnClose = $('button.js-adm-modal-close').get(0),
    btnBack = $('.js-modal-back').get(0),
    btnNext = $('.js-modal-next').get(0),
    codigoBarra = document.getElementById('codigo_barra'),
    spanProductName = document.getElementById('span-product-name'),
    gridCatalog = document.getElementById('js-catalog-grid'),
    searchCatalog = document.getElementById('js-search-catalog'),
    formCatalog = document.getElementById('js-mlcatalog'),
    productHeader = document.getElementById('js-product-header'),
    productSelectedCatalogProduct = document.getElementById('js-selected-catalog-product'),
    productHeaderGrid = document.getElementById('js-product-grid-header'),
    attributesCatalog = document.getElementById('js-catalog-attributes'),
    mainAdId = productInfo.market_ad_id;

    function showField(field, show) {
      if (field != null && field != undefined) {
        if (show) {
          field.classList.remove('hidden');
        } else {
          field.classList.add('hidden');
        }
      }
    }

    function isHidden(element) {
      return element.classList.contains('hidden');
    }

    function getProductGridCatalogInfo(productFromGridId) {
      productCatalogId.dataset.foundByBarcode = false;
      $.ajax({
        url: 'index.php?route=module/mercadolivre/catalog/getProductGridCatalogInfo&token=' + token +
          '&product_id=' + productFromGridId + '&product_grid_id=' + productId,
        type: 'get',
        dataType: 'json',
        success: function(json) {
          productHeaderGrid.innerHTML = json.html;
          codigoBarra.value = json.codigo_barra;
          spanProductName.innerHTML = '<b>Produto E-commerce:</b> ' + json.grid_descr;
          getCatalogProductByCodigoBarra(true);
          if (productCatalogId.dataset.foundByBarcode == 'true'){
            prepareFichaTecnica();
          } else {
            prepareSearchGridFields();
          }
        },
      });
    }

    function prepareSearchGrid(){
      try {
        $('body').append(loadBeforeSend());
        getProductGridCatalogInfo($("input[name='grid_product_ml']").get(0).value);
      } finally {
        $('.loadBeforeSend').fadeOut();
      }
    }

    function prepareFichaTecnica(canBack){
      showField(attributesCatalog, true);
      showField(gridCatalog, false);
      showField(searchCatalog, false);
      showField(formCatalog, false);
      showField(productSelectedCatalogProduct, true);
      showField(productHeader, false);
      showField(productHeaderGrid, false);

      showField(btnClose, false);
      showField(btnBack, (canBack || isGrid));
      showField(btnNext, false);
      showField(btnSave, true);
      showField(btnSyncronize, (!isGrid));

    }

    function prepareSearchGridFields(){
      showField(gridCatalog, false);
      showField(searchCatalog, true);
      showField(formCatalog, true);
      showField(attributesCatalog, false);
      showField(productHeader, false);
      showField(productHeaderGrid, true);
      showField(productSelectedCatalogProduct, false);

      showField(btnSave, false);
      showField(btnSyncronize, false);
      showField(btnClose, false);
      showField(btnBack, true);
      showField(btnNext, true);
    }

    function backFromSearchGrid(){
      getProductsGrid();

      showField(gridCatalog, true);
      showField(searchCatalog, false);
      showField(formCatalog, false);
      showField(attributesCatalog, false);
      showField(productHeader, true);
      showField(productHeaderGrid, false);
      showField(productSelectedCatalogProduct, false);

      showField(btnSave, false);
      showField(btnSyncronize, true);
      showField(btnClose, true);
      showField(btnBack, false);
      showField(btnNext, false);
    }

    function backFromBulkSetting(){
      showField(gridCatalog, false);
      showField(searchCatalog, true);
      showField(formCatalog, true);
      showField(attributesCatalog, false);
      showField(productHeader, !isGrid);
      showField(productHeaderGrid, isGrid);
      showField(productSelectedCatalogProduct, false);

      showField(btnSave, false);
      showField(btnSyncronize, false);
      showField(btnClose, false);
      showField(btnBack, true);
      showField(btnNext, true);
    }

    function backFromBulkSettingUnique(){
      showField(searchCatalog, true);
      showField(formCatalog, true);
      showField(attributesCatalog, false);
      showField(productHeader, true);
      showField(productHeaderGrid, false);
      showField(productSelectedCatalogProduct, false);

      showField(btnSave, false);
      showField(btnSyncronize, false);
      showField(btnClose, true);
      showField(btnBack, false);
      showField(btnNext, true);
    }

    function getProductsGrid(){
      $.ajax({
        url:
          'index.php?route=catalog/product/retornoProductsGrid&token=' +
          token +
          '&product_grid_id=' +
          productId +
          '&type_marketplace=' +
          typeMarketplace +
          '&onlyList=true' +
          '&removeLink=true' +
          '&showTagMlCatalog=true' +
          urlFilter +
          '&filterMlCatalogAd=' +
          mainAdId,
        type: 'get',
        dataType: 'html',
        beforeSend: function() {
        },
        complete: function() {
        },
        success: function(html) {
          gridCatalog.innerHTML = html;

          var productGridRow = document.querySelectorAll('.js-product-grid-select');
          for (let i = 0; i < productGridRow.length; i++) {
            productGridRow[i].onclick = function() {
              $("input[name='grid_product_ml']").get(0).value = productGridRow[i].id;
              prepareSearchGrid();
            };
          }
        },
      });
    }

    $(document).on("click", ".js-modal-search", function () {
      var page = typeof $(this).data('page') == 'undefined' ? 1 : $(this).data('page');
      searchcatalogml(page);
    });

    $('.js-modal-save').on('click', function (e) {
      salvarcatalogml(true);
    });

    $('.js-modal-syncronize').on('click', function (e) {
      if (!isGrid) {
        salvarcatalogml(false);
      }
      sincronizarcatalogml();
    });

    $('.js-modal-back').on('click', function (e) {
      if (isGrid){
        if ((isHidden(attributesCatalog)) || (productCatalogId.dataset.foundByBarcode == 'true')){
          backFromSearchGrid();
        } else {
          backFromBulkSetting();
        }
      } else {
        backFromBulkSettingUnique();
      }
    });

    $('.js-modal-next').on('click', function (e) {
        var
          inputSelectedProduct = $("input[name='mlcatalog-product']:checked").get(0),
          selectedProduct, productName;

        if (!inputSelectedProduct){
          alert('Selecione um produto!');
          return;
        }

        productName = $("input[name='mlcatalog-product']:checked").get(0).parentNode.parentNode.parentNode.querySelector('.js-product-catalog-name').innerHTML;
        selectedProduct = inputSelectedProduct.value;

        productCatalogId.value = selectedProduct;
        productCatalogId.dataset.name = productName;
        productCatalogId.dataset.foundByBarcode = false;

        getFichaTecnica(selectedProduct);
        prepareFichaTecnica(true);
    });

    function getFichaTecnica(selectedProduct) {
      let data = {};
      data['productId'] = productId;
      data['typeProduct'] = typeProduct;
      data['selectedProduct'] = selectedProduct;

      $.ajax({
        url: 'index.php?route=module/mercadolivre/catalog/getBulksetting&token=' + token,
        dataType: 'json',
        type: 'POST',
        data: data,
        beforeSend: function () {
          $('.js-modal-next').addClass('btn-loading');
          $('.js-modal-next').attr('disabled', true);
          $('#synchronize-catalog').addClass('js-adm-modal-overlay-no-close');
        },
        complete: function () {
        },
        success: function (json) {
          $('.js-modal-next').attr('disabled', false);
          $('.js-modal-next').removeClass('btn-loading');
          $('#synchronize-catalog').removeClass('js-adm-modal-overlay-no-close');

          document.getElementById('js-mlcatalog').classList.add('hidden');

          document.getElementById('js-selected-catalog-product-info').innerHTML = json.selectedCatalogProduct;
          document.getElementById('js-catalog-attributes').innerHTML = json.atributtes;
        }
      });
    }

    function searchcatalogml(page = 1) {
      var data = {};
      data['filter_product'] = $("input[name='product_search']").val();
      data['product_id'] = $("input[name='product_ml']").val();
      data['product_type'] = $("input[name='type_product[" + data['product_id'] + "]']").val();
      data['page'] = page;
      $.ajax({
        url: 'index.php?route=module/mercadolivre/catalog/searchCatalogProducts&token=' + token,
        type: 'get',
        data: data,
        dataType: 'json',
        beforeSend: function() {
          $('body').append(loadBeforeSend());
        },
        complete: function() {
          $('.loadBeforeSend').fadeOut();
        },
        success: function(json) {
          $('.search-products').html(json.html);
        }
      });
    }

    function salvarcatalogml(canClose) {
      var data = {};
      data['product_id'] = (isGrid ? $("input[name='grid_product_ml']").val() : $("input[name='product_ml']").val());
      data['product_catalog_id'] = productCatalogId.value;
      data['name'] = productCatalogId.dataset.name;
      $.ajax({
        url: 'index.php?route=module/mercadolivre/catalog/saveCatalogProduct&token=' + token,
        type: 'get',
        data: data,
        dataType: 'html',
        async: true,
        beforeSend: function() {
          $('body').append(loadBeforeSend());
        },
        complete: function() {
          $('.loadBeforeSend').fadeOut();
        },
        success: function(html) {
          if (isGrid && canClose){
            backFromSearchGrid();
          } else if (canClose) {
            btnClose.click();
          }
        }
      });
    }

    function sincronizarcatalogml() {
      var data = {}, productIdValue = $("input[name='product_ml']").val();

      data['product_id'] = $("input[name='product_ml']").val();
      data['product_catalog_id'] = productCatalogId.value;
      data['name'] = productCatalogId.dataset.name;
      data['redirect'] = $("input[name='redirect']").val();
      data['product_ml'] = $("input[name='product_ml']").val();
      data['type_product'] = $("input[name='type_product[" + $("input[name='product_ml']").val() + "]']").val();
      data['main_ad'] = $("input[name='main_ad']").val();

      data['mercaShipping'] = $("#mercaShipping").val();
      data['mercaListType'] = $("#mercaListType").val();
      data['mercaWarrantyType'] = $("#mercaWarrantyType").val();
      data['mercaWarranty'] = $("#mercaWarranty").val();
      data['mercaWarrantyTypeTime'] = $("#mercaWarrantyTypeTime").val();
      data['mercaShippingFree'] = $("#mercaShippingFree").val();
      $.ajax({
        url: 'index.php?route=module/mercadolivre/catalog/synchronyzeCatalogProduct&token=' + token,
        type: 'post',
        data: data,
        dataType: 'json',
        beforeSend: function() {
          $('body').append(loadBeforeSend());
        },
        complete: function() {
          $('.loadBeforeSend').fadeOut();
        },
        success: function(json) {
          if (json) {
            location = json.redirect;
          }
        },
        error: function(xhr, ajaxOptions, thrownError) {
          console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
        }
      });
    }

    function getCatalogProductByCodigoBarra(searchByNameIfNotFound = false) {
      var data = {};
      data['filter_barcode'] = codigoBarra.value;
      data['page'] = typeof $(this).data('page') == 'undefined' ? 1 : $(this).data('page');
      $.ajax({
        url: 'index.php?route=module/mercadolivre/catalog/searchCatalogProducts&token=' + token,
        type: 'get',
        data: data,
        dataType: 'json',
        async: false,
        success: function(json) {
          if (json.total > 0){
            var
            productName = json.results[0].name,
            selectedProduct = json.results[0].id;

            productCatalogId.value = selectedProduct;
            productCatalogId.dataset.name = productName;
            productCatalogId.dataset.foundByBarcode = true;

            getFichaTecnica(selectedProduct);
            prepareFichaTecnica(false);
          } else if (searchByNameIfNotFound){
            // Se não achou quando abriu a tela por codigo de barras, pesquisa por descrição
            searchcatalogml();
          }
        },
        error: function(xhr, ajaxOptions, thrownError) {
          console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
        }
      });
    }

    if (isGrid){
      getProductsGrid();
    }

    if ((!isGrid) && (codigoBarra.value)){
      getCatalogProductByCodigoBarra(true);
    }  else {
      searchcatalogml();
    }

