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

tenants_dash.prototype.load_left = function (callback) {
  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({filter: this.filter, selected: this.selected}, "tenants/header/left.html", "main-container-left-header");
  progress();
  var atldff = ajax_loader({filter: this.filter}, "tenants_dash/footer/left.html", "main-container-left-footer");
  progress();
  var atldbf = ajax_loader({filter: this.filter}, "tenants/tenants_list/view_for_json.html", "main-container-left-body");
  progress();
  $.when(atldhf, atldff, atldbf).then(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_dash.prototype.load_right = function () {
  var dfd_TenantsRight = jQuery.Deferred();
  $("#main-container-right-body").addClass("loading");
  var atrdhf = ajax_loader({filter: this.filter, tab: this.tab}, "tenants_dash/header/right.html", "main-container-right-header");
  progress();
  var atrdff = ajax_loader({filter: this.filter, tab: this.tab}, "tenants_dash/footer/right.html", "main-container-right-footer");
  progress();
  
  /** Right Body defined here: */
  var right_body = 'tenants/notes/index.html';
  switch (the_tab) {
    case 'Dashboard': 
      right_body = 'tenants_dash/dashboard/index.html'; 
      $.get("tenants/todays_transactions/index.html", {trans_day: ''}, function (data) {
        $("#transactionHistory").html(data);
      });
      break;
    case 'Reports': right_body = 'tenants/report/index.html'; break;
    case 'NewTenant': right_body = 'tenants/new_tenant/index.html'; break;
    case 'Maintenance': right_body = 'maintenance/list/index.html'; break;  
  }
  var atrdbf = ajax_loader({filter: this.filter, tab: this.tab}, right_body, "main-container-right-body");
  $.when(atrdhf, atrdff, atrdbf).then(function () {
    progress();
    $("#main-container-right-body").removeClass("loading");
    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_dash.prototype.refresh = function () {
    
};

tenants_dash.prototype.start_up = function () {
    var filter = this.filter; /* This defines the filter for HASH navigate */
   
    // Restore scroll position
    var scroll_pos = get_cookie('scrollPos');
    if (scroll_pos > 0) {
      $('#main-container-left-body').scrollTop(scroll_pos);
    }
    
    debug_print('CleanUp');
    $('.money').mask('#,##0.00', {reverse: true});
    $('.ui.accordion').accordion();    
    $('.dropdown').dropdown(drop_effect); /* Keep towards top of start_up ! */
    $('#tenantTable').stupidtable();
    $('#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();
    });

    $('#tenantTable').searchable({
      searchField: '#tenantSearch',
      searchType: 'fuzzy',
      onSearchActive: function () {
        $("#main-container-left-body").scrollTop(0);
        $("#defaultSearch").css("display", "none"); /* Added 1-16-18 */
        $("#closeSearch").css("display", "inline-block"); /* Added 1-16-18 */
        //debug_print("Search Input is active"); /* Added 1-16-18 */

      },
      onSearchEmpty: function (elem) {
        //debug_print("Search Input is empty"); /* Added 1-16-18 */
        $("#closeSearch").css("display", "none"); /* Added 1-16-18 */
        $("#defaultSearch").css("display", "inline-block"); /* Added 1-16-18 */
      }
    });

    $('#tenantTable tr:last').after('<tr id="noResults" class="noCount" style="display: none; cursor: default;"><td colspan="4" style="text-align: center; font-weight: 800;">No Tenants Found...</td></tr>');
    $("#tenantSearch").on("keyup", function () { /* Added 1-16-18 */
      
     /* 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();
      }
      
      /* Detect changes to search field to show no results box */
      var activeRows = $('#tenantTable tr:not([style*="display: none"]):not(".noCount")').length;
      var realRows = activeRows - 1;
      $('#tenantCount').html(realRows);
      if (activeRows == 1) {
        //debug_print("No Results Found");
        $("#noResults").css("display", "");
      } else {
        //debug_print("Results Found and showing");
        $("#noResults").css("display", "none");
      }
    });

    // 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();
    });


    $('.phoneNum').mask('(000) 000-0000');

    // Row click function for Tenant Profile
    $(".list-row").off("click"); /* Added 12-28-17 */
    $(".list-row").on("click", function(e) {
      // Save Scroll Position
      if (! $(e.target).parents().hasClass('exclude') ) {
        var scroll_pos = $('#main-container-left-body').scrollTop();
        set_cookie('scrollPos', scroll_pos, 60);
        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-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 LeaseID = $(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/' + LeaseID);
               }
             }
           }
         });
      }
    });

    $(".trasactionClick").off("click");
    $("#main-container-right-body").on("click", ".trasactionClick", function () {
      var id = $(this).data("id");
      var LeaseID = $(this).data("leaseid");
      /* Profile the the Default route when you click a profile */
      filter = $('#filterStatus').dropdown('get value');  
      router.navigate('Tenants/' + filter + '/' + id + '/Transactions/' + LeaseID);
    });

    $("#transDay").off("change");
    $("#transDay").on("change", function () {
      // Get the transaction ID
      var trans_day = $(this).val();
      // Get transaction information
      $.get("tenants/todays_transactions/index.html", {trans_day: trans_day}, function (data) {
        $("#transactionHistory").html(data);
      });
    });

    $("#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();
              }
            });
      }
    });

    $("#tenantSearch").focus();
	/**
     	var past_week = moment().subtract(7, 'days').format('MM/DD/YYYY');
        var yymd_today = moment().format('MM/DD/YYYY');
    	*/
		$('#transDay').daterangepicker({
			singleDatePicker: true,
			showDropdowns: true,
			autoApply: true,
			opens: 'left',
//			startDate: past_week,
//			endDate: yymd_today
		}, function(start, end, label) {
			//console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
		});

    done_loading();

};
