/**
 * jQuery TOOLS plugin :: tabs.subtab 0.1
 *
 * Author: LELAK web+design
 * Launch: November 2009
 */
(function($) {
	
    var t = null;
    var tabApi = null;
    var mainCurrentTab = null;
    var pane = new Array();
    var actualSubTab = -1;
    var hashParams = null;
    
    
    
    $.fn.subtab = function(query) {
        t = $.tools.tabs;
        t.plugins = t.plugins || {};

        t.plugins.subtab = {
            version: '0.1',
            conf: {
                api: false,
                level: 3
            }
        };
		
        hashParams = $.getHashParams();
	
        query.options['api'] = true;
        tabApi = this.tabs(query.pane, query.options);
		
        if(query.level) {
            t.plugins.subtab.conf.level = query.level;
        }

        // Set the opened tab by hash query string "#?tab={tab_name}"
        if(hashParams.tab) {
            tabApi.click(hashParams.tab);
        }

        // Open the correct tab to level 2 tabs
        if(t.plugins.subtab.conf.level==2) {
			
            if(hashParams.urlHash != null) {
                queryParams = hashParams.urlHash;
                queryParams = queryParams.split('/');
                if(queryParams[0] != '')
                    // Open tab by Hash folder name "#{tab_name}/{file}"
                    tabApi.click(queryParams[0]);
            } else {
                // Open tab by URL Query String "?tab={tab_name}"
                tabApi.click(hashParams.urlQuery.tab);
            }

        }

        this.find("li > a").click(function() {
            var locHash = '?tab=' + $(this).attr('href').substr(1);

            if(hashParams.urlQuery.tab != '') {
                // Redirect page to clear URL Query String and add Hash Query String
                window.location = hashParams.urlFile + '#' + locHash;
            } else {
                // Add hash query string to open correct main tab
                window.location.hash = locHash;
            }
            if( mainCurrentTab != null) {
                mainCurrentTab.show();
                mainCurrentTab.next().hide();
            }
        });
		//console.log(this)

        for ( i = 0; i < query.tab.length; i++ ) {
            // run this to create new instance for each level 2 tab
            new subTabLinks(query.tab[i], i, tabApi);
        }

        return tabApi;
    };

    /**
     * Functions level 2 tabs
     */
    function subTabLinks(currentTab, i, mainTab) {
    	
        // Location that will receive the contents of level 3 tabs
        pane[i] = jQuery( currentTab + ' > .pane');

        // Create level 2 tabs
        if(t.plugins.subtab.conf.level==2) {
			
            jQuery( currentTab + " ul.links-list" ).tabs( pane[i], {
                effect: 'ajax'
            } ).history();

        } else {

            jQuery( currentTab + " > ul" ).tabs( currentTab + " > #pane",{

                initialIndex: -1,

                onClick: function(event, index) {

                    if( this.getTabs().eq(index).attr('class') == 'tab-link' ) {

                        //jQuery(pane[i]).html('<img src="/common/com/jquery/tools/img/spinner.gif" />');

                        if( mainCurrentTab == null ) jQuery( currentTab + ' > ul').hide();

                        // Load page to the level 3 tabs
                        jQuery(pane[i]).load(this.getTabs().eq(index).attr("href").split('#')[1],

                            // [callback] When level 3 page is loaded
                            function() {
                                //jHash('#tabs');
                                jQuery( currentTab + ' > ul').hide();
                                setSubTab(currentTab, pane[i]);
                                pane[i].show();
                                mainCurrentTab = systemsTabsApi.getCurrentTab().parent().parent();
                            }
                        );
                    } else {
                        if(index >= 0 && this.getTabs().eq(index).attr('href') != undefined && !this.getTabs().eq(index).attr('rel')) {
                            window.location = this.getTabs().eq(index).attr('href');
                        }
                    }
                }
            }).history();

            var systemsTabsApi = jQuery( currentTab + " > ul").tabs();

            jQuery( currentTab + " > ul > li a.tab-link").click(function() {
                jQuery( currentTab + ' > ul').fadeOut(300);
                pane[i].fadeIn(300);
            });
        }
    }
    
    /**
     * Set links to submenu for opened page on level 3 tabs
     */
    function setSubTab(currentTab, pane){
    	
        jQuery( currentTab + " #subtab-menu > ul:first").tabs( currentTab + " > #sub-pane",{

            initialIndex: -1,

            onClick: function(event, index) {

                if( index != actualSubTab ) {

                    actualSubTab = index;

                    if($.browser.msie && $.browser.version < '8') {
                        jQuery(pane).load(this.getTabs().eq(index).attr("href"), {}, function() {
                            jQuery(pane).fadeIn(200);
                            setSubTab(currentTab, pane);
                        });
                    }
                   
                    var section = "/balneo/";
                    var newUrl = this.getTabs().eq(index).attr("href");
                    newUrl = newUrl.split(section);
                    window.location.hash = newUrl[(newUrl.length-1)];
                }
            }
        });
        myLytebox.updateLyteboxItems();
    }

})(jQuery);
