// Define Globals
var user_id;
var transtype;
var baltype;
var theTenant;
var theFilter;
var transType; 
var transBal; 
var trans_id;
var lease_id;

tenants.prototype.edit_transaction = function () {
  user_id = this.user_id; /* This defines the User for AJAX Save */
  transtype = this.transtype;
  baltype = this.baltype;
  theTenant = this.id;
  theFilter = this.filter;
  transType = transtype; 
  transBal = baltype; 
  trans_id = $('#last_transaction').val();
  lease_id = this.lease_id;

    $('#printReceiptBtn').prop("disabled", true);
    $('#processTransaction').css('opacity', '0'); // hide submit on startup
	
	// New modal for creating transactions
	$(".createTransaction").off("click");
    $(".createTransaction").on("click", function() { 
        var CTtransType = $(this).attr('data-transType');
        var CTtransBal = $(this).attr('data-transBal');
        router.navigate('Tenants/' + theFilter + '/' + theTenant + '/Transactions/'+lease_id+'/NewTransaction/Create/'+CTtransType+'/'+CTtransBal+'/Modal');
    });

    // Create Transaction load form page
    $.get("app/tenants/create-new-transaction.php", {transType: transType, transBal: transBal, trans_id: trans_id}, function (data) {

        $("#newTransactionForm").html(data);
        cloneObject.actions();

    }); // end of GET creat new trans
       
};

