angular.module("app").directive("quantTabsVirtual", function($rootScope, $timeout) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: "../app/directives/quantTabsVirtual/quantTabsVirtual.html",
        scope: {
            instance: '=',
        },
        link: function (scope, element, attrs) {
            scope.onSelectTab = function(tab){
                var tabs = scope.instance.tabs;

                for(var i=0; i<tabs.length; i++){
                    if(tabs[i] == tab){
                        tabs[i].active = true;
                    } else {
                        tabs[i].active = false;
                    }
                }
                
                scope.instance.onClick(tab);
            }
            
            scope.instance.getActiveTab = function(){
                var tabs = scope.instance.tabs;
                for(var i=0; i<tabs.length; i++){
                    if(tabs[i].active){
                        return tabs[i];
                    }
                }
            }

            scope.instance.switchToTab = function(tabTitle){
                var tab = getItem(scope.instance.tabs, 'title', tabTitle);
                if(tab){
                    scope.onSelectTab(tab);
                }
                else {
                    console.error("Tab '" + tabTitle + "' doesn't exist");
                }
            }
            
            if(scope.instance.afterInit){
                $timeout(function(){
                    scope.instance.afterInit();

                    if(scope.instance.tabs && scope.instance.tabs.length > 0){
                        var activeTab = scope.instance.getActiveTab();
                        if(activeTab){
                            scope.instance.onClick(activeTab);
                        }
                        else {
                            scope.onSelectTab(scope.instance.tabs[0]);
                        }
                    }
                });
            }
        }
    };
});