define(['cla_angular', './date_picker.html', 'bootstrap-datetimepicker', 'jquery'], function (angular, template, dp, $) {
	var moduleName = 'cla.core.date_picker';
	var module;
	try {
		module = angular.module(moduleName);
	} catch(err) {
		// named module does not exist, so create one
		module = angular.module(moduleName, []);
	}

	module.directive('claDatePicker', datePicker);

	function datePicker() {
		return {
			restrict: 'E',
			require: '^ngModel',
			//templateUrl: '/intranet/js/angular/cla/date_picker/date_picker.html',
			templateUrl: template,
			scope: {
				ngModel: '=',
                minDate: '@'
			},
			link: function(scope, iElement, iAttrs, ctrl)
			{
                if (typeof iAttrs.minDate === 'undefined')
                    iAttrs.minDate = '1900-01-01';
				scope.id = iAttrs.id;
				scope.name = iAttrs.name;
				scope.placeholder = iAttrs.placeholder;
				scope.ctrl = ctrl;
				var attachToInput = iAttrs.attachToInput;

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

				scope.clickCalendar = function(event)
				{
					event.preventDefault();

					var $el = $('#' + scope.id + '-inner');
					var $pickerInputGroup = $el.closest('.js-datepicker-input-group');
                    var placeholder;

					if (attachToInput)
					{
						// User wants the calendar to be local in the DOM (maybe for modals)
						var $parent = $el.parent();
						placeholder = $parent.find('.js-calendarPlaceholder');
						if (placeholder.length === 0)
						{
							$parent.append('<span class="js-calendarPlaceholder position-absolute"></span>');
							placeholder = $parent.find('.js-calendarPlaceholder');
						}
					} else
					{
						// Make sure the popup doesn't get clipped by anchoring it to a container element on the main page
						placeholder = $('#calendarPlaceholder');
						if (placeholder.length === 0)
						{
							$('body').append('<span id="calendarPlaceholder" class="calendar-placeholder position-absolute"></span>');
							placeholder = $('#calendarPlaceholder');
						}
					}

                    var inputOffset = $pickerInputGroup.offset();

                    placeholder.offset({top: inputOffset.top, left: (inputOffset.left - 38) });
                    placeholder.width($pickerInputGroup.outerWidth());

					var options = {
					    'format': cla_locale.date_format,
                        useCurrent: false,
                        widgetParent: placeholder,
                        widgetPositioning: {
					        horizontal: 'left'
                        }
					};
					if (scope.minDate !== 'false')
                        options.minDate = scope.minDate;
					if (!$el.data('DateTimePicker'))
						$el.datetimepicker(options).on('dp.change', function (e) { jQuery(this).trigger('change'); });
					$el.data('DateTimePicker').show();
					return false;
				};
			}
		};
	}

	return null;
});
