Merge pull request #6982 from eileenmcnaughton/CRM-17412
[civicrm-core.git] / ang / crmMailing / RadioDate.js
1 (function(angular, $, _) {
2 // Represent a datetime field as if it were a radio ('schedule.mode') and a datetime ('schedule.datetime').
3 // example: <div crm-mailing-radio-date="mySchedule" ng-model="mailing.scheduled_date">...</div>
4 angular.module('crmMailing').directive('crmMailingRadioDate', function(crmUiAlert) {
5 return {
6 require: 'ngModel',
7 link: function($scope, element, attrs, ngModel) {
8
9 var schedule = $scope[attrs.crmMailingRadioDate] = {
10 mode: 'now',
11 datetime: ''
12 };
13
14 ngModel.$render = function $render() {
15 var sched = ngModel.$viewValue;
16 if (!_.isEmpty(sched)) {
17 schedule.mode = 'at';
18 schedule.datetime = sched;
19 }
20 else {
21 schedule.mode = 'now';
22 schedule.datetime = '';
23 }
24 };
25
26 var updateParent = (function() {
27 switch (schedule.mode) {
28 case 'now':
29 ngModel.$setViewValue(null);
30 schedule.datetime = '';
31 break;
32 case 'at':
33 schedule.datetime = schedule.datetime || '?';
34 ngModel.$setViewValue(schedule.datetime);
35 break;
36 default:
37 throw 'Unrecognized schedule mode: ' + schedule.mode;
38 }
39 });
40
41 element
42 // Open datepicker when clicking "At" radio
43 .on('click', ':radio[value=at]', function() {
44 $('.crm-form-date', element).focus();
45 })
46 // Reset mode if user entered an invalid date
47 .on('change', '.crm-hidden-date', function(e, context) {
48 if (context === 'userInput' && $(this).val() === '' && $(this).siblings('.crm-form-date').val().length) {
49 schedule.mode = 'at';
50 schedule.datetime = '?';
51 } else {
52 var d = new Date(),
53 month = '' + (d.getMonth() + 1),
54 day = '' + d.getDate(),
55 year = d.getFullYear(),
56 hours = '' + d.getHours(),
57 minutes = '' + d.getMinutes();
58 var submittedDate = $(this).val();
59 if (month.length < 2) month = '0' + month;
60 if (day.length < 2) day = '0' + day;
61 date = [year, month, day].join('-');
62 time = [hours, minutes, "00"].join(':');
63 currentDate = date + ' ' + time;
64 ngModel.$setValidity('dateTimeInThePast', !($(this).val().length && submittedDate < currentDate));
65 if ($(this).val().length && submittedDate < currentDate) {
66 crmUiAlert({
67 text: ts('The scheduled date and time is in the past'),
68 title: ts('Error')
69 });
70 }
71 }
72 });
73
74 $scope.$watch(attrs.crmMailingRadioDate + '.mode', updateParent);
75 $scope.$watch(attrs.crmMailingRadioDate + '.datetime', function(newValue, oldValue) {
76 // automatically switch mode based on datetime entry
77 if (typeof oldValue === 'undefined') {
78 oldValue = '';
79 }
80 if (typeof newValue === 'undefined') {
81 newValue = '';
82 }
83 if (oldValue !== newValue) {
84 if (_.isEmpty(newValue)) {
85 schedule.mode = 'now';
86 }
87 else {
88 schedule.mode = 'at';
89 }
90 }
91 updateParent();
92 });
93 }
94 };
95 });
96 })(angular, CRM.$, CRM._);