/* 
 Fluid Router Tool 2.0 ALPHA
 Copyright 2016 Christopher Allen 
 */

properties_dash.prototype.main = function () {
  var dfd_PropertiesDash_main = jQuery.Deferred();
  start_progress();
  $.when(this.load_left(), this.load_right()).done(function () {
    stop_progress();
    debug_print('AJAX complete');
    dfd_PropertiesDash_main.resolve("ajax_complete");
  });
  return dfd_PropertiesDash_main.promise();
};

properties_dash.prototype.load_left = function () {
  var dfd_PropertiesLeft = 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}, "app/properties/properties-left-header.php", "main-container-left-header");
  progress();
  var atldff = ajax_loader({id: this.id, filter: this.filter, selected: this.selected}, "app/properties/properties-left-footer.php", "main-container-left-footer");
  progress();
  var atldbf = ajax_loader({id: this.id, filter: this.filter, selected: this.selected}, "app/properties/properties-left-body.php", "main-container-left-body");
  progress();
  $.when(atldhf, atldff, atldbf).done(function () {
    progress();
    $("#main-container-left-body").removeClass("loading");
    debug_print('Left');
    dfd_PropertiesLeft.resolve("ajax_done_left");
  });
  return dfd_PropertiesLeft.promise();
};

properties_dash.prototype.load_right = function () {
  var dfd_Properties = jQuery.Deferred();
  $("#main-container-right-body").addClass("loading");
  var atrdhf = ajax_loader({id: this.id, filter: this.filter, tab: this.tab}, "app/properties/properties-right-header-dash.php", "main-container-right-header");
  progress();
  var atrdff = ajax_loader({id: this.id, filter: this.filter, tab: this.tab}, "app/properties/properties-right-footer-dash.php", "main-container-right-footer");
  progress();
  var atrdbf = ajax_loader({id: this.id, filter: this.filter, tab: this.tab}, "app/properties/properties-right-body-dash.php", "main-container-right-body");
  $.when(atrdhf, atrdff, atrdbf).done(function () {
    /* Slide out right Effect for clicked profiles */
//    $('.rightSlide').css('opacity', '1');
//    $('.rightSlide')
//            .transition('fade right', '0ms')
//            .transition('fade right', '300ms');
    progress();
    $("#main-container-right-body").removeClass("loading");
    debug_print('Right');
    dfd_Properties.resolve("ajax_done_right");
  });
  return dfd_Properties.promise();
};

properties_dash.prototype.start_up = function () {
  var filter = this.filter; /* This Filter is used for HASH router navigate */
  var user_id = this.user_id; /* This user ID is used for AJAX Save */

    debug_print('StartUp');
    // Scrool to the top of left container onLoad
    $("#main-container-left-body").scrollTop(-1);
    // Activate the Dropdowns
    $('.dropdown').dropdown(drop_effect);
//    $('#filter, #sections').dropdown({action: 'select', on: 'hover'});
    $('#propertyTable').tablesort();
    $('#propertyTable').on('tablesort:start', function (event, tablesort) {
      debug_print("Starting the sort...");
      showLoading();
    });
    $('#propertyTable').on('tablesort:complete', function (event, tablesort) {
      debug_print("Sort finished!");
      done_loading();
    });
    $('#propertyTable').searchable({
      searchField: '#propertySearch',
      searchType: 'fuzzy',
      onSearchActive: function () {
        $("#main-container-left-body").scrollTop(0);
        $("#topSearch").css("display", "none"); /* Added 1-16-18 */
        $("#topSearchClose").css("display", "inline-block"); /* Added 1-16-18 */
      },
      onSearchEmpty: function (elem) {
        $("#topSearchClose").css("display", "none"); /* Added 1-16-18 */
        $("#topSearch").css("display", "inline-block"); /* Added 1-16-18 */
      }
    });

    $('#propertyTable 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>');
    $("#propertySearch").on("keyup", function () { /* Added 1-16-18 */
      /* Detect changes to search field to show no results box */
      var activeRows = $('#propertyTable tr:not([style*="display: none"]):not(".noCount")').length;
      var realRows = activeRows - 1;
      $('#propertyCount').html(realRows);
      if (activeRows == 1) {
        $("#noResults").css("display", "");
      } else {
        $("#noResults").css("display", "none");
      }
    });

    // Button Clear the search value
    $("#topSearchClose").off("click"); /* Added 1-16-18 */
    $("#topSearchClose").on("click", function () {
      /* Clear The Search Field */
      $("#propertySearch").val("");
      $("#propertySearch").keyup();
      $("#propertySearch").focus();
    });

    // Row click function for Tenant Profile
    $(".list-row").on("click", function () {
      var id = $(this).data("id");
      // Profile the the Default route when you click a profile        
      router.navigate('Properties/' + filter + '/' + id + '/Profile');
    });
    // Activate Popups (There is a CSS version, update to that ASAP)    
    $('.item').popup({
      hoverable: true,
      position: 'bottom center',
      delay: {
        show: 100,
        hide: 0
      },
      transition: 'Vertical Flip'
    });

    $('#newProp')
            .form({
              inline: true,
              on: 'blur',
              onSuccess: function () {

                debug_print('#newProp Form Was Successfully Validated');

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

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

                $.ajax({
                  beforeSend: saving_toast,
                  url: 'app/properties/save-property.php',
                  type: 'POST',
                  data: $(this).serialize(),
                  success: function (response, status, xhr) {
                    if (!has_error(response, xhr)) {
                      saved_toast('property');
                      // Go straight to the new profile
                      router.navigate(response);
                    } // END IF !ERROR
                  }

                });
                return false;
              },
              fields: {
                status: {
                  identifier: 'status',
                  rules: [
                    {
                      type: 'empty',
                      prompt: 'Select Property Status'
                    }
                  ]
                },
                entity: {
                  identifier: 'entity',
                  rules: [
                    {
                      type: 'empty',
                      prompt: 'Select Entity Account'
                    }
                  ]
                },
                rent: {
                  identifier: 'rent',
                  rules: [
                    {
                      type: 'decimal',
                      prompt: 'Enter a valid decimal amount: e.g. $0.00'
                    }
                  ]
                },
                deposit: {
                  identifier: 'deposit',
                  rules: [
                    {
                      type: 'decimal',
                      prompt: 'Enter a valid decimal amount: e.g. $0.00'
                    }
                  ]
                },
                houseNumber: {
                  identifier: 'houseNumber',
                  rules: [
                    {
                      type: 'empty',
                      prompt: 'Enter House Number.'
                    }
                  ]
                },
                streetName: {
                  identifier: 'streetName',
                  rules: [
                    {
                      type: 'empty',
                      prompt: 'Enter Street Name.'
                    }
                  ]
                },
                city: {
                  identifier: 'city',
                  rules: [
                    {
                      type: 'empty',
                      prompt: 'Enter City Name'
                    }
                  ]
                },
                zip: {
                  identifier: 'zip',
                  rules: [
                    {
                      type: 'minLength[5]',
                      prompt: 'Enter 5 Digit ZIP Code'
                    }
                  ]
                }

              }
            });
    done_loading();
    set_height();
    auto_right_menus();
    
    $("#propertySearch").focus();

};