(function(){
	var TradeNotes_Buy = function () {
		var storage = {};
    var config = { 
      filterLimit: 10
    }, notesDT, modal;

    return {
        init: function () {

          $('#filterForm').submit(function(e){
            e.preventDefault();
            $('#filterBtn').prop('disabled', 'disabled');
            notesDT.ajax.reload();
          });

        	$('table#notes').on('click', 'tbody tr:not(.details) td', function(e) {
              var _this = $(this).parent('tr'),
                activeTr = $('table#notes 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.actions > button').is(':active') ) 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>';

          modal = $('#note-modal');

          modal.find('#sendOfferBtn').on('click', function(e) {
          	var amountField = modal.find('#amountField'),
          			amount = amountField.val(),
          			noteID = modal.attr('id');

          	if( amount == '' || (!( (amount - 0) == amount && ('' + amount).trim().length > 0) ) || amount >= parseInt(modal.find('.modal-body').find('span#maxAmount').html()) ) {
          		amountField.parents('.form-group').addClass('has-error');
          		return;
          	} else {
          		amountField.parents('.form-group').removeClass('has-error');
          	}

          	App.ajax({
	          	url: ajaxUrl_buyNoteConfirm,
	          	data: {
	          		id: noteID,
	          		amount: amount
	          	}
	          }, function( data ) {
	          	if(data) {
                TradeNotes_Buy.reloadNotes();
                modal.modal('hide');
              }
          	});
          });

          modal.find('#amountField').on('change', function(){

          });

	        $('table#notes').on('click', 'tbody tr:not(.details) td:last-child button', function(e){
	          e.stopPropagation();
	          var self = $(this),
	          		row_index = self.parents('tr').index(),
                row_data = notesDT.row(row_index).data(); 

	          $('body').modalmanager('loading');

	          App.ajax({
	          	url: ajaxUrl_buyNote,
	          	data: {
	          		id: row_data.id
	          	}
	          }, function( data ) {
	          	var modalBody = modal.find('.modal-body'), note = data.data;
	          	modal.attr('id', note.id);
	          	modalBody.find('span#maxAmount').html(note.amount);
	          	modalBody.find('span#noteID').html(note.id);
	          	modal.modal();
	       
	          });
	        });
        },

        paginator: App.paginator,

        getNotes: function( page, cb, data ) {

          notesDT = $('#notes').on('xhr.dt', function ( e, settings, json ) {
            $('#filterBtn').prop('disabled', false);
          }).DataTable( {
            ajax: {
              url: ajaxUrl_getNotes,
              type: 'POST',
              data: function(d){
                d.id = $('#noteSellID').val();
                d.amount = $('#noteSellAmount').val();
                d.current_amount = $('#noteCurrentAmount').val();
              }
            },
            lengthMenu: [ 25, 50, 75, 100 ],
            pageLength: 25,
            serverSide: true,
            retrieve: true,
            paging: true,
            searching: false,
            "columns": [
              { "title": "ID", "sortable": true, "data": "id" },
              { "title": "Amount", "data": "amount", "sortable": true, },
              { "title": "Note Amount", "data": "note_amount", "sortable": true, },
              { "title": "Note Current Amount", "data": "note_current_amount", "sortable": true, },
              { "title": "Created at", "data": "created_at", "sortable": true, },
              { "title": "Actions", "data": null, "sortable": false },
            ],
            "columnDefs": [
              {
                  "targets": [5],
                  "render": function ( data, type, full, meta ) {
                      return '<button class="btn btn-sm green"><i class="icon-wallet"></i> Buy</button>';
                  }
              }
            ]
          });
        },

        reloadNotes: function() {
          notesDT.ajax.reload();
        }
    };

	}();

	$(document).ready(function() {
    TradeNotes_Buy.init();
    TradeNotes_Buy.getNotes();

      $('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");
        TradeNotes_Buy.reloadNotes();
      });

       Object.freeze(TradeNotes_Buy);
	});
})();