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