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

    var reloadTables = function()
    {
      TradeNotes_Sell.reloadMyNotes();
      TradeNotes_Sell.reloadMyNotesForSale();
    };

    return {
        init: function () {
        	$('table.notes tbody, table.notes-fs').on('click', 'tbody tr:not(.details) td', function(e) {
              var _this = $(this).parent('tr'), tableClass = _this.parents('table').attr('id'),
                activeTr = $('table.' + tableClass + ' 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');
          modalConfirm = $('#modal-confirm');

          modal.find('#sellBtn').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_sellNoteConfirm,
	          	data: {
	          		id: noteID,
	          		amount: amount
	          	}
	          }, function( data ) {
	          	if(data.data) {
               modal.modal('hide');
               reloadTables();
              }
          	});
          });

          modalConfirm.find('#confirmCancelBtn').on('click', function(e) {
            var noteID = modalConfirm.attr('id');

            App.ajax({
              url: ajaxUrl_noteSellingCancel,
              data: {
                id: noteID
              }
            }, function( data ) {
              if(data){
                modalConfirm.modal('hide');
                reloadTables();
              }
            });
          });

          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(); 

            //tr.moveToAnimation($('.forsale-notes tbody'));

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

	          App.ajax({
	          	url: ajaxUrl_sellNote,
	          	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();
	       
	          });
	        });

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

            modalConfirm.attr('id', row_data.id);
            modalConfirm.find('#noteID').html(row_data.id);
            modalConfirm.modal();

          });
        },

        paginator: App.paginator,

        getMyNotes: function( page, cb, data ) {

          notesDT = $('#notes').DataTable( {
            ajax: {
              url: ajaxUrl_getMyNotes,
              type: 'POST'
            },
            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": "Current amount", "data": "current_amount", "sortable": true, },
              { "title": "Actions", "data": null, "sortable": false },
            ],
            "columnDefs": [
              {
                  "targets": [3],
                  "render": function ( data, type, full, meta ) {
                      return '<button class="btn btn-sm green"><i class="icon-wallet"></i> Sell</button>';
                  }
              }
            ]
          });
        },

        getMyNotesForSale: function( page, cb, data ) {

          notesFsDT = $('#notes-fs').DataTable( {
            ajax: {
              url: ajaxUrl_getMyNotesForSale,
              type: 'POST'
            },
            lengthMenu: [ 25, 50, 75, 100 ],
            pageLength: 25,
            serverSide: true,
            retrieve: true,
            paging: true,
            searching: false,
            "columns": [
              { "title": "ID", "sortable": true, "data": "id" },
              { "title": "Selling Amount", "data": "amount", "sortable": true, },
              { "title": "Note Amount", "data": "note_amount", "sortable": true, },
              { "title": "Note Current Amount", "data": "note_current_amount", "sortable": true, },
              { "title": "Actions", "data": null, "sortable": false },
            ],
            "columnDefs": [
              {
                  "targets": [4],
                  "render": function ( data, type, full, meta ) {
                      return '<button class="btn btn-sm red"><i class="fa fa-close"></i> Cancel</button>';
                  }
              }
            ]
          });
            
        },

        reloadMyNotes: function() {
          notesDT.ajax.reload();
        },

        reloadMyNotesForSale: function() {
          notesFsDT.ajax.reload();
        }
    };

	}();

	$(document).ready(function() {
    TradeNotes_Sell.init();
    TradeNotes_Sell.getMyNotes();
    TradeNotes_Sell.getMyNotesForSale();

    $('body .portlet > .portlet-title > .tools > a.reload').off();
    $('body').on('click', '.portlet#my-notes > .portlet-title > .tools > a.reload', function(e) {
      e.preventDefault();
      //var el = $(this).closest(".portlet").children(".portlet-body");
      //TradeNotes_Sell.reloadMyNotes();
    });
    $('body').on('click', '.portlet#my-notes-fs > .portlet-title > .tools > a.reload', function(e) {
      e.preventDefault();
      //var el = $(this).closest(".portlet").children(".portlet-body");
      TradeNotes_Sell.reloadMyNotesForSale();
    });

    Object.freeze(TradeNotes_Sell);
	});

})();