tenants.prototype.actions = function () {
      // Covert the HTML selects to semantic dropdowns (Added by Chris 8/15/2018)
      // Selection will drop down and reset.... which sucks...but looks good.
      $('#createNewTransaction select').dropdown();

      $('#process-trans-type').html(transType);  
      $('#process-trans-bal').html(transBal);
    
      $('#process-amount').html($("#amount_tendered").val());
      if (transType == "Payment") {
        $("#payment_method_text").text("Payment Method");
        $("#payment_method").html("<option value='none' selected>Select Option</option><option value='Cash'>Cash</option><option value='Check'>Check</option><option value='moneyOrder'>Money Order</option><option value='moneyGram'>Money Gram</option><option value='westernUnion'>Western Union</option><option value='cashiersCheck'>Cashier's Check</option><option value='directDeposit'>Direct Deposit</option>");
      } else if (transType == "Receivable") {
        $("#payment_method_text").text("Charge Type");
        $("#payment_method").html("<option value='Charge'>Account Charge</option>");
      } 
         
	// Start of Create Form           
	var counter_for_trans = 0;
	$(document).off('blur', '#createNewTransaction');
    $('#createNewTransaction')
            .form({
              inline: true,
              on: 'blur',
              onSuccess: function (e) {
				e.stopImmediatePropagation();  
			if (counter_for_trans === 0) { 
					counter_for_trans++;  
			} else {
				throw "Duplicate!";
			}		

                debug_print('#newTransaction Form Passed Validation');

                // do what you like with the input
                $input = $('<input type="hidden" name="user_id"/>').val(user_id);

                // append to the form
                $('#createNewTransaction').append($input);

                $.ajax({
//                  beforeSend: saving_toast,
                  url: 'app/tenants/new-transaction.php',
                  type: 'GET',
                  data: $('#include-ids, #createNewTransaction').serialize(),
                  success: function (response, status, xhr) {
                    if (!check_for_error('transaction-message',response, xhr)) {
                      did_save('transaction-message', response, xhr, 'transaction');
                      console.log('Receipt trans_id#'+response.transaction_id);
                      $('#printReceiptBtn').attr('data-trans-id', response.transaction_id);
                      $('#printReceiptBtn').prop("disabled", false);
                      $('#printReceiptBtn').css('opacity', '1');
                      
                      if ($('#checkboxReceipt').checkbox('is checked') === true) {
                        if (response.transaction_id > 0) {  
                          print_frame('NewPrintReceipt', 'app/tenants/print-receipt.php?trans_id=' + response.transaction_id);
                        }
                      }
                      
                    } // END if !ERROR
                  }

                }); // END ajax call
                return false;
              },
              fields: {
                trans_type: {
                  identifier: 'trans_type',
                  rules: [ { type: 'empty', prompt: 'Please select a transaction type' } ]
                },
                balance_type: {
                  identifier: 'balance_type',
                  rules: [ { type: 'empty', prompt: 'Please select a balance type' } ]
                },
                amount_tendered: {
                  identifier: 'amount_tendered',
                  rules: [ { type: 'decimalMoney', prompt: 'Please enter a decimal amount (Example: 100.00)' } ]
                },
                payment_method: {
                  identifier: 'payment_method',
                  rules: [ { type: 'not[none]', prompt: 'Please select a payment method' } ]
                }
              }// END fields
            });	// END #newTransaction form	
          

    // Make sure you cant select the wrong payment method
    $("#trans_type").off('change');
    $("#trans_type").on("change", function (event) {
      var val = $(this).val();
      $('#process-trans-type').html(val); // transType
      // Only show the options that apply to the transaction type
      if (val == "Payment") {
		$("#payment_method_text").text("Payment Method");
        $("#payment_method").html("<option value='none' selected>Select Option</option><option value='Cash'>Cash</option><option value='Check'>Check</option><option value='moneyOrder'>Money Order</option><option value='moneyGram'>Money Gram</option><option value='westernUnion'>Western Union</option><option value='cashiersCheck'>Cashier's Check</option><option value='directDeposit'>Direct Deposit</option>");
        checkForm();
      } else if (val == "Receivable") {
		$("#payment_method_text").text("Charge Type");
        $("#payment_method").html("<option value='Charge' selected>Account Charge</option>");
        checkForm();
      } else if (val == "Credit") {
        $("#payment_method_text").text("Credit Type");
        $("#payment_method").html("<option value='Credit' selected>Account Credit</option>");
        checkForm();
      }
    });

    $("#balance_type").off('change');
    $("#balance_type").on("change", function (event) {
      var transBal = $("#balance_type").val();
      $('#process-trans-bal').html(transBal);
    });  

    $("#amount_tendered").off('change');
    $("#amount_tendered").on("change", function (event) {
      var amount = $("#amount_tendered").val();
      var decimal = amount.includes('.');
      if (decimal === false && amount > 9) {
          $("#amount_tendered").val(String(amount) + '.00');
          $('#process-amount').html(String(amount) + '.00');
      } else {
        $('#process-amount').html(amount);
      }
	  // Check to see if form is valid
      checkForm();
    });
    
    $('#payment_method').off("change");    
    $('#payment_method').on("change", function (event) {
	  // Check to see if form is valid
      checkForm();
    });
    
    $('#notes').off("change");    
    $('#notes').on("change", function (event) {
	  // Check to see if form is valid
      checkForm();
    });   
    
    $(document).off("click", "#printReceiptBtn");
    $(document).on("click", "#printReceiptBtn", function () {
      var trans_id = $('#printReceiptBtn').attr('data-trans-id');
      console.log("Trans ID: " + trans_id);
      print_frame('NewReceipt', 'app/tenants/print-receipt.php?trans_id=' + trans_id);
    });
        
    setTimeout(function (){ $('#amount_tendered').focus(); }, 1000);
      
	
    $(document).off("click", ".trasactionItem");
    $(document).on("click", ".trasactionItem", function () {
      $("#print_frame").remove();
      var trans_id = $(this).data("id");
      router.navigate('Tenants/' + theFilter + '/' + theTenant + '/Transactions/'+lease_id+'/ViewTransaction/Details/'+trans_id+'/Modal');
    });
	
    $("#closeTransaction").off("click");
    $("#closeTransaction").on("click", function() {
        //alert("Navigating...");
        $('#newTransactionModal').modal('hide');
        router.navigate('Tenants/' + theFilter + '/' + theTenant + '/Transactions');
    });
    
    $(document).off("click", "#processTransaction");
    $(document).on("click", "#processTransaction", function (event) {
      $('#createNewTransaction').form('submit');
      $('#createNewTransaction').form('reset');
    });
	
    $(".closeTrans").off("click");
    $(".closeTrans").on("click", function () {
      $('#transactionModal').modal('hide');
    });
    
    $('.coupled.modal').modal({allowMultiple: true });
    
    $(document).off("click", ".printRecipt");
    $(document).on("click", ".printRecipt", function () {
      var trans_id = $('#modalTransID').val()
      $('#modalTransID').val(trans_id);
      $('#print_frame').attr('src', 'app/tenants/print-receipt.php?trans_id=' + trans_id + '');
      $("#print_frame").get(0).contentWindow.print();
      $('#modalTransID').val('');
    });

    $(".filterTrans").off("change");
    $(".filterTrans").on("change", function () {
      var lease_id = $('#lease_id').val();
      var trans_type_filter = $('#trans_type_filter').val();
      var balance_type_filter = $('#balance_type_filter').val();
      var date_filter = $('#date_filter').val();
      // Get transaction information
      $.holdReady( true );
      $.get("app/tenants/view-transactions.php", {lease_id: lease_id, trans_type_filter: trans_type_filter, balance_type_filter: balance_type_filter, date_filter: date_filter}, function (data) {
        $.holdReady( false );
        $("#transactionHistory").html(data);
      });
    });
    
    $(document).off("click", ".voidTransaction");
    $(document).on("click", ".voidTransaction", function () {
       $('#voidModalTransID').val($('#modalTransID').val());
       $('#voidModal').modal('show');
    });
    
    $(document).off("click", ".doVoid");
    $(document).on("click", ".doVoid", function () {
       var void_id = $('#voidModalTransID').val();
       alert(void_id);
    });
	
   // hmm SHould be called EDIT...
   $('#newTransactionModal').modal({
          centered: false,
          closable: false
      }).modal('setting', 'transition', 'vertical flip')
      .modal('show');
      
  
};
// End of Actions


