$(document).ready(function() {
  var Loan = function() {

    return {

        init: function() {
          $('a[data-widget="tooltip"]').tooltip({'trigger':'hover', 'html': true, 'placement': 'right', 'container': 'body'});

          $('a#details').on('click', function(){
            //$('body').modalmanager('loading');
            var el = $(this);
            var $modal = $('#loan-details-modal_' + el.data('id'));
            $modal.modal();
            
          });

          $("#amount").keydown(function (e) {
            // Allow: backspace, delete, tab, escape, enter and .
            if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
                 // Allow: Ctrl+A
                (e.keyCode == 65 && e.ctrlKey === true) ||
                 // Allow: Ctrl+C
                (e.keyCode == 67 && e.ctrlKey === true) ||
                 // Allow: Ctrl+X
                (e.keyCode == 88 && e.ctrlKey === true) ||
                 // Allow: home, end, left, right
                (e.keyCode >= 35 && e.keyCode <= 39)) {
                     // let it happen, don't do anything
                     return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
          });

          $("#amount").keyup(function (e) {
            var value = $(this).val(), max = parseInt($('button#calculate').data('max'));
            if( parseInt(value) > parseInt($('button#calculate').data('max')) ) {
              $(this).val(max);
              return;
            }

            $('input#amount').parents('.input-group').removeClass('has-error');

          });

          $('button#calculate').on('click', function(){
            var amount = $('input#amount').val();

            if($.trim(amount) == '') {
              $('input#amount').parents('.input-group').addClass('has-error');
              App.notification('error', 'This field is required');
              return;
            }

            amount = parseInt(amount.split('.').join(''));

            if( isNaN(amount) ) {
              $('input#amount').parents('.input-group').addClass('has-error');
              App.notification('error', 'Must be a number');
              return;
            }

            if( parseInt($(this).data('max')) < amount ) {
              $('input#amount').parents('.input-group').addClass('has-error');
              App.notification('error', 'Cannot be higher than your limit');
            }

            $('input#amount').parents('.input-group').removeClass('has-error');

            $('input#_amount').val(amount);

            App.ajax({
              url: ajax_quick_calculation,
              data: {
                amount: amount
              },
              block: true,
              blockTarget: '.loan-calculations'
            }, function (data) {
              var i, item_c, item_d, ii, _modal, _table, items_d, d;

              for(i = 0; i < 3; i++) {
                item_c = data.data[ i ];
                for( ii in item_c ) {
                  $('#' + ii + '_' + i).html(item_c[ii]);
                }

                item_d = item_c.data;
                _modal = $('#loan-details-modal_' + i);
                _summary = _modal.find('#summary');
                _table = _modal.find('.loan-detail tbody');
                _table.empty();

                _summary.find('td#start_date').html(item_c['beginDate']);
                _summary.find('td#loan_amount').html('$' + item_c['total_value']);
                _summary.find('td#loan_period_in_y').html(item_c['periods']);
                _summary.find('td#payment_freq').html(item_c['paymentFreq']);
                _summary.find('td#annual_interest').html(parseFloat(item_c['rate']).toFixed(2) + '%');

                _summary.find('td#scheduled_payment').html(item_c['scheduledPayment']);
                _summary.find('td#scheduled_num_payment').html(item_c['paymentNumber']);
                _summary.find('td#actual_num_payments').html(item_c['realPaymentNumber']);
                _summary.find('td#total_interest').html('$' + item_c['total_interest']);
                _summary.find('td#cost_of_loan').html('$' + item_c['cost']);

                var iii = 1;
                for( due in item_d ) {
                  items_d = item_d[due];
                  row = '<td>' + (iii++) + '</td>';
                  row += '<td>' + due + '</td>';
                  row += '<td>' + item_d[due]['value'] + '</td>';
                  row += '<td>' + item_d[due]['scheduled_payment'] + '</td>';
                  row += '<td>' + item_d[due]['principal'] + '</td>';
                  row += '<td>' + item_d[due]['interest'] + '</td>';
                  row += '<td>' + item_d[due]['nextValue'] + '</td>';

                  _table.append('<tr>' + row + '</tr>');
                }
              }

            }, function (err) {
              $('input#amount').parents('.input-group').addClass('has-error');
            });
          });

          $('button#calculate').trigger('click');

          
        }
    };

  }();

	Loan.init();
});