var taskItemLoaded = taskItemLoaded || false;

(function()
{
    var template = require('../../html/directives/project_nav_tabs.directive.html');
	var moduleName = 'claromentis.project';
	var module;

	try {
		module = angular.module(moduleName);
	} catch(err) {
		// named module does not exist, so create one
		module = angular.module(moduleName, []);
	}

	if (!taskItemLoaded)
	{
		module.directive('projectNavTabs', ['$timeout', 'claProjectDetailsService', function ($timeout, service) {
            return {
                restrict: 'E',
                templateUrl: template,
                bindToController: true,
                controllerAs: 'ctrl',
                controller: function() {
                    var ctrl = this

                    ctrl.tab = 'overviewTab';
                    ctrl.tabCounts = {};
                },
                link: function($scope, elements, attr, ctrl) {
                    ctrl.project_perms = project_perms;

                    ctrl.tabCounts = service.tabCounts;
                    service.registerCallback(function(locationData) {
                        ctrl.tab = locationData.tab;
                        ctrl.tabCounts.taskCount = locationData.counts.taskCount;
                        ctrl.tabCounts.totalTaskCount = locationData.counts.totalTaskCount;
                        ctrl.tabCounts.teamCount = locationData.counts.teamCount;
                        ctrl.tabCounts.topicCount = locationData.counts.topicCount;
                        ctrl.tabCounts.fileCount = locationData.counts.fileCount;

                        $timeout(function() {
                            $scope.$digest();
                        }, 0);
                    });

                    // Deal with page load
                    if (window.location.hash !== '') {
                        service.setLocation(window.location.hash.slice(2));
                    }

                    // Store the basic URL that we should check hash changes for
                    var thisPage = window.location.host + window.location.pathName;

                    // Deal with subsequent URL changes
                    window.addEventListener('hashchange', function() {
                        // Do nothing if the page itself is being changed
                        if (thisPage !== window.location.host + window.location.pathName)
                            return;

                        service.setLocation(window.location.hash.slice(2));
                    })
                }
            };
        }]);
	}
}());
