(function(){
	var LendingBidding = function() {

		var maxAcc = 10;
        var storage = {};

		var countAccItems = function() {
			var num = $('.form-body .mixed-accordion .panel').length;

			if( num < maxAcc ) $('.add-accordion').show();
			else $('.add-accordion').hide();

			return num;
		};

		var amountChanged = function( val ) {
			$('input[name="amount"]').val( val );
			$('.mixed-accordion .panel .panel-heading span#amount').each(function () {
				$(this).html('$' + val );
			});
		};

    return {

        init: function() {

        	$('input[name="amount"]').on('keyup', function(){
        		var _this = $(this), val = parseInt(_this.val());
        		amountChanged( (isNaN(val)) ? 0 : val );
        	});

        	$('input[name="amount"]').trigger('keyup');

        	$('.mixed-accordion').on('change', '.panel #select_term', function (e) {
        		var _this = $(this), parent = _this.parents('.panel'), val = _this.val(), head = parent.find('.accordion-toggle');

        		head.children('span#term').html(val);
        	});

        	$('.mixed-accordion').on('change', '.panel #select_interest', function (e) {
        		var _this = $(this), parent = _this.parents('.panel'), val = _this.val(), head = parent.find('.accordion-toggle');

        		head.children('span#int').html(val);
        	});

        	$('.add-accordion').on('click', function(){
        		var _clone, id, term, interest, count = countAccItems();

        		if( count <= maxAcc ) {
        			_clone = $('.form-body .mixed-accordion .panel').last().clone();

        			id = parseInt( _clone.data('id') ) + count;
        			_clone.data('id', id);

        			// 
        			_clone.find('#num').html(id);

        			// 
        			term = _clone.find('#select_term')[0].selectedIndex;
        			_clone.find('#select_term')[0].selectedIndex = term + count;
        			_clone.find('.panel-title span#term').html( _clone.find('#select_term option:selected').val() );

        			// 
        			interest = _clone.find('#select_interest')[0].selectedIndex;
        			_clone.find('#select_interest')[0].selectedIndex = interest + count;
        			_clone.find('.panel-title span#int').html( _clone.find('#select_interest option:selected').val() );

        			_clone.find('.accordion-toggle').attr('href', '#item_' + id);
        			_clone.find('.panel-collapse').attr('id', 'item_' + id);
        			_clone.find('.accordion-close').show();

        			$('.panel-group').append( _clone );

        			countAccItems();
        		}
        	});

        	$('.mixed-accordion').on('click', '.panel .accordion-close', function (e) {
        		var parent;
        		e.preventDefault();

        		if( countAccItems() > 1 ) {
        			parent = $(this).parents('.panel');
        			parent.fadeOut(400).remove();
        			countAccItems();
        			
        			if( parent.id ) {
        				
        			}
        		}
        	});

          $('table.loans.mixed 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( activeTr.length ) {
                activeTr.next('tr.details').hide(200, open);
                activeTr.removeClass('open');
              } else open();
              
           });

          LendingBidding.paginator_simple = new LendingBidding.paginator( '#tablePaginator_simple', {
            visiblePages: 8,
            href: false,
            onPageClick: function ( page, next ) {
              LendingBidding.getMyLoans('simple', page, next );
            }
          });

          LendingBidding.paginator_mixed = new LendingBidding.paginator( '#tablePaginator_mixed', {
            visiblePages: 8,
            href: false,
            onPageClick: function ( page, next ) {
              LendingBidding.getMyLoans('mixed', page, next );
            }
          });
        },

        paginator: App.paginator,

        getMyLoans: function( type, page, cb ) {

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

            tableBody.empty();

            for( i in data ) {
              item = data[ i ];
              newRow = emptyRow;

              switch( type ) {
                case 'simple':
                  for( ik in item ) {
                    newRow = App.replaceAll( newRow, '%' + ik + '%', item[ ik ] );
                  }
                break;
                case 'mixed':
                  for( ik in item ) {
                    switch( ik ) {
                      case 'loans':
                        newRow = App.replaceAll( newRow, '%' + ik + '%', item[ ik ], '%' + ik + '%', function() {
                          var l, _loans = item[ ik ], _item, loans = '', s;

                          for( l in _loans ) {
                            _item = _loans[ l ];
                            s = (_item['status']) ? 'text-success' : 'text-muted';
                            loans += '<li class="' + s + '"># ' + _item['id'] + ' - <strong>Interest:</strong> ' + _item['interest'] + '% - <strong>Term:</strong> ' + _item['term'] + ' - <strong>Monthly payment:</strong> $' + _item['monthly_payment'] + '</li>';
                          }

                          return '<ol>' + loans + '</ol>';
                        });
                      break;

                      default:
                        newRow = App.replaceAll( newRow, '%' + ik + '%', item[ ik ] );
                      break;
                    }
                  }
                break;
              }

              tableBody.append( newRow );
            }

            storage.paginator = result.paginator;

            LendingBidding['paginator_' + type].update({
              totalPages: result.paginator.totalPages,
              startPage: result.paginator.currentPage
            });

            if( cb ) cb();

          });
        }
    };

	}();

    $(document).ready(function() {

      LendingBidding.init();
      LendingBidding.getMyLoans('simple', null, function(){
        LendingBidding.getMyLoans('mixed');
      });

    });

})();