// Define Globals
var user_id, transtype, baltype, the_tenant, the_filter, trans_type, trans_bal, trans_id, the_tab, lease_id;
var counter_for_trans = 0, reloadonNewTransaction = false;
tenants.prototype.new_transaction = function () {
  counter_for_trans = 0; // Reenable submit
  user_id = this.user_id; /* This defines the User for AJAX Save */
  transtype = this.transtype;
  baltype = this.baltype;
  the_tenant = this.id;
  the_filter = this.filter;
  the_tab = this.tab;
  trans_id = this.transid;
  lease_id = this.lease_id;
  trans_type = transtype; 
  trans_bal = baltype; 
  
      rem(); // Remind me if on Development Database...with a toast.
      $('#process-trans-type').html(trans_type);  
      $('#process-trans-bal').html(trans_bal);
    
      $('#process-amount').html($("#amount_tendered").val());
      if (trans_type == "Payment") {
        $('#checkboxReceipt').checkbox('check');
        $("#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 (trans_type == "Receivable") {
        $('#checkboxReceipt').checkbox('uncheck');
        $("#payment_method_text").text("Charge Type");
        $("#payment_method").html("<option value='Charge'>Account Charge</option>");
      }

  //     $('#createNewTransaction select').dropdown(drop_effect);
      
  var form_submit = function () {
      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 TransID#'+response.transaction_id);
  /* Check to make sure Transaction was error Free */              
  if (response.transaction_id > 0) {

//                      $('#printReceiptBtn').attr('data-trans-id', response.transaction_id);
//                      $('#printReceiptBtn').removeClass("disabled");
//                      $('#printReceiptBtn').css('opacity', '1');
                $('#processNewTransaction').css('opacity', '0');
                $('#processNewTransaction').addClass('disabledHidden'); // Halfway is a css hack for btn opacity

                if ($('#checkboxReceipt').checkbox('is checked') === true) {
                  if (response.transaction_id > 0) {  
                    print_frame('NewPrintReceipt', 'app/tenants/print-receipt.php?trans_id=' + response.transaction_id);
                  }
                }
                $('#createNewTransaction').form('reset');
                router.navigate('Tenants/' + the_filter + '/' + the_tenant + '/Transactions/'+lease_id+'/ViewTransaction/' + response.transaction_id + '/View');
  }


              } // END if !ERROR
            }

          }); // END ajax call
          return false;
  }
      
	// Start of Create Form           
	$(document).off('blur', '#createNewTransaction');
    $('#createNewTransaction')
            .form({
              inline: true,
              on: 'blur',
              onSuccess: function (e) {
				e.stopImmediatePropagation();  
              },
              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); // trans_type
      // Only show the options that apply to the transaction type
      if (val == "Payment") {
        $('#amountTypeText').text('Payment Amount');
        //$('#checkboxReceipt').checkbox('check');
		$("#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>");
        checkFormNewTransaction();
      } else if (val == "Receivable") {
        $('#amountTypeText').text('Receivable Amount');
        //$('#checkboxReceipt').checkbox('uncheck');
		$("#payment_method_text").text("Charge Type");
        $("#payment_method").html("<option value='Charge' selected>Account Charge</option>");
        checkFormNewTransaction();
      } else if (val == "Credit") {
        $('#amountTypeText').text('Credit Amount');
        $("#payment_method_text").text("Credit Type");
        $("#payment_method").html("<option value='Credit' selected>Account Credit</option>");
        checkFormNewTransaction();
      }
    });
/*
    $("#balance_type").off('change');
    $("#balance_type").on("change", function (event) {
      var trans_bal = $("#balance_type").val();
      $('#process-trans-bal').html(trans_bal);
    });  
*/
    $("#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
      checkFormNewTransaction();
    });
    
    $('#payment_method').off("change");    
    $('#payment_method').on("change", function (event) {
      if ($('#payment_method').val() == 'Cash') {
        $('#refNumBlock').hide();
     } else {
        $('#refNumBlock').show();

        var method_text = '';
        switch($('#payment_method').val()) {
          case 'Check':
            method_text = 'Check';
            break;
          case 'moneyOrder':
            method_text = 'Money Order';
            break;
          case 'moneyGram':
            method_text = 'Money Gram';
            break;
          case 'westernUnion':
            method_text = 'Western Union';            
            break;
          case 'cashiersCheck':
            method_text = 'Cashiers Check';            
            break;
          case 'directDeposit':
            method_text = 'Direct Deposit';            
            break;
        }

        $('#refNumText').text(method_text + " #");
        $('#refrence_number').attr('placeholder', "Please enter the " + method_text + " #");
      }
      // Check to see if form is valid
      checkFormNewTransaction();
   });
    
    $('#refrence_number').off("change");    
    $('#refrence_number').on("change", function (event) {
	  // Check to see if form is valid
      checkFormNewTransaction();
    });   
    
//    $(document).off("click", "#printReceiptBtn");
//    $(document).on("click", "#printReceiptBtn", function () {
//      var trans_id = $('#printReceiptBtn').attr('data-trans-id');
//      if (trans_id == '0') {
//        /**
//         * @ todo: Build a retry event here
//         */
//        console.log('Sorry, reciept generation error.')
//      } else {
//        console.log("Printing via Trans ID: " + trans_id);
//        print_frame('NewReceipt', 'app/tenants/print-receipt.php?trans_id=' + trans_id);
//      }
//    });
    
    $(document).off("click", "#closeTransaction");
    $(document).on("click", "#closeTransaction", function () {  
      router.navigate('Tenants/' + the_filter + '/' + the_tenant + '/Transactions/'+lease_id);
    });

    $(document).off("click", "#processNewTransaction");
    $(document).on("click", "#processNewTransaction", function (event) {
      reloadonNewTransaction = true;
      form_submit();
    });
    
};

var b_notes = false;
function checkFormNewTransaction() {
    var method = $("#payment_method").val();
    var notes = $("#refrence_number").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', 'refrence_number', { identifier: 'refrence_number', rules: [ { type: 'empty', prompt: 'Please enter reference#' } ] } );
      $('#createNewTransaction').form('validate field', 'refrence_number');
      b_notes = true;
    } else {
      if (b_notes === true) {
        $('#createNewTransaction').form('remove rule', 'refrence_number', );
        $('#createNewTransaction').form('validate field', 'refrence_number');
        b_notes = false;
      }
    }
    if ( valid === true && $('#createNewTransaction').form('is valid') ) {
      console.log('Attempting to enable Process Transaction!');
        // Validation Passed for New Transaction (Enabled the button)
        if ( $('#processNewTransaction').hasClass("disabled") ) {
          $('#processNewTransaction').removeClass('disabled');
        }
        if ( $('#processNewTransaction').hasClass("grey") ) {
          $('#processNewTransaction').removeClass('grey');
        }
        if ( ! $('#processNewTransaction').hasClass("green") ) {
          $('#processNewTransaction').addClass('green');
          $('#processNewTransaction').css('opacity', '1'); 
        }
    } else {
        // Validation Failed
        if ( $('#processNewTransaction').hasClass("green") ) {
          $('#processNewTransaction').removeClass('green');
        }
        if ( ! $('#processNewTransaction').hasClass("grey") ) {
          $('#processNewTransaction').addClass('grey');
          $('#processNewTransaction').addClass('disabled');
          $('#processNewTransaction').css('opacity', '0');
        }
    }
}