$(document).ready(function () {
  $.tablesorter.addParser({
    id: 'date_parser',
    is: function (s, table, cell, $cell) {
      return false;
    },
    format: function (s, table, cell, cellIndex) {
      return $(cell).text().trim().split(".").reverse().join("-");
    },
    parsed: false,
    type: "text"
  });
  $("#allTable").tablesorter({
    sortList: [[0,1]],
    theme: "blue",
    widthFixed: true,
    widgets: ["zebra", "stickyHeaders"],
    fixedWidth: true,
    headers: {
      3: { sorter: "date_parser"},
      4: { sorter: "date_parser"}
    },
  });
});

function exportToRewizor(source, date, type) {
  if (type == undefined || type == null || type == "") {
    alert("Wybierz rodzaj faktur (normalne lub korekty).");
    return;
  }
    if (source == undefined || source == null || source == "") {
    alert("Wybierz źródło faktur.");
    return;
  }

  blockUI("Trwa generowanie pliku...");
  
  var xhr = new XMLHttpRequest();
  xhr.open('GET', "index.php?module=EcmInvoiceOuts&action=ecommerce&ajax=exportToRewizor&to_pdf=1&source="+source+"&date="+date+"&type="+type, true);
  xhr.responseType = 'arraybuffer';
  
  xhr.onload = function() {
    if (xhr.status === 200) {
      var arrayBuffer = xhr.response;
      var bytes = new Uint8Array(arrayBuffer);
      var data = '';
      for (var i = 0; i < bytes.length; i++) {
        data += String.fromCharCode(bytes[i]);
      }
      
      data = data.replace(/ {4}/g, "");
      data = data.replace(/\n/g, "\r\n");
      
      var finalBytes = new Uint8Array(data.length);
      for (var i = 0; i < data.length; i++) {
        finalBytes[i] = data.charCodeAt(i) & 0xFF;
      }
      
      var filename = `rewizor-${source}-${type}.epp`;
      var blob = new Blob([finalBytes], { type: "text/plain;charset=iso-8859-2"});
      
      if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, filename);
      } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
          var url = URL.createObjectURL(blob);
          link.setAttribute("href", url);
          link.setAttribute("download", filename);
          link.style.visibility = "hidden";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        }
      }
      $.unblockUI();
      
    } else {
      window.alert("Błąd eksportu.");
      $.unblockUI();
    }
  };
  
  xhr.onerror = function() {
    window.alert("Błąd eksportu.");
    $.unblockUI();
  };
  
  xhr.send();
}

function blockUI($msg) {
  $.blockUI(
      {
        css: {
          border: 'none',
          padding: '15px',
          backgroundColor: '#000',
          '-webkit-border-radius': '10px',
          '-moz-border-radius': '10px',
          opacity: .5,
          'font-weight': 'bold',
          'font-size': '16px',
          color: '#fff',
        },
        message: $msg
      });
}
function copyToClipboard(text) {
  navigator.clipboard.writeText(text);
}
function openDetails(id, origin) {
    window.console.log(origin);
    if  (origin.startsWith('Apilo')) {
      window.open("index.php?module=EcmInvoiceOuts&action=ecommerce&apilo_details="+id, "_blank");
    } else {
      window.open("index.php?module=EcmInvoiceOuts&action=ecommerce&baselinker_details="+id, "_blank");
    }

}