$(document).ready(function() {
    function get_url_param(name) {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);

        if (results == null)
            return "";
        else
            return results[1];
    }

    var selLang = get_url_param("lang");

    function changeLang(lang) {
        var i = document.location.href.indexOf('?');
        if (i > 0)
        {
            newURL = document.location.href.substr(0, i);
        }
        else
        {
            newURL = document.location.href;
        }

        newURL += "?lang="+ lang
        document.location.href = newURL;
    }


    var shown = false;
    $(".selected-language").click(function() {
        shown = !shown;
        update();
    });

    $(".lang-option").click(function() {
        changeLang($(this).data("lang"));
        shown = false;
        update();
    });

    function update() {
        if(shown) {
            $(".language-menu").addClass("active");
        } else {
            $(".language-menu").removeClass("active");
        }

        $(".lang-preview").attr("src", "icon_flag_" + selLang + ".png");
    }

    update();
});

