CRM-16353 - For tables hidden by collapsed accordions, wait
[civicrm-core.git] / js / Common.js
1 // https://civicrm.org/licensing
2 /* global CRM:true */
3 var CRM = CRM || {};
4 var cj = CRM.$ = jQuery;
5 CRM._ = _;
6
7 /**
8 * Short-named function for string translation, defined in global scope so it's available everywhere.
9 *
10 * @param text string for translating
11 * @param params object key:value of additional parameters
12 *
13 * @return string
14 */
15 function ts(text, params) {
16 "use strict";
17 var d = (params && params.domain) ? ('strings::' + params.domain) : null;
18 if (d && CRM[d] && CRM[d][text]) {
19 text = CRM[d][text];
20 }
21 else if (CRM.strings[text]) {
22 text = CRM.strings[text];
23 }
24 if (typeof(params) === 'object') {
25 for (var i in params) {
26 if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') {
27 // sprintf emulation: escape % characters in the replacements to avoid conflicts
28 text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-'));
29 }
30 }
31 return text.replace(/%-crmescaped-/g, '%');
32 }
33 return text;
34 }
35
36 // Legacy code - ignore warnings
37 /* jshint ignore:start */
38
39 /**
40 * This function is called by default at the bottom of template files which have forms that have
41 * conditionally displayed/hidden sections and elements. The PHP is responsible for generating
42 * a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to
43 * this function.
44 *
45 * @deprecated
46 * @param showBlocks Array of element Id's to be displayed
47 * @param hideBlocks Array of element Id's to be hidden
48 * @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...)
49 */
50 function on_load_init_blocks(showBlocks, hideBlocks, elementType) {
51 if (elementType == null) {
52 elementType = 'block';
53 }
54
55 var myElement, i;
56
57 /* This loop is used to display the blocks whose IDs are present within the showBlocks array */
58 for (i = 0; i < showBlocks.length; i++) {
59 myElement = document.getElementById(showBlocks[i]);
60 /* getElementById returns null if element id doesn't exist in the document */
61 if (myElement != null) {
62 myElement.style.display = elementType;
63 }
64 else {
65 alert('showBlocks array item not in .tpl = ' + showBlocks[i]);
66 }
67 }
68
69 /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
70 for (i = 0; i < hideBlocks.length; i++) {
71 myElement = document.getElementById(hideBlocks[i]);
72 /* getElementById returns null if element id doesn't exist in the document */
73 if (myElement != null) {
74 myElement.style.display = 'none';
75 }
76 else {
77 alert('showBlocks array item not in .tpl = ' + hideBlocks[i]);
78 }
79 }
80 }
81
82 /**
83 * This function is called when we need to show or hide a related form element (target_element)
84 * based on the value (trigger_value) of another form field (trigger_field).
85 *
86 * @deprecated
87 * @param trigger_field_id HTML id of field whose onchange is the trigger
88 * @param trigger_value List of integers - option value(s) which trigger show-element action for target_field
89 * @param target_element_id HTML id of element to be shown or hidden
90 * @param target_element_type Type of element to be shown or hidden ('block' or 'table-row')
91 * @param field_type Type of element radio/select
92 * @param invert Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match
93 */
94 function showHideByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, invert) {
95 var target, j;
96
97 if (field_type == 'select') {
98 var trigger = trigger_value.split("|");
99 var selectedOptionValue = cj('#' + trigger_field_id).val();
100
101 target = target_element_id.split("|");
102 for (j = 0; j < target.length; j++) {
103 if (invert) {
104 cj('#' + target[j]).show();
105 }
106 else {
107 cj('#' + target[j]).hide();
108 }
109 for (var i = 0; i < trigger.length; i++) {
110 if (selectedOptionValue == trigger[i]) {
111 if (invert) {
112 cj('#' + target[j]).hide();
113 }
114 else {
115 cj('#' + target[j]).show();
116 }
117 }
118 }
119 }
120
121 }
122 else {
123 if (field_type == 'radio') {
124 target = target_element_id.split("|");
125 for (j = 0; j < target.length; j++) {
126 if (cj('[name="' + trigger_field_id + '"]:first').is(':checked')) {
127 if (invert) {
128 cj('#' + target[j]).hide();
129 }
130 else {
131 cj('#' + target[j]).show();
132 }
133 }
134 else {
135 if (invert) {
136 cj('#' + target[j]).show();
137 }
138 else {
139 cj('#' + target[j]).hide();
140 }
141 }
142 }
143 }
144 }
145 }
146
147 /**
148 * Function to change button text and disable one it is clicked
149 * @deprecated
150 * @param obj object - the button clicked
151 * @param formID string - the id of the form being submitted
152 * @param string procText - button text after user clicks it
153 * @return bool
154 */
155 var submitcount = 0;
156 /* Changes button label on submit, and disables button after submit for newer browsers.
157 Puts up alert for older browsers. */
158 function submitOnce(obj, formId, procText) {
159 // if named button clicked, change text
160 if (obj.value != null) {
161 cj('input[name=' + obj.name + ']').val(procText + " ...");
162 }
163 cj(obj).closest('form').attr('data-warn-changes', 'false');
164 if (document.getElementById) { // disable submit button for newer browsers
165 cj('input[name=' + obj.name + ']').attr("disabled", true);
166 document.getElementById(formId).submit();
167 return true;
168 }
169 else { // for older browsers
170 if (submitcount == 0) {
171 submitcount++;
172 return true;
173 }
174 else {
175 alert("Your request is currently being processed ... Please wait.");
176 return false;
177 }
178 }
179 }
180
181 /**
182 * Function to show / hide the row in optionFields
183 * @deprecated
184 * @param index string, element whose innerHTML is to hide else will show the hidden row.
185 */
186 function showHideRow(index) {
187 if (index) {
188 cj('tr#optionField_' + index).hide();
189 if (cj('table#optionField tr:hidden:first').length) {
190 cj('div#optionFieldLink').show();
191 }
192 }
193 else {
194 cj('table#optionField tr:hidden:first').show();
195 if (!cj('table#optionField tr:hidden:last').length) {
196 cj('div#optionFieldLink').hide();
197 }
198 }
199 return false;
200 }
201
202 /* jshint ignore:end */
203
204 if (!CRM.utils) CRM.utils = {};
205 if (!CRM.strings) CRM.strings = {};
206 if (!CRM.vars) CRM.vars = {};
207
208 (function ($, _, undefined) {
209 "use strict";
210 /* jshint validthis: true */
211
212 // Theme classes for unattached elements
213 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container';
214
215 // https://github.com/ivaynberg/select2/pull/2090
216 $.fn.select2.defaults.width = 'resolve';
217
218 // Workaround for https://github.com/ivaynberg/select2/issues/1246
219 $.ui.dialog.prototype._allowInteraction = function(e) {
220 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop, .cke_dialog, #civicrm-menu').length;
221 };
222
223 // Implements jQuery hook.prop
224 $.propHooks.disabled = {
225 set: function (el, value, name) {
226 // Sync button enabled status with wrapper css
227 if ($(el).is('span.crm-button > input.crm-form-submit')) {
228 $(el).parent().toggleClass('crm-button-disabled', !!value);
229 }
230 // Sync button enabled status with dialog button
231 if ($(el).is('.ui-dialog input.crm-form-submit')) {
232 $(el).closest('.ui-dialog').find('.ui-dialog-buttonset button[data-identifier='+ $(el).attr('name') +']').prop('disabled', value);
233 }
234 if ($(el).is('.crm-form-date-wrapper .crm-hidden-date')) {
235 $(el).siblings().prop('disabled', value);
236 }
237 }
238 };
239
240 /**
241 * Populate a select list, overwriting the existing options except for the placeholder.
242 * @param select jquery selector - 1 or more select elements
243 * @param options array in format returned by api.getoptions
244 * @param placeholder string|bool - new placeholder or false (default) to keep the old one
245 * @param value string|array - will silently update the element with new value without triggering change
246 */
247 CRM.utils.setOptions = function(select, options, placeholder, value) {
248 $(select).each(function() {
249 var
250 $elect = $(this),
251 val = value || $elect.val() || [],
252 opts = placeholder || placeholder === '' ? '' : '[value!=""]';
253 $elect.find('option' + opts).remove();
254 var newOptions = CRM.utils.renderOptions(options, val);
255 if (typeof placeholder === 'string') {
256 if ($elect.is('[multiple]')) {
257 select.attr('placeholder', placeholder);
258 } else {
259 newOptions = '<option value="">' + placeholder + '</option>' + newOptions;
260 }
261 }
262 $elect.append(newOptions);
263 if (!value) {
264 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
265 }
266 });
267 };
268
269 /**
270 * Render an option list
271 * @param options {array}
272 * @param val {string} default value
273 * @param escapeHtml {bool}
274 * @return string
275 */
276 CRM.utils.renderOptions = function(options, val, escapeHtml) {
277 var rendered = '',
278 esc = escapeHtml === false ? _.identity : _.escape;
279 if (!$.isArray(val)) {
280 val = [val];
281 }
282 _.each(options, function(option) {
283 if (option.children) {
284 rendered += '<optgroup label="' + esc(option.value) + '">' +
285 CRM.utils.renderOptions(option.children, val) +
286 '</optgroup>';
287 } else {
288 var selected = ($.inArray('' + option.key, val) > -1) ? 'selected="selected"' : '';
289 rendered += '<option value="' + esc(option.key) + '"' + selected + '>' + esc(option.value) + '</option>';
290 }
291 });
292 return rendered;
293 };
294
295 function chainSelect() {
296 var $form = $(this).closest('form'),
297 $target = $('select[data-name="' + $(this).data('target') + '"]', $form),
298 data = $target.data(),
299 val = $(this).val();
300 $target.prop('disabled', true);
301 if ($target.is('select.crm-chain-select-control')) {
302 $('select[data-name="' + $target.data('target') + '"]', $form).prop('disabled', true).blur();
303 }
304 if (!(val && val.length)) {
305 CRM.utils.setOptions($target.blur(), [], data.emptyPrompt);
306 } else {
307 $target.addClass('loading');
308 $.getJSON(CRM.url(data.callback), {_value: val}, function(vals) {
309 $target.prop('disabled', false).removeClass('loading');
310 CRM.utils.setOptions($target, vals || [], (vals && vals.length ? data.selectPrompt : data.nonePrompt));
311 });
312 }
313 }
314
315 /**
316 * Compare Form Input values against cached initial value.
317 *
318 * @return {Boolean} true if changes have been made.
319 */
320 CRM.utils.initialValueChanged = function(el) {
321 var isDirty = false;
322 $(':input:visible, .select2-container:visible+:input:hidden', el).not('[type=submit], [type=button], .crm-action-menu, :disabled').each(function () {
323 var
324 initialValue = $(this).data('crm-initial-value'),
325 currentValue = $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val();
326 // skip change of value for submit buttons
327 if (initialValue !== undefined && !_.isEqual(initialValue, currentValue)) {
328 isDirty = true;
329 }
330 });
331 return isDirty;
332 };
333
334 /**
335 * This provides defaults for ui.dialog which either need to be calculated or are different from global defaults
336 *
337 * @param settings
338 * @returns {*}
339 */
340 CRM.utils.adjustDialogDefaults = function(settings) {
341 settings = $.extend({width: '65%', height: '65%', modal: true}, settings || {});
342 // Support relative height
343 if (typeof settings.height === 'string' && settings.height.indexOf('%') > 0) {
344 settings.height = parseInt($(window).height() * (parseFloat(settings.height)/100), 10);
345 }
346 // Responsive adjustment - increase percent width on small screens
347 if (typeof settings.width === 'string' && settings.width.indexOf('%') > 0) {
348 var screenWidth = $(window).width(),
349 percentage = parseInt(settings.width.replace('%', ''), 10),
350 gap = 100-percentage;
351 if (screenWidth < 701) {
352 settings.width = '100%';
353 }
354 else if (screenWidth < 1400) {
355 settings.width = '' + parseInt(percentage+gap-((screenWidth - 700)/7*(gap)/100), 10) + '%';
356 }
357 }
358 return settings;
359 };
360
361 /**
362 * Wrapper for select2 initialization function; supplies defaults
363 * @param options object
364 */
365 $.fn.crmSelect2 = function(options) {
366 if (options === 'destroy') {
367 return $(this).each(function() {
368 $(this)
369 .removeClass('crm-ajax-select')
370 .select2('destroy');
371 });
372 }
373 return $(this).each(function () {
374 var
375 $el = $(this),
376 settings = {allowClear: !$el.hasClass('required')};
377 // quickform doesn't support optgroups so here's a hack :(
378 $('option[value^=crm_optgroup]', this).each(function () {
379 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
380 $(this).remove();
381 });
382
383 // quickform does not support disabled option, so yet another hack to
384 // add disabled property for option values
385 $('option[value^=crm_disabled_opt]', this).attr('disabled', 'disabled');
386
387 // Defaults for single-selects
388 if ($el.is('select:not([multiple])')) {
389 settings.minimumResultsForSearch = 10;
390 if ($('option:first', this).val() === '') {
391 settings.placeholderOption = 'first';
392 }
393 }
394 $.extend(settings, $el.data('select-params') || {}, options || {});
395 if (settings.ajax) {
396 $el.addClass('crm-ajax-select');
397 }
398 $el.select2(settings);
399 });
400 };
401
402 /**
403 * @see CRM_Core_Form::addEntityRef for docs
404 * @param options object
405 */
406 $.fn.crmEntityRef = function(options) {
407 if (options === 'destroy') {
408 return $(this).each(function() {
409 var entity = $(this).data('api-entity') || '';
410 $(this)
411 .off('.crmEntity')
412 .removeClass('crm-form-entityref crm-' + entity.toLowerCase() + '-ref')
413 .crmSelect2('destroy');
414 });
415 }
416 options = options || {};
417 options.select = options.select || {};
418 return $(this).each(function() {
419 var
420 $el = $(this).off('.crmEntity'),
421 entity = options.entity || $el.data('api-entity') || 'contact',
422 selectParams = {};
423 $el.data('api-entity', entity);
424 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
425 $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api));
426 $el.data('create-links', options.create || $el.data('create-links'));
427 $el.addClass('crm-form-entityref crm-' + entity.toLowerCase() + '-ref');
428 var settings = {
429 // Use select2 ajax helper instead of CRM.api3 because it provides more value
430 ajax: {
431 url: CRM.url('civicrm/ajax/rest'),
432 data: function (input, page_num) {
433 var params = getEntityRefApiParams($el);
434 params.input = input;
435 params.page_num = page_num;
436 return {
437 entity: $el.data('api-entity'),
438 action: 'getlist',
439 json: JSON.stringify(params)
440 };
441 },
442 results: function(data) {
443 return {more: data.more_results, results: data.values || []};
444 }
445 },
446 minimumInputLength: 1,
447 formatResult: CRM.utils.formatSelect2Result,
448 formatSelection: function(row) {
449 return (row.prefix !== undefined ? row.prefix + ' ' : '') + row.label + (row.suffix !== undefined ? ' ' + row.suffix : '');
450 },
451 escapeMarkup: function (m) {return m;},
452 initSelection: function($el, callback) {
453 var
454 multiple = !!$el.data('select-params').multiple,
455 val = $el.val(),
456 stored = $el.data('entity-value') || [];
457 if (val === '') {
458 return;
459 }
460 // If we already have this data, just return it
461 if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
462 callback(multiple ? stored : stored[0]);
463 } else {
464 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
465 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
466 callback(multiple ? result.values : result.values[0]);
467 // Trigger change (store data to avoid an infinite loop of lookups)
468 $el.data('entity-value', result.values).trigger('change');
469 });
470 }
471 }
472 };
473 // Create new items inline - works for tags
474 if ($el.data('create-links') && entity.toLowerCase() === 'tag') {
475 selectParams.createSearchChoice = function(term, data) {
476 if (!_.findKey(data, {label: term})) {
477 return {id: "0", term: term, label: term + ' (' + ts('new tag') + ')'};
478 }
479 };
480 selectParams.tokenSeparators = [','];
481 selectParams.createSearchChoicePosition = 'bottom';
482 $el.on('select2-selecting.crmEntity', function(e) {
483 if (e.val === "0") {
484 // Create a new term
485 e.object.label = e.object.term;
486 CRM.api3(entity, 'create', $.extend({name: e.object.term}, $el.data('api-params').params || {}))
487 .done(function(created) {
488 var
489 val = $el.select2('val'),
490 data = $el.select2('data'),
491 item = {id: created.id, label: e.object.term};
492 if (val === "0") {
493 $el.select2('data', item, true);
494 }
495 else if ($.isArray(val) && $.inArray("0", val) > -1) {
496 _.remove(data, {id: "0"});
497 data.push(item);
498 $el.select2('data', data, true);
499 }
500 });
501 }
502 });
503 }
504 else {
505 selectParams.formatInputTooShort = function() {
506 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
507 txt += renderEntityRefFilters($el) + renderEntityRefCreateLinks($el);
508 return txt;
509 };
510 selectParams.formatNoMatches = function() {
511 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
512 txt += renderEntityRefFilters($el) + renderEntityRefCreateLinks($el);
513 return txt;
514 };
515 $el.on('select2-open.crmEntity', function() {
516 var $el = $(this);
517 loadEntityRefFilterOptions($el);
518 $('#select2-drop')
519 .off('.crmEntity')
520 .on('click.crmEntity', 'a.crm-add-entity', function(e) {
521 $el.select2('close');
522 CRM.loadForm($(this).attr('href'), {
523 dialog: {width: 500, height: 220}
524 }).on('crmFormSuccess', function(e, data) {
525 if (data.status === 'success' && data.id) {
526 CRM.status(ts('%1 Created', {1: data.label}));
527 if ($el.select2('container').hasClass('select2-container-multi')) {
528 var selection = $el.select2('data');
529 selection.push(data);
530 $el.select2('data', selection, true);
531 } else {
532 $el.select2('data', data, true);
533 }
534 }
535 });
536 return false;
537 })
538 .on('change.crmEntity', 'select.crm-entityref-filter-value', function() {
539 var filter = $el.data('user-filter') || {};
540 filter.value = $(this).val();
541 $(this).toggleClass('active', !!filter.value);
542 $el.data('user-filter', filter);
543 if (filter.value) {
544 // Once a filter has been chosen, rerender create links and refocus the search box
545 $el.select2('close');
546 $el.select2('open');
547 }
548 })
549 .on('change.crmEntity', 'select.crm-entityref-filter-key', function() {
550 var filter = $el.data('user-filter') || {};
551 filter.key = $(this).val();
552 $(this).toggleClass('active', !!filter.key);
553 $el.data('user-filter', filter);
554 loadEntityRefFilterOptions($el);
555 });
556 });
557 }
558 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams));
559 });
560 };
561
562 /**
563 * Combine api-params with user-filter
564 * @param $el
565 * @returns {*}
566 */
567 function getEntityRefApiParams($el) {
568 var
569 params = $.extend({params: {}}, $el.data('api-params') || {}),
570 // Prevent original data from being modified - $.extend and _.clone don't cut it, they pass nested objects by reference!
571 combined = _.cloneDeep(params),
572 filter = $.extend({}, $el.data('user-filter') || {});
573 if (filter.key && filter.value) {
574 // Special case for contact type/sub-type combo
575 if (filter.key === 'contact_type' && (filter.value.indexOf('__') > 0)) {
576 combined.params.contact_type = filter.value.split('__')[0];
577 combined.params.contact_sub_type = filter.value.split('__')[1];
578 } else {
579 // Allow json-encoded api filters e.g. {"BETWEEN":[123,456]}
580 combined.params[filter.key] = filter.value.charAt(0) === '{' ? $.parseJSON(filter.value) : filter.value;
581 }
582 }
583 return combined;
584 }
585
586 function copyAttributes($source, $target, attributes) {
587 _.each(attributes, function(name) {
588 if ($source.attr(name)) {
589 $target.attr(name, $source.attr(name));
590 }
591 });
592 }
593
594 $.fn.crmDatepicker = function(options) {
595 return $(this).each(function() {
596 if ($(this).is('.crm-form-date-wrapper .crm-hidden-date')) {
597 // Already initialized
598 return;
599 }
600 var
601 $dataField = $(this).wrap('<span class="crm-form-date-wrapper" />'),
602 settings = $.extend({}, $dataField.data('datepicker') || {}, options || {}),
603 $dateField = $(),
604 $timeField = $(),
605 $clearLink = $();
606
607 if (settings.allowClear !== undefined ? settings.allowClear : !$dataField.hasClass('required')) {
608 $clearLink = $('<a class="crm-hover-button crm-clear-link" title="'+ ts('Clear') +'"><span class="icon ui-icon-close"></span></a>')
609 .insertAfter($dataField);
610 }
611 if (settings.time !== false) {
612 $timeField = $('<input>').insertAfter($dataField);
613 copyAttributes($dataField, $timeField, ['class', 'disabled']);
614 $timeField
615 .addClass('crm-form-text crm-form-time')
616 .attr('placeholder', $dataField.attr('time-placeholder') === undefined ? ts('Time') : $dataField.attr('time-placeholder'))
617 .change(updateDataField)
618 .timeEntry({
619 spinnerImage: '',
620 show24Hours: settings.time === true || settings.time === undefined ? CRM.config.timeIs24Hr : settings.time == '24'
621 });
622 }
623 if (settings.date !== false) {
624 $dateField = $('<input>').insertAfter($dataField);
625 copyAttributes($dataField, $dateField, ['placeholder', 'style', 'class', 'disabled']);
626 $dateField.addClass('crm-form-text crm-form-date');
627 settings.dateFormat = settings.dateFormat || CRM.config.dateInputFormat;
628 settings.changeMonth = _.includes('m', settings.dateFormat);
629 settings.changeYear = _.includes('y', settings.dateFormat);
630 $dateField.datepicker(settings).change(updateDataField);
631 }
632 // Rudimentary validation. TODO: Roll into use of jQUery validate and ui.datepicker.validation
633 function isValidDate() {
634 try {
635 $.datepicker.parseDate(settings.dateFormat, $dateField.val());
636 return true;
637 } catch (e) {
638 return false;
639 }
640 }
641 function updateInputFields(e, context) {
642 var val = $dataField.val(),
643 time = null;
644 if (context !== 'userInput' && context !== 'crmClear') {
645 if ($dateField.length) {
646 $dateField.datepicker('setDate', _.includes(val, '-') ? $.datepicker.parseDate('yy-mm-dd', val) : null);
647 }
648 if ($timeField.length) {
649 if (val.length === 8) {
650 time = val;
651 } else if (val.length === 19) {
652 time = val.split(' ')[1];
653 }
654 $timeField.timeEntry('setTime', time);
655 }
656 }
657 $clearLink.css('visibility', val ? 'visible' : 'hidden');
658 }
659 function updateDataField(e, context) {
660 // The crmClear event wipes all the field values anyway, so no need to respond
661 if (context !== 'crmClear') {
662 var val = '';
663 if ($dateField.val()) {
664 if (isValidDate()) {
665 val = $.datepicker.formatDate('yy-mm-dd', $dateField.datepicker('getDate'));
666 $dateField.removeClass('crm-error');
667 } else {
668 $dateField.addClass('crm-error');
669 }
670 }
671 if ($timeField.val()) {
672 val += (val ? ' ' : '') + $timeField.timeEntry('getTime').toTimeString().substr(0, 8);
673 }
674 $dataField.val(val).trigger('change', ['userInput']);
675 }
676 }
677 $dataField.hide().addClass('crm-hidden-date').on('change', updateInputFields);
678 updateInputFields();
679 });
680 };
681
682 $.fn.crmAjaxTable = function() {
683 return $(this).each(function() {
684 //Declare the defaults for DataTables
685 var defaults = {
686 "processing": true,
687 "serverSide": true,
688 "dom": '<"crm-datatable-pager-top"lfp>rt<"crm-datatable-pager-bottom"ip>',
689 "pageLength": 25,
690 "drawCallback": function(settings) {
691 //Add data attributes to cells
692 $('thead th', settings.nTable).each( function( index ) {
693 $.each(this.attributes, function() {
694 if(this.name.match("^cell-")) {
695 var cellAttr = this.name.substring(5);
696 var cellValue = this.value;
697 $('tbody tr', settings.nTable).each( function() {
698 $('td:eq('+ index +')', this).attr( cellAttr, cellValue );
699 });
700 }
701 });
702 });
703 //Reload table after draw
704 $(settings.nTable).trigger('crmLoad');
705 }
706 };
707 //Include any table specific data
708 var settings = $.extend(true, defaults, $(this).data('table'));
709 //Make the DataTables call
710 $(this).DataTable(settings);
711 });
712 };
713
714 CRM.utils.formatSelect2Result = function (row) {
715 var markup = '<div class="crm-select2-row">';
716 if (row.image !== undefined) {
717 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
718 }
719 else if (row.icon_class) {
720 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
721 }
722 markup += '<div><div class="crm-select2-row-label '+(row.label_class || '')+'">' +
723 (row.prefix !== undefined ? row.prefix + ' ' : '') + row.label + (row.suffix !== undefined ? ' ' + row.suffix : '') +
724 '</div>' +
725 '<div class="crm-select2-row-description">';
726 $.each(row.description || [], function(k, text) {
727 markup += '<p>' + text + '</p>';
728 });
729 markup += '</div></div></div>';
730 return markup;
731 };
732
733 function renderEntityRefCreateLinks($el) {
734 var
735 createLinks = $el.data('create-links'),
736 params = getEntityRefApiParams($el).params,
737 markup = '<div class="crm-entityref-links">';
738 if (!createLinks || $el.data('api-entity').toLowerCase() !== 'contact') {
739 return '';
740 }
741 if (createLinks === true) {
742 createLinks = params.contact_type ? _.where(CRM.config.entityRef.contactCreate, {type: params.contact_type}) : CRM.config.entityRef.contactCreate;
743 }
744 _.each(createLinks, function(link) {
745 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
746 if (link.type) {
747 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
748 }
749 markup += link.label + '</a>';
750 });
751 markup += '</div>';
752 return markup;
753 }
754
755 function getEntityRefFilters($el) {
756 var
757 entity = $el.data('api-entity').toLowerCase(),
758 filters = $.extend([], CRM.config.entityRef.filters[entity] || []),
759 filter = $el.data('user-filter') || {},
760 params = $.extend({params: {}}, $el.data('api-params') || {}).params,
761 result = [];
762 $.each(filters, function() {
763 if (typeof params[this.key] === 'undefined') {
764 result.push(this);
765 }
766 else if (this.key == 'contact_type' && typeof params.contact_sub_type === 'undefined') {
767 this.options = _.remove(this.options, function(option) {
768 return option.key.indexOf(params.contact_type + '__') === 0;
769 });
770 result.push(this);
771 }
772 });
773 return result;
774 }
775
776 function renderEntityRefFilters($el) {
777 var
778 filters = getEntityRefFilters($el),
779 filter = $el.data('user-filter') || {},
780 filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null;
781 if (!filters.length) {
782 return '';
783 }
784 var markup = '<div class="crm-entityref-filters">' +
785 '<select class="crm-entityref-filter-key' + (filter.key ? ' active' : '') + '">' +
786 '<option value="">' + ts('Refine search...') + '</option>' +
787 CRM.utils.renderOptions(filters, filter.key) +
788 '</select> &nbsp; ' +
789 '<select class="crm-entityref-filter-value' + (filter.key ? ' active"' : '"') + (filter.key ? '' : ' style="display:none;"') + '>' +
790 '<option value="">' + ts('- select -') + '</option>';
791 if (filterSpec && filterSpec.options) {
792 markup += CRM.utils.renderOptions(filterSpec.options, filter.value);
793 }
794 markup += '</select></div>';
795 return markup;
796 }
797
798 /**
799 * Fetch options for a filter (via ajax if necessary) and populate the appropriate select list
800 * @param $el
801 */
802 function loadEntityRefFilterOptions($el) {
803 var
804 filters = getEntityRefFilters($el),
805 filter = $el.data('user-filter') || {},
806 filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null,
807 $valField = $('.crm-entityref-filter-value', '#select2-drop');
808 if (filterSpec) {
809 $valField.show().val('');
810 if (filterSpec.options) {
811 CRM.utils.setOptions($valField, filterSpec.options, false, filter.value);
812 } else {
813 $valField.prop('disabled', true);
814 CRM.api3(filterSpec.entity || $el.data('api-entity'), 'getoptions', {field: filter.key, context: 'search', sequential: 1})
815 .done(function(result) {
816 var entity = $el.data('api-entity').toLowerCase(),
817 globalFilterSpec = _.find(CRM.config.entityRef.filters[entity], {key: filter.key}) || {};
818 // Store options globally so we don't have to look them up again
819 globalFilterSpec.options = result.values;
820 $valField.prop('disabled', false);
821 CRM.utils.setOptions($valField, result.values);
822 $valField.val(filter.value || '');
823 });
824 }
825 } else {
826 $valField.hide();
827 }
828 }
829
830 //CRM-15598 - Override url validator method to allow relative url's (e.g. /index.htm)
831 $.validator.addMethod("url", function(value, element) {
832 if (/^\//.test(value)) {
833 // Relative url: prepend dummy path for validation.
834 value = 'http://domain.tld' + value;
835 }
836 // From jQuery Validation Plugin v1.12.0
837 return this.optional(element) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
838 });
839
840 /**
841 * Wrapper for jQuery validate initialization function; supplies defaults
842 */
843 $.fn.crmValidate = function(params) {
844 return $(this).each(function () {
845 var that = this,
846 settings = $.extend({}, CRM.validate._defaults, CRM.validate.params);
847 $(this).validate(settings);
848 // Call any post-initialization callbacks
849 if (CRM.validate.functions && CRM.validate.functions.length) {
850 $.each(CRM.validate.functions, function(i, func) {
851 func.call(that);
852 });
853 }
854 });
855 };
856
857 // Initialize widgets
858 $(document)
859 .on('crmLoad', function(e) {
860 $('table.row-highlight', e.target)
861 .off('.rowHighlight')
862 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) {
863 var filter, $table = $(this).closest('table');
864 if ($(this).hasClass('select-rows')) {
865 filter = $(this).prop('checked') ? ':not(:checked)' : ':checked';
866 $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
867 }
868 else {
869 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
870 if (data !== 'master-selected') {
871 $('input.select-rows', $table).prop('checked', $(".select-row:not(':checked')", $table).length < 1);
872 }
873 }
874 })
875 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
876 $('table.crm-sortable', e.target).DataTable();
877 $('table.crm-ajax-table', e.target).each(function() {
878 var
879 $table = $(this),
880 $accordion = $table.closest('.crm-accordion-wrapper.collapsed, .crm-collapsible.collapsed');
881 // For tables hidden by collapsed accordions, wait.
882 if ($accordion.length) {
883 $accordion.one('crmAccordion:open', function() {
884 $table.crmAjaxTable();
885 });
886 } else {
887 $table.crmAjaxTable();
888 }
889 });
890 if ($("input:radio[name=radio_ts]").size() == 1) {
891 $("input:radio[name=radio_ts]").prop("checked", true);
892 }
893 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
894 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
895 $('select.crm-chain-select-control', e.target).off('.chainSelect').on('change.chainSelect', chainSelect);
896 // Cache Form Input initial values
897 $('form[data-warn-changes] :input', e.target).each(function() {
898 $(this).data('crm-initial-value', $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val());
899 });
900 $('textarea.crm-form-wysiwyg', e.target)
901 .not('.crm-wysiwyg-enabled')
902 .addClass('crm-wysiwyg-enabled')
903 .each(function() {
904 if ($(this).hasClass("collapsed")) {
905 CRM.wysiwyg.createCollapsed(this);
906 } else {
907 CRM.wysiwyg.create(this);
908 }
909 });
910 })
911 .on('dialogopen', function(e) {
912 var $el = $(e.target);
913 // Modal dialogs should disable scrollbars
914 if ($el.dialog('option', 'modal')) {
915 $el.addClass('modal-dialog');
916 $('body').css({overflow: 'hidden'});
917 }
918 // Add resize button
919 if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) {
920 $el.parent().find('.ui-dialog-titlebar').append($('<button class="crm-dialog-titlebar-resize ui-dialog-titlebar-close" title="'+ts('Toggle fullscreen')+'" style="right:2em;"/>').button({icons: {primary: 'ui-icon-newwin'}, text: false}));
921 $('.crm-dialog-titlebar-resize', $el.parent()).click(function(e) {
922 if ($el.data('origSize')) {
923 $el.dialog('option', $el.data('origSize'));
924 $el.data('origSize', null);
925 } else {
926 var menuHeight = $('#civicrm-menu').outerHeight();
927 $el.data('origSize', {
928 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
929 width: $el.dialog('option', 'width'),
930 height: $el.dialog('option', 'height')
931 });
932 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: {my: "top", at: "top+"+menuHeight, of: window}});
933 }
934 $el.trigger('dialogresize');
935 e.preventDefault();
936 });
937 }
938 })
939 .on('dialogclose', function(e) {
940 // Restore scrollbars when closing modal
941 if ($('.ui-dialog .modal-dialog:visible').not(e.target).length < 1) {
942 $('body').css({overflow: ''});
943 }
944 })
945 .on('submit', function(e) {
946 // CRM-14353 - disable changes warn when submitting a form
947 $('[data-warn-changes]').attr('data-warn-changes', 'false');
948 });
949
950 // CRM-14353 - Warn of unsaved changes for forms which have opted in
951 window.onbeforeunload = function() {
952 if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
953 return ts('You have unsaved changes.');
954 }
955 };
956
957 $.fn.crmtooltip = function () {
958 $(document)
959 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
960 $(this).addClass('crm-processed crm-tooltip-active');
961 var topDistance = e.pageY - $(window).scrollTop();
962 if (topDistance < 300 || topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
963 $(this).addClass('crm-tooltip-down');
964 }
965 if (!$(this).children('.crm-tooltip-wrapper').length) {
966 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
967 $(this).children().children('.crm-tooltip')
968 .html('<div class="crm-loading-element"></div>')
969 .load(this.href);
970 }
971 })
972 .on('mouseout', 'a.crm-summary-link', function () {
973 $(this).removeClass('crm-processed crm-tooltip-active crm-tooltip-down');
974 })
975 .on('click', 'a.crm-summary-link', false);
976 };
977
978 var helpDisplay, helpPrevious;
979 CRM.help = function (title, params, url) {
980 if (helpDisplay && helpDisplay.close) {
981 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
982 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
983 helpDisplay.close();
984 return;
985 }
986 helpDisplay.close();
987 }
988 helpPrevious = JSON.stringify(params);
989 params.class_name = 'CRM_Core_Page_Inline_Help';
990 params.type = 'page';
991 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
992 $.ajax(url || CRM.url('civicrm/ajax/inline'),
993 {
994 data: params,
995 dataType: 'html',
996 success: function (data) {
997 $('#crm-notification-container .crm-help .notify-content:last').html(data);
998 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
999 },
1000 error: function () {
1001 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
1002 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
1003 }
1004 }
1005 );
1006 };
1007 /**
1008 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1009 */
1010 CRM.status = function(options, deferred) {
1011 // For simple usage without async operations you can pass in a string. 2nd param is optional string 'error' if this is not a success msg.
1012 if (typeof options === 'string') {
1013 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
1014 }
1015 var opts = $.extend({
1016 start: ts('Saving...'),
1017 success: ts('Saved'),
1018 error: function(data) {
1019 var msg = $.isPlainObject(data) && data.error_message;
1020 CRM.alert(msg || ts('Sorry an error occurred and your information was not saved'), ts('Error'), 'error');
1021 }
1022 }, options || {});
1023 var $msg = $('<div class="crm-status-box-outer status-start"><div class="crm-status-box-inner"><div class="crm-status-box-msg">' + opts.start + '</div></div></div>')
1024 .appendTo('body');
1025 $msg.css('min-width', $msg.width());
1026 function handle(status, data) {
1027 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
1028 if (endMsg) {
1029 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg);
1030 window.setTimeout(function() {
1031 $msg.fadeOut('slow', function() {
1032 $msg.remove();
1033 });
1034 }, 2000);
1035 } else {
1036 $msg.remove();
1037 }
1038 }
1039 return (deferred || new $.Deferred())
1040 .done(function(data) {
1041 // If the server returns an error msg call the error handler
1042 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
1043 handle(status, data);
1044 })
1045 .fail(function(data) {
1046 handle('error', data);
1047 });
1048 };
1049
1050 // Convert an Angular promise to a jQuery promise
1051 CRM.toJqPromise = function(aPromise) {
1052 var jqDeferred = $.Deferred();
1053 aPromise.then(
1054 function(data) { jqDeferred.resolve(data); },
1055 function(data) { jqDeferred.reject(data); }
1056 // should we also handle progress events?
1057 );
1058 return jqDeferred.promise();
1059 };
1060
1061 CRM.toAPromise = function($q, jqPromise) {
1062 var aDeferred = $q.defer();
1063 jqPromise.then(
1064 function(data) { aDeferred.resolve(data); },
1065 function(data) { aDeferred.reject(data); }
1066 // should we also handle progress events?
1067 );
1068 return aDeferred.promise;
1069 };
1070
1071 /**
1072 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1073 */
1074 CRM.alert = function (text, title, type, options) {
1075 type = type || 'alert';
1076 title = title || '';
1077 options = options || {};
1078 if ($('#crm-notification-container').length) {
1079 var params = {
1080 text: text,
1081 title: title,
1082 type: type
1083 };
1084 // By default, don't expire errors and messages containing links
1085 var extra = {
1086 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
1087 unique: true
1088 };
1089 options = $.extend(extra, options);
1090 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
1091 if (options.unique && options.unique !== '0') {
1092 $('#crm-notification-container .ui-notify-message').each(function () {
1093 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
1094 $('.icon.ui-notify-close', this).click();
1095 }
1096 });
1097 }
1098 return $('#crm-notification-container').notify('create', params, options);
1099 }
1100 else {
1101 if (title.length) {
1102 text = title + "\n" + text;
1103 }
1104 alert(text);
1105 return null;
1106 }
1107 };
1108
1109 /**
1110 * Close whichever alert contains the given node
1111 *
1112 * @param node
1113 */
1114 CRM.closeAlertByChild = function (node) {
1115 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
1116 };
1117
1118 /**
1119 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1120 */
1121 CRM.confirm = function (options) {
1122 var dialog, url, msg, buttons = [], settings = {
1123 title: ts('Confirm'),
1124 message: ts('Are you sure you want to continue?'),
1125 url: null,
1126 width: 'auto',
1127 height: 'auto',
1128 resizable: false,
1129 dialogClass: 'crm-container crm-confirm',
1130 close: function () {
1131 $(this).dialog('destroy').remove();
1132 },
1133 options: {
1134 no: ts('Cancel'),
1135 yes: ts('Continue')
1136 }
1137 };
1138 if (options && options.url) {
1139 settings.resizable = true;
1140 settings.height = '50%';
1141 }
1142 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
1143 settings = CRM.utils.adjustDialogDefaults(settings);
1144 if (!settings.buttons && $.isPlainObject(settings.options)) {
1145 $.each(settings.options, function(op, label) {
1146 buttons.push({
1147 text: label,
1148 'data-op': op,
1149 icons: {primary: op === 'no' ? 'ui-icon-close' : 'ui-icon-check'},
1150 click: function() {
1151 var event = $.Event('crmConfirm:' + op);
1152 $(this).trigger(event);
1153 if (!event.isDefaultPrevented()) {
1154 dialog.dialog('close');
1155 }
1156 }
1157 });
1158 });
1159 // Order buttons so that "no" goes on the right-hand side
1160 settings.buttons = _.sortBy(buttons, 'data-op').reverse();
1161 }
1162 url = settings.url;
1163 msg = url ? '' : settings.message;
1164 delete settings.options;
1165 delete settings.message;
1166 delete settings.url;
1167 dialog = $('<div class="crm-confirm-dialog"></div>').html(msg || '').dialog(settings);
1168 if ($.isFunction(options)) {
1169 dialog.on('crmConfirm:yes', options);
1170 }
1171 if (url) {
1172 CRM.loadPage(url, {target: dialog});
1173 }
1174 else {
1175 dialog.trigger('crmLoad');
1176 }
1177 return dialog;
1178 };
1179
1180 /** provides a local copy of ts for a domain */
1181 CRM.ts = function(domain) {
1182 return function(message, options) {
1183 if (domain) {
1184 options = $.extend(options || {}, {domain: domain});
1185 }
1186 return ts(message, options);
1187 };
1188 };
1189
1190 CRM.addStrings = function(domain, strings) {
1191 var bucket = (domain == 'civicrm' ? 'strings' : 'strings::' + domain);
1192 CRM[bucket] = CRM[bucket] || {};
1193 _.extend(CRM[bucket], strings);
1194 };
1195
1196 /**
1197 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1198 */
1199 $.fn.crmError = function (text, title, options) {
1200 title = title || '';
1201 text = text || '';
1202 options = options || {};
1203
1204 var extra = {
1205 expires: 0
1206 };
1207 if ($(this).length) {
1208 if (title === '') {
1209 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
1210 if (label.length) {
1211 label.addClass('crm-error');
1212 var $label = label.clone();
1213 if (text === '' && $('.crm-marker', $label).length > 0) {
1214 text = $('.crm-marker', $label).attr('title');
1215 }
1216 $('.crm-marker', $label).remove();
1217 title = $label.text();
1218 }
1219 }
1220 $(this).addClass('crm-error');
1221 }
1222 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
1223 if ($(this).length) {
1224 var ele = $(this);
1225 setTimeout(function () {
1226 ele.one('change', function () {
1227 if (msg && msg.close) msg.close();
1228 ele.removeClass('error');
1229 label.removeClass('crm-error');
1230 });
1231 }, 1000);
1232 }
1233 return msg;
1234 };
1235
1236 // Display system alerts through js notifications
1237 function messagesFromMarkup() {
1238 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
1239 var text, title = '';
1240 $(this).removeClass('status messages');
1241 var type = $(this).attr('class').split(' ')[0] || 'alert';
1242 type = type.replace('crm-', '');
1243 $('.icon', this).remove();
1244 if ($('.msg-text', this).length > 0) {
1245 text = $('.msg-text', this).html();
1246 title = $('.msg-title', this).html();
1247 }
1248 else {
1249 text = $(this).html();
1250 }
1251 var options = $(this).data('options') || {};
1252 $(this).remove();
1253 // Duplicates were already removed server-side
1254 options.unique = false;
1255 CRM.alert(text, title, type, options);
1256 });
1257 // Handle qf form errors
1258 $('form :input.error', this).one('blur', function() {
1259 $('.ui-notify-message.error a.ui-notify-close').click();
1260 $(this).removeClass('error');
1261 $(this).next('span.crm-error').remove();
1262 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
1263 .removeClass('crm-error')
1264 .find('.crm-error').removeClass('crm-error');
1265 });
1266 }
1267
1268 /**
1269 * Improve blockUI when used with jQuery dialog
1270 */
1271 var originalBlock = $.fn.block,
1272 originalUnblock = $.fn.unblock;
1273
1274 $.fn.block = function(opts) {
1275 if ($(this).is('.ui-dialog-content')) {
1276 originalBlock.call($(this).parents('.ui-dialog'), opts);
1277 return $(this);
1278 }
1279 return originalBlock.call(this, opts);
1280 };
1281 $.fn.unblock = function(opts) {
1282 if ($(this).is('.ui-dialog-content')) {
1283 originalUnblock.call($(this).parents('.ui-dialog'), opts);
1284 return $(this);
1285 }
1286 return originalUnblock.call(this, opts);
1287 };
1288
1289 // Preprocess all CRM ajax calls to display messages
1290 $(document).ajaxSuccess(function(event, xhr, settings) {
1291 try {
1292 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
1293 var response = $.parseJSON(xhr.responseText);
1294 if (typeof(response.crmMessages) == 'object') {
1295 $.each(response.crmMessages, function(n, msg) {
1296 CRM.alert(msg.text, msg.title, msg.type, msg.options);
1297 });
1298 }
1299 if (response.backtrace) {
1300 CRM.console('log', response.backtrace);
1301 }
1302 if (typeof response.deprecated === 'string') {
1303 CRM.console('warn', response.deprecated);
1304 }
1305 }
1306 }
1307 // Ignore errors thrown by parseJSON
1308 catch (e) {}
1309 });
1310
1311 $(function () {
1312 $.blockUI.defaults.message = null;
1313 $.blockUI.defaults.ignoreIfBlocked = true;
1314
1315 if ($('#crm-container').hasClass('crm-public')) {
1316 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container crm-public';
1317 }
1318
1319 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1320 $('.crm-container').trigger('crmLoad');
1321
1322 if ($('#crm-notification-container').length) {
1323 // Initialize notifications
1324 $('#crm-notification-container').notify();
1325 messagesFromMarkup.call($('#crm-container'));
1326 }
1327
1328 $('body')
1329 // bind the event for image popup
1330 .on('click', 'a.crm-image-popup', function(e) {
1331 CRM.confirm({
1332 title: ts('Preview'),
1333 resizable: true,
1334 // Prevent overlap with the menubar
1335 maxHeight: $(window).height() - 30,
1336 position: {my: 'center', at: 'center center+15', of: window},
1337 message: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
1338 options: null
1339 });
1340 e.preventDefault();
1341 })
1342
1343 .on('click', function (event) {
1344 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1345 if ($(event.target).is('.btn-slide')) {
1346 $(event.target).addClass('btn-slide-active').find('.panel').show();
1347 }
1348 })
1349
1350 // Handle clear button for form elements
1351 .on('click', 'a.crm-clear-link', function() {
1352 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).trigger('change', ['crmClear']);
1353 $(this).siblings('input:text').val('').trigger('change', ['crmClear']);
1354 return false;
1355 })
1356 .on('change', 'input.crm-form-radio:checked', function() {
1357 $(this).siblings('.crm-clear-link').css({visibility: ''});
1358 })
1359
1360 // Allow normal clicking of links within accordions
1361 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
1362 e.stopPropagation();
1363 })
1364 // Handle accordions
1365 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
1366 var action = 'open';
1367 if ($(this).parent().hasClass('collapsed')) {
1368 $(this).next().css('display', 'none').slideDown(200);
1369 }
1370 else {
1371 $(this).next().css('display', 'block').slideUp(200);
1372 action = 'close';
1373 }
1374 $(this).parent().toggleClass('collapsed').trigger('crmAccordion:' + action);
1375 e.preventDefault();
1376 });
1377
1378 $().crmtooltip();
1379 });
1380
1381 /**
1382 * Collapse or expand an accordion
1383 * @param speed
1384 */
1385 $.fn.crmAccordionToggle = function (speed) {
1386 $(this).each(function () {
1387 var action = 'open';
1388 if ($(this).hasClass('collapsed')) {
1389 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
1390 }
1391 else {
1392 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1393 action = 'close';
1394 }
1395 $(this).toggleClass('collapsed').trigger('crmAccordion:' + action);
1396 });
1397 };
1398
1399 /**
1400 * Clientside currency formatting
1401 * @param number value
1402 * @param [optional] boolean onlyNumber - if true, we return formatted amount without currency sign
1403 * @param [optional] string format - currency representation of the number 1234.56
1404 * @return string
1405 */
1406 var currencyTemplate;
1407 CRM.formatMoney = function(value, onlyNumber, format) {
1408 var decimal, separator, sign, i, j, result;
1409 if (value === 'init' && format) {
1410 currencyTemplate = format;
1411 return;
1412 }
1413 format = format || currencyTemplate;
1414 result = /1(.?)234(.?)56/.exec(format);
1415 if (result === null) {
1416 return 'Invalid format passed to CRM.formatMoney';
1417 }
1418 separator = result[1];
1419 decimal = result[2];
1420 sign = (value < 0) ? '-' : '';
1421 //extracting the absolute value of the integer part of the number and converting to string
1422 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
1423 j = ((j = i.length) > 3) ? j % 3 : 0;
1424 result = sign + (j ? i.substr(0, j) + separator : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + separator) + (2 ? decimal + Math.abs(value - i).toFixed(2).slice(2) : '');
1425 if ( onlyNumber ) {
1426 return result;
1427 }
1428 return format.replace(/1.*234.*56/, result);
1429 };
1430
1431 CRM.console = function(method, title, msg) {
1432 if (window.console) {
1433 method = $.isFunction(console[method]) ? method : 'log';
1434 if (msg === undefined) {
1435 return console[method](title);
1436 } else {
1437 return console[method](title, msg);
1438 }
1439 }
1440 };
1441
1442 // Determine if a user has a given permission.
1443 // @see CRM_Core_Resources::addPermissions
1444 CRM.checkPerm = function(perm) {
1445 return CRM.permissions[perm];
1446 };
1447
1448 // Round while preserving sigfigs
1449 CRM.utils.sigfig = function(n, digits) {
1450 var len = ("" + n).length;
1451 var scale = Math.pow(10.0, len-digits);
1452 return Math.round(n / scale) * scale;
1453 };
1454 })(jQuery, _);