Function.prototype.createDelegate = function (obj, args)
{
    var method = this;
    return function()
    {
        return method.apply(obj || window, args || arguments);
    }
};

jQuery.fn.setVisible = function (visible) { return visible? this.show() : this.hide() };


CurrencyCalc = {
    state: null,
    best: {usdSell: 1e9, usdBuy: 1e-9, euroSell: 1e9, euroBuy: 1e-9},
    bestBanks: {usdSell: '', usdBuy: '', euroSell: '', euroBuy: ''},

    init: function () {
        // Устанавливаем обработчики переключения направления
        $('#rub').focus( this.setState.createDelegate(this, ['buy']) );
        $('#usd').focus( this.setState.createDelegate(this, ['usdSell']) );
        $('#euro').focus( this.setState.createDelegate(this, ['euroSell']) );
        this.setState(null);

        $('#calc-do').click( this.calc.createDelegate(this) );
        $('#calc input').keypress( function (e) {
            if ((e || event).keyCode == 13) this.calc()
        }.createDelegate(this) );

        // Собираем данные банков
        var banks = $('#banks_data tr').map(function () {
              var td = $(this).find('td');
              return {
                  link:     $(td[1]).html() + '<br/>',
                  usdSell:  $(td[2]).text() * 1,
                  usdBuy:   $(td[3]).text() * 1,
                  euroSell: $(td[4]).text() * 1,
                  euroBuy:  $(td[5]).text() * 1
              };
        });

        // Выбираем лучшие курсы обмена
        for (var i=0; i < banks.length; i++)
        {
            b = banks[i];
            if (b.usdSell < this.best.usdSell) this.best.usdSell = b.usdSell;
            if (b.usdBuy > this.best.usdBuy) this.best.usdBuy = b.usdBuy;
            if (b.euroSell < this.best.euroSell) this.best.euroSell = b.euroSell;
            if (b.euroBuy > this.best.euroBuy) this.best.euroBuy = b.euroBuy;
        }

        // Выбираем лучшие банки
        for (var i=0; i < banks.length; i++)
        {
            b = banks[i];
            if (b.usdSell == this.best.usdSell) this.bestBanks.usdSell += b.link;
            if (b.usdBuy == this.best.usdBuy) this.bestBanks.usdBuy += b.link;
            if (b.euroSell == this.best.euroSell) this.bestBanks.euroSell += b.link;
            if (b.euroBuy == this.best.euroBuy) this.bestBanks.euroBuy += b.link;
        }
    },

    setState: function (state) {
        this.state = state;

        $('#calc-buy').setVisible( state == 'buy' );
        $('#calc-sell').setVisible( state == 'usdSell' || state == 'euroSell' );

        if (state == 'buy')
        {
            $('#calc-banks-usd').html(this.bestBanks.usdSell);
            $('#calc-banks-euro').html(this.bestBanks.euroSell);
        }
        else if (state == 'usdSell' || state == 'euroSell')
        {
            $('#calc-banks-usd').html(this.bestBanks.usdBuy);
            $('#calc-banks-euro').html(this.bestBanks.euroBuy);
        }

        if (state) {
            $('#calc-banks div').show();
            $('#calc-banks td').css({'padding-top': '0.4em', 'padding-bottom': '0.4em'});
        }
    },

    calc: function () {
        if (this.state == 'buy')
        {
            var rub = $('#rub').val() * 1;
            $('#usd').val( (rub / this.best.usdSell).toFixed(2) );
            $('#euro').val( (rub / this.best.euroSell).toFixed(2) );
        }
        else if (this.state == 'usdSell')
        {
            $('#rub').val( ($('#usd').val() * this.best.usdBuy).toFixed(2) );
            $('#euro').val('');
        }
        else if (this.state == 'euroSell')
        {
            $('#rub').val( ($('#euro').val() * this.best.euroBuy).toFixed(2) );
            $('#usd').val('');
        }
    }
}
