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