// Content : Lang-switcher plugin for Jquery
// Author  : Raphaël Jolivet
// Version : 28 Feb 2008
// Usage :
//      See http://www.lalala.fr/stuff/lang-switcher/readme.html
//
// Releases :
// * 05 Oct 2007 - Initial release
// * 28 Feb 2008 - Add support of cookies to remember prefered language 
//                 (use of jquery.cookies plugin by Klaus Hartl)
// * 07 Mar 2008 - Fix the bug of "indexOf" in IE7 identified by Renaud (http://developax.blogspot.com/) 
//


// Constants
LGS_COOKIE = "LANG_SWITHER_PREFERED_LANG";
LGS_COOKIE_EXPIRE = 100000; // 100000 Days = infinite ...

// indexOf for IE
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

// Recursive search/replace function in nodes
function replace_rec(node, search, replace) {

    // Replace the value (attr value of text node)
    if (node.nodeValue != null) {
        try { // for IE who doesn't like when we set some attributes
            node.nodeValue = node.nodeValue.replace(search, replace);
        } catch(e) {}
    }

    // Loop on all child nodes 
    var nodes = node.childNodes;
    if (nodes) for(var i = 0; i < nodes.length; i++) {
        replace_rec(nodes[i], search, replace);
    }
    
    // For elements, look for attributes also
    if (node.nodeType == 1) {
        var nodes = node.attributes;
        if (nodes) for(var i = 0; i < nodes.length; i++) {
            replace_rec(nodes[i], search, replace);
        }
    }
}

// Instrument jQuery for a new method : replace
jQuery.fn.replace = function(search, replace) {
    return $(this).each(function() {
        replace_rec(this, search, replace);
    });
}

// Associative array to remember which button controls what
gLangButtons = new Array;
gLangButtonId = 0; // IUD for each lang button

function install_switch(
    placeholder, // DOM Node or jQuery object : Where to put buttons 
    targets,     // jQuery object : Which tree will change on clic on button 
    template)    // HTML template of a single button : "$lang" will be replaced by actual lang
{
    // Search all elements with a "lang" attribute
    var nodes = $("[lang]", targets);

    // Get all the possible 'lang' values
    var list = $.map(nodes, function (node) {return $(node).attr('lang')})

    // Remove duplicates
    uniques = new Object;
    for(var i=0; i < list.length; i++) {
        uniques[list[i]] = list[i];
    }
    list = new Array;
    for(var val in uniques) {
        list.push(val);
    }

    // No need for a switch if we have only one language
    if (list.length <= 1) return;
    
    var buttons = new Array;

    // Create button to switch on langages
    $.map(list, function(lang) {

        // Prepare a button for this language (from template)
        var button = $(template).clone().replace('$lang', lang);
        
        // Set the id of the lang (to get associated targets later)
        button.attr("id", "lang-" + gLangButtonId + "-" + lang);

        // On click
        $(button).click(function() {
            var ids = $(this).attr('id').split('-');
            var lang_id = ids[1];
            var lang = ids[2];

            switch_to(
                lang_id,
                lang);

            // Set a cookie to remember the prefered language
            if ($.cookie) {$.cookie(LGS_COOKIE, lang, {expires: LGS_COOKIE_EXPIRE});}

            return false;
        })

        // Add to the list
        buttons.push(button);
    })
        
    // Append the buttons at the beginning of the placeholder
    $(buttons).each(function(){$(placeholder).prepend(this)});

    // Remember the association id => (targets, buttons)
    gLangButtons[gLangButtonId] =
    {
        buttons: buttons,
        targets: targets
    };

    var lang;
    // By default, switch to prefered language stored in cookie 
    if (($.cookie) && 
        (lang = $.cookie(LGS_COOKIE)) &&
        (list.indexOf(lang) != -1))
    {
        switch_to(gLangButtonId, lang);
    } else {
        // else, switch to first language 
        switch_to(gLangButtonId, list[0]);
    }

    // Next UID for other langages
    gLangButtonId++;
}


// Switch to a particular language under a given node
function switch_to(id, lang) {
    
    // Get the targets/buttons for this id
    var targets = gLangButtons[id].targets;
    var buttons = gLangButtons[id].buttons;

    // Show/Hide localized part of the DOM
    $("[lang]", targets).each(function() {
        if (lang == $(this).attr("lang")) {
            $(this).show();
        } else {
            $(this).hide();
        }
    }) 

    // Higlight the button of the selected language
    $(buttons).each(function() {
      
        // Lang of current button
        var butLang = $(this).attr("id").split("-")[2];

        // Switch class "on"/"off"
        if (lang == butLang) {
            $(this).
            removeClass("off").
            addClass("on");
        } else {
            $(this).
            removeClass("on").
            addClass("off");
        }
    });
}



