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