(function () {
	'use strict';

    var ng_module_name = 'site_link';

	angular.module(ng_module_name)
		.directive('editLink', editLink);

	editLink.$inject = ['siteLinkService', 'growl.service'];
	function editLink(siteLinkService, growlService)
	{
		return {
			replace: false,
			restrict: 'E',
			controller: controller,
			controllerAs: 'newLink',
			templateUrl: '/intranet/pages/html/includes/edit_link_modal.directive.html'
		};

		function controller()
		{
			var ctrl = this;
			ctrl.data = {};

			ctrl.show = function()
			{
				ctrl.data = siteLinkService.data;
				angular.element('#linkEditModal').modal();
			};

			ctrl.submit = function()
			{
				var result = ctrl.validate();
				if (result === true)
				{
					siteLinkService.submit();
					angular.element('#linkEditModal').modal('hide');
				} else
				{
					growlService.showError(result);
				}
			};

			ctrl.validate = function()
			{
				// Quick rejections
				if (ctrl.data.title.length === 0)
					return lmsg('pages.sites.error.no_title');
				if (ctrl.data.url.length === 0)
					return lmsg('pages.url.errorno_url');

				// URL
				var email_regex = /^(((?:https?\:|ftp\:)\/)?\/[-a-z0-9\.\\_]+[-a-z0-9.\\_~:\/?\#\[\]@!$&\'\(\)*+,;=%\|]*)|^([-a-z0-9\\_]+\.[-a-z0-9.\\_~:\/?\#\[\]@!$&\'\(\)*+,;=%\|]*)|^((?:mailto\:)?([\da-z\._-]+\@[\da-z\._-]+\.[\da-z]{2,4}))/i;
				var matches = email_regex.exec(ctrl.data.url);
				if (matches === null)
					return lmsg('pages.url.error.invalid_url');

				return true;
			};

			siteLinkService.registerDisplayCallback(ctrl.show);
		}
	}
}());