/**
 * Simple tabbing plugin.
 * @author geraldyeo
 */
(function($){

    function initUI(settings){
        var that = this, prefix = settings.prefix, $tabsul = $(that).find("ul");
        
        // hide static divs
        that.find("div[id^='" + prefix + "']").each(function(i, item){
            $(item).hide();
        });
        
        // find them li's
        $tabsul.find("li > a").each(function(i, item){
            var $item = $(item), hrefStr = $item.attr("href");
            
            // skip anchors with ids
            if ($item.attr("id")) return false;
            
            $item.data("tabindex", i);
            var $tabDiv = that.find("div[id='" + prefix + (i + 1) + "']");
            
            // if no div provided
            if ($tabDiv.length === 0) {
                that.children(":last").after("<div></div>");
                $tabDiv = that.children(":last");
                $tabDiv.attr({
                    id: prefix + (i + 1)
                }).addClass("tab_content").hide();
            }
            
            if (hrefStr.indexOf("#") === -1) {
                // ajax content
                $item.click(function(evt){
                    $tabDiv.load(hrefStr, function(data){
                        clickHandler.apply($tabDiv);
                    });
                    return false;
                });
            }
            else {
                // static content for #link.
                $item.click(function(evt){
                    clickHandler.apply($tabDiv);
                    return false;
                });
            }
        });
        
        function clickHandler(){
            if (that.data("currentTabDiv") !== undefined) {
                that.data("currentTabDiv").hide();
                $tabsul.removeClass("tab_" + that.data("currentTabDiv").attr("id"));
            }
            that.data("currentTabDiv", this);
            $tabsul.addClass("tab_" + this.attr("id"));
            this.fadeIn(200);
            
            if (typeof settings.onLoaded === 'function'){
                settings.onLoaded(this.attr("id"));
            }
        }
        
        // select the defaulted tab
        $tabsul.find("li:eq(" + (settings.selected - 1) + ") > a").click();
    }
    
    // jQuery plugin implementation
    $.simpletabs = {
        defaults : {
            selected : "1",
            prefix : "tabs-",
            onLoaded : ""
        }
    };
    
    // constructor
    $.fn.extend({
        simpletabs: function(options){
            var settings = $.extend({}, $.simpletabs.defaults, options);
            initUI.apply(this, [settings]);
            return this;
        }
    });
    
})(jQuery);
