define(['cla_angular', './colour_picker.html', 'jquery', 'colour_picker'], function (angular, template) {
	var moduleName = 'cla.core.colour_picker';
	var module;

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

	module
		.directive('claColourPicker', claColourPicker);

	claColourPicker.$inject = ['$timeout'];
	function claColourPicker($timeout)
	{
		return {
			restrict: 'E',
			require: '^ngModel',
			templateUrl: template,
			scope: {
				ngModel: '=',
				control: '='
			},
			link: link
		};

		function link(scope, iElement, iAttrs, ctrl)
		{
			var $elem = angular.element(iElement).find('input');

			// Compatibility with Pages settings if needed
			if (window.cla.pagesEdit !== undefined)
			{
				$elem.on('kolorPickerOpen', function()
				{
					window.cla.pagesEdit.popoverAutoClose = false;
				});
				$elem.on('kolorPickerClose', function()
				{
					window.cla.pagesEdit.popoverAutoClose = true;
				});
			}

			$elem.trigger('kolorPickerUpdate');

			// Set the initial colour
			$timeout(function()
			{
				$elem.trigger('init');
			}, 0);

			scope.id = iAttrs.id;

			ctrl.$viewChangeListeners.push(function()
			{
				scope.$eval(iAttrs.ngChange);
			});

			scope.internalControl = scope.control || {};
			scope.internalControl.reset = function()
			{
				$timeout(function ()
				{
					$elem.trigger('init');
				}, 0);
			};
		}
	}
});