var vnotes = false;
function checkForm() {
    var method = $("#payment_method").val();
    var notes = $("#notes").val();
    if (method == '' || method == 'Cash' || method == 'Charge' || method == 'Credit') {
      var valid = true;
    } else if (notes == '') {
      var valid = false;
    } else {
      var valid = true;
    }
    if (valid === false) {
      $('#createNewTransaction').form('add rule', 'notes', { identifier: 'notes', rules: [ { type: 'empty', prompt: 'Please enter reference#' } ] } );
      $('#createNewTransaction').form('validate field', 'notes');
      vnotes = true;
    } else {
      if (vnotes === true) {
        $('#createNewTransaction').form('remove rule', 'notes');
        $('#createNewTransaction').form('validate field', 'notes');
        vnotes = false;
      }
    }
    if ( valid === true && $('#createNewTransaction').form('is valid') ) {
      console.log('Attempting to enable Process Transaction!');
        $('#processTransaction').removeClass('grey');
        $('#processTransaction').addClass('green');
        $('#processTransaction').removeClass('disabled');
        $('#processTransaction').css('opacity', '1'); // show
    } else {
        $('#processTransaction').addClass('grey');
        $('#processTransaction').removeClass('green');
        $('#processTransaction').addClass('disabled');
        $('#processTransaction').css('opacity', '0');
    }
}

function print_ledger() {
  var trans_type_filter = $('#trans_type_filter').val();
  var balance_type_filter = $('#balance_type_filter').val();
  var date_filter = $('#date_filter').val();
  var lease_id = $('#lease_id').val();
  var printTrans = $('#printTrans').val();
//                console.log('trans_type_filter: '+trans_type_filter+' balance_type_filter: '+balance_type_filter+' lease_id: '+lease_id+' printTrans: '+printTrans);
  var frame_id = 'printTransReport';
  var src = 'app/tenants/print-transactions.php?lease_id=' + lease_id + '&trans_type_filter=' + trans_type_filter + '&balance_type_filter=' + balance_type_filter + '&date_filter=' + date_filter;
  print_frame(frame_id, src);
}