// Controller used on modal dialog for new project to pick a template project
(function()
{
	var moduleName = 'projectListApp';

	angular.module(moduleName)
		.controller("projectNewCtrl", ["$scope", projectNewController])
		.directive("ngFormCommit", formCommitDirective);

	function projectNewController($scope)
	{
		$scope.template_projects_count = new_project.template_projects.length;
		$scope.non_template_projects_count = new_project.non_template_projects.length;
		$scope.project_options =
		{
			template: new_project.template_projects,
			project: new_project.non_template_projects
		};
		$scope.template_type = 'blank';
		$scope.template_selected =
		{
			template: new_project.template_projects[0],
			project: new_project.non_template_projects[0]
		};

		// Angular won't have created the select options yet so delay turning it into a select2 control
		setTimeout(function()
		{
			$('#projectTemplate').select2({ width: '100%' });
			$('#projectNonTemplate').select2({ width: '100%' });
		}, 50);

		$scope.submit = function(event, form)
		{
			// plain add doesn't need a form so just go to the add project page directly
			if ($scope.template_type == 'blank')
			{
				event.preventDefault();
				window.location = '/projects/add';
			} else
			{
				form.commit();
			}
		}
	}

	// Need to commit a form from outside of itself.
	// jQuery would work but not very Angular so this is a way to allow one to be submitted
	function formCommitDirective()
	{
		function link($scope, $el, $attr, $form)
		{
			$form.commit = function() {
				$el[0].submit();
			};
		}

		return {
			require:"form",
			link: link
		};
	}
}());