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