Merge pull request #4677 from colemanw/CRM-15495
[civicrm-core.git] / js / Common.js
CommitLineData
353ea873 1// https://civicrm.org/licensing
6a488035 2var CRM = CRM || {};
4b513f23
CW
3var cj = CRM.$ = jQuery;
4CRM._ = _;
6a488035
TO
5
6/**
7 * Short-named function for string translation, defined in global scope so it's available everywhere.
8 *
353ea873
CW
9 * @param text string for translating
10 * @param params object key:value of additional parameters
6a488035 11 *
353ea873 12 * @return string
6a488035
TO
13 */
14function ts(text, params) {
7553cf23 15 "use strict";
6a488035 16 text = CRM.strings[text] || text;
2788147f 17 if (typeof(params) === 'object') {
6a488035 18 for (var i in params) {
32155ad6 19 if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') {
2788147f 20 // sprintf emulation: escape % characters in the replacements to avoid conflicts
32155ad6 21 text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-'));
2788147f 22 }
6a488035
TO
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 *
353ea873 35 * @deprecated
6a488035
TO
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 ...)
6a488035 39 */
0f5816a6
KJ
40function 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;
6a488035 51 }
0f5816a6
KJ
52 else {
53 alert('showBlocks array item not in .tpl = ' + showBlocks[i]);
54 }
55 }
6a488035 56
0f5816a6
KJ
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]);
6a488035 66 }
0f5816a6 67 }
6a488035
TO
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 *
353ea873 74 * @deprecated
6a488035
TO
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
0f5816a6
KJ
81 */
82function showHideByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, invert) {
0f5816a6
KJ
83
84 if (field_type == 'select') {
85 var trigger = trigger_value.split("|");
24cc4545 86 var selectedOptionValue = cj('#' + trigger_field_id).val();
0f5816a6
KJ
87
88 var target = target_element_id.split("|");
89 for (var j = 0; j < target.length; j++) {
90 if (invert) {
91 cj('#' + target[j]).show();
92 }
93 else {
94 cj('#' + target[j]).hide();
95 }
96 for (var i = 0; i < trigger.length; i++) {
97 if (selectedOptionValue == trigger[i]) {
98 if (invert) {
99 cj('#' + target[j]).hide();
100 }
101 else {
102 cj('#' + target[j]).show();
103 }
6a488035 104 }
0f5816a6
KJ
105 }
106 }
6a488035 107
0f5816a6
KJ
108 }
109 else {
110 if (field_type == 'radio') {
111 var target = target_element_id.split("|");
112 for (var j = 0; j < target.length; j++) {
5fb3af09 113 if (cj('[name="' + trigger_field_id + '"]:first').is(':checked')) {
0f5816a6
KJ
114 if (invert) {
115 cj('#' + target[j]).hide();
116 }
117 else {
118 cj('#' + target[j]).show();
119 }
6a488035 120 }
0f5816a6
KJ
121 else {
122 if (invert) {
123 cj('#' + target[j]).show();
124 }
125 else {
126 cj('#' + target[j]).hide();
127 }
128 }
129 }
6a488035 130 }
0f5816a6 131 }
6a488035
TO
132}
133
6a488035
TO
134/**
135 * Function to change button text and disable one it is clicked
353ea873 136 * @deprecated
6a488035
TO
137 * @param obj object - the button clicked
138 * @param formID string - the id of the form being submitted
139 * @param string procText - button text after user clicks it
353ea873 140 * @return bool
6a488035 141 */
0f5816a6 142var submitcount = 0;
c6edd786 143/* Changes button label on submit, and disables button after submit for newer browsers.
144 Puts up alert for older browsers. */
0f5816a6
KJ
145function submitOnce(obj, formId, procText) {
146 // if named button clicked, change text
147 if (obj.value != null) {
148 obj.value = procText + " ...";
149 }
47ea29e3 150 cj(obj).closest('form').attr('data-warn-changes', 'false');
0f5816a6
KJ
151 if (document.getElementById) { // disable submit button for newer browsers
152 obj.disabled = true;
153 document.getElementById(formId).submit();
154 return true;
155 }
156 else { // for older browsers
157 if (submitcount == 0) {
158 submitcount++;
159 return true;
160 }
161 else {
162 alert("Your request is currently being processed ... Please wait.");
163 return false;
6a488035 164 }
0f5816a6 165 }
6a488035 166}
6a488035 167
6a488035
TO
168/**
169 * Function to show / hide the row in optionFields
353ea873
CW
170 * @deprecated
171 * @param index string, element whose innerHTML is to hide else will show the hidden row.
6a488035 172 */
0f5816a6
KJ
173function showHideRow(index) {
174 if (index) {
175 cj('tr#optionField_' + index).hide();
176 if (cj('table#optionField tr:hidden:first').length) {
177 cj('div#optionFieldLink').show();
6a488035 178 }
0f5816a6
KJ
179 }
180 else {
181 cj('table#optionField tr:hidden:first').show();
182 if (!cj('table#optionField tr:hidden:last').length) {
183 cj('div#optionFieldLink').hide();
184 }
185 }
186 return false;
6a488035
TO
187}
188
475e9f44 189CRM.utils = CRM.utils || {};
6a488035 190CRM.strings = CRM.strings || {};
6a488035 191
4b513f23 192(function ($, _, undefined) {
7553cf23 193 "use strict";
d664f648 194
3f586963
CW
195 // Theme classes for unattached elements
196 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container';
197
47f21f3a
CW
198 // https://github.com/ivaynberg/select2/pull/2090
199 $.fn.select2.defaults.width = 'resolve';
200
e20523a8
CW
201 // Workaround for https://github.com/ivaynberg/select2/issues/1246
202 $.ui.dialog.prototype._allowInteraction = function(e) {
a7c4a5a8 203 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop, .cke_dialog').length;
e20523a8
CW
204 };
205
475e9f44
CW
206 /**
207 * Populate a select list, overwriting the existing options except for the placeholder.
581c7be2 208 * @param select jquery selector - 1 or more select elements
475e9f44 209 * @param options array in format returned by api.getoptions
b7ceb253
CW
210 * @param placeholder string|bool - new placeholder or false (default) to keep the old one
211 * @param value string|array - will silently update the element with new value without triggering change
475e9f44 212 */
b7ceb253 213 CRM.utils.setOptions = function(select, options, placeholder, value) {
581c7be2 214 $(select).each(function() {
475e9f44
CW
215 var
216 $elect = $(this),
b7ceb253
CW
217 val = value || $elect.val() || [],
218 opts = placeholder || placeholder === '' ? '' : '[value!=""]';
23e8a31b 219 $elect.find('option' + opts).remove();
b7ceb253 220 var newOptions = CRM.utils.renderOptions(options, val);
1d07e7ab 221 if (typeof placeholder === 'string') {
581c7be2
CW
222 if ($elect.is('[multiple]')) {
223 select.attr('placeholder', placeholder);
1d07e7ab
CW
224 } else {
225 newOptions = '<option value="">' + placeholder + '</option>' + newOptions;
226 }
227 }
228 $elect.append(newOptions);
b7ceb253
CW
229 if (!value) {
230 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
231 }
475e9f44
CW
232 });
233 };
234
b7ceb253
CW
235 /**
236 * Render an option list
237 * @param options array
238 * @param val default value
239 * @internal param rendered
240 * @return string
241 */
242 CRM.utils.renderOptions = function(options, val) {
243 var rendered = arguments[2] || '';
244 if (!$.isArray(val)) {
245 val = [val];
246 }
247 _.each(options, function(option) {
248 if (option.children) {
249 rendered += '<optgroup label="' + option.value + '">' +
250 CRM.utils.renderOptions(option.children, val, rendered) +
251 '</optgroup>';
252 } else {
253 var selected = ($.inArray('' + option.key, val) > -1) ? 'selected="selected"' : '';
254 rendered += '<option value="' + option.key + '"' + selected + '>' + option.value + '</option>';
255 }
256 });
257 return rendered;
258 };
259
1d07e7ab
CW
260 function chainSelect() {
261 var $form = $(this).closest('form'),
262 $target = $('select[data-name="' + $(this).data('target') + '"]', $form),
263 data = $target.data(),
264 val = $(this).val();
265 $target.prop('disabled', true);
266 if ($target.is('select.crm-chain-select-control')) {
267 $('select[data-name="' + $target.data('target') + '"]', $form).prop('disabled', true).blur();
268 }
269 if (!(val && val.length)) {
270 CRM.utils.setOptions($target.blur(), [], data.emptyPrompt);
271 } else {
272 $target.addClass('loading');
273 $.getJSON(CRM.url(data.callback), {_value: val}, function(vals) {
274 $target.prop('disabled', false).removeClass('loading');
275 CRM.utils.setOptions($target, vals || [], (vals && vals.length ? data.selectPrompt : data.nonePrompt));
276 });
277 }
278 }
279
3e201321 280/**
281 * Compare Form Input values against cached initial value.
88e9380e
CW
282 *
283 * @return {Boolean} true if changes have been made.
3e201321 284 */
285 CRM.utils.initialValueChanged = function(el) {
88e9380e 286 var isDirty = false;
18469bf2 287 $(':input:visible, .select2-container:visible+:input.select2-offscreen', el).not('[type=submit], [type=button], .crm-action-menu').each(function () {
88e9380e 288 var initialValue = $(this).data('crm-initial-value');
3c0624e2 289 // skip change of value for submit buttons
bf7a4fbc 290 if (initialValue !== undefined && !_.isEqual(initialValue, $(this).val())) {
88e9380e
CW
291 isDirty = true;
292 }
3e201321 293 });
294 return isDirty;
8d36b801 295 };
3e201321 296
ba4fb2b2 297 /**
353ea873 298 * Wrapper for select2 initialization function; supplies defaults
a88cf11a 299 * @param options object
ba4fb2b2 300 */
a88cf11a
CW
301 $.fn.crmSelect2 = function(options) {
302 return $(this).each(function () {
303 var
304 $el = $(this),
a243158e 305 settings = {allowClear: !$el.hasClass('required')};
a88cf11a
CW
306 // quickform doesn't support optgroups so here's a hack :(
307 $('option[value^=crm_optgroup]', this).each(function () {
308 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
309 $(this).remove();
310 });
311 // Defaults for single-selects
312 if ($el.is('select:not([multiple])')) {
a243158e 313 settings.minimumResultsForSearch = 10;
a88cf11a 314 if ($('option:first', this).val() === '') {
a243158e 315 settings.placeholderOption = 'first';
a88cf11a 316 }
ba4fb2b2 317 }
a243158e
CW
318 $.extend(settings, $el.data('select-params') || {}, options || {});
319 if (settings.ajax) {
320 $el.addClass('crm-ajax-select');
321 }
322 $el.select2(settings);
a88cf11a
CW
323 });
324 };
325
326 /**
353ea873 327 * @see CRM_Core_Form::addEntityRef for docs
a88cf11a
CW
328 * @param options object
329 */
330 $.fn.crmEntityRef = function(options) {
331 options = options || {};
332 options.select = options.select || {};
333 return $(this).each(function() {
334 var
4c993609 335 $el = $(this).off('.crmEntity'),
a88cf11a
CW
336 entity = options.entity || $el.data('api-entity') || 'contact',
337 selectParams = {};
338 $el.data('api-entity', entity);
339 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
340 $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api));
a4799f04 341 $el.data('create-links', options.create || $el.data('create-links'));
b7ceb253 342 $el.addClass('crm-form-entityref crm-' + entity.toLowerCase() + '-ref');
ba4fb2b2 343 var settings = {
b7ceb253 344 // Use select2 ajax helper instead of CRM.api3 because it provides more value
ba4fb2b2
CW
345 ajax: {
346 url: CRM.url('civicrm/ajax/rest'),
347 data: function (input, page_num) {
b7ceb253 348 var params = getEntityRefApiParams($el);
ba4fb2b2
CW
349 params.input = input;
350 params.page_num = page_num;
351 return {
352 entity: $el.data('api-entity'),
353 action: 'getlist',
354 json: JSON.stringify(params)
355 };
356 },
357 results: function(data) {
358 return {more: data.more_results, results: data.values || []};
359 }
360 },
a88cf11a 361 minimumInputLength: 1,
3c0b6a40 362 formatResult: CRM.utils.formatSelect2Result,
ba4fb2b2
CW
363 formatSelection: function(row) {
364 return row.label;
365 },
366 escapeMarkup: function (m) {return m;},
a88cf11a
CW
367 initSelection: function($el, callback) {
368 var
369 multiple = !!$el.data('select-params').multiple,
370 val = $el.val(),
371 stored = $el.data('entity-value') || [];
372 if (val === '') {
373 return;
374 }
375 // If we already have this data, just return it
376 if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
377 callback(multiple ? stored : stored[0]);
378 } else {
78b203e5 379 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
a88cf11a 380 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
d2b4810b
CW
381 callback(multiple ? result.values : result.values[0]);
382 // Trigger change (store data to avoid an infinite loop of lookups)
383 $el.data('entity-value', result.values).trigger('change');
a88cf11a
CW
384 });
385 }
ba4fb2b2
CW
386 }
387 };
b7ceb253
CW
388 // Create new items inline - works for tags
389 if ($el.data('create-links') && entity.toLowerCase() === 'tag') {
390 selectParams.createSearchChoice = function(term, data) {
391 if (!_.findKey(data, {label: term})) {
392 return {id: "0", term: term, label: term + ' (' + ts('new tag') + ')'};
393 }
394 };
395 selectParams.tokenSeparators = [','];
396 selectParams.createSearchChoicePosition = 'bottom';
05b21c58
CW
397 $el.on('select2-selecting.crmEntity', function(e) {
398 if (e.val === "0") {
399 // Create a new term
400 e.object.label = e.object.term;
401 CRM.api3(entity, 'create', $.extend({name: e.object.term}, $el.data('api-params').params || {}))
402 .done(function(created) {
403 var
404 val = $el.select2('val'),
405 data = $el.select2('data'),
406 item = {id: created.id, label: e.object.term};
407 if (val === "0") {
408 $el.select2('data', item, true);
409 }
410 else if ($.isArray(val) && $.inArray("0", val) > -1) {
411 _.remove(data, {id: "0"});
412 data.push(item);
413 $el.select2('data', data, true);
414 }
415 });
416 }
417 });
b7ceb253
CW
418 }
419 else {
a88cf11a
CW
420 selectParams.formatInputTooShort = function() {
421 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
b7ceb253
CW
422 txt += renderEntityRefFilters($el);
423 txt += renderEntityRefCreateLinks($el);
ba4fb2b2
CW
424 return txt;
425 };
a88cf11a 426 selectParams.formatNoMatches = function() {
ba4fb2b2 427 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
b7ceb253
CW
428 txt += renderEntityRefFilters($el);
429 txt += renderEntityRefCreateLinks($el);
430 return txt;
ba4fb2b2 431 };
4c993609 432 $el.on('select2-open.crmEntity', function() {
ba4fb2b2 433 var $el = $(this);
b7ceb253
CW
434 loadEntityRefFilterOptions($el);
435 $('#select2-drop')
436 .off('.crmEntity')
437 .on('click.crmEntity', 'a.crm-add-entity', function(e) {
438 $el.select2('close');
439 CRM.loadForm($(this).attr('href'), {
440 dialog: {width: 500, height: 'auto'}
441 }).on('crmFormSuccess', function(e, data) {
442 if (data.status === 'success' && data.id) {
443 CRM.status(ts('%1 Created', {1: data.label}));
444 if ($el.select2('container').hasClass('select2-container-multi')) {
445 var selection = $el.select2('data');
446 selection.push(data);
447 $el.select2('data', selection, true);
448 } else {
449 $el.select2('data', data, true);
450 }
c92f6436 451 }
b7ceb253
CW
452 });
453 return false;
454 })
455 .on('change.crmEntity', 'select.crm-entityref-filter-value', function() {
456 var filter = $el.data('user-filter') || {};
457 filter.value = $(this).val();
458 $(this).toggleClass('active', !!filter.value);
459 $el.data('user-filter', filter);
460 if (filter.value) {
461 // Once a filter has been chosen, rerender create links and refocus the search box
462 $el.select2('close');
463 $el.select2('open');
ba4fb2b2 464 }
b7ceb253
CW
465 })
466 .on('change.crmEntity', 'select.crm-entityref-filter-key', function() {
467 var filter = $el.data('user-filter') || {};
468 filter.key = $(this).val();
469 $(this).toggleClass('active', !!filter.key);
470 $el.data('user-filter', filter);
471 loadEntityRefFilterOptions($el);
ba4fb2b2 472 });
ba4fb2b2
CW
473 });
474 }
05b21c58 475 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams));
a88cf11a 476 });
ba4fb2b2
CW
477 };
478
b7ceb253
CW
479 /**
480 * Combine api-params with user-filter
481 * @param $el
482 * @returns {*}
483 */
484 function getEntityRefApiParams($el) {
485 var
486 params = $.extend({params: {}}, $el.data('api-params') || {}),
487 // Prevent original data from being modified - $.extend and _.clone don't cut it, they pass nested objects by reference!
488 combined = _.cloneDeep(params),
489 filter = $.extend({}, $el.data('user-filter') || {});
490 if (filter.key && filter.value) {
491 // Special case for contact type/sub-type combo
492 if (filter.key === 'contact_type' && (filter.value.indexOf('.') > 0)) {
493 combined.params.contact_type = filter.value.split('.')[0];
494 combined.params.contact_sub_type = filter.value.split('.')[1];
495 } else {
496 combined.params[filter.key] = filter.value;
497 }
498 }
499 return combined;
500 }
501
3c0b6a40 502 CRM.utils.formatSelect2Result = function (row) {
88881f79 503 var markup = '<div class="crm-select2-row">';
ff88d165 504 if (row.image !== undefined) {
88881f79 505 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
ff88d165 506 }
54bee7df 507 else if (row.icon_class) {
88881f79 508 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
54bee7df 509 }
3c0b6a40 510 markup += '<div><div class="crm-select2-row-label '+(row.label_class || '')+'">' + row.label + '</div>';
88881f79
CW
511 markup += '<div class="crm-select2-row-description">';
512 $.each(row.description || [], function(k, text) {
513 markup += '<p>' + text + '</p>';
514 });
515 markup += '</div></div></div>';
ff88d165 516 return markup;
3c0b6a40 517 };
a4799f04 518
b7ceb253 519 function renderEntityRefCreateLinks($el) {
a4799f04
CW
520 var
521 createLinks = $el.data('create-links'),
b7ceb253
CW
522 params = getEntityRefApiParams($el).params,
523 markup = '<div class="crm-entityref-links">';
524 if (!createLinks || $el.data('api-entity').toLowerCase() !== 'contact') {
525 return '';
526 }
a4799f04 527 if (createLinks === true) {
b7ceb253 528 createLinks = params.contact_type ? _.where(CRM.config.entityRef.contactCreate, {type: params.contact_type}) : CRM.config.entityRef.contactCreate;
a4799f04 529 }
a4799f04 530 _.each(createLinks, function(link) {
79ae07d9 531 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
a4799f04
CW
532 if (link.type) {
533 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
79ae07d9
CW
534 }
535 markup += link.label + '</a>';
536 });
b7ceb253
CW
537 markup += '</div>';
538 return markup;
539 }
540
541 function getEntityRefFilters($el) {
542 var
543 entity = $el.data('api-entity').toLowerCase(),
544 filters = $.extend([], CRM.config.entityRef.filters[entity] || []),
545 filter = $el.data('user-filter') || {},
546 params = $.extend({params: {}}, $el.data('api-params') || {}).params,
547 result = [];
548 $.each(filters, function() {
549 if (typeof params[this.key] === 'undefined') {
550 result.push(this);
551 }
552 else if (this.key == 'contact_type' && typeof params.contact_sub_type === 'undefined') {
553 this.options = _.remove(this.options, function(option) {
554 return option.key.indexOf(params.contact_type + '.') === 0;
555 });
556 result.push(this);
557 }
558 });
559 return result;
560 }
561
562 function renderEntityRefFilters($el) {
563 var
564 filters = getEntityRefFilters($el),
565 filter = $el.data('user-filter') || {},
566 filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null;
567 if (!filters.length) {
568 return '';
569 }
570 var markup = '<div class="crm-entityref-filters">' +
571 '<select class="crm-entityref-filter-key' + (filter.key ? ' active' : '') + '">' +
572 '<option value="">' + ts('Refine search...') + '</option>' +
573 CRM.utils.renderOptions(filters, filter.key) +
574 '</select> &nbsp; ' +
575 '<select class="crm-entityref-filter-value' + (filter.key ? ' active"' : '"') + (filter.key ? '' : ' style="display:none;"') + '>' +
576 '<option value="">' + ts('- select -') + '</option>';
577 if (filterSpec && filterSpec.options) {
578 markup += CRM.utils.renderOptions(filterSpec.options, filter.value);
579 }
580 markup += '</select></div>';
79ae07d9 581 return markup;
a4799f04 582 }
ff88d165 583
b7ceb253
CW
584 /**
585 * Fetch options for a filter (via ajax if necessary) and populate the appropriate select list
586 * @param $el
587 */
588 function loadEntityRefFilterOptions($el) {
589 var
590 filters = getEntityRefFilters($el),
591 filter = $el.data('user-filter') || {},
592 filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null,
593 $valField = $('.crm-entityref-filter-value', '#select2-drop');
594 if (filterSpec) {
595 $valField.show().val('');
596 if (filterSpec.options) {
597 CRM.utils.setOptions($valField, filterSpec.options, false, filter.value);
598 } else {
599 $valField.prop('disabled', true);
600 CRM.api3(filterSpec.entity || $el.data('api-entity'), 'getoptions', {field: filter.key, sequential: 1})
601 .done(function(result) {
602 var entity = $el.data('api-entity').toLowerCase(),
603 globalFilterSpec = _.find(CRM.config.entityRef.filters[entity], {key: filter.key}) || {};
604 // Store options globally so we don't have to look them up again
605 globalFilterSpec.options = result.values;
606 $valField.prop('disabled', false);
607 CRM.utils.setOptions($valField, result.values);
608 $valField.val(filter.value || '');
609 });
610 }
611 } else {
612 $valField.hide();
613 }
614 }
615
3d527838
CW
616 /**
617 * Wrapper for jQuery validate initialization function; supplies defaults
3d527838
CW
618 */
619 $.fn.crmValidate = function(params) {
620 return $(this).each(function () {
621 var that = this,
622 settings = $.extend({}, CRM.validate._defaults, CRM.validate.params);
623 $(this).validate(settings);
624 // Call any post-initialization callbacks
625 if (CRM.validate.functions && CRM.validate.functions.length) {
626 $.each(CRM.validate.functions, function(i, func) {
627 func.call(that);
628 });
629 }
630 });
b7ceb253 631 };
3d527838 632
f7b92fcd 633 // Initialize widgets
eb90857a
CW
634 $(document)
635 .on('crmLoad', function(e) {
636 $('table.row-highlight', e.target)
637 .off('.rowHighlight')
7e13d44e
CW
638 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) {
639 var filter, $table = $(this).closest('table');
eb90857a 640 if ($(this).hasClass('select-rows')) {
7e13d44e
CW
641 filter = $(this).prop('checked') ? ':not(:checked)' : ':checked';
642 $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
eb90857a
CW
643 }
644 else {
7e13d44e
CW
645 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
646 if (data !== 'master-selected') {
647 $('input.select-rows', $table).prop('checked', $(".select-row:not(':checked')", $table).length < 1);
648 }
eb90857a 649 }
eb90857a
CW
650 })
651 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
82661158
JP
652 if ($("input:radio[name=radio_ts]").size() == 1) {
653 $("input:radio[name=radio_ts]").prop("checked", true);
654 }
5f34e50b
CW
655 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
656 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
1d07e7ab 657 $('select.crm-chain-select-control', e.target).off('.chainSelect').on('change.chainSelect', chainSelect);
3e201321 658 // Cache Form Input initial values
88e9380e 659 $('form[data-warn-changes] :input', e.target).each(function() {
329758bb 660 $(this).data('crm-initial-value', $(this).val());
3e201321 661 });
eb90857a 662 })
eb90857a 663 .on('dialogopen', function(e) {
f292709b
CW
664 var $el = $(e.target);
665 // Modal dialogs should disable scrollbars
666 if ($el.dialog('option', 'modal')) {
667 $el.addClass('modal-dialog');
eb90857a
CW
668 $('body').css({overflow: 'hidden'});
669 }
f292709b 670 // Add resize button
a243158e 671 if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) {
77a8d7f9 672 $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}));
f292709b
CW
673 $('.crm-dialog-titlebar-resize', $el.parent()).click(function(e) {
674 if ($el.data('origSize')) {
675 $el.dialog('option', $el.data('origSize'));
676 $el.data('origSize', null);
677 } else {
28d510ab 678 var menuHeight = $('#civicrm-menu').outerHeight();
f292709b 679 $el.data('origSize', {
28d510ab 680 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
f292709b
CW
681 width: $el.dialog('option', 'width'),
682 height: $el.dialog('option', 'height')
683 });
f2f191fe 684 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: {my: "top", at: "top+"+menuHeight, of: window}});
f292709b
CW
685 }
686 e.preventDefault();
687 });
688 }
eb90857a
CW
689 })
690 .on('dialogclose', function(e) {
f292709b 691 // Restore scrollbars when closing modal
5a6148a0 692 if ($('.ui-dialog .modal-dialog:visible').not(e.target).length < 1) {
eb90857a
CW
693 $('body').css({overflow: ''});
694 }
afc021d8 695 })
696 .on('submit', function(e) {
f582fc8f 697 // CRM-14353 - disable changes warn when submitting a form
abb6e044 698 $('[data-warn-changes]').attr('data-warn-changes', 'false');
afc021d8 699 })
f582fc8f
CW
700 ;
701
702 // CRM-14353 - Warn of unsaved changes for forms which have opted in
703 window.onbeforeunload = function() {
18469bf2 704 if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
f582fc8f
CW
705 return ts('You have unsaved changes.');
706 }
707 };
148c4e8d
CW
708
709 /**
710 * Function to make multiselect boxes behave as fields in small screens
711 */
712 function advmultiselectResize() {
713 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
714 if (amswidth < 700) {
715 $("form table.advmultiselect td").css('display', 'block');
0f5816a6
KJ
716 }
717 else {
148c4e8d
CW
718 $("form table.advmultiselect td").css('display', 'table-cell');
719 }
720 var contactwidth = $('#crm-container #mainTabContainer').width();
721 if (contactwidth < 600) {
722 $('#crm-container #mainTabContainer').addClass('narrowpage');
0f5816a6 723 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
148c4e8d 724 if (index > 1) {
0f5816a6 725 if (index % 2 == 0) {
148c4e8d
CW
726 $(this).parent().after('<tr class="narrowadded"></tr>');
727 }
728 var item = $(this);
729 $(this).parent().next().append(item);
730 }
731 });
0f5816a6
KJ
732 }
733 else {
148c4e8d 734 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
0f5816a6 735 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
148c4e8d
CW
736 var nitem = $(this);
737 var parent = $(this).parent();
738 $(this).parent().prev().append(nitem);
0f5816a6 739 if (parent.children().size() == 0) {
148c4e8d
CW
740 parent.remove();
741 }
742 });
743 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
744 }
745 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
0f5816a6 746
148c4e8d
CW
747 if (cformwidth < 720) {
748 $('#crm-container .contact_basic_information-section').addClass('narrowform');
749 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
750 if (cformwidth < 480) {
751 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
0f5816a6
KJ
752 }
753 else {
148c4e8d
CW
754 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
755 }
0f5816a6
KJ
756 }
757 else {
148c4e8d
CW
758 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
759 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
760 }
761 }
0f5816a6 762
148c4e8d 763 advmultiselectResize();
a2c28a94 764 $(window).resize(advmultiselectResize);
6a488035 765
0f5816a6 766 $.fn.crmtooltip = function () {
2c29c2ac
RN
767 $(document)
768 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
769 $(this).addClass('crm-processed');
e24b17b9
CW
770 $(this).addClass('crm-tooltip-active');
771 var topDistance = e.pageY - $(window).scrollTop();
772 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
773 $(this).addClass('crm-tooltip-down');
774 }
775 if (!$(this).children('.crm-tooltip-wrapper').length) {
6a488035
TO
776 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
777 $(this).children().children('.crm-tooltip')
778 .html('<div class="crm-loading-element"></div>')
779 .load(this.href);
780 }
781 })
2c29c2ac
RN
782 .on('mouseout', 'a.crm-summary-link', function () {
783 $(this).removeClass('crm-processed');
e24b17b9
CW
784 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
785 })
2c29c2ac 786 .on('click', 'a.crm-summary-link', false);
6a488035
TO
787 };
788
b0ca6188 789 var helpDisplay, helpPrevious;
8e3272a1 790 CRM.help = function (title, params, url) {
55a93b02 791 if (helpDisplay && helpDisplay.close) {
b0ca6188 792 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
55a93b02
CW
793 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
794 helpDisplay.close();
b0ca6188
CW
795 return;
796 }
55a93b02 797 helpDisplay.close();
b0ca6188
CW
798 }
799 helpPrevious = JSON.stringify(params);
6a488035
TO
800 params.class_name = 'CRM_Core_Page_Inline_Help';
801 params.type = 'page';
b0ca6188 802 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
8e3272a1 803 $.ajax(url || CRM.url('civicrm/ajax/inline'),
6a488035
TO
804 {
805 data: params,
806 dataType: 'html',
e24b17b9 807 success: function (data) {
6a488035
TO
808 $('#crm-notification-container .crm-help .notify-content:last').html(data);
809 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
810 },
e24b17b9 811 error: function () {
6a488035
TO
812 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
813 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
814 }
815 }
816 );
817 };
8960d9b9 818 /**
7442e8f6 819 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
8960d9b9 820 */
1b2475e1 821 CRM.status = function(options, deferred) {
9a7ef94f 822 // 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
823 if (typeof options === 'string') {
824 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
8960d9b9 825 }
1b2475e1
CW
826 var opts = $.extend({
827 start: ts('Saving...'),
9a7ef94f 828 success: ts('Saved'),
1b2475e1
CW
829 error: function() {
830 CRM.alert(ts('Sorry an error occurred and your information was not saved'), ts('Error'));
831 }
832 }, options || {});
833 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>')
834 .appendTo('body');
835 $msg.css('min-width', $msg.width());
836 function handle(status, data) {
837 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
838 if (endMsg) {
839 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg);
840 window.setTimeout(function() {
841 $msg.fadeOut('slow', function() {$msg.remove()});
4bad157e
CW
842 }, 2000);
843 } else {
1b2475e1 844 $msg.remove();
4bad157e 845 }
1b2475e1
CW
846 }
847 return (deferred || new $.Deferred())
848 .done(function(data) {
849 // If the server returns an error msg call the error handler
850 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
851 handle(status, data);
852 })
853 .fail(function(data) {
854 handle('error', data);
855 });
8960d9b9 856 };
6a488035
TO
857
858 /**
7442e8f6 859 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 860 */
0f5816a6 861 CRM.alert = function (text, title, type, options) {
6a488035
TO
862 type = type || 'alert';
863 title = title || '';
864 options = options || {};
865 if ($('#crm-notification-container').length) {
866 var params = {
867 text: text,
868 title: title,
869 type: type
870 };
871 // By default, don't expire errors and messages containing links
872 var extra = {
873 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
874 unique: true
875 };
876 options = $.extend(extra, options);
e24b17b9 877 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
6a488035 878 if (options.unique && options.unique !== '0') {
0f5816a6 879 $('#crm-notification-container .ui-notify-message').each(function () {
6a488035
TO
880 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
881 $('.icon.ui-notify-close', this).click();
882 }
883 });
884 }
885 return $('#crm-notification-container').notify('create', params, options);
886 }
887 else {
888 if (title.length) {
889 text = title + "\n" + text;
890 }
891 alert(text);
892 return null;
893 }
e24b17b9 894 };
6a488035
TO
895
896 /**
897 * Close whichever alert contains the given node
898 *
899 * @param node
900 */
0f5816a6 901 CRM.closeAlertByChild = function (node) {
6a488035 902 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
e24b17b9 903 };
6a488035
TO
904
905 /**
7442e8f6 906 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 907 */
5fb83680 908 CRM.confirm = function (options) {
27f190b4 909 var dialog, url, msg, buttons = [], settings = {
a65e5f52 910 title: ts('Confirm'),
7553cf23 911 message: ts('Are you sure you want to continue?'),
3f4328da 912 url: null,
0d5f99d4 913 width: 'auto',
5fb83680 914 modal: true,
a243158e 915 resizable: false,
5fb83680 916 dialogClass: 'crm-container crm-confirm',
0f5816a6 917 close: function () {
5fb83680 918 $(this).dialog('destroy').remove();
0f5816a6 919 },
5fb83680
CW
920 options: {
921 no: ts('Cancel'),
922 yes: ts('Continue')
923 }
0f5816a6 924 };
5fb83680
CW
925 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
926 if (!settings.buttons && $.isPlainObject(settings.options)) {
27f190b4
CW
927 $.each(settings.options, function(op, label) {
928 buttons.push({
5fb83680 929 text: label,
27f190b4
CW
930 'data-op': op,
931 icons: {primary: op === 'no' ? 'ui-icon-close' : 'ui-icon-check'},
5fb83680 932 click: function() {
27f190b4 933 var event = $.Event('crmConfirm:' + op);
5fb83680
CW
934 $(this).trigger(event);
935 if (!event.isDefaultPrevented()) {
936 dialog.dialog('close');
937 }
938 }
939 });
940 });
27f190b4
CW
941 // Order buttons so that "no" goes on the right-hand side
942 settings.buttons = _.sortBy(buttons, 'data-op').reverse();
2a06342c 943 }
3f4328da 944 url = settings.url;
c0b7c815 945 msg = url ? '' : settings.message;
5fb83680
CW
946 delete settings.options;
947 delete settings.message;
3f4328da 948 delete settings.url;
c0b7c815 949 dialog = $('<div class="crm-confirm-dialog"></div>').html(msg || '').dialog(settings);
5fb83680
CW
950 if ($.isFunction(options)) {
951 dialog.on('crmConfirm:yes', options);
7553cf23 952 }
3f4328da
CW
953 if (url) {
954 CRM.loadPage(url, {target: dialog});
955 }
c0b7c815
CW
956 else {
957 dialog.trigger('crmLoad');
3f4328da
CW
958 }
959 return dialog;
e24b17b9 960 };
6a488035 961
ed7225e6
CW
962 /** provides a local copy of ts for a domain */
963 CRM.ts = function(domain) {
964 return function(message, options) {
965 if (domain) {
966 options = $.extend(options || {}, {domain: domain});
967 }
f97524d9
TO
968 return ts(message, options);
969 };
f97524d9
TO
970 };
971
6a488035 972 /**
7442e8f6 973 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 974 */
0f5816a6 975 $.fn.crmError = function (text, title, options) {
6a488035
TO
976 title = title || '';
977 text = text || '';
978 options = options || {};
979
980 var extra = {
981 expires: 0
982 };
983 if ($(this).length) {
984 if (title == '') {
985 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
986 if (label.length) {
987 label.addClass('crm-error');
988 var $label = label.clone();
989 if (text == '' && $('.crm-marker', $label).length > 0) {
990 text = $('.crm-marker', $label).attr('title');
991 }
992 $('.crm-marker', $label).remove();
993 title = $label.text();
994 }
995 }
996 $(this).addClass('error');
997 }
998 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
999 if ($(this).length) {
1000 var ele = $(this);
0f5816a6
KJ
1001 setTimeout(function () {
1002 ele.one('change', function () {
1003 msg && msg.close && msg.close();
1004 ele.removeClass('error');
1005 label.removeClass('crm-error');
1006 });
1007 }, 1000);
6a488035
TO
1008 }
1009 return msg;
e24b17b9 1010 };
6a488035
TO
1011
1012 // Display system alerts through js notifications
1013 function messagesFromMarkup() {
0f5816a6 1014 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
e24b17b9 1015 var text, title = '';
6a488035
TO
1016 $(this).removeClass('status messages');
1017 var type = $(this).attr('class').split(' ')[0] || 'alert';
1018 type = type.replace('crm-', '');
1019 $('.icon', this).remove();
6a488035 1020 if ($('.msg-text', this).length > 0) {
e24b17b9 1021 text = $('.msg-text', this).html();
6a488035
TO
1022 title = $('.msg-title', this).html();
1023 }
1024 else {
e24b17b9 1025 text = $(this).html();
6a488035
TO
1026 }
1027 var options = $(this).data('options') || {};
1028 $(this).remove();
1029 // Duplicates were already removed server-side
1030 options.unique = false;
1031 CRM.alert(text, title, type, options);
1032 });
1033 // Handle qf form errors
1034 $('form :input.error', this).one('blur', function() {
1035 $('.ui-notify-message.error a.ui-notify-close').click();
1036 $(this).removeClass('error');
1037 $(this).next('span.crm-error').remove();
1038 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
1039 .removeClass('crm-error')
1040 .find('.crm-error').removeClass('crm-error');
1041 });
1042 }
1043
e4762285
CW
1044 /**
1045 * Improve blockUI when used with jQuery dialog
1046 */
1adbbe2d
CW
1047 var originalBlock = $.fn.block,
1048 originalUnblock = $.fn.unblock;
1049
1050 $.fn.block = function(opts) {
1051 if ($(this).is('.ui-dialog-content')) {
1052 originalBlock.call($(this).parents('.ui-dialog'), opts);
1053 return $(this);
1054 }
1055 return originalBlock.call(this, opts);
e4762285 1056 };
1adbbe2d
CW
1057 $.fn.unblock = function(opts) {
1058 if ($(this).is('.ui-dialog-content')) {
1059 originalUnblock.call($(this).parents('.ui-dialog'), opts);
1060 return $(this);
1061 }
1062 return originalUnblock.call(this, opts);
e4762285 1063 };
1adbbe2d 1064
e4762285 1065 // Preprocess all CRM ajax calls to display messages
03a7ec8f
CW
1066 $(document).ajaxSuccess(function(event, xhr, settings) {
1067 try {
1068 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
1069 var response = $.parseJSON(xhr.responseText);
1070 if (typeof(response.crmMessages) == 'object') {
1071 $.each(response.crmMessages, function(n, msg) {
1072 CRM.alert(msg.text, msg.title, msg.type, msg.options);
1073 })
1074 }
bba9b4f0
CW
1075 if (response.backtrace) {
1076 CRM.console('log', response.backtrace);
1077 }
82983331
CW
1078 if (typeof response.deprecated === 'string') {
1079 CRM.console('warn', response.deprecated);
1080 }
03a7ec8f
CW
1081 }
1082 }
82983331 1083 // Ignore errors thrown by parseJSON
03a7ec8f
CW
1084 catch (e) {}
1085 });
1086
0f5816a6 1087 $(function () {
fdeb4de2 1088 $.blockUI.defaults.message = null;
1adbbe2d 1089 $.blockUI.defaults.ignoreIfBlocked = true;
fdeb4de2 1090
65b86482
CW
1091 if ($('#crm-container').hasClass('crm-public')) {
1092 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container crm-public';
1093 }
1094
205bb8ae 1095 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
8547369d 1096 $('.crm-container').trigger('crmLoad');
205bb8ae 1097
ef3309b6 1098 if ($('#crm-notification-container').length) {
6a488035
TO
1099 // Initialize notifications
1100 $('#crm-notification-container').notify();
1101 messagesFromMarkup.call($('#crm-container'));
6a488035 1102 }
ebb9197b 1103
475e9f44 1104 $('body')
5fb83680
CW
1105 // bind the event for image popup
1106 .on('click', 'a.crm-image-popup', function(e) {
1107 CRM.confirm({
1108 title: ts('Preview'),
a243158e 1109 resizable: true,
e4762285 1110 message: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
5fb83680
CW
1111 options: null
1112 });
1113 e.preventDefault();
475e9f44 1114 })
ebb9197b 1115
475e9f44
CW
1116 .on('click', function (event) {
1117 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1118 if ($(event.target).is('.btn-slide')) {
1119 $(event.target).addClass('btn-slide-active').find('.panel').show();
1120 }
1121 })
d664f648 1122
4a143c04
CW
1123 // Handle clear button for form elements
1124 .on('click', 'a.crm-clear-link', function() {
1125 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
bcb4280c 1126 $(this).siblings('input:text').val('').change();
4a143c04
CW
1127 return false;
1128 })
1129 .on('change', 'input.crm-form-radio:checked', function() {
1130 $(this).siblings('.crm-clear-link').css({visibility: ''});
843bfb07 1131 })
6a488035 1132
843bfb07 1133 // Allow normal clicking of links within accordions
cf021bc5 1134 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
843bfb07 1135 e.stopPropagation();
cf021bc5 1136 })
843bfb07
CW
1137 // Handle accordions
1138 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
6a488035 1139 if ($(this).parent().hasClass('collapsed')) {
843bfb07 1140 $(this).next().css('display', 'none').slideDown(200);
6a488035
TO
1141 }
1142 else {
843bfb07 1143 $(this).next().css('display', 'block').slideUp(200);
6a488035
TO
1144 }
1145 $(this).parent().toggleClass('collapsed');
843bfb07 1146 e.preventDefault();
6a488035 1147 });
843bfb07
CW
1148
1149 $().crmtooltip();
1150 });
1151 /**
1152 * @deprecated
1153 */
1154 $.fn.crmAccordions = function () {};
1155 /**
1156 * Collapse or expand an accordion
1157 * @param speed
1158 */
0f5816a6
KJ
1159 $.fn.crmAccordionToggle = function (speed) {
1160 $(this).each(function () {
6a488035
TO
1161 if ($(this).hasClass('collapsed')) {
1162 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
1163 }
1164 else {
1165 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1166 }
1167 $(this).toggleClass('collapsed');
1168 });
1169 };
5ec182d9
CW
1170
1171 /**
1172 * Clientside currency formatting
e4762285
CW
1173 * @param number value
1174 * @param [optional] string format - currency representation of the number 1234.56
5ec182d9
CW
1175 * @return string
1176 */
1177 var currencyTemplate;
1178 CRM.formatMoney = function(value, format) {
1179 var decimal, separator, sign, i, j, result;
1180 if (value === 'init' && format) {
1181 currencyTemplate = format;
1182 return;
1183 }
1184 format = format || currencyTemplate;
1185 result = /1(.?)234(.?)56/.exec(format);
1186 if (result === null) {
1187 return 'Invalid format passed to CRM.formatMoney';
1188 }
1189 separator = result[1];
1190 decimal = result[2];
1191 sign = (value < 0) ? '-' : '';
1192 //extracting the absolute value of the integer part of the number and converting to string
1193 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
5ec182d9
CW
1194 j = ((j = i.length) > 3) ? j % 3 : 0;
1195 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) : '');
1196 return format.replace(/1.*234.*56/, result);
1197 };
bba9b4f0
CW
1198
1199 CRM.console = function(method, title, msg) {
1200 if (window.console) {
1201 method = $.isFunction(console[method]) ? method : 'log';
1202 if (msg === undefined) {
1203 return console[method](title);
1204 } else {
1205 return console[method](title, msg);
1206 }
1207 }
e4762285 1208 };
4b513f23 1209})(jQuery, _);