/*
Example:

<div id="my_tabs">
    <div class="tab" title="Tab one">
        Text text text
    </div>
    <div class="tab" title="Tab two">
        Text text text
    </div>
</div>

$('#my_tabs').tabs()

*/
$.fn.tabs = function(conf) {
    function toascii(s) {
        return s.toLowerCase().replace('ö', 'o').replace('ä', 'a').replace('å', 'a').replace(/[^a-z0-9-_]+/g, '_').replace('__', '_');
    } 
    var config = conf || {}
    return this.each(function() {

        var tabpages = {}
        var tabs = {}    

        function onTabClick(e) {
            selectTab(e.data.title); 
        }

        function selectTab(title) {
            // Hide current
            if(tabpages[title]) {
                $.each(tabs, function(title) {
                    $(tabs[title]).removeClass('selected')
                    hideTabPage(title)
                })
            }

            // show new
            $(tabs[title]).addClass('selected')        
            showTabPage(title)
        }
        function hideTabPage(title) {
            tabpages[title].css({position: 'absolute', left: '-10000px'})
        }
        function showTabPage(title) {
            tabpages[title].css({position: 'relative', left: 0, top: 0})
        }

        $('<div style="clear: both"></div>').prependTo(this)
        var ul = $('<ul class="tabs"></ul>').prependTo(this)

        var first = null
        $(this).children('.tab').each(function(i) {
            var title = toascii($(this).attr('title'))
            var title_org = $(this).attr('title')
            if(!first)
                first = title
                            
            tabpages[title] = $(this)
            $(this).attr('title', '') 
            var tab = tabs[title] = $('<li><a href="#'+title+'">' + title_org + '</a></li>').appendTo(ul)
            $(tab).children('a').bind('click', {title: title}, onTabClick)        
        })
        
        var hashindex = window.location.href.indexOf('#')
        if(hashindex !== -1) {
            selectTab(window.location.href.substr(unescape(hashindex+1)))
        }
        else { 
            selectTab(first)
        }
            
    })
    

}

