tenants.prototype.lease = function () {
  var tenant_id = this.id; /* This tenant ID is used by AJAX saves */
  var user_id = this.user_id; /* This User ID is used by AJAX saves */
  
//alert("In the lease Tab");
    // Select from Available Properties
    $("#availableSearch").on("change", function () {
      var idProp = $(this).find(':selected').val();
      //alert(id);
      property_id = idProp;

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

      // append to the form
      $('#newLease').append($hiddenPropertyID);

      //var address = $(this).data("address");
      var address = $(this).find(':selected').data('address');

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

      // append to the form
      $('#newLease').append($hiddenAddress);
      $('#no-lease').css('display', 'none');
      $('#no-lease').transition('slide down', '0ms')
              .transition('slide down', 300, function () {
                $('#no-lease').css('display', 'none');
              });
      $('#lease-form').show();
    });

    $('#editLease')
            .form({
            inline: true,
            fields: {
              rent: {
                identifier: 'rent',
                rules: [ { type: 'decimalMoney', prompt: 'Please enter a valid decmial number (Example: 100.00)'} ]
              },
              deposit: {
                identifer: 'deposit',
                rules: [ { type: 'decimalMoney', prompt: 'Please enter a valid decmial number (Example: 100.00)' }  ]
              }, 
            }
    });
    
    // Validation for #addLease
    $('#newLease')
            .form({
              inline: true,
              on: 'submit',
              keyboardShortcuts: false,
              onSuccess: function (e) {
                e.preventDefault();
                debug_print('#newLease form has passed validation');
                debug_print("Adding Lease as user_id: " + user);
                var property_id = $("#availableSearch").val();
                var property_address = $("#property_address").val();
                var occupants_num = $("#occupants_num").val();
                var list_occupants = $("#list_occupants").val();
                var billing_day = $("#billing_day").val();
                var water_payed_by = $("#water_payed_by").val();
                var consumers_payed_by = $("#consumers_payed_by").val();
                $.ajax({
                  beforeSend: saving_toast,
                  url: 'app/tenants/add-lease.php',
                  type: 'GET',
                  async: true,
                  data: {tenant_id: tenant_id, property_id: property_id, user_id: user_id, occupants_num: occupants_num, list_occupants: list_occupants, billing_day: billing_day, property_address: property_address, water_payed_by: water_payed_by, consumers_payed_by: consumers_payed_by},
                  success: function (response, status, xhr) {
                    if (!has_error(response, xhr)) {
                      start_progress(); /* Restart percentage to 1 */
                      cloneObject.reload_right();
                      cloneObject.load_left('start_up');
                      has_saved(response, xhr, 'lease');
                      
                      /* Make sure Lease was Created... */
                      if (response.lease_id > 0) {
                        router.navigate('Tenants/Active/'+tenant_id+'/Profile/'+response.lease_id);
                      }
                      
                    } // END if !Error
                  }
                }); // <-- END: .ajax() 

              },
              fields: {
                availableSearch: {
                  identifier: 'availableSearch',
                  rules: [ { type: 'empty', prompt: 'Please select a property to create a new lease.' } ]
                },
                occupants_num: {
                  identifier: 'occupants_num',
                  rules: [ { type: 'empty', prompt: 'How many occupants are they?' } ]
                },
                billing_day: {
                  identifier: 'billing_day',
                  rules: [ { type: 'empty', prompt: 'Select automatic rent billing date.' } ]
                }
              } // <-- END: fields

    }); // <-- END: #addLease 


// UPDATE LEASE
// NOTE: Always unbind the last events that bubbled up the DOM tree.
    $(document).off('change enter', '.updateLease');
// Now bind the newly created event listeners.
    $(document).on("change enter", ".updateLease", function () {
      // Get data attributes from the input that was changed.
      var leaseid = $(this).attr('data-leaseID');
      var fieldname = $(this).attr('data-changed');
      var newvalue = $(this).val();
      var tenantid = tenant_id; // Fixed on 12/19/2017
//                      alert(tenantid+"-"+fieldname+"-"+newvalue);

      make_changes_lease(leaseid, fieldname, newvalue, tenantid);
    }); // <-- END: onChane event (.updateLease)

    $(document).off('change enter', '.updateLeaseSelect');
    $(document).on("change enter", ".updateLeaseSelect", function () {
      // Get data attributes from the input that was changed.
      var leaseid = $(this).find(':selected').attr('data-leaseID');
      var fieldname = $(this).find(':selected').attr('data-changed');
      var newvalue = $(this).find(':selected').val();
      var tenantid = tenant_id;
      make_changes_lease(leaseid, fieldname, newvalue, tenantid);
    }); // <-- END: onChane event (.updateLeaseSelected)               

    function make_changes_lease(leaseid, fieldname, newvalue, tenantid) {
      var saving = '';
      // validate the form before we proccess it.
      var validate = $('#editLease').form('validate form');
      // Get the result of the validation.
      var validateResult = $('#editLease').form('is valid');
      // If the form passes validation the begin processing.
      if (validateResult === true) {

        // Get data attributes from the input that was changed.
        var leaseid = leaseid;
        var fieldname = fieldname;
        var newvalue = newvalue;
        debug_print("Data Passed to AJAX: leaseid=" + leaseid + "&field=" + fieldname + "&newvalue=" + newvalue + "&tenant_id=" + tenantid);
        $.ajax({
          beforeSend: saving_toast,
          url: 'app/tenants/edit-lease.php',
          type: 'GET',
          async: true,
          data: {id: leaseid, field: fieldname, val: newvalue, user_id: user_id, tenant_id: tenantid},
          success: function (response, status, xhr) {
            if (!hasError(response, xhr)) {
              hasSaved(response, xhr, fieldname);
    
              // Re load the right side without the animation for sticky message timestamp update
              if (fieldname == "status_msg") {
                start_progress(); /* Restart percentage to 1 */
                cloneObject.reloadRight();
                done_loading();
              }
            } // END if !Error check
          }// <-- END: on success

        }); // <-- END: .ajax() 

      } // <-- END: validate Results
    } // End makeChanges() function	

}; // END if Tab = Lease

