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