Merge pull request #6943 from totten/master-navmenu
[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 /**
595 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/crmDatepicker
596 */
597 $.fn.crmDatepicker = function(options) {
598 return $(this).each(function() {
599 if ($(this).is('.crm-form-date-wrapper .crm-hidden-date')) {
600 // Already initialized
601 return;
602 }
603 var
604 $dataField = $(this).wrap('<span class="crm-form-date-wrapper" />'),
605 settings = $.extend({}, $dataField.data('datepicker') || {}, options || {}),
606 $dateField = $(),
607 $timeField = $(),
608 $clearLink = $();
609
610 if (settings.allowClear !== undefined ? settings.allowClear : !$dataField.is('.required, [required]')) {
611 $clearLink = $('<a class="crm-hover-button crm-clear-link" title="'+ ts('Clear') +'"><i class="crm-i fa-times"></i></a>')
612 .insertAfter($dataField);
613 }
614 if (settings.time !== false) {
615 $timeField = $('<input>').insertAfter($dataField);
616 copyAttributes($dataField, $timeField, ['class', 'disabled']);
617 $timeField
618 .addClass('crm-form-text crm-form-time')
619 .attr('placeholder', $dataField.attr('time-placeholder') === undefined ? ts('Time') : $dataField.attr('time-placeholder'))
620 .change(updateDataField)
621 .timeEntry({
622 spinnerImage: '',
623 show24Hours: settings.time === true || settings.time === undefined ? CRM.config.timeIs24Hr : settings.time == '24'
624 });
625 }
626 if (settings.date !== false) {
627 $dateField = $('<input>').insertAfter($dataField);
628 copyAttributes($dataField, $dateField, ['placeholder', 'style', 'class', 'disabled']);
629 $dateField.addClass('crm-form-text crm-form-date');
630 settings.date = typeof settings.date === 'string' ? settings.date : CRM.config.dateInputFormat;
631 settings.changeMonth = _.includes('m', settings.date);
632 settings.changeYear = _.includes('y', settings.date);
633 $dateField.datepicker(settings).change(updateDataField);
634 }
635 // Rudimentary validation. TODO: Roll into use of jQUery validate and ui.datepicker.validation
636 function isValidDate() {
637 try {
638 $.datepicker.parseDate(settings.date, $dateField.val());
639 return true;
640 } catch (e) {
641 return false;
642 }
643 }
644 function updateInputFields(e, context) {
645 var val = $dataField.val(),
646 time = null;
647 if (context !== 'userInput' && context !== 'crmClear') {
648 if ($dateField.length) {
649 $dateField.datepicker('setDate', _.includes(val, '-') ? $.datepicker.parseDate('yy-mm-dd', val) : null);
650 }
651 if ($timeField.length) {
652 if (val.length === 8) {
653 time = val;
654 } else if (val.length === 19) {
655 time = val.split(' ')[1];
656 }
657 $timeField.timeEntry('setTime', time);
658 }
659 }
660 $clearLink.css('visibility', val ? 'visible' : 'hidden');
661 }
662 function updateDataField(e, context) {
663 // The crmClear event wipes all the field values anyway, so no need to respond
664 if (context !== 'crmClear') {
665 var val = '';
666 if ($dateField.val()) {
667 if (isValidDate()) {
668 val = $.datepicker.formatDate('yy-mm-dd', $dateField.datepicker('getDate'));
669 $dateField.removeClass('crm-error');
670 } else {
671 $dateField.addClass('crm-error');
672 }
673 }
674 if ($timeField.val()) {
675 val += (val ? ' ' : '') + $timeField.timeEntry('getTime').toTimeString().substr(0, 8);
676 }
677 $dataField.val(val).trigger('change', ['userInput']);
678 }
679 }
680 $dataField.hide().addClass('crm-hidden-date').on('change', updateInputFields);
681 updateInputFields();
682 });
683 };
684
685 $.fn.crmAjaxTable = function() {
686 return $(this).each(function() {
687 //Declare the defaults for DataTables
688 var defaults = {
689 "processing": true,
690 "serverSide": true,
691 "dom": '<"crm-datatable-pager-top"lfp>rt<"crm-datatable-pager-bottom"ip>',
692 "pageLength": 25,
693 "drawCallback": function(settings) {
694 //Add data attributes to cells
695 $('thead th', settings.nTable).each( function( index ) {
696 $.each(this.attributes, function() {
697 if(this.name.match("^cell-")) {
698 var cellAttr = this.name.substring(5);
699 var cellValue = this.value;
700 $('tbody tr', settings.nTable).each( function() {
701 $('td:eq('+ index +')', this).attr( cellAttr, cellValue );
702 });
703 }
704 });
705 });
706 //Reload table after draw
707 $(settings.nTable).trigger('crmLoad');
708 }
709 };
710 //Include any table specific data
711 var settings = $.extend(true, defaults, $(this).data('table'));
712 //Make the DataTables call
713 $(this).DataTable(settings);
714 });
715 };
716
717 CRM.utils.formatSelect2Result = function (row) {
718 var markup = '<div class="crm-select2-row">';
719 if (row.image !== undefined) {
720 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
721 }
722 else if (row.icon_class) {
723 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
724 }
725 markup += '<div><div class="crm-select2-row-label '+(row.label_class || '')+'">' +
726 (row.prefix !== undefined ? row.prefix + ' ' : '') + row.label + (row.suffix !== undefined ? ' ' + row.suffix : '') +
727 '</div>' +
728 '<div class="crm-select2-row-description">';
729 $.each(row.description || [], function(k, text) {
730 markup += '<p>' + text + '</p>';
731 });
732 markup += '</div></div></div>';
733 return markup;
734 };
735
736 function renderEntityRefCreateLinks($el) {
737 var
738 createLinks = $el.data('create-links'),
739 params = getEntityRefApiParams($el).params,
740 markup = '<div class="crm-entityref-links">';
741 if (!createLinks || $el.data('api-entity').toLowerCase() !== 'contact') {
742 return '';
743 }
744 if (createLinks === true) {
745 createLinks = params.contact_type ? _.where(CRM.config.entityRef.contactCreate, {type: params.contact_type}) : CRM.config.entityRef.contactCreate;
746 }
747 _.each(createLinks, function(link) {
748 var icon;
749 switch (link.type) {
750 case 'Individual':
751 icon = 'fa-user';
752 break;
753
754 case 'Organization':
755 icon = 'fa-building';
756 break;
757
758 case 'Household':
759 icon = 'fa-home';
760 break;
761 }
762 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
763 if (icon) {
764 markup += '<i class="crm-i ' + icon + '"></i> ';
765 }
766 markup += link.label + '</a>';
767 });
768 markup += '</div>';
769 return markup;
770 }
771
772 function getEntityRefFilters($el) {
773 var
774 entity = $el.data('api-entity').toLowerCase(),
775 filters = $.extend([], CRM.config.entityRef.filters[entity] || []),
776 filter = $el.data('user-filter') || {},
777 params = $.extend({params: {}}, $el.data('api-params') || {}).params,
778 result = [];
779 $.each(filters, function() {
780 if (typeof params[this.key] === 'undefined') {
781 result.push(this);
782 }
783 else if (this.key == 'contact_type' && typeof params.contact_sub_type === 'undefined') {
784 this.options = _.remove(this.options, function(option) {
785 return option.key.indexOf(params.contact_type + '__') === 0;
786 });
787 result.push(this);
788 }
789 });
790 return result;
791 }
792
793 function renderEntityRefFilters($el) {
794 var
795 filters = getEntityRefFilters($el),
796 filter = $el.data('user-filter') || {},
797 filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null;
798 if (!filters.length) {
799 return '';
800 }
801 var markup = '<div class="crm-entityref-filters">' +
802 '<select class="crm-entityref-filter-key' + (filter.key ? ' active' : '') + '">' +
803 '<option value="">' + ts('Refine search...') + '</option>' +
804 CRM.utils.renderOptions(filters, filter.key) +
805 '</select> &nbsp; ' +
806 '<select class="crm-entityref-filter-value' + (filter.key ? ' active"' : '"') + (filter.key ? '' : ' style="display:none;"') + '>' +
807 '<option value="">' + ts('- select -') + '</option>';
808 if (filterSpec && filterSpec.options) {
809 markup += CRM.utils.renderOptions(filterSpec.options, filter.value);
810 }
811 markup += '</select></div>';
812 return markup;
813 }
814
815 /**
816 * Fetch options for a filter (via ajax if necessary) and populate the appropriate select list
817 * @param $el
818 */
819 function loadEntityRefFilterOptions($el) {
820 var
821 filters = getEntityRefFilters($el),
822 filter = $el.data('user-filter') || {},
823 filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null,
824 $valField = $('.crm-entityref-filter-value', '#select2-drop');
825 if (filterSpec) {
826 $valField.show().val('');
827 if (filterSpec.options) {
828 CRM.utils.setOptions($valField, filterSpec.options, false, filter.value);
829 } else {
830 $valField.prop('disabled', true);
831 CRM.api3(filterSpec.entity || $el.data('api-entity'), 'getoptions', {field: filter.key, context: 'search', sequential: 1})
832 .done(function(result) {
833 var entity = $el.data('api-entity').toLowerCase(),
834 globalFilterSpec = _.find(CRM.config.entityRef.filters[entity], {key: filter.key}) || {};
835 // Store options globally so we don't have to look them up again
836 globalFilterSpec.options = result.values;
837 $valField.prop('disabled', false);
838 CRM.utils.setOptions($valField, result.values);
839 $valField.val(filter.value || '');
840 });
841 }
842 } else {
843 $valField.hide();
844 }
845 }
846
847 //CRM-15598 - Override url validator method to allow relative url's (e.g. /index.htm)
848 $.validator.addMethod("url", function(value, element) {
849 if (/^\//.test(value)) {
850 // Relative url: prepend dummy path for validation.
851 value = 'http://domain.tld' + value;
852 }
853 // From jQuery Validation Plugin v1.12.0
854 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);
855 });
856
857 /**
858 * Wrapper for jQuery validate initialization function; supplies defaults
859 */
860 $.fn.crmValidate = function(params) {
861 return $(this).each(function () {
862 var that = this,
863 settings = $.extend({}, CRM.validate._defaults, CRM.validate.params);
864 $(this).validate(settings);
865 // Call any post-initialization callbacks
866 if (CRM.validate.functions && CRM.validate.functions.length) {
867 $.each(CRM.validate.functions, function(i, func) {
868 func.call(that);
869 });
870 }
871 });
872 };
873
874 // Initialize widgets
875 $(document)
876 .on('crmLoad', function(e) {
877 $('table.row-highlight', e.target)
878 .off('.rowHighlight')
879 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) {
880 var filter, $table = $(this).closest('table');
881 if ($(this).hasClass('select-rows')) {
882 filter = $(this).prop('checked') ? ':not(:checked)' : ':checked';
883 $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
884 }
885 else {
886 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
887 if (data !== 'master-selected') {
888 $('input.select-rows', $table).prop('checked', $(".select-row:not(':checked')", $table).length < 1);
889 }
890 }
891 })
892 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
893 $('table.crm-sortable', e.target).DataTable();
894 $('table.crm-ajax-table', e.target).each(function() {
895 var
896 $table = $(this),
897 $accordion = $table.closest('.crm-accordion-wrapper.collapsed, .crm-collapsible.collapsed');
898 // For tables hidden by collapsed accordions, wait.
899 if ($accordion.length) {
900 $accordion.one('crmAccordion:open', function() {
901 $table.crmAjaxTable();
902 });
903 } else {
904 $table.crmAjaxTable();
905 }
906 });
907 if ($("input:radio[name=radio_ts]").size() == 1) {
908 $("input:radio[name=radio_ts]").prop("checked", true);
909 }
910 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
911 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
912 $('select.crm-chain-select-control', e.target).off('.chainSelect').on('change.chainSelect', chainSelect);
913 // Cache Form Input initial values
914 $('form[data-warn-changes] :input', e.target).each(function() {
915 $(this).data('crm-initial-value', $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val());
916 });
917 $('textarea.crm-form-wysiwyg', e.target)
918 .not('.crm-wysiwyg-enabled')
919 .addClass('crm-wysiwyg-enabled')
920 .each(function() {
921 if ($(this).hasClass("collapsed")) {
922 CRM.wysiwyg.createCollapsed(this);
923 } else {
924 CRM.wysiwyg.create(this);
925 }
926 });
927 })
928 .on('dialogopen', function(e) {
929 var $el = $(e.target);
930 // Modal dialogs should disable scrollbars
931 if ($el.dialog('option', 'modal')) {
932 $el.addClass('modal-dialog');
933 $('body').css({overflow: 'hidden'});
934 }
935 // Add resize button
936 if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) {
937 $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: 'fa-expand'}, text: false}));
938 $('.crm-dialog-titlebar-resize', $el.parent()).click(function(e) {
939 if ($el.data('origSize')) {
940 $el.dialog('option', $el.data('origSize'));
941 $el.data('origSize', null);
942 } else {
943 var menuHeight = $('#civicrm-menu').outerHeight();
944 $el.data('origSize', {
945 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
946 width: $el.dialog('option', 'width'),
947 height: $el.dialog('option', 'height')
948 });
949 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: {my: "top", at: "top+"+menuHeight, of: window}});
950 }
951 $el.trigger('dialogresize');
952 e.preventDefault();
953 });
954 }
955 })
956 .on('dialogclose', function(e) {
957 // Restore scrollbars when closing modal
958 if ($('.ui-dialog .modal-dialog:visible').not(e.target).length < 1) {
959 $('body').css({overflow: ''});
960 }
961 })
962 .on('submit', function(e) {
963 // CRM-14353 - disable changes warn when submitting a form
964 $('[data-warn-changes]').attr('data-warn-changes', 'false');
965 });
966
967 // CRM-14353 - Warn of unsaved changes for forms which have opted in
968 window.onbeforeunload = function() {
969 if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
970 return ts('You have unsaved changes.');
971 }
972 };
973
974 $.fn.crmtooltip = function () {
975 $(document)
976 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
977 $(this).addClass('crm-processed crm-tooltip-active');
978 var topDistance = e.pageY - $(window).scrollTop();
979 if (topDistance < 300 || topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
980 $(this).addClass('crm-tooltip-down');
981 }
982 if (!$(this).children('.crm-tooltip-wrapper').length) {
983 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
984 $(this).children().children('.crm-tooltip')
985 .html('<div class="crm-loading-element"></div>')
986 .load(this.href);
987 }
988 })
989 .on('mouseout', 'a.crm-summary-link', function () {
990 $(this).removeClass('crm-processed crm-tooltip-active crm-tooltip-down');
991 })
992 .on('click', 'a.crm-summary-link', false);
993 };
994
995 var helpDisplay, helpPrevious;
996 CRM.help = function (title, params, url) {
997 if (helpDisplay && helpDisplay.close) {
998 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
999 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
1000 helpDisplay.close();
1001 return;
1002 }
1003 helpDisplay.close();
1004 }
1005 helpPrevious = JSON.stringify(params);
1006 params.class_name = 'CRM_Core_Page_Inline_Help';
1007 params.type = 'page';
1008 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
1009 $.ajax(url || CRM.url('civicrm/ajax/inline'),
1010 {
1011 data: params,
1012 dataType: 'html',
1013 success: function (data) {
1014 $('#crm-notification-container .crm-help .notify-content:last').html(data);
1015 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
1016 },
1017 error: function () {
1018 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
1019 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
1020 }
1021 }
1022 );
1023 };
1024 /**
1025 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1026 */
1027 CRM.status = function(options, deferred) {
1028 // 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.
1029 if (typeof options === 'string') {
1030 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
1031 }
1032 var opts = $.extend({
1033 start: ts('Saving...'),
1034 success: ts('Saved'),
1035 error: function(data) {
1036 var msg = $.isPlainObject(data) && data.error_message;
1037 CRM.alert(msg || ts('Sorry an error occurred and your information was not saved'), ts('Error'), 'error');
1038 }
1039 }, options || {});
1040 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>')
1041 .appendTo('body');
1042 $msg.css('min-width', $msg.width());
1043 function handle(status, data) {
1044 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
1045 if (endMsg) {
1046 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg);
1047 window.setTimeout(function() {
1048 $msg.fadeOut('slow', function() {
1049 $msg.remove();
1050 });
1051 }, 2000);
1052 } else {
1053 $msg.remove();
1054 }
1055 }
1056 return (deferred || new $.Deferred())
1057 .done(function(data) {
1058 // If the server returns an error msg call the error handler
1059 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
1060 handle(status, data);
1061 })
1062 .fail(function(data) {
1063 handle('error', data);
1064 });
1065 };
1066
1067 // Convert an Angular promise to a jQuery promise
1068 CRM.toJqPromise = function(aPromise) {
1069 var jqDeferred = $.Deferred();
1070 aPromise.then(
1071 function(data) { jqDeferred.resolve(data); },
1072 function(data) { jqDeferred.reject(data); }
1073 // should we also handle progress events?
1074 );
1075 return jqDeferred.promise();
1076 };
1077
1078 CRM.toAPromise = function($q, jqPromise) {
1079 var aDeferred = $q.defer();
1080 jqPromise.then(
1081 function(data) { aDeferred.resolve(data); },
1082 function(data) { aDeferred.reject(data); }
1083 // should we also handle progress events?
1084 );
1085 return aDeferred.promise;
1086 };
1087
1088 /**
1089 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1090 */
1091 CRM.alert = function (text, title, type, options) {
1092 type = type || 'alert';
1093 title = title || '';
1094 options = options || {};
1095 if ($('#crm-notification-container').length) {
1096 var params = {
1097 text: text,
1098 title: title,
1099 type: type
1100 };
1101 // By default, don't expire errors and messages containing links
1102 var extra = {
1103 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
1104 unique: true
1105 };
1106 options = $.extend(extra, options);
1107 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
1108 if (options.unique && options.unique !== '0') {
1109 $('#crm-notification-container .ui-notify-message').each(function () {
1110 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
1111 $('.icon.ui-notify-close', this).click();
1112 }
1113 });
1114 }
1115 return $('#crm-notification-container').notify('create', params, options);
1116 }
1117 else {
1118 if (title.length) {
1119 text = title + "\n" + text;
1120 }
1121 alert(text);
1122 return null;
1123 }
1124 };
1125
1126 /**
1127 * Close whichever alert contains the given node
1128 *
1129 * @param node
1130 */
1131 CRM.closeAlertByChild = function (node) {
1132 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
1133 };
1134
1135 /**
1136 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1137 */
1138 CRM.confirm = function (options) {
1139 var dialog, url, msg, buttons = [], settings = {
1140 title: ts('Confirm'),
1141 message: ts('Are you sure you want to continue?'),
1142 url: null,
1143 width: 'auto',
1144 height: 'auto',
1145 resizable: false,
1146 dialogClass: 'crm-container crm-confirm',
1147 close: function () {
1148 $(this).dialog('destroy').remove();
1149 },
1150 options: {
1151 no: ts('Cancel'),
1152 yes: ts('Continue')
1153 }
1154 };
1155 if (options && options.url) {
1156 settings.resizable = true;
1157 settings.height = '50%';
1158 }
1159 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
1160 settings = CRM.utils.adjustDialogDefaults(settings);
1161 if (!settings.buttons && $.isPlainObject(settings.options)) {
1162 $.each(settings.options, function(op, label) {
1163 buttons.push({
1164 text: label,
1165 'data-op': op,
1166 icons: {primary: op === 'no' ? 'fa-times' : 'fa-check'},
1167 click: function() {
1168 var event = $.Event('crmConfirm:' + op);
1169 $(this).trigger(event);
1170 if (!event.isDefaultPrevented()) {
1171 dialog.dialog('close');
1172 }
1173 }
1174 });
1175 });
1176 // Order buttons so that "no" goes on the right-hand side
1177 settings.buttons = _.sortBy(buttons, 'data-op').reverse();
1178 }
1179 url = settings.url;
1180 msg = url ? '' : settings.message;
1181 delete settings.options;
1182 delete settings.message;
1183 delete settings.url;
1184 dialog = $('<div class="crm-confirm-dialog"></div>').html(msg || '').dialog(settings);
1185 if ($.isFunction(options)) {
1186 dialog.on('crmConfirm:yes', options);
1187 }
1188 if (url) {
1189 CRM.loadPage(url, {target: dialog});
1190 }
1191 else {
1192 dialog.trigger('crmLoad');
1193 }
1194 return dialog;
1195 };
1196
1197 /** provides a local copy of ts for a domain */
1198 CRM.ts = function(domain) {
1199 return function(message, options) {
1200 if (domain) {
1201 options = $.extend(options || {}, {domain: domain});
1202 }
1203 return ts(message, options);
1204 };
1205 };
1206
1207 CRM.addStrings = function(domain, strings) {
1208 var bucket = (domain == 'civicrm' ? 'strings' : 'strings::' + domain);
1209 CRM[bucket] = CRM[bucket] || {};
1210 _.extend(CRM[bucket], strings);
1211 };
1212
1213 /**
1214 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1215 */
1216 $.fn.crmError = function (text, title, options) {
1217 title = title || '';
1218 text = text || '';
1219 options = options || {};
1220
1221 var extra = {
1222 expires: 0
1223 };
1224 if ($(this).length) {
1225 if (title === '') {
1226 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
1227 if (label.length) {
1228 label.addClass('crm-error');
1229 var $label = label.clone();
1230 if (text === '' && $('.crm-marker', $label).length > 0) {
1231 text = $('.crm-marker', $label).attr('title');
1232 }
1233 $('.crm-marker', $label).remove();
1234 title = $label.text();
1235 }
1236 }
1237 $(this).addClass('crm-error');
1238 }
1239 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
1240 if ($(this).length) {
1241 var ele = $(this);
1242 setTimeout(function () {
1243 ele.one('change', function () {
1244 if (msg && msg.close) msg.close();
1245 ele.removeClass('error');
1246 label.removeClass('crm-error');
1247 });
1248 }, 1000);
1249 }
1250 return msg;
1251 };
1252
1253 // Display system alerts through js notifications
1254 function messagesFromMarkup() {
1255 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
1256 var text, title = '';
1257 $(this).removeClass('status messages');
1258 var type = $(this).attr('class').split(' ')[0] || 'alert';
1259 type = type.replace('crm-', '');
1260 $('.icon', this).remove();
1261 if ($('.msg-text', this).length > 0) {
1262 text = $('.msg-text', this).html();
1263 title = $('.msg-title', this).html();
1264 }
1265 else {
1266 text = $(this).html();
1267 }
1268 var options = $(this).data('options') || {};
1269 $(this).remove();
1270 // Duplicates were already removed server-side
1271 options.unique = false;
1272 CRM.alert(text, title, type, options);
1273 });
1274 // Handle qf form errors
1275 $('form :input.error', this).one('blur', function() {
1276 $('.ui-notify-message.error a.ui-notify-close').click();
1277 $(this).removeClass('error');
1278 $(this).next('span.crm-error').remove();
1279 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
1280 .removeClass('crm-error')
1281 .find('.crm-error').removeClass('crm-error');
1282 });
1283 }
1284
1285 /**
1286 * Improve blockUI when used with jQuery dialog
1287 */
1288 var originalBlock = $.fn.block,
1289 originalUnblock = $.fn.unblock;
1290
1291 $.fn.block = function(opts) {
1292 if ($(this).is('.ui-dialog-content')) {
1293 originalBlock.call($(this).parents('.ui-dialog'), opts);
1294 return $(this);
1295 }
1296 return originalBlock.call(this, opts);
1297 };
1298 $.fn.unblock = function(opts) {
1299 if ($(this).is('.ui-dialog-content')) {
1300 originalUnblock.call($(this).parents('.ui-dialog'), opts);
1301 return $(this);
1302 }
1303 return originalUnblock.call(this, opts);
1304 };
1305
1306 // Preprocess all CRM ajax calls to display messages
1307 $(document).ajaxSuccess(function(event, xhr, settings) {
1308 try {
1309 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
1310 var response = $.parseJSON(xhr.responseText);
1311 if (typeof(response.crmMessages) == 'object') {
1312 $.each(response.crmMessages, function(n, msg) {
1313 CRM.alert(msg.text, msg.title, msg.type, msg.options);
1314 });
1315 }
1316 if (response.backtrace) {
1317 CRM.console('log', response.backtrace);
1318 }
1319 if (typeof response.deprecated === 'string') {
1320 CRM.console('warn', response.deprecated);
1321 }
1322 }
1323 }
1324 // Ignore errors thrown by parseJSON
1325 catch (e) {}
1326 });
1327
1328 $(function () {
1329 $.blockUI.defaults.message = null;
1330 $.blockUI.defaults.ignoreIfBlocked = true;
1331
1332 if ($('#crm-container').hasClass('crm-public')) {
1333 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container crm-public';
1334 }
1335
1336 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1337 $('.crm-container').trigger('crmLoad');
1338
1339 if ($('#crm-notification-container').length) {
1340 // Initialize notifications
1341 $('#crm-notification-container').notify();
1342 messagesFromMarkup.call($('#crm-container'));
1343 }
1344
1345 $('body')
1346 // bind the event for image popup
1347 .on('click', 'a.crm-image-popup', function(e) {
1348 CRM.confirm({
1349 title: ts('Preview'),
1350 resizable: true,
1351 // Prevent overlap with the menubar
1352 maxHeight: $(window).height() - 30,
1353 position: {my: 'center', at: 'center center+15', of: window},
1354 message: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
1355 options: null
1356 });
1357 e.preventDefault();
1358 })
1359
1360 .on('click', function (event) {
1361 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1362 if ($(event.target).is('.btn-slide')) {
1363 $(event.target).addClass('btn-slide-active').find('.panel').show();
1364 }
1365 })
1366
1367 // Handle clear button for form elements
1368 .on('click', 'a.crm-clear-link', function() {
1369 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).trigger('change', ['crmClear']);
1370 $(this).siblings('input:text').val('').trigger('change', ['crmClear']);
1371 return false;
1372 })
1373 .on('change', 'input.crm-form-radio:checked', function() {
1374 $(this).siblings('.crm-clear-link').css({visibility: ''});
1375 })
1376
1377 // Allow normal clicking of links within accordions
1378 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
1379 e.stopPropagation();
1380 })
1381 // Handle accordions
1382 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
1383 var action = 'open';
1384 if ($(this).parent().hasClass('collapsed')) {
1385 $(this).next().css('display', 'none').slideDown(200);
1386 }
1387 else {
1388 $(this).next().css('display', 'block').slideUp(200);
1389 action = 'close';
1390 }
1391 $(this).parent().toggleClass('collapsed').trigger('crmAccordion:' + action);
1392 e.preventDefault();
1393 });
1394
1395 $().crmtooltip();
1396 });
1397
1398 /**
1399 * Collapse or expand an accordion
1400 * @param speed
1401 */
1402 $.fn.crmAccordionToggle = function (speed) {
1403 $(this).each(function () {
1404 var action = 'open';
1405 if ($(this).hasClass('collapsed')) {
1406 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
1407 }
1408 else {
1409 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1410 action = 'close';
1411 }
1412 $(this).toggleClass('collapsed').trigger('crmAccordion:' + action);
1413 });
1414 };
1415
1416 /**
1417 * Clientside currency formatting
1418 * @param number value
1419 * @param [optional] boolean onlyNumber - if true, we return formatted amount without currency sign
1420 * @param [optional] string format - currency representation of the number 1234.56
1421 * @return string
1422 */
1423 var currencyTemplate;
1424 CRM.formatMoney = function(value, onlyNumber, format) {
1425 var decimal, separator, sign, i, j, result;
1426 if (value === 'init' && format) {
1427 currencyTemplate = format;
1428 return;
1429 }
1430 format = format || currencyTemplate;
1431 result = /1(.?)234(.?)56/.exec(format);
1432 if (result === null) {
1433 return 'Invalid format passed to CRM.formatMoney';
1434 }
1435 separator = result[1];
1436 decimal = result[2];
1437 sign = (value < 0) ? '-' : '';
1438 //extracting the absolute value of the integer part of the number and converting to string
1439 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
1440 j = ((j = i.length) > 3) ? j % 3 : 0;
1441 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) : '');
1442 if ( onlyNumber ) {
1443 return result;
1444 }
1445 return format.replace(/1.*234.*56/, result);
1446 };
1447
1448 CRM.console = function(method, title, msg) {
1449 if (window.console) {
1450 method = $.isFunction(console[method]) ? method : 'log';
1451 if (msg === undefined) {
1452 return console[method](title);
1453 } else {
1454 return console[method](title, msg);
1455 }
1456 }
1457 };
1458
1459 // Determine if a user has a given permission.
1460 // @see CRM_Core_Resources::addPermissions
1461 CRM.checkPerm = function(perm) {
1462 return CRM.permissions[perm];
1463 };
1464
1465 // Round while preserving sigfigs
1466 CRM.utils.sigfig = function(n, digits) {
1467 var len = ("" + n).length;
1468 var scale = Math.pow(10.0, len-digits);
1469 return Math.round(n / scale) * scale;
1470 };
1471 })(jQuery, _);