var Rapida = Rapida || {};

Rapida.CurrencyCalc = function(mainInput, secondaryInput1, secondaryInput2) {
    this.uiBlocks = [$(mainInput), $(secondaryInput1), $(secondaryInput2)];
    this.mainRates = ['RUR', 'USD', 'EUR'];
    this.rates = {};
    this.ratesTomorrow = {};
    this.uiElements = {};
    this.values = [];
    this.conversionRates = [];
    /*var self = this;
    this.replace = $(mainInput).find('#replace').on('click', function() {
        self.mainRates = self.rotate(self.mainRates);
        self.values = self.rotate(self.values);
        self.update();
    });*/
};
Rapida.CurrencyCalc.prototype.rotate = function(arr) {
    return [arr[2], arr[0], arr[1]];
}

Rapida.CurrencyCalc.prototype.setRates = function(ratesToday, ratesTomorrow) {
    this.rates = ratesToday;
    this.ratesTomorrow = ratesTomorrow;
}

Rapida.CurrencyCalc.prototype.init = function() {
    this.update(null);
}

Rapida.CurrencyCalc.prototype.update = function(source) {
    for (var i=0; i<3; i++) {
        if (source  != i)
            this.updateBlockWithCurrency(i, this.uiBlocks[i], this.mainRates[i]);
    }
}

Rapida.CurrencyCalc.prototype.convert = function(fromCurrency, toCurrency, value) {
    var rate = this.conversionRates[fromCurrency];
    if (rate)
        rate = rate[toCurrency];
    if (!rate) {
        rate = this.rates[fromCurrency] / this.rates[toCurrency];
        if (!this.conversionRates[fromCurrency])
            this.conversionRates[fromCurrency] = [];
        this.conversionRates[fromCurrency][toCurrency] = rate;
    }

    return rate * value;
}

Rapida.CurrencyCalc.prototype.sumChange = function(index, currencyCode, value) {
    var floatVal = parseFloat(value.replace(',','.'));
    if (floatVal != NaN) {
        var newVal = this.formatFloat(floatVal, "", 2);
        if (newVal != this.values[index]) {
            this.values[index] = newVal;
            for (var i=0; i<3; i++) {
                if (i != index) {
                    this.values[i] = this.formatFloat(this.convert(currencyCode, this.mainRates[i], floatVal), "", 2);
                }
            }
        }
    } else {
        this.values = [0,0,0];
    }
    this.update(index);
}

Rapida.CurrencyCalc.prototype.formatFloat = function(val, defaultValue, precision) {
    if (!val || val==NaN) {
        return defaultValue;
    }
    return Math.round(val * Math.pow(10, precision)) / Math.pow(10, precision);
}

Rapida.CurrencyCalc.prototype.updateBlockWithCurrency = function(index, block, currencyCode) {
    var elements = this.uiElements[index];
    var self = this;
    if (!elements){
        elements = {};
        elements.input = block.find('input[type=text]');
        elements.currencyName = block.find('.currency-name');
        elements.currencyRate = block.find('.currency-value');
        elements.currencyDiff = block.find('.currency-diff');
        elements.currencyForecast = block.find('.currency-forecast');
        elements.input.on('keypress', function(event) {
            var validator = function(evt, sender) {
                var theEvent = evt || window.event;
                var key = theEvent.keyCode || theEvent.which;
                if ((key==8) || (key==46) || (key==27) || (key==9) || (key=37) || (key==39))
                    return true;
                key = String.fromCharCode( key );
                var regex = /[0-9]|\./;
                if ( sender.val().length>9 || (key != '' && key && !regex.test(key))) {
                    theEvent.returnValue = false;
                    if(theEvent.preventDefault) theEvent.preventDefault();
                    return false;
                }
                return true;
            }
            return validator(event, $(this));
        });
        elements.input.on('keyup', function(event) {
            var val = $(this).val();
            self.sumChange(index, currencyCode, val);
        });
        this.uiElements[index] = elements;
    }

    elements.currencyName.html(currencyCode);
    if (this.values[index])
        elements.input.val(this.values[index]);
    else
        elements.input.val('');

    elements.currencyForecast.html(this.formatFloat(this.ratesTomorrow[currencyCode], "-", 4));
    var diff = this.ratesTomorrow[currencyCode]-this.rates[currencyCode];
    if (diff < 0) {
        elements.currencyDiff.removeClass('up').addClass('down');
    } else if (!diff) {
        elements.currencyDiff.removeClass('up').removeClass('down');
    } else {
        elements.currencyDiff.removeClass('down').addClass('up');
    }
    elements.currencyDiff.html(this.formatFloat(diff, "-", 4));

    elements.currencyRate.html(this.rates[currencyCode]);
}
