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