CRM-14353 - More accurate comparison with multiselects and excluding buttons
[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 if (target_element_type == null) {
84 var target_element_type = 'block';
85 }
86 else {
87 if (target_element_type == 'table-row') {
88 var target_element_type = '';
89 }
90 }
91
92 if (field_type == 'select') {
93 var trigger = trigger_value.split("|");
94 var selectedOptionValue = cj('#' + trigger_field_id).val();
95
96 var target = target_element_id.split("|");
97 for (var j = 0; j < target.length; j++) {
98 if (invert) {
99 cj('#' + target[j]).show();
100 }
101 else {
102 cj('#' + target[j]).hide();
103 }
104 for (var i = 0; i < trigger.length; i++) {
105 if (selectedOptionValue == trigger[i]) {
106 if (invert) {
107 cj('#' + target[j]).hide();
108 }
109 else {
110 cj('#' + target[j]).show();
111 }
112 }
113 }
114 }
115
116 }
117 else {
118 if (field_type == 'radio') {
119 var target = target_element_id.split("|");
120 for (var j = 0; j < target.length; j++) {
121 if (cj('[name="' + trigger_field_id + '"]').is(':checked')) {
122 if (invert) {
123 cj('#' + target[j]).hide();
124 }
125 else {
126 cj('#' + target[j]).show();
127 }
128 }
129 else {
130 if (invert) {
131 cj('#' + target[j]).show();
132 }
133 else {
134 cj('#' + target[j]).hide();
135 }
136 }
137 }
138 }
139 }
140 }
141
142 /**
143 * Function to change button text and disable one it is clicked
144 * @deprecated
145 * @param obj object - the button clicked
146 * @param formID string - the id of the form being submitted
147 * @param string procText - button text after user clicks it
148 * @return bool
149 */
150 var submitcount = 0;
151 /* Changes button label on submit, and disables button after submit for newer browsers.
152 Puts up alert for older browsers. */
153 function submitOnce(obj, formId, procText) {
154 // if named button clicked, change text
155 if (obj.value != null) {
156 obj.value = procText + " ...";
157 }
158 if (document.getElementById) { // disable submit button for newer browsers
159 obj.disabled = true;
160 document.getElementById(formId).submit();
161 return true;
162 }
163 else { // for older browsers
164 if (submitcount == 0) {
165 submitcount++;
166 return true;
167 }
168 else {
169 alert("Your request is currently being processed ... Please wait.");
170 return false;
171 }
172 }
173 }
174
175 /**
176 * Function to show / hide the row in optionFields
177 * @deprecated
178 * @param index string, element whose innerHTML is to hide else will show the hidden row.
179 */
180 function showHideRow(index) {
181 if (index) {
182 cj('tr#optionField_' + index).hide();
183 if (cj('table#optionField tr:hidden:first').length) {
184 cj('div#optionFieldLink').show();
185 }
186 }
187 else {
188 cj('table#optionField tr:hidden:first').show();
189 if (!cj('table#optionField tr:hidden:last').length) {
190 cj('div#optionFieldLink').hide();
191 }
192 }
193 return false;
194 }
195
196 CRM.utils = CRM.utils || {};
197 CRM.strings = CRM.strings || {};
198 CRM.validate = CRM.validate || {
199 params: {},
200 functions: []
201 };
202
203 (function ($, _, undefined) {
204 "use strict";
205
206 // Theme classes for unattached elements
207 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container';
208
209 // https://github.com/ivaynberg/select2/pull/2090
210 $.fn.select2.defaults.width = 'resolve';
211
212 // Workaround for https://github.com/ivaynberg/select2/issues/1246
213 $.ui.dialog.prototype._allowInteraction = function(e) {
214 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop').length;
215 };
216
217 /**
218 * Populate a select list, overwriting the existing options except for the placeholder.
219 * @param $el jquery collection - 1 or more select elements
220 * @param options array in format returned by api.getoptions
221 * @param removePlaceholder bool
222 */
223 CRM.utils.setOptions = function($el, options, removePlaceholder) {
224 $el.each(function() {
225 var
226 $elect = $(this),
227 val = $elect.val() || [],
228 opts = removePlaceholder ? '' : '[value!=""]';
229 if (!$.isArray(val)) {
230 val = [val];
231 }
232 $elect.find('option' + opts).remove();
233 _.each(options, function(option) {
234 var selected = ($.inArray(''+option.key, val) > -1) ? 'selected="selected"' : '';
235 $elect.append('<option value="' + option.key + '"' + selected + '>' + option.value + '</option>');
236 });
237 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
238 });
239 };
240
241 /**
242 * Compare Form Input values against cached initial value.
243 *
244 * @return {Boolean} true if changes have been made.
245 */
246 CRM.utils.initialValueChanged = function(el) {
247 var isDirty = false;
248 $(':input:visible, :input.select2-offscreen', el).not('[type=submit], [type=button], .crm-action-menu').each(function () {
249 var initialValue = $(this).data('crm-initial-value');
250 // skip change of value for submit buttons
251 if (initialValue !== undefined && !_.isEqual(initialValue, $(this).val())) {
252 isDirty = true;
253 }
254 });
255 return isDirty;
256 };
257
258 /**
259 * Wrapper for select2 initialization function; supplies defaults
260 * @param options object
261 */
262 $.fn.crmSelect2 = function(options) {
263 return $(this).each(function () {
264 var
265 $el = $(this),
266 settings = {allowClear: !$el.hasClass('required')};
267 // quickform doesn't support optgroups so here's a hack :(
268 $('option[value^=crm_optgroup]', this).each(function () {
269 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
270 $(this).remove();
271 });
272 // Defaults for single-selects
273 if ($el.is('select:not([multiple])')) {
274 settings.minimumResultsForSearch = 10;
275 if ($('option:first', this).val() === '') {
276 settings.placeholderOption = 'first';
277 }
278 }
279 $.extend(settings, $el.data('select-params') || {}, options || {});
280 if (settings.ajax) {
281 $el.addClass('crm-ajax-select');
282 }
283 $el.select2(settings);
284 });
285 };
286
287 /**
288 * @see CRM_Core_Form::addEntityRef for docs
289 * @param options object
290 */
291 $.fn.crmEntityRef = function(options) {
292 options = options || {};
293 options.select = options.select || {};
294 return $(this).each(function() {
295 var
296 $el = $(this).off('.crmEntity'),
297 entity = options.entity || $el.data('api-entity') || 'contact',
298 selectParams = {};
299 $el.data('api-entity', entity);
300 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
301 $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api));
302 $el.data('create-links', options.create || $el.data('create-links'));
303 $el.addClass('crm-form-entityref crm-' + entity + '-ref');
304 var settings = {
305 // Use select2 ajax helper instead of CRM.api because it provides more value
306 ajax: {
307 url: CRM.url('civicrm/ajax/rest'),
308 data: function (input, page_num) {
309 var params = $el.data('api-params') || {};
310 params.input = input;
311 params.page_num = page_num;
312 return {
313 entity: $el.data('api-entity'),
314 action: 'getlist',
315 json: JSON.stringify(params)
316 };
317 },
318 results: function(data) {
319 return {more: data.more_results, results: data.values || []};
320 }
321 },
322 minimumInputLength: 1,
323 formatResult: formatSelect2Result,
324 formatSelection: function(row) {
325 return row.label;
326 },
327 escapeMarkup: function (m) {return m;},
328 initSelection: function($el, callback) {
329 var
330 multiple = !!$el.data('select-params').multiple,
331 val = $el.val(),
332 stored = $el.data('entity-value') || [];
333 if (val === '') {
334 return;
335 }
336 // If we already have this data, just return it
337 if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
338 callback(multiple ? stored : stored[0]);
339 } else {
340 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
341 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
342 callback(multiple ? result.values : result.values[0])
343 });
344 }
345 }
346 };
347 if ($el.data('create-links') && entity.toLowerCase() === 'contact') {
348 selectParams.formatInputTooShort = function() {
349 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
350 if ($el.data('create-links')) {
351 txt += ' ' + ts('or') + '<br />' + formatSelect2CreateLinks($el);
352 }
353 return txt;
354 };
355 selectParams.formatNoMatches = function() {
356 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
357 return txt + '<br />' + formatSelect2CreateLinks($el);
358 };
359 $el.on('select2-open.crmEntity', function() {
360 var $el = $(this);
361 $('#select2-drop').off('.crmEntity').on('click.crmEntity', 'a.crm-add-entity', function(e) {
362 $el.select2('close');
363 CRM.loadForm($(this).attr('href'), {
364 dialog: {width: 500, height: 'auto'}
365 }).on('crmFormSuccess', function(e, data) {
366 if (data.status === 'success' && data.id) {
367 CRM.status(ts('%1 Created', {1: data.label}));
368 if ($el.select2('container').hasClass('select2-container-multi')) {
369 var selection = $el.select2('data');
370 selection.push(data);
371 $el.select2('data', selection, true);
372 } else {
373 $el.select2('data', data, true);
374 }
375 }
376 });
377 return false;
378 });
379 });
380 }
381 // Create new items inline - works for tags
382 else if ($el.data('create-links')) {
383 selectParams.createSearchChoice = function(term, data) {
384 if (!_.findKey(data, {label: term})) {
385 return {id: "0", term: term, label: term + ' (' + ts('new tag') + ')'};
386 }
387 };
388 selectParams.tokenSeparators = [','];
389 selectParams.createSearchChoicePosition = 'bottom';
390 }
391 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams))
392 .on('select2-selecting.crmEntity', function(e) {
393 if (e.val === "0") {
394 e.object.label = e.object.term;
395 CRM.api3(entity, 'create', $.extend({name: e.object.term}, $el.data('api-params').params || {}))
396 .done(function(created) {
397 var
398 multiple = !!$el.data('select-params').multiple,
399 val = $el.select2('val'),
400 data = $el.select2('data'),
401 item = {id: created.id, label: e.object.term};
402 if (val === "0") {
403 $el.select2('data', item, true);
404 }
405 else if ($.isArray(val) && $.inArray("0", val) > -1) {
406 _.remove(data, {id: "0"});
407 data.push(item);
408 $el.select2('data', data, true);
409 }
410 });
411 }
412 });
413 });
414 };
415
416 function formatSelect2Result(row) {
417 var markup = '<div class="crm-select2-row">';
418 if (row.image !== undefined) {
419 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
420 }
421 else if (row.icon_class) {
422 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
423 }
424 markup += '<div><div class="crm-select2-row-label">' + row.label + '</div>';
425 markup += '<div class="crm-select2-row-description">';
426 $.each(row.description || [], function(k, text) {
427 markup += '<p>' + text + '</p>';
428 });
429 markup += '</div></div></div>';
430 return markup;
431 }
432
433 function formatSelect2CreateLinks($el) {
434 var
435 createLinks = $el.data('create-links'),
436 api = $el.data('api-params') || {},
437 type = api.params ? api.params.contact_type : null;
438 if (createLinks === true) {
439 createLinks = type ? _.where(CRM.profile.contactCreate, {type: type}) : CRM.profile.contactCreate;
440 }
441 var markup = '';
442 _.each(createLinks, function(link) {
443 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
444 if (link.type) {
445 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
446 }
447 markup += link.label + '</a>';
448 });
449 return markup;
450 }
451
452 // Initialize widgets
453 $(document)
454 .on('crmLoad', function(e) {
455 $('table.row-highlight', e.target)
456 .off('.rowHighlight')
457 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) {
458 var filter, $table = $(this).closest('table');
459 if ($(this).hasClass('select-rows')) {
460 filter = $(this).prop('checked') ? ':not(:checked)' : ':checked';
461 $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
462 }
463 else {
464 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
465 if (data !== 'master-selected') {
466 $('input.select-rows', $table).prop('checked', $(".select-row:not(':checked')", $table).length < 1);
467 }
468 }
469 })
470 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
471 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
472 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
473 // Cache Form Input initial values
474 $('form[data-warn-changes] :input', e.target).each(function() {
475 $(this).data('crm-initial-value', $(this).val());
476 });
477 })
478 .on('dialogopen', function(e) {
479 var $el = $(e.target);
480 // Modal dialogs should disable scrollbars
481 if ($el.dialog('option', 'modal')) {
482 $el.addClass('modal-dialog');
483 $('body').css({overflow: 'hidden'});
484 }
485 $el.parent().find('.ui-dialog-titlebar-close').attr('title', ts('Close'));
486 // Add resize button
487 if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) {
488 $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}));
489 $('.crm-dialog-titlebar-resize', $el.parent()).click(function(e) {
490 if ($el.data('origSize')) {
491 $el.dialog('option', $el.data('origSize'));
492 $el.data('origSize', null);
493 } else {
494 $el.data('origSize', {
495 position: 'center',
496 width: $el.dialog('option', 'width'),
497 height: $el.dialog('option', 'height')
498 });
499 var menuHeight = $('#civicrm-menu').height();
500 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: [0, menuHeight]});
501 }
502 e.preventDefault();
503 });
504 }
505 })
506 .on('dialogclose', function(e) {
507 // Restore scrollbars when closing modal
508 if ($('.ui-dialog .modal-dialog:visible').not(e.target).length < 1) {
509 $('body').css({overflow: ''});
510 }
511 })
512 .on('submit', function(e) {
513 // CRM-14353 - disable changes warn when submitting the form
514 $('[data-warn-changes]').removeAttr('data-warn-changes');
515 })
516 ;
517
518 window.onbeforeunload = function() {
519 if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]'))) {
520 return ts('You have unsaved changes.');
521 }
522 };
523
524 /**
525 * Function to make multiselect boxes behave as fields in small screens
526 */
527 function advmultiselectResize() {
528 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
529 if (amswidth < 700) {
530 $("form table.advmultiselect td").css('display', 'block');
531 }
532 else {
533 $("form table.advmultiselect td").css('display', 'table-cell');
534 }
535 var contactwidth = $('#crm-container #mainTabContainer').width();
536 if (contactwidth < 600) {
537 $('#crm-container #mainTabContainer').addClass('narrowpage');
538 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
539 if (index > 1) {
540 if (index % 2 == 0) {
541 $(this).parent().after('<tr class="narrowadded"></tr>');
542 }
543 var item = $(this);
544 $(this).parent().next().append(item);
545 }
546 });
547 }
548 else {
549 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
550 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
551 var nitem = $(this);
552 var parent = $(this).parent();
553 $(this).parent().prev().append(nitem);
554 if (parent.children().size() == 0) {
555 parent.remove();
556 }
557 });
558 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
559 }
560 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
561
562 if (cformwidth < 720) {
563 $('#crm-container .contact_basic_information-section').addClass('narrowform');
564 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
565 if (cformwidth < 480) {
566 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
567 }
568 else {
569 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
570 }
571 }
572 else {
573 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
574 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
575 }
576 }
577
578 advmultiselectResize();
579 $(window).resize(function () {
580 advmultiselectResize();
581 });
582
583 $.fn.crmtooltip = function () {
584 $(document)
585 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
586 $(this).addClass('crm-processed');
587 $(this).addClass('crm-tooltip-active');
588 var topDistance = e.pageY - $(window).scrollTop();
589 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
590 $(this).addClass('crm-tooltip-down');
591 }
592 if (!$(this).children('.crm-tooltip-wrapper').length) {
593 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
594 $(this).children().children('.crm-tooltip')
595 .html('<div class="crm-loading-element"></div>')
596 .load(this.href);
597 }
598 })
599 .on('mouseout', 'a.crm-summary-link', function () {
600 $(this).removeClass('crm-processed');
601 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
602 })
603 .on('click', 'a.crm-summary-link', false);
604 };
605
606 var helpDisplay, helpPrevious;
607 CRM.help = function (title, params, url) {
608 if (helpDisplay && helpDisplay.close) {
609 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
610 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
611 helpDisplay.close();
612 return;
613 }
614 helpDisplay.close();
615 }
616 helpPrevious = JSON.stringify(params);
617 params.class_name = 'CRM_Core_Page_Inline_Help';
618 params.type = 'page';
619 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
620 $.ajax(url || CRM.url('civicrm/ajax/inline'),
621 {
622 data: params,
623 dataType: 'html',
624 success: function (data) {
625 $('#crm-notification-container .crm-help .notify-content:last').html(data);
626 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
627 },
628 error: function () {
629 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
630 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
631 }
632 }
633 );
634 };
635 /**
636 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
637 */
638 CRM.status = function(options, deferred) {
639 // 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.
640 if (typeof options === 'string') {
641 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
642 }
643 var opts = $.extend({
644 start: ts('Saving...'),
645 success: ts('Saved'),
646 error: function() {
647 CRM.alert(ts('Sorry an error occurred and your information was not saved'), ts('Error'));
648 }
649 }, options || {});
650 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>')
651 .appendTo('body');
652 $msg.css('min-width', $msg.width());
653 function handle(status, data) {
654 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
655 if (endMsg) {
656 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg);
657 window.setTimeout(function() {
658 $msg.fadeOut('slow', function() {$msg.remove()});
659 }, 2000);
660 } else {
661 $msg.remove();
662 }
663 }
664 return (deferred || new $.Deferred())
665 .done(function(data) {
666 // If the server returns an error msg call the error handler
667 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
668 handle(status, data);
669 })
670 .fail(function(data) {
671 handle('error', data);
672 });
673 };
674
675 /**
676 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
677 */
678 CRM.alert = function (text, title, type, options) {
679 type = type || 'alert';
680 title = title || '';
681 options = options || {};
682 if ($('#crm-notification-container').length) {
683 var params = {
684 text: text,
685 title: title,
686 type: type
687 };
688 // By default, don't expire errors and messages containing links
689 var extra = {
690 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
691 unique: true
692 };
693 options = $.extend(extra, options);
694 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
695 if (options.unique && options.unique !== '0') {
696 $('#crm-notification-container .ui-notify-message').each(function () {
697 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
698 $('.icon.ui-notify-close', this).click();
699 }
700 });
701 }
702 return $('#crm-notification-container').notify('create', params, options);
703 }
704 else {
705 if (title.length) {
706 text = title + "\n" + text;
707 }
708 alert(text);
709 return null;
710 }
711 };
712
713 /**
714 * Close whichever alert contains the given node
715 *
716 * @param node
717 */
718 CRM.closeAlertByChild = function (node) {
719 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
720 };
721
722 /**
723 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
724 */
725 CRM.confirm = function (options) {
726 var dialog, settings = {
727 title: ts('Confirm Action'),
728 message: ts('Are you sure you want to continue?'),
729 width: 'auto',
730 modal: true,
731 resizable: false,
732 dialogClass: 'crm-container crm-confirm',
733 close: function () {
734 $(this).dialog('destroy').remove();
735 },
736 options: {
737 no: ts('Cancel'),
738 yes: ts('Continue')
739 }
740 };
741 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
742 if (!settings.buttons && $.isPlainObject(settings.options)) {
743 settings.buttons = [];
744 $.each(settings.options, function(key, label) {
745 settings.buttons.push({
746 text: label,
747 click: function() {
748 var event = $.Event('crmConfirm:' + key);
749 $(this).trigger(event);
750 if (!event.isDefaultPrevented()) {
751 dialog.dialog('close');
752 }
753 }
754 });
755 });
756 }
757 dialog = $('<div class="crm-confirm-dialog"></div>').html(settings.message);
758 delete settings.options;
759 delete settings.message;
760 if ($.isFunction(options)) {
761 dialog.on('crmConfirm:yes', options);
762 }
763 return dialog.dialog(settings).trigger('crmLoad');
764 };
765
766 /** provides a local copy of ts for a domain */
767 CRM.ts = function(domain) {
768 return function(message, options) {
769 if (domain) {
770 options = $.extend(options || {}, {domain: domain});
771 }
772 return ts(message, options);
773 };
774 };
775
776 /**
777 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
778 */
779 $.fn.crmError = function (text, title, options) {
780 title = title || '';
781 text = text || '';
782 options = options || {};
783
784 var extra = {
785 expires: 0
786 };
787 if ($(this).length) {
788 if (title == '') {
789 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
790 if (label.length) {
791 label.addClass('crm-error');
792 var $label = label.clone();
793 if (text == '' && $('.crm-marker', $label).length > 0) {
794 text = $('.crm-marker', $label).attr('title');
795 }
796 $('.crm-marker', $label).remove();
797 title = $label.text();
798 }
799 }
800 $(this).addClass('error');
801 }
802 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
803 if ($(this).length) {
804 var ele = $(this);
805 setTimeout(function () {
806 ele.one('change', function () {
807 msg && msg.close && msg.close();
808 ele.removeClass('error');
809 label.removeClass('crm-error');
810 });
811 }, 1000);
812 }
813 return msg;
814 };
815
816 // Display system alerts through js notifications
817 function messagesFromMarkup() {
818 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
819 var text, title = '';
820 $(this).removeClass('status messages');
821 var type = $(this).attr('class').split(' ')[0] || 'alert';
822 type = type.replace('crm-', '');
823 $('.icon', this).remove();
824 if ($('.msg-text', this).length > 0) {
825 text = $('.msg-text', this).html();
826 title = $('.msg-title', this).html();
827 }
828 else {
829 text = $(this).html();
830 }
831 var options = $(this).data('options') || {};
832 $(this).remove();
833 // Duplicates were already removed server-side
834 options.unique = false;
835 CRM.alert(text, title, type, options);
836 });
837 // Handle qf form errors
838 $('form :input.error', this).one('blur', function() {
839 $('.ui-notify-message.error a.ui-notify-close').click();
840 $(this).removeClass('error');
841 $(this).next('span.crm-error').remove();
842 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
843 .removeClass('crm-error')
844 .find('.crm-error').removeClass('crm-error');
845 });
846 }
847
848 // Preprocess all cj ajax calls to display messages
849 $(document).ajaxSuccess(function(event, xhr, settings) {
850 try {
851 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
852 var response = $.parseJSON(xhr.responseText);
853 if (typeof(response.crmMessages) == 'object') {
854 $.each(response.crmMessages, function(n, msg) {
855 CRM.alert(msg.text, msg.title, msg.type, msg.options);
856 })
857 }
858 }
859 }
860 // Suppress errors
861 catch (e) {}
862 });
863
864 $(function () {
865 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
866 $('.crm-container').trigger('crmLoad');
867
868 if ($('#crm-notification-container').length) {
869 // Initialize notifications
870 $('#crm-notification-container').notify();
871 messagesFromMarkup.call($('#crm-container'));
872 }
873
874 $('body')
875 // bind the event for image popup
876 .on('click', 'a.crm-image-popup', function(e) {
877 CRM.confirm({
878 title: ts('Preview'),
879 resizable: true,
880 message: '<div class="crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>',
881 options: null
882 });
883 e.preventDefault();
884 })
885
886 .on('click', function (event) {
887 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
888 if ($(event.target).is('.btn-slide')) {
889 $(event.target).addClass('btn-slide-active').find('.panel').show();
890 }
891 })
892
893 // Handle clear button for form elements
894 .on('click', 'a.crm-clear-link', function() {
895 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
896 $(this).siblings('input:text').val('').change();
897 return false;
898 })
899 .on('change', 'input.crm-form-radio:checked', function() {
900 $(this).siblings('.crm-clear-link').css({visibility: ''});
901 })
902
903 // Allow normal clicking of links within accordions
904 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
905 e.stopPropagation();
906 })
907 // Handle accordions
908 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
909 if ($(this).parent().hasClass('collapsed')) {
910 $(this).next().css('display', 'none').slideDown(200);
911 }
912 else {
913 $(this).next().css('display', 'block').slideUp(200);
914 }
915 $(this).parent().toggleClass('collapsed');
916 e.preventDefault();
917 });
918
919 $().crmtooltip();
920 });
921 /**
922 * @deprecated
923 */
924 $.fn.crmAccordions = function () {};
925 /**
926 * Collapse or expand an accordion
927 * @param speed
928 */
929 $.fn.crmAccordionToggle = function (speed) {
930 $(this).each(function () {
931 if ($(this).hasClass('collapsed')) {
932 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
933 }
934 else {
935 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
936 }
937 $(this).toggleClass('collapsed');
938 });
939 };
940
941 /**
942 * Clientside currency formatting
943 * @param value
944 * @param format - currency representation of the number 1234.56
945 * @return string
946 * @see CRM_Core_Resources::addCoreResources
947 */
948 var currencyTemplate;
949 CRM.formatMoney = function(value, format) {
950 var decimal, separator, sign, i, j, result;
951 if (value === 'init' && format) {
952 currencyTemplate = format;
953 return;
954 }
955 format = format || currencyTemplate;
956 result = /1(.?)234(.?)56/.exec(format);
957 if (result === null) {
958 return 'Invalid format passed to CRM.formatMoney';
959 }
960 separator = result[1];
961 decimal = result[2];
962 sign = (value < 0) ? '-' : '';
963 //extracting the absolute value of the integer part of the number and converting to string
964 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
965 j = ((j = i.length) > 3) ? j % 3 : 0;
966 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) : '');
967 return format.replace(/1.*234.*56/, result);
968 };
969 })(jQuery, _);