﻿// ********** Currency functions **********

var Currency = function()
{
    this.rates = new Object();
    this.current = 'EUR';
}

Currency.prototype =
{
    setCurrency: function(curr)
    {
        this.current = curr;
    },

    setExchangeRate: function(curr, rate)
    {
        this.rates[curr.toUpperCase()] = rate;
    },

    getExchangeRate: function(curr)
    {
        var rate = this.rates[curr.toUpperCase()];
        if (rate == null)
            rate = 1.0;
        return rate;
    },

    convertFromEUR: function(value, toCurrency)
    {
        if (toCurrency == null)
            toCurrency = this.current;
        if (toCurrency == 'EUR')
            return value;

        return value * this.getExchangeRate(toCurrency);
    },

    convertToEUR: function(value, fromCurrency)
    {
        if (fromCurrency == null)
            fromCurrency = this.current;
        if (fromCurrency == 'EUR')
            return value;

        return value / this.getExchangeRate(fromCurrency);
    },

    convert: function(value, fromCurrency, toCurrency)
    {
        if (fromCurrency == null || toCurrency == null || fromCurrency == toCurrency)
            return value;

        var fromRate = this.getExchangeRate(fromCurrency);
        var toRate = this.getExchangeRate(toCurrency);
        return value * toRate / fromRate;
    },

    formatPriceEx: function(price, convert)
    {
        if (convert)
            price = this.convertFromEUR(price);
        var price = Math.round(price);
        return price.toString();
    },

    formatPrice: function(price)
    {
        return this.formatPriceEx(price, true);
    },

    displayPrice: function(price)
    {
        return this.formatPrice(price) + ' ' + GCurrency.current;
    }
}

var GCurrency = new Currency();