var url = $('meta[name="base-url"]').attr('content');

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});


$(document).ajaxStart(function() {
  $("#loading").fadeIn('200');
}).ajaxStop(function() {
  $("#loading").fadeOut('200');
});

function openPreview(disputeId, DisputeLabel) 
{
  document.getElementById("pdf-canvas-list").innerHTML = ""; //clear old document                
  $.ajax({
    type:'get',
    url:url+'/getInvoice/'+disputeId+'/'+2,
    success:function(res)
    {
      var pdf = url+'/uploads/'+disputeId+'/Dispute.pdf';
      $('#pdf-canvas-list').html('<iframe src="'+pdf+'"></iframe>');                     
      document.getElementById('lblDisputeName').innerText = DisputeLabel;
      $('#mdlPreview').modal('show');
    }
  });
}

function openSentMail(id)
{
  var mindate = new Date($('.create_date'+id).text());
  var maxdate = new Date();
  maxdate.setDate(maxdate.getDate() + 1);

  $('#hidSubmitButtonId').val(id);
  $('#popup').modal('show');
}

function markSent()
{
 var disputeId = $('#hidSubmitButtonId').val(); 
 var sentDate = document.getElementById("txtSendDate").value;
 var method = document.getElementById("drpMethod").value;
 // console.log(disputeId,sentDate,method);
 var formdata = new FormData(); //FormData object
 var fileInput = document.getElementById('file-upload_upload-file');
 //Iterating through each files selected in fileInput
 for (i = 0; i < fileInput.files.length; i++) {
    //Appending each file to FormData object
    formdata.append('doc', fileInput.files[i]);
 }

 formdata.append('disputeId',disputeId);
 formdata.append('sentDate',sentDate);
 formdata.append('method',method);

 $.ajax({
    type:'post',
    url:url+'/markLetterSent',
    data:formdata,
    contentType: false,
    processData: false,
    success:function(res)
    {
      $('#popup').modal('hide');
      $('#alertmessage').html('<p class="text-center">Marked Sent</p>');
      $('#divLayoutAlert').fadeIn();
      setTimeout(function(){$('#divLayoutAlert').fadeOut();window.location.reload(true);},5000);
    }
 });
}

function deleteDisputeLatter(id)
{
  $('#disputeId').val(id);
  $('#popup_closepopup').modal('show');
}

function showCreditDispute(id)
{
	$.ajax({
		type:'get',
		url:url+'/setDisputeSession/'+id,
		success:function(res)
		{
			window.location = url+'/create_dispute';
		}
	});
}

function deleteDispute()
{
  var id = $('#disputeId').val();
  $.ajax({
      type:'get',
      url:url+'/deleteDispute/'+id,
      success:function()
      {
          window.location.reload(true);
      }
  });
}

function DownloadDispute(id)
{
  $.ajax({
    type:'get',
    url:url+'/getInvoice/'+id+'/'+1,
    success:function(res)
    {
      var blob = new Blob([res], { type: "application/pdf" });
      var link = document.createElement('a');
      link.href = window.URL = 'uploads/'+id+'/Dispute.pdf';
      link.download = "Dispute.pdf";
      link.click();
    }
  });
}

function emailDispute(id)
{
  $.ajax({
      type:'get',
      url:url+'/sendDisputeMail/'+id,
      success:function(res)
      {
        $('#alertmessage').html('<p class="text-center">Dispute Emailed</p> <br> check your spam and make sure to mark it as not spam and add info@togglebytes.co.in to your contacts to ensure the emails are delivered to your Inbox');
        $('#divLayoutAlert').fadeIn();
        setTimeout(function(){$('#divLayoutAlert').fadeOut();window.location.reload(true);},5000);
      }
  });
}

function editTrans(trans_id)
{
  localStorage.setItem('dispute_letter','edit');
  window.location = url+'/create_dispute?disputeId='+trans_id;
}

function UndoEvent(id)
{
  $.ajax({
    type:'get',
    url:url+'/changeStatus/'+id,
    success:function(res)
    {
      window.location.reload(true);
    }
  });
}

if(window.FileReader) { 
  //var drop; 
  addEventHandler(window, 'load', function() {
    var status = document.getElementsByClassName('status')[0];
    var drop   = document.getElementsByClassName('drop')[0];
    var list   = document.getElementsByClassName('list')[0];

    function cancel(e) {
      if (e.preventDefault) { 
        e.preventDefault(); 
      }
      return false;
    }

    // Tells the browser that we *can* drop on this target
    addEventHandler(drop, 'dragover', cancel);
    addEventHandler(drop, 'dragenter', cancel);
    addEventHandler(drop, 'drop', function (e) {
      e = e || window.event; // get window.event if e argument missing (in IE)   

      if (e.preventDefault) { 
        e.preventDefault(); 
      } // stops the browser from redirecting off to the image.

      var dt = e.dataTransfer;
      var files = dt.files;
      for (var i=0; i<files.length; i++) {
        var file = files[i];
        var reader = new FileReader();

        //attach event handlers here...
        reader.readAsDataURL(file);
        addEventHandler(reader, 'loadend', function(e, file) {
        var bin = this.result; 
        $('.drop').html('<img src="'+e.target.result+'" style="width:150px;height:150px"/>');
        $('#upload-file').html('<i class="fa fa-address-card"></i> <strong>'+file.name+'</strong>');
        $('#imageName').val(file.name);  

        }.bindToEventHandler(file));
      }
      return false;
    });

    Function.prototype.bindToEventHandler = function bindToEventHandler() {
      var handler = this;
      var boundParameters = Array.prototype.slice.call(arguments);
      //create closure
      return function(e) {
        e = e || window.event; // get window.event if e argument missing (in IE)   
        boundParameters.unshift(e);
        handler.apply(this, boundParameters);
      };
    };
  });
} else { 
  document.getElementsByClassName('status')[0].innerHTML = 'Your browser does not support the HTML5 FileReader.';
}

function addEventHandler(obj, evt, handler) {
  if(obj.addEventListener) {
    // W3C method
    obj.addEventListener(evt, handler, false);
  } else if(obj.attachEvent) {
    // IE method.
    obj.attachEvent('on'+evt, handler);
  } else {
    // Old school method.
    obj['on'+evt] = handler;
  }
}

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    
    reader.onload = function(e) {
      $('.drop').html('<img src="'+e.target.result+'" style="width:150px;height:150px"/>');
    }
    $('#upload-file').html('<i class="fa fa-address-card"></i> <strong>'+input.files[0].name+'</strong>');
    reader.readAsDataURL(input.files[0]); // convert to base64 string
  }
}

