CRM-14408 - handle accordions automatically
[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 (typeof(val) !== 'array') {
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 * Wrapper for select2 initialization function; supplies defaults
243 * @param options object
244 */
245 $.fn.crmSelect2 = function(options) {
246 return $(this).each(function () {
247 var
248 $el = $(this),
249 defaults = {allowClear: !$el.hasClass('required')};
250 // quickform doesn't support optgroups so here's a hack :(
251 $('option[value^=crm_optgroup]', this).each(function () {
252 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
253 $(this).remove();
254 });
255 // Defaults for single-selects
256 if ($el.is('select:not([multiple])')) {
257 defaults.minimumResultsForSearch = 10;
258 if ($('option:first', this).val() === '') {
259 defaults.placeholderOption = 'first';
260 }
261 }
262 $el.select2($.extend(defaults, $el.data('select-params') || {}, options || {}));
263 });
264 };
265
266 /**
267 * @see CRM_Core_Form::addEntityRef for docs
268 * @param options object
269 */
270 $.fn.crmEntityRef = function(options) {
271 options = options || {};
272 options.select = options.select || {};
273 return $(this).each(function() {
274 var
275 $el = $(this),
276 entity = options.entity || $el.data('api-entity') || 'contact',
277 selectParams = {};
278 $el.data('api-entity', entity);
279 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
280 $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api));
281 $el.data('create-links', options.create || $el.data('create-links'));
282 $el.addClass('crm-ajax-select crm-' + entity + '-ref');
283 var settings = {
284 // Use select2 ajax helper instead of CRM.api because it provides more value
285 ajax: {
286 url: CRM.url('civicrm/ajax/rest'),
287 data: function (input, page_num) {
288 var params = $el.data('api-params') || {};
289 params.input = input;
290 params.page_num = page_num;
291 return {
292 entity: $el.data('api-entity'),
293 action: 'getlist',
294 json: JSON.stringify(params)
295 };
296 },
297 results: function(data) {
298 return {more: data.more_results, results: data.values || []};
299 }
300 },
301 minimumInputLength: 1,
302 formatResult: formatSelect2Result,
303 formatSelection: function(row) {
304 return row.label;
305 },
306 escapeMarkup: function (m) {return m;},
307 initSelection: function($el, callback) {
308 var
309 multiple = !!$el.data('select-params').multiple,
310 val = $el.val(),
311 stored = $el.data('entity-value') || [];
312 if (val === '') {
313 return;
314 }
315 // If we already have this data, just return it
316 if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
317 callback(multiple ? stored : stored[0]);
318 } else {
319 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
320 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
321 callback(multiple ? result.values : result.values[0])
322 });
323 }
324 }
325 };
326 if ($el.data('create-links')) {
327 selectParams.formatInputTooShort = function() {
328 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
329 if ($el.data('create-links')) {
330 txt += ' ' + ts('or') + '<br />' + formatSelect2CreateLinks($el);
331 }
332 return txt;
333 };
334 selectParams.formatNoMatches = function() {
335 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
336 return txt + '<br />' + formatSelect2CreateLinks($el);
337 };
338 $el.off('.createLinks').on('select2-open.createLinks', function() {
339 var $el = $(this);
340 $('#select2-drop').off('.crmEntity').on('click.crmEntity', 'a.crm-add-entity', function(e) {
341 $el.select2('close');
342 CRM.loadForm($(this).attr('href'), {
343 dialog: {width: 500, height: 'auto'}
344 }).on('crmFormSuccess', function(e, data) {
345 if (data.status === 'success' && data.id) {
346 CRM.status(ts('%1 Created', {1: data.label}));
347 if ($el.select2('container').hasClass('select2-container-multi')) {
348 var selection = $el.select2('data');
349 selection.push(data);
350 $el.select2('data', selection, true);
351 } else {
352 $el.select2('data', data, true);
353 }
354 }
355 });
356 return false;
357 });
358 });
359 }
360 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams));
361 });
362 };
363
364 function formatSelect2Result(row) {
365 var markup = '<div class="crm-select2-row">';
366 if (row.image !== undefined) {
367 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
368 }
369 else if (row.icon_class) {
370 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
371 }
372 markup += '<div><div class="crm-select2-row-label">' + row.label + '</div>';
373 markup += '<div class="crm-select2-row-description">';
374 $.each(row.description || [], function(k, text) {
375 markup += '<p>' + text + '</p>';
376 });
377 markup += '</div></div></div>';
378 return markup;
379 }
380
381 function formatSelect2CreateLinks($el) {
382 var
383 createLinks = $el.data('create-links'),
384 api = $el.data('api-params') || {},
385 type = api.params ? api.params.contact_type : null;
386 if (createLinks === true) {
387 createLinks = type ? _.where(CRM.profile.contactCreate, {type: type}) : CRM.profile.contactCreate;
388 }
389 var markup = '';
390 _.each(createLinks, function(link) {
391 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
392 if (link.type) {
393 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
394 }
395 markup += link.label + '</a>';
396 });
397 return markup;
398 }
399
400 // Initialize widgets
401 $(document)
402 .on('crmLoad', function(e) {
403 $('table.row-highlight', e.target)
404 .off('.rowHighlight')
405 .on('change.rowHighlight', 'input.select-row, input.select-rows', function () {
406 var target, table = $(this).closest('table');
407 if ($(this).hasClass('select-rows')) {
408 target = $('tbody tr', table);
409 $('input.select-row', table).prop('checked', $(this).prop('checked'));
410 }
411 else {
412 target = $(this).closest('tr');
413 $('input.select-rows', table).prop('checked', $(".select-row:not(':checked')", table).length < 1);
414 }
415 target.toggleClass('crm-row-selected', $(this).is(':checked'));
416 })
417 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
418 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
419 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
420 })
421 .on('dialogopen', function(e) {
422 var $el = $(e.target);
423 // Modal dialogs should disable scrollbars
424 if ($el.dialog('option', 'modal')) {
425 $el.addClass('modal-dialog');
426 $('body').css({overflow: 'hidden'});
427 }
428 $el.parent().find('.ui-dialog-titlebar-close').attr('title', ts('Close'));
429 // Add resize button
430 if ($el.parent().hasClass('crm-container')) {
431 $el.parent().find('.ui-dialog-titlebar').append($('<button class="crm-dialog-titlebar-resize ui-dialog-titlebar-close" title="'+ts('Resize')+'" style="right:2em;"/>').button({icons: {primary: 'ui-icon-newwin'}, text: false}));
432 $('.crm-dialog-titlebar-resize', $el.parent()).click(function(e) {
433 if ($el.data('origSize')) {
434 $el.dialog('option', $el.data('origSize'));
435 $el.data('origSize', null);
436 } else {
437 $el.data('origSize', {
438 position: 'center',
439 width: $el.dialog('option', 'width'),
440 height: $el.dialog('option', 'height')
441 });
442 var menuHeight = $('#civicrm-menu').height();
443 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: [0, menuHeight]});
444 }
445 e.preventDefault();
446 });
447 }
448 })
449 .on('dialogclose', function(e) {
450 // Restore scrollbars when closing modal
451 if ($('.ui-dialog .modal-dialog').not(e.target).length < 1) {
452 $('body').css({overflow: ''});
453 }
454 });
455
456 /**
457 * Function to make multiselect boxes behave as fields in small screens
458 */
459 function advmultiselectResize() {
460 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
461 if (amswidth < 700) {
462 $("form table.advmultiselect td").css('display', 'block');
463 }
464 else {
465 $("form table.advmultiselect td").css('display', 'table-cell');
466 }
467 var contactwidth = $('#crm-container #mainTabContainer').width();
468 if (contactwidth < 600) {
469 $('#crm-container #mainTabContainer').addClass('narrowpage');
470 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
471 if (index > 1) {
472 if (index % 2 == 0) {
473 $(this).parent().after('<tr class="narrowadded"></tr>');
474 }
475 var item = $(this);
476 $(this).parent().next().append(item);
477 }
478 });
479 }
480 else {
481 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
482 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
483 var nitem = $(this);
484 var parent = $(this).parent();
485 $(this).parent().prev().append(nitem);
486 if (parent.children().size() == 0) {
487 parent.remove();
488 }
489 });
490 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
491 }
492 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
493
494 if (cformwidth < 720) {
495 $('#crm-container .contact_basic_information-section').addClass('narrowform');
496 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
497 if (cformwidth < 480) {
498 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
499 }
500 else {
501 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
502 }
503 }
504 else {
505 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
506 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
507 }
508 }
509
510 advmultiselectResize();
511 $(window).resize(function () {
512 advmultiselectResize();
513 });
514
515 $.fn.crmtooltip = function () {
516 $(document)
517 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
518 $(this).addClass('crm-processed');
519 $(this).addClass('crm-tooltip-active');
520 var topDistance = e.pageY - $(window).scrollTop();
521 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
522 $(this).addClass('crm-tooltip-down');
523 }
524 if (!$(this).children('.crm-tooltip-wrapper').length) {
525 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
526 $(this).children().children('.crm-tooltip')
527 .html('<div class="crm-loading-element"></div>')
528 .load(this.href);
529 }
530 })
531 .on('mouseout', 'a.crm-summary-link', function () {
532 $(this).removeClass('crm-processed');
533 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
534 })
535 .on('click', 'a.crm-summary-link', false);
536 };
537
538 var helpDisplay, helpPrevious;
539 CRM.help = function (title, params, url) {
540 if (helpDisplay && helpDisplay.close) {
541 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
542 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
543 helpDisplay.close();
544 return;
545 }
546 helpDisplay.close();
547 }
548 helpPrevious = JSON.stringify(params);
549 params.class_name = 'CRM_Core_Page_Inline_Help';
550 params.type = 'page';
551 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
552 $.ajax(url || CRM.url('civicrm/ajax/inline'),
553 {
554 data: params,
555 dataType: 'html',
556 success: function (data) {
557 $('#crm-notification-container .crm-help .notify-content:last').html(data);
558 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
559 },
560 error: function () {
561 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
562 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
563 }
564 }
565 );
566 };
567 /**
568 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
569 */
570 CRM.status = function(options, deferred) {
571 // 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.
572 if (typeof options === 'string') {
573 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
574 }
575 var opts = $.extend({
576 start: ts('Saving...'),
577 success: ts('Saved'),
578 error: function() {
579 CRM.alert(ts('Sorry an error occurred and your information was not saved'), ts('Error'));
580 }
581 }, options || {});
582 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>')
583 .appendTo('body');
584 $msg.css('min-width', $msg.width());
585 function handle(status, data) {
586 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
587 if (endMsg) {
588 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg);
589 window.setTimeout(function() {
590 $msg.fadeOut('slow', function() {$msg.remove()});
591 }, 2000);
592 } else {
593 $msg.remove();
594 }
595 }
596 return (deferred || new $.Deferred())
597 .done(function(data) {
598 // If the server returns an error msg call the error handler
599 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
600 handle(status, data);
601 })
602 .fail(function(data) {
603 handle('error', data);
604 });
605 };
606
607 /**
608 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
609 */
610 CRM.alert = function (text, title, type, options) {
611 type = type || 'alert';
612 title = title || '';
613 options = options || {};
614 if ($('#crm-notification-container').length) {
615 var params = {
616 text: text,
617 title: title,
618 type: type
619 };
620 // By default, don't expire errors and messages containing links
621 var extra = {
622 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
623 unique: true
624 };
625 options = $.extend(extra, options);
626 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
627 if (options.unique && options.unique !== '0') {
628 $('#crm-notification-container .ui-notify-message').each(function () {
629 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
630 $('.icon.ui-notify-close', this).click();
631 }
632 });
633 }
634 return $('#crm-notification-container').notify('create', params, options);
635 }
636 else {
637 if (title.length) {
638 text = title + "\n" + text;
639 }
640 alert(text);
641 return null;
642 }
643 };
644
645 /**
646 * Close whichever alert contains the given node
647 *
648 * @param node
649 */
650 CRM.closeAlertByChild = function (node) {
651 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
652 };
653
654 /**
655 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
656 */
657 CRM.confirm = function (options) {
658 var dialog, settings = {
659 title: ts('Confirm Action'),
660 message: ts('Are you sure you want to continue?'),
661 width: 'auto',
662 modal: true,
663 dialogClass: 'crm-container crm-confirm',
664 close: function () {
665 $(this).dialog('destroy').remove();
666 },
667 options: {
668 no: ts('Cancel'),
669 yes: ts('Continue')
670 }
671 };
672 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
673 if (!settings.buttons && $.isPlainObject(settings.options)) {
674 settings.buttons = [];
675 $.each(settings.options, function(key, label) {
676 settings.buttons.push({
677 text: label,
678 click: function() {
679 var event = $.Event('crmConfirm:' + key);
680 $(this).trigger(event);
681 if (!event.isDefaultPrevented()) {
682 dialog.dialog('close');
683 }
684 }
685 });
686 });
687 }
688 dialog = $('<div class="crm-confirm-dialog"></div>').html(settings.message);
689 delete settings.options;
690 delete settings.message;
691 if ($.isFunction(options)) {
692 dialog.on('crmConfirm:yes', options);
693 }
694 return dialog.dialog(settings).trigger('crmLoad');
695 };
696
697 /**
698 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
699 */
700 $.fn.crmError = function (text, title, options) {
701 title = title || '';
702 text = text || '';
703 options = options || {};
704
705 var extra = {
706 expires: 0
707 };
708 if ($(this).length) {
709 if (title == '') {
710 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
711 if (label.length) {
712 label.addClass('crm-error');
713 var $label = label.clone();
714 if (text == '' && $('.crm-marker', $label).length > 0) {
715 text = $('.crm-marker', $label).attr('title');
716 }
717 $('.crm-marker', $label).remove();
718 title = $label.text();
719 }
720 }
721 $(this).addClass('error');
722 }
723 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
724 if ($(this).length) {
725 var ele = $(this);
726 setTimeout(function () {
727 ele.one('change', function () {
728 msg && msg.close && msg.close();
729 ele.removeClass('error');
730 label.removeClass('crm-error');
731 });
732 }, 1000);
733 }
734 return msg;
735 };
736
737 // Display system alerts through js notifications
738 function messagesFromMarkup() {
739 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
740 var text, title = '';
741 $(this).removeClass('status messages');
742 var type = $(this).attr('class').split(' ')[0] || 'alert';
743 type = type.replace('crm-', '');
744 $('.icon', this).remove();
745 if ($('.msg-text', this).length > 0) {
746 text = $('.msg-text', this).html();
747 title = $('.msg-title', this).html();
748 }
749 else {
750 text = $(this).html();
751 }
752 var options = $(this).data('options') || {};
753 $(this).remove();
754 // Duplicates were already removed server-side
755 options.unique = false;
756 CRM.alert(text, title, type, options);
757 });
758 // Handle qf form errors
759 $('form :input.error', this).one('blur', function() {
760 $('.ui-notify-message.error a.ui-notify-close').click();
761 $(this).removeClass('error');
762 $(this).next('span.crm-error').remove();
763 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
764 .removeClass('crm-error')
765 .find('.crm-error').removeClass('crm-error');
766 });
767 }
768
769 // Preprocess all cj ajax calls to display messages
770 $(document).ajaxSuccess(function(event, xhr, settings) {
771 try {
772 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
773 var response = $.parseJSON(xhr.responseText);
774 if (typeof(response.crmMessages) == 'object') {
775 $.each(response.crmMessages, function(n, msg) {
776 CRM.alert(msg.text, msg.title, msg.type, msg.options);
777 })
778 }
779 }
780 }
781 // Suppress errors
782 catch (e) {}
783 });
784
785 /**
786 * Temporary stub to get around name conflict with legacy jQuery.autocomplete plugin
787 * FIXME: Remove this before 4.5 release
788 */
789 $.widget('civi.crmAutocomplete', $.ui.autocomplete, {});
790
791 $(function () {
792 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
793 $('.crm-container').trigger('crmLoad');
794
795 if ($('#crm-notification-container').length) {
796 // Initialize notifications
797 $('#crm-notification-container').notify();
798 messagesFromMarkup.call($('#crm-container'));
799 }
800
801 $('body')
802 // bind the event for image popup
803 .on('click', 'a.crm-image-popup', function(e) {
804 CRM.confirm({
805 title: ts('Preview'),
806 message: '<div class="crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>',
807 options: null
808 });
809 e.preventDefault();
810 })
811
812 .on('click', function (event) {
813 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
814 if ($(event.target).is('.btn-slide')) {
815 $(event.target).addClass('btn-slide-active').find('.panel').show();
816 }
817 })
818
819 // Handle clear button for form elements
820 .on('click', 'a.crm-clear-link', function() {
821 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
822 $(this).siblings('input:text').val('').change();
823 return false;
824 })
825 .on('change', 'input.crm-form-radio:checked', function() {
826 $(this).siblings('.crm-clear-link').css({visibility: ''});
827 })
828
829 // Allow normal clicking of links within accordions
830 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
831 e.stopPropagation();
832 })
833 // Handle accordions
834 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
835 if ($(this).parent().hasClass('collapsed')) {
836 $(this).next().css('display', 'none').slideDown(200);
837 }
838 else {
839 $(this).next().css('display', 'block').slideUp(200);
840 }
841 $(this).parent().toggleClass('collapsed');
842 e.preventDefault();
843 });
844
845 $().crmtooltip();
846 });
847 /**
848 * @deprecated
849 */
850 $.fn.crmAccordions = function () {};
851 /**
852 * Collapse or expand an accordion
853 * @param speed
854 */
855 $.fn.crmAccordionToggle = function (speed) {
856 $(this).each(function () {
857 if ($(this).hasClass('collapsed')) {
858 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
859 }
860 else {
861 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
862 }
863 $(this).toggleClass('collapsed');
864 });
865 };
866
867 /**
868 * Clientside currency formatting
869 * @param value
870 * @param format - currency representation of the number 1234.56
871 * @return string
872 * @see CRM_Core_Resources::addCoreResources
873 */
874 var currencyTemplate;
875 CRM.formatMoney = function(value, format) {
876 var decimal, separator, sign, i, j, result;
877 if (value === 'init' && format) {
878 currencyTemplate = format;
879 return;
880 }
881 format = format || currencyTemplate;
882 result = /1(.?)234(.?)56/.exec(format);
883 if (result === null) {
884 return 'Invalid format passed to CRM.formatMoney';
885 }
886 separator = result[1];
887 decimal = result[2];
888 sign = (value < 0) ? '-' : '';
889 //extracting the absolute value of the integer part of the number and converting to string
890 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
891 j = ((j = i.length) > 3) ? j % 3 : 0;
892 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) : '');
893 return format.replace(/1.*234.*56/, result);
894 };
895 })(jQuery, _);