$(document).ready(function()
{
  
  var trades = $('.trades');
  
  var startDate = '19000101';
  var endDate = '300001001';
  var sortOrder = "trade date DESC";
  
  $('#new-bank-account').dialog(
  {
    bgiframe: true,
    autoOpen: false,
    width: 400,
    title: 'New Bank Account',
    modal: true
  });
  
  if(trades.html() != null)
  {
    fixTradesTable();
    $('.tradeDateSelector').hide();
    
    $('#new-instruction').dialog(
      {
        bgiframe: true,
        autoOpen: false,
        width: 400,
        title: 'New Instruction',
        modal: true
      });
    
    $('#new-instruction #chart').progressbar();
    
    $('#amount-slider').slider(
      {
        range:'min'
      });
      
      $('#new-instruction #amount').keyup(function()
      {
        $('#amount-slider').slider('value',[numberize($(this).val())]);
      })
      
      var bankAccounts = $('#bank-accounts-selector option').not(':first-child');
  }
  
  $('.tradeDateSelector input:text, .date').datepicker({
    dateFormat: 'dd/mm/yy'
  });
  
  
  $('select#tradesFilter').click(function()
  {
    $('.tradeDateSelector').hide();
    
    switch($(this).val())
    {
      case 'all'  :
        startDate = '19000101';
        endDate = '30000101';
      break;
      case 'active' :
        startDate = '20091024';
        endDate = '30000101';
      break;
      case 'inactive' :
        startDate = '19000101';
        endDate = '20091023';
      break;
      case 'advanced' :
        $('.tradeDateSelector').show();
      break;
    }
    
    if($(this).val() != 'advanced')
    {
      refreshTrades();
    }
    
  });
  
  $('.tradeDateSelector input:submit').click(function()
  {
    startDate = formatDate(new Date(getDateFromFormat($('.tradeDateSelector .startDate').val(),'dd/MM/yyyy')),'yyyyMMdd');
    endDate = formatDate(new Date(getDateFromFormat($('.tradeDateSelector .endDate').val(),'dd/MM/yyyy')),'yyyyMMdd');
    refreshTrades();
  })
  
  function fixTradesTable()
  {
    trades.find('tr:odd').addClass('odd');
    $('.sold-amount, .bought-amount').each(formatCurrency);
    $('.trades .trade').attr("title", "Click to Expand Instructions");
  }
  
  $('.trades .trade').toggle(function()
  {
    var row = $(this);
    row.attr("title", "Click to Collapse");
    $(this).next('.instructions').remove();
    getInstructionsForTradeOnRow(row);
    
  },function()
  {
    var row = $(this);
    $('.trades .trade').removeAttr('title');
    row.next('.instructions').slideUp('slow',function(){$(this).remove(); row.removeClass('expanded');});
  });
  
  function refreshTrades()
  {
    $.ajax(
    {
      url: '/account/trades',
      type: 'POST',
      data: {startDate:startDate, endDate:endDate,sortOrder:sortOrder},
      dataType: 'html',
      success: function(data)
      {
        if(data == "") data = "<tr><td colspan='7' style='text-align:center'>Sorry, No Matches</td></tr>"
        $('.trades tbody').html(data);
        fixTradesTable(); 
        $('.tradeDateSelector').hide();
      },
      error: function(request, data){window.location = 'account/login?session_expired=true'} 
    });
  }
  
  var currentRow = 0;
  
  function getInstructionsForTradeOnRow(row)
  {
    var tradeID = row.attr('id');
    
    $.ajax(
    {
       url: '/account/trades/' + row.attr('id') + '/instructions',
       type: "GET",
       dataType: "html",
       success: function(data)
       {
         var tradeBeingUpdated = false;

         if(row.hasClass('expanded'))
         {
           tradeBeingUpdated = true;
           row.next('.instructions').remove();
         }

         row.after(data);
         row.addClass('expanded');
         var instructions = row.next('.instructions');
         if(!tradeBeingUpdated) row.next('.instructions').hide().slideDown('slow');
         instructions.find('.instruction-amount').each(formatCurrency);

         var boughtCurrency = row.find('.bought-amount span').text();
         var boughtCurrencySymbol = row.find('.bought-amount').text().replace(new RegExp("[0-9.,a-zA-z ]", "g"), "");
         var boughtAmount = numberize(row.find('.bought-amount').text());
         var instructionsAmount = 0;
         instructions.find('.instruction').each(function(){instructionsAmount += numberize($(this).find('.instruction-amount').text());});
         var totalAvailable = parseFloat((boughtAmount - instructionsAmount).toFixed(2));

         if(totalAvailable <= 0) instructions.find('.instructionButton').hide();

         instructions.find('.instructionButton, .add-one').click(function(event)
         {
           currentRow = row;

           showInstructionForm();
           $('#new-instruction #accept-instruction').click(showInstructionConfirmation);
           $('#new-instruction #review-instruction').click(showInstructionForm);

           event.preventDefault();
           $('#new-instruction').attr('action', '/account/trades/' + tradeID + '/instruction')
           .dialog('open').dialog('option','title',tradeID + ' - New Instruction')[0].reset();
           $('#new-instruction #amount-available em').text(monetize(totalAvailable, boughtCurrencySymbol));

           $('#amount-slider')
           .slider('option','step',0.01)
           .slider('option','max',totalAvailable)
           .slider('option','value',totalAvailable*.3)
           .bind('slidestart',function(event, ui) {$("#amount").val(monetize(ui.value, boughtCurrencySymbol))})
           .bind('slide',function(event, ui) {$("#amount").val(monetize(ui.value, boughtCurrencySymbol))});

           $("#amount").val(monetize($('#amount-slider').slider('value'), boughtCurrencySymbol))
           var remainingPercentage = parseInt((totalAvailable/boughtAmount)*100);
           $('#new-instruction #chart').progressbar('option','value',remainingPercentage);
           remainingPercentage == 0 ? $('.ui-progressbar-value').css('visibility','hidden') : $('.ui-progressbar-value').css('visibility','visible');

           $('#bank-accounts-selector option').not(':first-child').remove();
           bankAccounts.each(function(){if($(this).hasClass(boughtCurrency)) $('#bank-accounts-selector').append(this)});
         });
       },
       error: function(request, data){window.location = 'account/login?session_expired=true'} 
    });
  }
  
  $('#new-instruction #confirm-instruction').click(function(event)
  {
    var row = currentRow;
    
    var bankAccountID = $('#new-instruction #information #bank-accounts-selector').val();
    var amount = $('#amount-slider').slider('value');
    var ccy = row.find('.bought-amount span').text();
    var comment = $('#new-instruction #information #reference').val();
    
    $.ajax(
    {
      url: '/account/trades/' + row.attr('id') + '/instructions',
      type: "POST",
      data: ({bankAccountID:bankAccountID,amount:amount,ccy:ccy,comment:comment}),
      dataType: "text",
      success: function(data){showInstructionSuccess(); getInstructionsForTradeOnRow(row)},
      error: function(request, data){showInstructionError()}
    });
    
  });
  
  $('#bank-account-button').click(function(event)
  {
    event.preventDefault();
    $('#new-bank-account').dialog('open');
  })
  
  $('#new-bank-account').submit(function(event)
  {
    event.preventDefault();
    $.ajax(
    {
      url:'/account/bank-accounts/',
      type: 'POST',
      dataType: 'text',
      data: $('#new-bank-account').serializeArray(),
      success: function(data){ alert(data) },
      error: function(request,data){ alert('error')}
    })
  });
  
  function showInstructionForm()
  {
    $('#new-instruction fieldset').hide();
    $('#new-instruction #information').show();
  }
  
  function showInstructionConfirmation()
  {
    $.getJSON('/account/bank-accounts/' + $('#new-instruction #information #bank-accounts-selector').val() + '.json',function(data)
    {
      $('#new-instruction fieldset').hide();
      $('#new-instruction #overview').show().
        find('#confirmation-bank-name span').text(data.Bank).closest('#overview').
        find('#confirmation-account-holder span').text(data.Holder).closest('#overview').
        find('#confirmation-account-number span').text(data.Number).closest('#overview').
        find('#confirmation-iban span').text(data.IBAN).closest('#overview').
        find('#confirmation-swift span').text(data.Swift).closest('#overview').
        find('#confirmation-amount span').text($('#new-instruction #information #amount').val()).closest('#overview').
        find('#confirmation-reference span').text($('#new-instruction #information #reference').val()).closest('#overview');
    });    
  }
  
  function showInstructionError()
  {
    $('#new-instruction fieldset').hide();
    $('#new-instruction #error').show(); 
  }
  
  function showInstructionSuccess()
  {
    $('#new-instruction fieldset').hide();
    $('#new-instruction #success').show();
  }
  
  
  //SORTING AND STYLING
  $('.trades thead td#trade-date').addClass('up');
  
  $('.trades thead td').toggle(function()
  {
    switch($(this).attr('id'))
    {
      case 'reference'    : sortOrder = 'reference DESC'    ; break;
      case 'trade-date'   : sortOrder = 'trade date DESC'   ; break;
      case 'value-date'   : sortOrder = 'value date DESC'   ; break;
      case 'sold-amount'  : sortOrder = 'sold amount DESC'  ; break;
      case 'bought-amount': sortOrder = 'bought amount DESC'; break;
      case 'client-rate'  : sortOrder = 'client rate DESC'  ; break;
      case 'status'       : sortOrder = 'trade status DESC' ; break;
    }    
    $('.trades thead td').removeClass('up down');
    $(this).addClass('up');
    refreshTrades();
    
  },function()
  {
    switch($(this).attr('id'))
    {
      case 'reference'    : sortOrder = 'reference ASC'    ; break;
      case 'trade-date'   : sortOrder = 'trade date ASC'   ; break;
      case 'value-date'   : sortOrder = 'value date ASC'   ; break;
      case 'sold-amount'  : sortOrder = 'sold amount ASC'  ; break;
      case 'bought-amount': sortOrder = 'bought amount ASC'; break;
      case 'client-rate'  : sortOrder = 'client rate ASC'  ; break;
      case 'status'       : sortOrder = 'trade status ASC' ; break; 
    }
    $('.trades thead td').removeClass('up down');
    $(this).addClass('down');
    refreshTrades();
  })
  
  function formatCurrency()
  {
    $(this).html($(this).html().replace('[ ', '<span>').replace(' ]','</span>')).find('span').css('background-color', getCurrencyColor($(this).find('span').text()))
  }
  
  function getCurrencyColor(currency)
  {
    var color = '';
    
    switch(currency.toLowerCase())
    {
      case 'gbp'  : color = '#CC0000';  break;
      case 'usd'  : color = '#0099CC'; break;
      case 'eur'  : color = '#FF6600'; break;
    }
    
    return color;
  }
  
})

// HELPERS
//To Unformat Currency to Number

function numberize(value)
{
  if(value.lastIndexOf('€') != -1)
  {
    return Number(value.replace(/[^0-9,]/g, '').replace(/\$|\,/g,'.'));
  }
  else
  {
    return Number(value.replace(/[^0-9.]/g, ''));
  }
  
}

function monetize(num,currency) {
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
currency == "€" ? result = (((sign)?'':'-') + num + '.' + cents + currency) : result = (((sign)?'':'-') + currency + num + '.' + cents);
return result;
}