tenants.prototype.reload_right = function () {
  var rside = cloneObject.load_right('StartUp');
  $.when( rside ).done(function () {
    cloneObject.Lease(); /* RE-bind self */
    stop_progress(); /* Make readonly fields styles */
  });
};

tenants.prototype.confirm_close = function (leaseID, property_id, address) {
  var tenant_id = this.id; /* This tenant ID is used by AJAX saves */
  var user_id = this.user_id; /* This User ID is used by AJAX saves */

  $.confirm({
    container: "#lease",
    useBootstrap: false,
    boxWidth: "80%",
    position: 'sticky',
    animation: 'bottom',
    closeAnimation: 'bottom',
    type: 'red',
    title: "Terminate Lease",
    content: "Are you sure you want to Terminate this lease for: " + address + "?",
    buttons: {
     cancel: function() {},
     terminate: {
       text: "Terminiate Lease",
       btnClass: 'btn-red',
       action: function() {
          debug_print('Termanited Tenant: leaseID=' + leaseID + ',user_id=' + user_id + ',tenant_id=' + tenant_id + ',property_id=' + property_id);
          $.ajax({
            url: 'app/tenants/close-lease.php',
            type: 'GET',
            async: true,
            data: {leaseID: leaseID, user_id: user_id, tenant_id: tenant_id, property_id: property_id},
            success: function (response, status, xhr) {
              if (!has_error(response, xhr)) {
                cloneObject.reload_right();
                cloneObject.loadLeft('start_up');
                has_saved(response, xhr, 'Terminated Lease');
              }
            }
          });
       }
     }
    }
  });     
}; // end of function confirmClose