﻿/**
 * Aplikuj prepocitavani men na DOM
 */
function applyCurrency(code) {

    /**
     * Pokud neni kod v parametru, precti jej z cookie
     */
    if (code == null) {
        code = $.cookie("currency");
    }
    /**
     * Default je 0 (Euro)
     */
    code = parseInt(code);
    if (!code||isNaN(code)) {
        code = 0;
    }

    /**
     * Nastav aktualni menu do cookie
     */
    var date = new Date();
    date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));
    $.cookie("currency", code, { path: '/', expires: date });

    var value = 0;

    if (code == 0) {
        /**
         * Pokud se jedna o Eura, pouze dopis euro znak a ztucni
         */
        $(".Euro").each(function() {
            var format = $(".Currencies .Currency").eq(code).children(".Format").text();
            var rate = parseFloat($(".Currencies .Currency").eq(code).children(".Rate").text());
            if (value = loadCurrencyValue(this)) {
                $(this).text("").printf("<strong>" + format + "</strong>", rate * value);
            }
        });
    } else {
        /**
         * Pokud nejde o Eura, dopis euro znak, ztucni, a do zavorky napis prepocitanou menu
         */
        $(".Euro").each(function() {
        var format = $(".Currencies .Currency").eq(code).children(".Format").text();
        var rate = parseFloat($(".Currencies .Currency").eq(code).children(".Rate").text());
        var euro = $(".Currencies .Currency").eq(0).children(".Format").text();
            if (value = loadCurrencyValue(this)) {
                $(this).text("").printf("<strong>" + euro + "</strong>" + " (" + format + ")", value, (rate * value));
            }
        });
    }
}

/**
 * Nacti z elementu hodnotu, ignoruj znaky pred i za cislem
 */
function loadCurrencyValue(element) {
    value = $(element).text();
    regex = new RegExp("^€[0-9]*", "gi");
    if (regex.test(value)) {
        value = value.substring(1);
    }

    value = parseInt(value);
    if (!isNaN(value)) {
        return value;
    } else {
        return false;
    }
}

/**
* Inicializuj meny. Nacti vybranou menu z CurencyMenu
*/
$(document).ready(function() {
    var codeIndex = $(".CurrencyMenu select").val();
    if ($.cookie("currency")) {
        codeIndex = $.cookie("currency");
        $(".CurrencyMenu select").attr("selectedIndex", codeIndex);
    }
    applyCurrency(codeIndex);

    $(".CurrencyMenu select").change(function() {
        $(".CurrencyMenu select").val($(this).val());
        codeIndex = $(".CurrencyMenu select").val();
        applyCurrency(codeIndex);
    });
});