

// This will be executed immediately
// Adds various classes to the document body before the <body> tag exists in the DOM
(function () {
    var isCompatible = true;
    var ua = navigator.userAgent.toLowerCase();
    var version = (ua.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1];
    var browser = {
        ie: /msie/.test(ua) && !/opera/.test(ua),
        mozilla: /mozilla/.test(ua) && !/(compatible|webkit)/.test(ua),
        safari: /(webkit|chrome)/.test(ua),
        opera: /opera/.test(ua),
        chrome: /chrome/.test(ua),
        konqueror: /KDE/.test(navigator.vendor)
    };
    
    // For easy CSS browser detection
    // Ex. for IE6, adds following classes: ie ie6 ie55-up ie6-up ie6-down ie7-down
    if (browser.ie) {
        var v = parseFloat(version);
        var n = [5.5, 6, 7, 8];
        var c = ' ie ie'+v;
        
        // Add the ieN-down and ieN-up classes
        for (var i = n.length; i--;) {
            if (n[i] >= v) {
                c += ' ie'+n[i]+'-down';
            }
            if (n[i] <= v) {
                c += ' ie'+n[i]+'-up';
            }
        }
        isCompatible = (v >= 6);
        document.documentElement.className += c.replace(/\./g, '');
    } else {
        for (var b in browser) {
            if (browser[b]) {
                document.documentElement.className += ' '+b;
            }
        }
    }
    
    // Tell the CSS that the JavaScript is initialized
    if (isCompatible) {
        document.documentElement.className += ' js';
    }
})();


// This will be executed once everything is ready
$(function() {
    $('a.external').attr('target','_blank');
    $('#login').compactForm();
    
    // Hover effect on buttons for IE6
    $('.ie6-down label.button').hover(function () {
        $(this).toggleClass('hover');
    });
});


var main = {};


main.initCountryMenu = function (menu) {
    $(menu).customSelect({
        initCallback: function (toggle, menu, select) {
            var emptyChoice = menu.find('a[href$=#0]');
            emptyChoice.parent().html('<span class="select-empty">'+emptyChoice.text()+'</span>');
        },
        selectedCallback: function (toggle, menu, item, itemData) {
            toggle.parents('form').submit();
        }
    });
};


main.initNavigation = function (nav, elem) {
    nav = $(nav);
    elem = $(elem, nav);
    $(elem[elem.length-1]).css('margin-right', 0);
    var width = 0;
    elem.each(function () {
        var e = $(this);
        width += e.width() + parseInt(e.css('margin-left')) + parseInt(e.css('margin-right'));
    });
    elem.css('padding', '0 '+parseInt((nav.width() - width) / (2*elem.length))+'px');
};


main.initCoffeePage = function (nbCaps) {
    var isModern  = ($.browser.msie && $.browser.version < 7) ? 0 : 1;
    var list      = $('#content .capsule-list');
    var listItems = list.find('a').append('<span class="capsule-hover"></span><span class="capsule-active"></span>');
    var hashItem  = listItems.filter('[href$='+findHash(window.location.hash)+']:first');
    var info      = $('#content .capsule-info');
    var infoBox   = info.find('.capsule-info-box').append('<span class="capsule-top"></span><span class="capsule-bottom"></span><span class="capsule-triangle"></span>');
    var infoTri   = info.find('.capsule-triangle');
    var infoItems = info.find('li');
    var infoBoxPos, infoTriPos, currentItem, futureItem;
    
    if (nbCaps == 8) {
        infoBoxPos = { roi: '15px', r: '63px', ef: '111px', el: '159px', lf: '206px', ll: '254px', ed: '302px', ld: '350px' };
        infoTriPos = { roi: '28px', r: '90px', ef: '152px', el: '214px', lf: '276px', ll: '338px', ed: '400px', ld: '463px' };
    } else {
        infoBoxPos = { ri: '29px', ef: '86px', el: '139px', lf: '189px', ll: '240px', ed: '290px', ld: '339px' };
        infoTriPos = { ri: '24px', ef: '116px', el: '179px', lf: '258px', ll: '323px', ed: '401px', ld: '463px' };
    }
    
    // To avoid the info element to be resized when showing another capsule, set all it's items to the height of the highest one.
    function setInfoHeight() {
        var maxHeight = 0;
        infoItems.each(function() {
            var height = $(this).outerHeight();
            if (height > maxHeight) {
                maxHeight = height;
            }
        });
        if (isModern) {
            infoItems.css('min-height', maxHeight);
        } else {
            infoItems.height(maxHeight);
        }
    }
    
    // Display the clicked item.
    function activateItem() {
        var item = $(this);
        var animSpeed = currentItem ? isModern : 0
        
        futureItem = $(item.attr('href'));
        if (!currentItem || currentItem.attr('id') != futureItem.attr('id')) {
            // Set the URL anchor
            var hash = window.location.hash = findHash(item.attr('href'));
            
            // Activate the appropriate list item
            list.find('li.active').removeClass('active').find('.capsule-active').fadeOut(animSpeed*500);
            item.closest('li').addClass('active').find('.capsule-active').fadeIn(animSpeed*300);
            
            infoBox.animate({ 'left': infoBoxPos[hash] }, animSpeed*300);
            infoTri.animate({ 'left': infoTriPos[hash] }, animSpeed*300);
            
            // Activate the appropriate info item
            toggleItem(currentItem, false, function (noCurrentItem) {
                currentItem = noCurrentItem ? futureItem.show() : toggleItem(futureItem, true, function() {
                    if ($.browser.msie) {
                        // The only way to avoid IE to display the outline is to put the focus on another link...
                        setTimeout(function () { currentItem.find('a:first').focus().blur(); }, 1);
                    }
                });
            });
        }
        
        return false;
    }
    
    // Returns the 2 last letters of the string
    function findHash(str) {
        return str && str.match(/([a-z]{1,3})$/)[1];
    }
    
    // Shows or hides the given item, depending on the show parameter.
    // Always calls the fn callback, even when there is no item.
    function toggleItem(item, show, fn) {
        if (item && item.length) {
            // Let's speed up things for the poor old IE6 and avoid animations
            if (isModern) {
                item.stop().css('opacity', null);
                show ? item.fadeIn(200, fn) : item.fadeOut(200, fn);
            } else {
                show ? item.show() : item.hide();
                fn && fn();
            }
        } else {
            fn && fn(true);
        }
        return item;
    }
    
    setInfoHeight();
    listItems.click(activateItem);
    listItems.hover(function() {
        $(this).find('.capsule-hover').stop().css('opacity', null).fadeIn(isModern*200);
    }, function() {
        $(this).find('.capsule-hover').stop().css('opacity', null).fadeOut(isModern*400);
    });
    activateItem.apply(hashItem);
}

