(function()
{
	var moduleName = 'projectDetailApp';

	angular.module(moduleName)
		.controller("projectDetailCtrl", ['$scope', '$http', '$timeout', 'breadcrumb.service', 'claProjectDetailsService', 'projectPreloadFactory', 'confirmService', projectDetailController]);

	function projectDetailController($scope, $http, $timeout, breadcrumbService, projectDetailsService, preload, confirmService)
	{
		$scope.project_header = project_header.info;
		$scope.project_perms = preload.perms;
		$scope.more_info_shown = false;
		$scope.summaryIsTooLong = false;
		$scope.editorEnabled = false;
		$scope.has_tasks_to_view = !!preload.tasks.length;
		$scope.show_tasks =
            $scope.project_perms.can_view_tasks ||
            ($scope.project_perms.is_team_member && $scope.has_tasks_to_view);

		// service
		$scope.service = projectDetailsService;
        $scope.currentTab = $scope.service.getLocation();

        // Delayed because the controls might not be instantiated yet to receive the event and they should not miss it
        $timeout(function() {
            angular.element(document).trigger('projectsTabChange', $scope.currentTab);
        }, 0);

        var crumbs = [
            {
                'url': '/projects',
                'name': lmsg('projects.breadcrumb.projects')
            },
            {
                'url': '/projects/' + $scope.project_header.id,
                'name': $scope.project_header.name
            },
            {
                'name': lmsg('projects.breadcrumb.overview')
            }
        ];

        breadcrumbService.setCrumbs(crumbs);

        angular.element(document).on('projectsTabChange', function($event, tabName) {
            if (tabName === 'overview')
                crumbs[2].name = lmsg('projects.breadcrumb.overview');

            if (tabName === 'tasks')
                crumbs[2].name = lmsg('projects.project.tasks');

            if (tabName === 'team')
                crumbs[2].name = lmsg('projects.project.team');

            if (tabName === 'discussion')
                crumbs[2].name = lmsg('projects.project.topics');

            if (tabName === 'files')
                crumbs[2].name = lmsg('projects.project.files');

            if (tabName === 'history')
                crumbs[2].name = lmsg('projects.project.history');

            breadcrumbService.setCrumbs(crumbs);

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

		$scope.statusClasses =
		{
            1: 'warning',        // Draft
            2: 'success',        // Live
            3: 'info',           // On hold
            4: 'secondary'       // Archived
		};

		$scope.setFollowButtonTitle = function()
		{
			if ($scope.project_header.follow == 0)
				$scope.project_header.follow_tooltip = lmsg('projects.project.follow');
			else
				$scope.project_header.follow_tooltip = lmsg('projects.project.unfollow');
		};
		$scope.setFollowButtonTitle();

		$scope.determineVisibleTab = function(location)
		{
			var  possibleTabs = [];
            if ($scope.project_perms.can_view_tasks)
            possibleTabs.push('overview');
            if ($scope.project_perms.can_view_tasks)
            possibleTabs.push('tasks');
            if ($scope.project_perms.can_view_team)
            possibleTabs.push('team');
            if ($scope.project_perms.can_view_discussion)
            possibleTabs.push('discussion');
            possibleTabs.push('files');
            possibleTabs.push('history');

			// Get first visible tab to use as default
			var tab = possibleTabs[0];

			// Find if one was supplied in the URL
			var regex = /([\w]+)Tab/;
			var matches = regex.exec(location);

			var byUrl = '';
			if ((matches !== null) &&
				(matches.length > 1))
				byUrl = matches[1];

			if (possibleTabs.indexOf(byUrl) > -1)
				tab = byUrl;

            angular.element(document).trigger('projectsTabChange', tab);

            $scope.currentTab = tab;
            $timeout(function() {
                $scope.$digest();
            }, 0);
		};
		$scope.determineVisibleTab($scope.service.getLocation());

        $scope.service.registerCallback(function(location) {
            $scope.determineVisibleTab(location.tab);
        });

		$scope.toggleFollow = function()
		{
			var url = '/api/projects/' + $scope.project_header.id + '/follow';

			if ($scope.project_header.follow == 0)
			{
				$http.put(url)
				.then(function(result)
				{
					angular.element('#follow-button').tooltip('hide');
					$scope.project_header.follow = result.data.follow;
					$scope.setFollowButtonTitle();
				});
			} else
			{
				$http.delete(url)
				.then(function(result)
				{
					angular.element('#follow-button').tooltip('hide');
					$scope.project_header.follow = result.data.follow;
					$scope.setFollowButtonTitle();
				});
			}

			$scope.setFollowButtonTitle();

			$scope.updateHistoryLog();
		};

		$scope.setRag = function(value, event)
		{
			event.preventDefault();

			if (!$scope.project_perms.can_edit_project)
				return;

			var url = '/api/projects/' + $scope.project_header.id + '/rag?value=' + value;
			$http.put(url).then(function(result)
			{
				if (result.data.result == false)
				{
					cla.showMessage(result.data.message, '', true);
				} else
				{
					$scope.project_header.rag_text = result.data.value;
					$scope.updateHistoryLog();
				}
			});
		};

		$scope.saveSummary = function (event)
		{
			event.preventDefault();

			var editor = $('#summaryText');
			editor.sync();
			var summary = editor.val();
			var url = '/api/projects/' + $scope.project_header.id + '/summary';
			$http({
				method: 'POST',
				url: url,
				data: "summary=" + encodeURIComponent(summary),
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			}).then(function(result)
			{
				if (result.data.result)
				{
					$scope.project_header.summary = result.data.summary;
					$scope.editorEnabled = !$scope.editorEnabled;
					$scope.updateHistoryLog();
				} else
				{
					cla.showMessage(result.data.message, '', true);
				}
			});
		};

		$scope.cancelSummary = function (event)
		{
			event.preventDefault();

			var editor = $('#summaryText');
			editor.bbcode($scope.project_header.summary.bbcode);

			$scope.editorEnabled = false;
		};

		$scope.toggleMoreInfo = function()
		{
			$scope.more_info_shown = !$scope.more_info_shown;
		};

		$scope.updateHistoryLog = function()
		{
			$scope.$root.$broadcast('updateHistoryLog', null);
		};

		$scope.$on('setTeamTabCount', function(event, args)
		{
            $scope.service.setTeamCount(parseInt(args));
		});

		$scope.$on('setTopicTabCount', function(event, args)
		{
            $scope.service.setTopicCount(parseInt(args));
		});

		$scope.$on('setFilesTabCount', function(event, args)
		{
			// TODO in phase 2 - Keep as 0 for now to not display anything
			//$scope.service.setFileCount(0);
		});

		$scope.$on('setUserPerms', function(event, args)
		{
			$scope.project_perms = args;
		});

		$scope.$on('updateProjectProgress', function(event, progress)
		{
			$scope.project_header.progress = progress;
			// IE doesn't update properly with aria values so set it directly
			angular.element('#progress-bar').css('width', progress + '%');
		});
		// Make IE start off with the right sized progress bar
		$scope.$root.$broadcast('updateProjectProgress', $scope.project_header.progress);

		$scope.isRepeatedMetadata = function(someVar)
		{
			return (typeof someVar === 'object');
		};

		$scope.checkSummaryLength = function()
		{
			var test = angular.element('#summaryText').data('wbb');
			if (typeof test !== 'undefined')
			{
				angular.element('#summaryText').sync();
				$scope.summaryIsTooLong = angular.element('#summaryText').bbcode().length > 2000;
			}
		};

        $scope.confirmDelete = function(event, project_id)
        {
            event.preventDefault();
            var url = '/api/projects/' + project_id;

            confirmService.show({
                title: lmsg('projects.project.delete_project.title'),
                message: lmsg('projects.project.delete_confirm'),
            }).then(function() {
                $http.delete(url).then(function(result)
                {
                    if (result.data.result)
                        window.location.href = '/projects?message=' + encodeURIComponent(lmsg('projects.js.project.project_deleted'));
                    else
                        cla.showMessage(lmsg('common.general.error') + ': ' + result.data.message, '', true);
                });
            }, function() {});
        };
	}
}());
