$(document).ready(function(){
    euro_calculator();
});

var isCtrl = false;
var paste  = false;

function euro_calculator() {

    $('#value1').keyup(function(e){if (paste == true) paste = false; keypress_action(e,'#value2', $(this));});
    $('#value2').keyup(function(e){if (paste == true) paste = false; keypress_action(e,'#value1', $(this));});

    $('#value1').keydown(function(e){
        if (e.which == 224) {
            isCtrl = true;
        }
        if (e.which == 86 && isCtrl == true) {
            paste = true;
        }
    });
}

function Calculator() {
    this.currencies = currencies;
}

Calculator.prototype.getCurrency = function() {
    return this.currencies[this.curr].title;
}

Calculator.prototype.getOtherCurrencyID = function() {
    return (this.curr == 1 ? 0 : 1);
}

Calculator.prototype.getCurrencyResult = function(num) {
    if (this.curr == 0) {
        return num * this.currencies[this.getOtherCurrencyID()].rate;
    } else {
        return num / this.currencies[this.curr].rate;
    }
}

Calculator.prototype.parseResult = function(result) {
    //var str  = new String(result);
    //return str.replace(/(\d*).(\d{2,2})\d*/, "$1.$2");
    return Math.round(result*100)/100;
}

function keypress_action(e, div, el) {

    var el_value = el.attr('value');

    if (el_value.match(/\./)) {
        el_value = el_value.replace(/,\./, "");
    }else {
        el_value = el_value.replace(/,/, ".");
    }
    el.attr('value', el_value);

    if ((e.which >= 48 && e.which <= 57)  ||
        (e.which >= 97 && e.which <= 105) ||
        e.which == 8                      ||
        e.which == 224                    ||
        e.which == 17
    ) {

        var calc = new Calculator();
        calc.curr = el.attr('class');

        $(div).attr('value', calc.parseResult(calc.getCurrencyResult(el_value)));
    }
}

