(function(){
  var LendingBrowse = function() {

    var storage = {};
    var config = { 
      filterLimit: 10
    };
    var modal, modalConfirm;
    var activeFilters = [];
    var filters = {
      1: {
        name: 'term',
        displayName: 'Loan Term',
        errors: ['Please select at least one term.'],
        collectData: function( id, self ) {
          var result = null, c = 0, d = [], i;

          self.elem.find('input[type=checkbox]').each(function ( item ) {
            i = $(this);
            if( $(this).is(':checked') ) d.push( i.val() );
          });

          if( d.length > 0 ) result = d;
          else self.lastError = 0;

          return result;
        }
      },
      2: {
        name: 'intRate',
        displayName: 'Interest Rate',
        errors: ['Please select at least one interest rate.'],
        collectData: function( id, self ) {
          var result = null, c = 0, d = [], i;

          self.elem.find('input[type=checkbox]').each(function ( item ) {
            i = $(this);
            if( $(this).is(':checked') ) d.push( i.val() );
          });

          if( d.length > 0 ) result = d;
          else self.lastError = 0;

          return result;
        }
      },
      3: {
        name: 'id',
        displayName: 'Loan ID',
        errors: ['Please enter numbers only.'],
        collectData: function( id, self ) {
          var result = null,
              val = self.elem.find('input[type=text]').val();

          if( val !== '' ) {
            if( !( (val - 0) == val && ('' + val).trim().length > 0) ) self.lastError = 0;
            else result = val;
          } else result = '';

          return result;
        }
      },
      4: {
        name: 'purpose',
        displayName: 'Purpose',
        errors: ['Wrong purpose'],
        collectData: function( id, self ) {
          var result = null,
              val = self.elem.find('select#4_1').val();

          if( val.length && val[0] !== '' ) {
            result = val;
          } else result = [];

          return result;
        }
      },
      5: {
        name: 'reviewStatus',
        displayName: 'Review Status',
        collectData: function( id, self ) {
          var result = null,
              c = self.elem.find('input[type=checkbox]');

          if( c.is(':checked') ) result = true;
          else result = false;

          return result;
        }
      },
      6: {
        name: 'recently',
        displayName: 'Recent Listings',
        collectData: function( id, self ) {
          var result = null,
              c = self.elem.find('input[type=checkbox]');

          if( c.is(':checked') ) result = true;
          else result = false;

          return result;
        }
      },
      7: {
        name: 'exludeInvested',
        displayName: 'Exclude Loans already invested in',
        collectData: function( id, self ) {
          var result = null,
              c = self.elem.find('input[type=checkbox]');

          if( c.is(':checked') ) result = true;
          else result = false;

          return result;
        }
      },
      8: {
        name: 'homeOwnership',
        displayName: 'Home Ownership',
        errors: ['Please select at least one home ownership.'],
        collectData: function( id, self ) {
          var result = null, c = 0, d = [], i;

          self.elem.find('input[type=checkbox]').each(function ( item ) {
            i = $(this);
            if( $(this).is(':checked') ) d.push( i.val() );
          });

          if( d.length > 0 ) result = d;
          else self.lastError = 0;

          return result;
        }
      },
      9: {
        name: 'creditScore',
        displayName: 'Credit Score',
        errors: ['Please select at least one credit score.'],
        collectData: function( id, self ) {
          var result = null, c = 0, d = [], i;

          self.elem.find('input[type=checkbox]').each(function ( item ) {
            i = $(this);
            if( $(this).is(':checked') ) d.push( i.val() );
          });

          if( d.length > 0 ) result = d;
          else self.lastError = 0;

          return result;
        }
      },
      10: {
        name: 'dti',
        displayName: 'Debt-to-income Ratio',
        errors: ['Invalid DTI Ratio.'],
        collectData: function( id, self ) {
          var result = null,
              s = document.getElementById('dti-slider').noUiSlider,
              val = s.get();

          if( val < 10 && val > 25 ) self.lastError = 0;
          else result = val;

          return result;
        }
      },
      11: {
        name: 'delinquency',
        displayName: 'Delinquencies (last 2 yrs)',
        errors: ['Please select at least one delinquency.'],
        collectData: function( id, self ) {
          var result = null, c = 0, d = [], i;

          self.elem.find('input[type=checkbox]').each(function ( item ) {
            i = $(this);
            if( $(this).is(':checked') ) d.push( i.val() );
          });

          if( d.length > 0 ) result = d;
          else self.lastError = 0;

          return result;
        }
      },
      12: {
        name: 'minLoE',
        displayName: 'Min length of Employment',
        errors: ['Invalid Min length of Employment.'],
        collectData: function( id, self ) {
          var result = null,
              s = document.getElementById('loe-slider').noUiSlider,
              val = s.get();

          if( val < 0 && val > 5 ) self.lastError = 0;
          else result = parseInt(val);

          return result;
        }
      },
      13: {
        name: 'fundingProgress',
        displayName: 'Funding Progress',
        errors: ['Invalid funding progress.'],
        collectData: function( id, self ) {
          var result = null,
              s = document.getElementById('fp-slider').noUiSlider,
              val = s.get();

          if( val < 0 && val > 100 ) self.lastError = 0;
          else result = parseInt(val);

          return result;
        }
      },
      14: {
        name: 'verifiedIncome',
        displayName: 'Verified Income',
        collectData: function( id, self ) {
          var result = null,
              c = self.elem.find('input[type=checkbox]');

          if( c.is(':checked') ) result = true;
          else result = false;

          return result;
        }
      },
      15: {
        name: 'expiresIn',
        displayName: 'Expires In',
        collectData: function( id, self ) {
          var result = null;


          return result;
        }
      },
      16: {
        name: 'keywords',
        displayName: 'Keywords',
        collectData: function( id, self ) {
          var result = null,
              val = self.elem.find('input[type=text]').val();

            result = val;

          return result;
        }
      },
      17: {
        name: 'maxLoanAmount',
        displayName: 'Max Loan Amount',
        errors: ['Please enter numbers or decimals only.'],
        collectData: function( id, self ) {
          var result = null,
              val = self.elem.find('input[type=text]').val();

          if( val !== '' ) {
            if( !( (val - 0) == val && ('' + val).trim().length > 0) ) self.lastError = 0;
            else result = val;
          } else result = '';

          return result;
        }
      },
      18: {
        name: 'monthlyIncome',
        displayName: 'Monthly Income',
        errors: ['Please enter numbers or decimals only.'],
        collectData: function( id, self ) {
          var result = null,
              val = self.elem.find('input[type=text]').val();

          if( val !== '' ) {
            if( !( (val - 0) == val && ('' + val).trim().length > 0) ) self.lastError = 0;
            else result = val;
          } else result = '';

          return result;
        }
      },
      19: {
        name: 'excludeRelisted',
        displayName: 'Exclude Relisted Loans',
        collectData: function( id, self ) {
          var result = null,
              c = self.elem.find('input[type=checkbox]');

          if( c.is(':checked') ) result = true;
          else result = false;

          return result;
        }
      }
    },
    cookieName = 'investor-zone.lending.browse:filter'
    filterSBList = '.filter-sidebar-list',
    filterSBListItem = '.filter-sidebar-list-item',
    filterSBListItems = filterSBList + ' ' + filterSBListItem,
    filterSBEnabled = filterSBListItems + '[data-enabled="1"]',
    filterSBDisabled = filterSBListItems + '[data-enabled="0"]',
    emptyResultRow = $('#emptyResultRow tbody').html();

    $.cookie.json = true;

    return {

        init: function() {

          var modal;

          var checkFilterLimit = function(id){
            if( activeFilters.length >= config.filterLimit ) {
              disableMoreFilters(id);
              return true;
            } else {
              enableMoreFilters();
              return false;
            }
          };

          var disableMoreFilters = function(id) {
            var ichecks = $(document).find('.modal-body').find('.icheckbox_minimal-grey');

            ichecks.each(function ( item ) {
              var i = $(this), inp = i.find('input');

              if( inp.data('id') !== id && !i.hasClass('checked') )
                i.find('input').iCheck('disable');

            });
          };

          var enableMoreFilters = function(id) {
            var ichecks = $(document).find('.modal-body').find('.icheckbox_minimal-grey');

            ichecks.each(function ( item ) {
              var i = $(this), inp = i.find('input');

              if( inp.data('id') !== id )
                i.find('input').iCheck('enable');

            });
          };

          var checkFilters = function() {
            var mfs = $(document).find('.modal-body'),
                cookie = $.cookie(cookieName);

            $( filterSBListItems ).each( function() {
              var self = $(this), id = self.data('id');

              if( !checkFilterLimit() && cookie !== undefined && cookie.indexOf(id) > -1 && activeFilters.indexOf(id) < 0 ) {

                activeFilters.push(id);
                mfs.find('input[data-id="' + id + '"]').iCheck('check');
                $(filterSBList).find('.filter-sidebar-list-item[data-id="' + id + '"]').attr('data-enabled', 1);

              } else {

                $(filterSBList).find('.filter-sidebar-list-item[data-id="' + id + '"]').attr('data-enabled', 0);

              }
            });
          };

          checkFilters();

          $('.filter-sidebar-wrapper .filter-sidebar .filter-sidebar-list').on('click', '.list-heading', function(e){
            var self = $(this),
                content = self.next('.list-item-content');

            if( self.hasClass('collapsed') ) {
              content.show();
              self.find('i').removeClass('fa-caret-up').addClass('fa-caret-down');
              self.removeClass('collapsed');
            } else {
              content.hide();
              self.find('i').removeClass('fa-caret-down').addClass('fa-caret-up');
              self.addClass('collapsed');
            }
          });

          $(document).on('ifChecked', '.modal-body .icheck', function(e) {
            var item = $(this), id = item.data('id'), index = activeFilters.indexOf(id);

            if( index < 0 ) activeFilters.push( id );
            checkFilterLimit(id);
          });

          $(document).on('ifUnchecked', '.modal-body .icheck', function(e) {
            var item = $(this), id = item.data('id'), index = activeFilters.indexOf(id);

            if( index > -1 ) activeFilters.splice( index, 1 );
            checkFilterLimit();
          });

          $(document).on('click', '#applyFiltersList', function(e){
            var i, _fs = $(filterSBList).find('.filter-sidebar-list-item');

            _fs.each(function ( item ) {
              var i = $(this), id = i.data('id');

              if( activeFilters.indexOf(id) > -1 ) {
                i.attr('data-enabled', 1);
              } else {
                i.attr('data-enabled', 0);
              }
            });

            $.cookie(cookieName, activeFilters, { expires: 7 });
          });

          $(filterSBListItems + ' input[name="filters_2[]"], ' + filterSBListItems + ' input[name="filters_8[]"], ' + filterSBListItems + ' input[name="filters_9[]"],' + filterSBListItems + ' input[name="filters_11[]"]').on('ifToggled', function(){
            var self = $(this), id = self.attr('id').split('_')[0];

            if( self.is(':checked') && self.val() == 'all' )
              $(filterSBListItems + ' input[name="filters_' + id + '[]"]').not('#' + id + '_all').iCheck('uncheck');
            else if( self.is(':checked') && self.val() !== 'all' )
              $(filterSBListItems + ' input#' + id + '_all').iCheck('uncheck');

          });

          var dtiSlider = document.getElementById('dti-slider');
          noUiSlider.create(dtiSlider, {
            start: [10],
            step: 1,
            orientation: "horizontal",
            connect: "lower",
            range: {
                'min': 10,
                'max': 25
            }
          });
          var tipHandles1 = dtiSlider.getElementsByClassName('noUi-handle'),
              tooltips1 = [];
          for ( var i = 0; i < tipHandles1.length; i++ ) {
            tooltips1[i] = document.createElement('div');
            tipHandles1[i].appendChild(tooltips1[i]);
          }
          // Add a class for styling
          tooltips1[0].className += 'noUi-tooltip';
          // Add additional markup
          tooltips1[0].innerHTML = '<strong></strong>';
          // Replace the tooltip reference with the span we just added
          tooltips1[0] = tooltips1[0].getElementsByTagName('strong')[0];

          // When the slider changes, write the value to the tooltips.
          dtiSlider.noUiSlider.on('update', function( values, handle ){
              tooltips1[handle].innerHTML = values[handle];
          });

          var loeSlider = document.getElementById('loe-slider');
          noUiSlider.create(loeSlider, {
            start: [0],
            step: 1,
            orientation: "horizontal",
            connect: "lower",
            range: {
                'min': 0,
                'max': 5
            }
          });
          var tipHandles2 = loeSlider.getElementsByClassName('noUi-handle'),
              tooltips2 = [];
          for ( var i = 0; i < tipHandles2.length; i++ ) {
            tooltips2[i] = document.createElement('div');
            tipHandles2[i].appendChild(tooltips2[i]);
          }
          // Add a class for styling
          tooltips2[0].className += 'noUi-tooltip';
          // Add additional markup
          tooltips2[0].innerHTML = '<strong></strong>';
          // Replace the tooltip reference with the span we just added
          tooltips2[0] = tooltips2[0].getElementsByTagName('strong')[0];

          // When the slider changes, write the value to the tooltips.
          loeSlider.noUiSlider.on('update', function( values, handle ){
              tooltips2[handle].innerHTML = parseInt(values[handle]);
          });

          var fpSlider = document.getElementById('fp-slider');
          noUiSlider.create(fpSlider, {
            start: [0],
            orientation: "horizontal",
            connect: "lower",
            tooltips: [ false, wNumb({ decimals: 0 }) ],
            range: {
                'min': 0,
                'max': 100
            }
          });
          var tipHandles3 = fpSlider.getElementsByClassName('noUi-handle'),
              tooltips3 = [];
          for ( var i = 0; i < tipHandles3.length; i++ ) {
            tooltips3[i] = document.createElement('div');
            tipHandles3[i].appendChild(tooltips3[i]);
          }
          // Add a class for styling
          tooltips3[0].className += 'noUi-tooltip';
          // Add additional markup
          tooltips3[0].innerHTML = '<strong></strong>';
          // Replace the tooltip reference with the span we just added
          tooltips3[0] = tooltips3[0].getElementsByTagName('strong')[0];

          // When the slider changes, write the value to the tooltips.
          fpSlider.noUiSlider.on('update', function( values, handle ){
              tooltips3[handle].innerHTML = parseInt(values[handle]);
          });

          /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
          $('button#updateResults').on('click', function(e){
            var afL = activeFilters.length, i, id, f, d, er,
                datas = {}, errors = {}, btn = $(this), errorList = '';

            e.preventDefault();

            $(filterSBListItems).removeClass('has-error');

            if( afL ) {
              for( i = 0; i < afL; i++ ) {
                id = activeFilters[ i ];
                f = filters[ id ];

                if( f.elem === undefined ) f.elem = $(filterSBListItems + '[data-id="' + id + '"]');

                d = f.collectData.call(this, id, f);
                
                if( d === null ) errors[id] = f.errors[ f.lastError ];
                else datas[ f.name ] = d;
       
              }

              if( Object.keys( errors ).length > 0 ) {
                for( er in errors ) {
                  filters[ er ].elem.addClass('has-error');
                  errorList += errors[er] + '<br>';
                }

                App.notification('error', errorList);

              } else {
                btn.prop('disabled', 'disabled');
                LendingBrowse.getLoans(1, function() {
                  btn.prop('disabled', false);
                }, { filters: datas });
              }

            } else App.notification('info', 'Please select at least one filter.');
          });
          /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */

           $('table.loans tbody').on('click', 'tr:not(.details) td', function(e) {
              var _this = $(this).parent('tr'),
                activeTr = $('table.loans tr.open'),
                open = function() {
                  if( !_this.hasClass('open') && activeTr.attr('id') !== _this.attr('id') ) {

                    _this.addClass('open');
                    _this.next('tr.details').show(200, function(){
                      App.scrollTo(_this);
                    });

                  }
                };

              if( _this.find('td.investment > input').is(':focus') ) return;

              if( activeTr.length ) {
                activeTr.next('tr.details').hide(200, open);
                activeTr.removeClass('open');
              } else open();

              
           });

           $.fn.modal.defaults.spinner = $.fn.modalmanager.defaults.spinner = 
            '<div class="loading-spinner" style="width: 200px; margin-left: -100px;">' +
              '<div class="progress progress-striped active">' +
                '<div class="progress-bar progress-bar-success" style="width: 100%;"></div>' +
              '</div>' +
            '</div>';

            modalConfirm = $('#modal-confirm');

            modalConfirm.find('#confirmCancelBtn').on('click', function(e) {
              var loanID = modalConfirm.attr('id'),
                  amount = modalConfirm.data('fundAmount'),
                  loanRow = $('table.loans tbody tr#' + loanID);

              App.ajax({
                url: ajaxUrl_fundLoanConfirm,
                data: {
                  id: loanID,
                  amount: amount
                }
              }, function( data ) {
                if( data ) {
                  if( data.error ) {
                    App.error( data.error.message );
                  } else {

                    if( data.result ) {

                      LendingBrowse.reloadLoans();
                      modalConfirm.modal('hide');

                    } else {
                      App.error('Something went wrong');
                    }

                    /*
                    loanRow.addClass('funded');
                    loanRow.find('button').prop('disabled', 'disabled');
                    loanRow.find('input#inv_amount').remove();
                    loanRow.find('td.investment').prepend('<span>$' + amount + '</span>');
                    */
                  }
                }
              });

              //LendingBrowse.reloadLoans();
            });

           $('table.loans tbody').on('click', 'tr:not(.details) td.investment button', function(e){
              e.stopPropagation();
              var self = $(this),
                loanID = self.parents('tr').attr('id'),
                amountInput = self.prev('input.amount'),
                amountMax = parseInt(amountInput.data('maxamount').split(',').join(''));

              if( amountInput.val() > amountMax ) {
                amountInput.val( amountMax );
              } else if( amountInput.val() < 25 ) {
                amountInput.val( 25 );
              }

              $('body').modalmanager('loading');
              modalConfirm.attr('id', loanID);
              modalConfirm.data('fundAmount', amountInput.val());
              modalConfirm.find('#loanID').html(loanID);
              modalConfirm.find('#fundAmount').html(amountInput.val());
              modalConfirm.modal();
           });

          LendingBrowse.paginator = new LendingBrowse.paginator( '#tablePaginator', {
            visiblePages: 8,
            onPageClick: function ( page, next ) {
              LendingBrowse.getLoans( page, next );
            }
          });

        },

        paginator: App.paginator,

        getLoans: function( page, cb, data ) {

          page = page || 1;

          if( data ) data = $.extend( true, { page: page }, data );
          else data = { page: page };

          App.ajax(
          {
            url: ajaxUrl_getLoans,
            data: data,
            block: true,
            blockTarget: 'table.loans'
          }, 
          function ( result ) {
            var emptyRow = $('#tableLoan-Row tbody').html(),
              newRow,
              tableBody = $('table.loans tbody'),
              data = result.data, i, item, l = data.length, ik;

            tableBody.empty();

            if( l ) {

              for( i = 0; i < l; i++ ) {
                item = data[ i ];
                newRow = emptyRow;

                for( ik in item ) {
                  newRow = App.replaceAll( newRow, '%' + ik + '%', item[ ik ] );
                }

                tableBody.append( newRow );
              }

            } else {
              tableBody.append( emptyResultRow );
            }

            storage.paginator = result.paginator;

            LendingBrowse.paginator.update({
              totalPages: result.paginator.totalPages,
              startPage: result.paginator.currentPage
            });

            if( cb ) cb();

          });
        },

        reloadLoans: function() {
          this.getLoans(storage.paginator.currentPage);
        }
    };
  }();

  $(document).ready(function() {
      LendingBrowse.init();
      LendingBrowse.getLoans();

      $('body .portlet > .portlet-title > .tools > a.reload').off();
      $('body').on('click', '.portlet > .portlet-title > .tools > a.reload', function(e) {
        e.preventDefault();
        //var el = $(this).closest(".portlet").children(".portlet-body");
        LendingBrowse.reloadLoans();
      });

      Object.freeze(LendingBrowse);
  });

})();