var the_tab;
tenants.prototype.main = function () {
  open = []; /* Tracks if menu item was already open */
  the_tab = this.tab;
  var dfd_Tenants_main = jQuery.Deferred();
  start_progress();
  $.when(this.load_left(), this.load_right()).done(function () {
    stop_progress();
    debug_print('AJAX complete');
    dfd_Tenants_main.resolve("ajax_complete");
  }).fail(function(msg) {
    stop_progress();
    dfd_Tenants_main.reject("AJAX Failed loading...");
  });
  
  return dfd_Tenants_main.promise();
};

tenants.prototype.load_left = function (callback) {
  var RowID = this.id; /* This tenant Row ID is used by row selection function */
  var dfd_TenantsLeft = jQuery.Deferred();
  $("#main-container-left-body").addClass("loading");
  $("main-container-left-footer").html('&nbsp;&nbsp;'); /* keep padding while loading */
  var atldhf = ajax_loader({id: this.id, filter: this.filter, selected: this.selected}, "tenants/header/left.html", "main-container-left-header");
  progress();
  var atldff = ajax_loader({id: this.id, filter: this.filter, tab: this.tab, selected: this.selected}, "tenants/footer/left.html", "main-container-left-footer");
  progress();
  var atldbf = ajax_loader({id: this.id, filter: this.filter, selected: this.selected, lease_id: this.lease_id}, "tenants/tenants_list/view_for_json.html", "main-container-left-body");
  progress();
  $.when(atldhf, atldff, atldbf).done(function () {
    progress();
    $("#main-container-left-body").removeClass("loading");
    debug_print('Left');
    var fixed_th = ajax_loader({}, "tenants/header/fixed_th.html", "left-fixed-th-container");
    $.when(fixed_th).then(function () {
      left_scroll();
    });
    if (typeof callback !== 'undefined' && cloneObject[callback]) {
      cloneObject[callback]();
    }
    dfd_TenantsLeft.resolve("ajax_done_left");
  }).fail(function() {
    $("#main-container-left-body").removeClass("loading");
    dfd_TenantsLeft.reject('load_left -> AJAX Failed loading...');
  });
  
  return dfd_TenantsLeft.promise();
};
  
tenants.prototype.load_right = function (callback) {
  var dfd_TenantsRight = jQuery.Deferred();
  $("#main-container-right-body").addClass("loading");
    
  var atrdhf = ajax_loader({id: this.id, filter: this.filter, tab: this.tab, lease_id: this.lease_id}, "tenants/header/right.html", "main-container-right-header");
  progress();
  var atrdff = ajax_loader({id: this.id, filter: this.filter, tab: this.tab, selected: "true"}, "tenants/footer/right.html", "main-container-right-footer");
  progress();

  if (this.tab == 'Transactions' || this.tab == 'ViewTransaction') { 
    var atrdmm = ajax_loader({id: this.id, filter: this.filter, tab: this.tab, lease_id: this.lease_id, trans_id: this.trans_id, trans_type: this.trans_type, trans_bal: this.bal_type}, "tenants/containers/right_menu.html", "ajax-menu-container-right-body");
  } else {
    var atrdmm = $.Deferred();
    atrdmm.resolve();
  }

    /** Right Body defined here: */
  var right_body = 'tenants/notes/index.html';
  switch (this.tab) {
    case 'Profile': right_body = 'tenants/profile/index.html'; break;
    case 'Notes': right_body = 'tenants/notes/index.html'; break;
    case 'Lease': right_body = 'tenants/lease/index.html'; break;
    case 'Activity': right_body = 'tenants/activity/index.html'; break;
    case 'Transactions': right_body = 'tenants/transactions/index.html'; break;
    case 'ViewTransaction': right_body = 'tenants/transactions/view_transaction.html'; break;
  }

 var main_body_deferred = $.Deferred();
 var all_right_body_vars = {id: this.id, filter: this.filter, tab: this.tab, lease_id: this.lease_id, trans_id: this.trans_id, trans_type: this.trans_type, trans_bal: this.bal_type};
 $.when(atrdmm).done(function() {
    atrdbf = ajax_loader(all_right_body_vars, right_body, "main-container-right-body");
    $.when(atrdbf).done(function() {
       main_body_deferred.resolve();
    });
  });
  
  $.when(main_body_deferred, atrdhf, atrdff).done(function () {
    $('#main-container-right-body').scrollTop(0);
    progress();
    $("#main-container-right-body").removeClass("loading");
    if (typeof callback !== 'undefined' && cloneObject[callback]) {
      cloneObject[callback]();
    }
    debug_print('Right');
    dfd_TenantsRight.resolve("ajax_done_right");
  }).fail(function() {
    $("#main-container-right-body").removeClass("loading");
    dfd_TenantsRight.reject('load_right -> AJAX Failed loading...');
  });

  return dfd_TenantsRight.promise();
};

