$(document).ready(function () {
  var
    token = $('body').data('token');

  function checkoption($this){
    var
      $content = $this.closest('.js-content-options').find('.field-group-join'),
      $discount = $('.js-discount-status').val();

    if ($this.is(':checked')) {
      $content.removeClass('hidden');
      $element = $content.find('.field-entry');
      $.each($content.find('.field-entry'), function(index, element){
        if($(element).hasClass('js-discount')){
          if($discount==1){
            $(element).prop('disabled', false);
          }else{
            $(element).prop('disabled', true);
          }
        }else{
          $(element).prop('disabled', false);
        }
      });
    } else {
      $content.addClass('hidden');
      $content.find('.field-entry').prop('disabled', true);
    }
  }

  function checkoptionAll(){
    $.each($('.js-check-options'), function(index, element){
      if($(element).is(':checked')){
        checkoption($(element));
      }
    });
  }

  $('.js-discount-status').on('change', function () {
   checkoptionAll();
  });

  $('.js-check-options').on('change', function () {
    checkoption($(this))
  });

  checkoptionAll();


  $('.js-check-bank').on('click', function(){

    $(this).closest('.js-content-options').siblings('.js-content-options').find('.js-check-bank').prop('checked', false).trigger('change');

  });

  if ($('.js-discount-value').length > 0) {
    $('.js-discount-value').each(function() {
      setFormatValue($(this));
    });
  }


  $('.js-type-discount').on('change', function(){
    $(this).closest('.field-group-join').find('.js-discount-value').val('').focus();
    setFormatValue($(this));
  });

  function setFormatValue(fieldEntryUnity) {
    var
      fieldEntryValue = fieldEntryUnity.closest('.js-content-options').find('.js-discount-value'),
      fieldLabelValue = fieldEntryValue.closest('.field-group-join').find('.js-label');
    if (fieldEntryUnity.val() == '1') {
      fieldEntryValue.mask('000.000.000.000.000.00', { reverse: true });
      fieldLabelValue.text('Desconto (R$)');
    } else {
      fieldEntryValue.mask('990.0', { reverse: true });
      fieldLabelValue.text('Desconto (%)');
    }
  }


});
