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

  if($('[data-order-tracking]').length > 0){

    var orderTracking = JSON.parse($('[data-order-tracking]').data('order-tracking'));

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

      var input = $('<input>')
          .attr('name', 'objetos')
          .val($(this).data('tracking-code')),
        form = $('<form>')
          .attr({ action: orderTracking.trackingLink, method: 'POST', target: 'Blank' })
          .append(input)
          .appendTo('body')
          .submit();

      form.remove();
    });


    $('.js-update-tracking-history').on('click', function() {
      $('.success, .warning').remove();

      var data = {};
      data['order_id'] = orderTracking.orderId;
      data['module'] = orderTracking.trackingModule;
     
      $.ajax({
        url: orderTracking.trackingUrl,
        type: 'get',
        data: data,
        dataType: 'json',
        timeout: 10000,
        beforeSend: function() {
          $('body').append(loadBeforeSend());
        },
        complete: function(json) {
          $('.loadBeforeSend').fadeOut();
        },
        success: function(json) {
          console.log(json);
          if (json['warning']) {
            $('.box').prepend('<div class="warning">' + json['warning'] + '</div>');
          }
          if (json['success']) {
            $('.box').prepend('<div class="success">' + json['success'] + '</div>');
            setTimeout(function() {
              location.reload();
            }, 3000);
          }
          $('html, body').animate(
            {
              scrollTop: 0,
            },
            300
          );
        },error: function (xhr, ajaxOptions, thrownError) {
          console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
        }
      });
    });

    $('.js-update-shipping-history').on('click', function() {
      $('.success, .warning').remove();

      var data = {};
      data['order_id'] = orderTracking.orderId;
      $.ajax({
        url: orderTracking.trackingUrl,
        type: 'get',
        data: data,
        dataType: 'html',
        timeout: 10000,
        beforeSend: function() {
          $('body').append(loadBeforeSend());
        },
        complete: function() {
          $('.loadBeforeSend').fadeOut();
        },
        success: function(html) {

          $('#tracking-events').html(html);

        },error: function (xhr, ajaxOptions, thrownError) {
          console.log(xhr.status);
          console.log(ajaxOptions);
          console.log(thrownError);
        }
      });
    });


  }


 });