tenants.prototype.start_up = function () {
  right_scroll(); // Double check that height is correct here...
  var filter = this.filter; /* This filter is used by HASH router navigate */
    $('.dropdown').dropdown(drop_effect); /* Keep towards top of start_up ! */
    debug_print('CleanUp FN - should be last now...');
    $('.ui.accordion').accordion();
    /* unbind the mouse enter left */
    $("#main-container-left-body").off("mouseenter");
    /* unbind the mouse enter right */
    $("#main-container-right-body").off("mouseenter");
    $('#tenantTable').stupidtable();
    $('.phoneNum').mask('(000) 000-0000');
    $('.money').mask('#,##0.00', {reverse: true});
    $('#tenantTable').on('tablesort:start', function (event, tablesort) {
      debug_print("Starting the sort...");
      showLoading();
    });
    $('#tenantTable').on('tablesort:complete', function (event, tablesort) {
      debug_print("Sort finished!");
      done_loading();
    });
    
    $("#tenantSearch").on("keyup", function () {
      /* Mark.js Added 1-31-18 */
      var keyword = $("#tenantSearch").val();
      if (keyword.length > 2) {
        setTimeout(function() {
          $('#tenantTable').unmark();
          $('#tenantTable').mark(keyword);
        }, 90);
      } else {
        $('#tenantTable').unmark();
      }
    });
    
    $('#tenantTable').searchable({
      searchField: '#tenantSearch',
      onSearchActive: function (term) {
        $("#defaultSearch").css("display", "none"); /* Added 1-16-18 */
        $("#closeSearch").css("display", "inline-block"); /* Added 1-16-18 */
      },
      onSearchEmpty: function (elem) {
        $("#closeSearch").css("display", "none"); /* Added 1-16-18 */
        $("#defaultSearch").css("display", "inline-block"); /* Added 1-16-18 */
      }
    });
    
    // Button Clear the search value
    $(".closeSearch").off("click"); /* Added 1-16-18 */
    $(".closeSearch").on("click", function () {
      /* Clear The Search Field */
      $("#tenantSearch").val("");
      $("#tenantSearch").keyup();
      $("#tenantSearch").focus();
    });

    $('.closeTenant').off("click");
    $('.closeTenant').on("click", function() {
      /* Init Balence counters: to nothing then force it to Zeros */
//      $('#right-secondary-content').html('');
//      var ajax_right_secondary_content = ajax_loader({id: this.id}, "app/tenants/tenants-right-secondary-content-transactions.php", "right-secondary-content");
    });  
  
    /* Row click function for Tenant Profile */
    $(".list-row").off("click");
    $(".list-row").on("click", function (e) {
      var id = $(this).data("id");
      var lease_id = $(this).data("leaseid");
      if (! $(e.target).parents().hasClass('exclude') ) {
        filter = $('#filterStatus').dropdown('get value');  
        router.navigate('Tenants/' + filter + '/' + id + '/Transactions/' + lease_id);
      }
    });
    
    $(".view-trans").off("click");
    $(".view-trans").on("click", function() {
      var id = $(this).data("id");
      var lease_id = $(this).data("leaseid");
      filter = $('#filterStatus').dropdown('get value');  
      router.navigate('Tenants/' + filter + '/' + id + '/Transactions/' + lease_id);
    });

    $(".view-maintenance").off("click");
    $(".view-maintenance").on("click", function() {
      var id = $(this).data("id");
      var lease_id = $(this).data("leaseid");      
      router.navigate('Maintenance/' + id + '/New/' + lease_id);
    });

/* 7-7 New Feature to show alert on Inactive tenants
 * 
 */
    $(".inactive-row").off("click");
    $(".inactive-row").on("click", function(e) {
      var id = $(this).data("id");
      var lease_id = $(this).data("leaseid");
      if (! $(e.target).parents().hasClass('exclude') ) {
          $.confirm({
            container: "#main-container-left-body",
            useBootstrap: false,
            boxWidth: "80%",
            position: 'sticky',
            animation: 'bottom',
            closeAnimation: 'bottom',
            type: 'blue',
            title: "Notice",
            content: "This tenant is Inactive! Payments for this account is disabled.",
            buttons: {
             cancel: function() {},
             Proceed: {
               text: "Continue",
               btnClass: 'btn-blue',
               action: function() {
                 filter = $('#filterStatus').dropdown('get value');    
                 router.navigate('Tenants/' + filter + '/' + id + '/Transactions/' + lease_id);
               }
             }
           }
         });
      }
    });

    $("#filterStatus").dropdown({
        on: 'hover',
        onChange: function (val) {
            var entity_text = $('#filterEntity').dropdown('get value');
            window.update_tenants_list(val, entity_text);
            cloneObject.start_up();
        }
    });
    
    $("#filterEntity").dropdown({
        on: 'hover',
        onChange: function (val) {  
            $.ajax({
              url: "app/home/set_entity.html",
              type: 'GET',
              data: {entity_id: val},
              async: true,
              dataType: "html",
              success: function (response) {
                start_progress(); /* Restart percentage to 1 */
                var tenant_status_text = $('#filterStatus').dropdown('get value');
                window.update_tenants_list(tenant_status_text, val);
                cloneObject.start_up();
              }
            });
      }
    });
/*
    $('.ui.accordion').accordion({
      onChange: function () {
        $('#main-container-right-body').perfectScrollbar('update'); // UPDATE .right-panel-scroll
      }
    });
*/
    $("#tenantSearch").focus();
    done_loading();

    auto_right_menus();
    /* Fixes postion for transactions right body */
    $('#main-container-right-body').css('margin-top', '0');       
};
