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

  $('select[name="return_action_id"]').bind('change', function() {
    $.ajax({
      url: 'index.php?route=sale/return/action&token=' + token + '&return_id=' + window.returnId,
      type: 'post',
      dataType: 'json',
      data: 'return_action_id=' + this.value,
      beforeSend: function() {
        $('.success, .warning, .attention').remove();

        $('.box').before(
          '<div class="attention"><img src="../assets/img/loading-black.svg" alt="" />' + window.textWait + '</div>'
        );
      },
      success: function(json) {
        $('.success, .warning, .attention').remove();

        if (json['error']) {
          $('.box').before('<div class="warning" style="display: none;">' + json['error'] + '</div>');

          $('.warning').fadeIn('slow');
        }

        if (json['success']) {
          $('.box').before('<div class="success" style="display: none;">' + json['success'] + '</div>');

          $('.success').fadeIn('slow');
        }
      },
      error: function(xhr, ajaxOptions, thrownError) {
        alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
      },
    });
  });

  $('#history .pagination a').live('click', function() {
    $('#history').load(this.href);

    return false;
  });

  $('#history').on('click', '.adm-pagination a', function(event) {
    event.preventDefault();
    $('#history').load(this.href, function() {
      initHandleDropdown();
      selectErrors();
    });
    return false;
  });  

  $('#history').load('index.php?route=sale/return/history&token=' + token + '&return_id=' + window.returnId);

  $('#button-history').on('click', function() {
    $.ajax({
      url: 'index.php?route=sale/return/history&token=' + token + '&return_id=' + window.returnId,
      type: 'post',
      dataType: 'html',
      data:
        'return_status_id=' +
        encodeURIComponent($('select[name="return_status_id"]').val()) +
        '&notify=' +
        encodeURIComponent($('input[name="notify"]').attr('checked') ? 1 : 0) +
        '&append=' +
        encodeURIComponent($('input[name="append"]').attr('checked') ? 1 : 0) +
        '&comment=' +
        encodeURIComponent($('textarea[name="comment"]').val()),
      beforeSend: function() {
        $('.success, .warning').remove();
        $('#button-history').attr('disabled', true);
        $('#history').prepend(
          '<div class="attention"><img src="../assets/img/loading-black.svg" alt="" />' + window.textWait + '</div>'
        );
      },
      complete: function() {
        $('#button-history').attr('disabled', false);
        $('.attention').remove();
      },
      success: function(html) {
        $('#history').html(html);

        $('textarea[name="comment"]').val('');

        $('#return-status').html($('select[name="return_status_id"] option:selected').text());
      },
    });
  });
});
