Merge pull request #6091 from davecivicrm/CRM-16747
[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 cj('input[name=' + obj.name + ']').val(procText + " ...");
162 }
163 cj(obj).closest('form').attr('data-warn-changes', 'false');
164 if (document.getElementById) { // disable submit button for newer browsers
165 cj('input[name=' + obj.name + ']').attr("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, #civicrm-menu').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 if ($(el).is('.crm-form-date-wrapper .crm-hidden-date')) {
234 $(el).siblings().prop('disabled', value);
235 }
236 }
237 };
238
239 /**
240 * Populate a select list, overwriting the existing options except for the placeholder.
241 * @param select jquery selector - 1 or more select elements
242 * @param options array in format returned by api.getoptions
243 * @param placeholder string|bool - new placeholder or false (default) to keep the old one
244 * @param value string|array - will silently update the element with new value without triggering change
245 */
246 CRM.utils.setOptions = function(select, options, placeholder, value) {
247 $(select).each(function() {
248 var
249 $elect = $(this),
250 val = value || $elect.val() || [],
251 opts = placeholder || placeholder === '' ? '' : '[value!=""]';
252 $elect.find('option' + opts).remove();
253 var newOptions = CRM.utils.renderOptions(options, val);
254 if (typeof placeholder === 'string') {
255 if ($elect.is('[multiple]')) {
256 select.attr('placeholder', placeholder);
257 } else {
258 newOptions = '<option value="">' + placeholder + '</option>' + newOptions;
259 }
260 }
261 $elect.append(newOptions);
262 if (!value) {
263 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
264 }
265 });
266 };
267
268 /**
269 * Render an option list
270 * @param options {array}
271 * @param val {string} default value
272 * @param escapeHtml {bool}
273 * @return string
274 */
275 CRM.utils.renderOptions = function(options, val, escapeHtml) {
276 var rendered = '',
277 esc = escapeHtml === false ? _.identity : _.escape;
278 if (!$.isArray(val)) {
279 val = [val];
280 }
281 _.each(options, function(option) {
282 if (option.children) {
283 rendered += '<optgroup label="' + esc(option.value) + '">' +
284 CRM.utils.renderOptions(option.children, val) +
285 '</optgroup>';
286 } else {
287 var selected = ($.inArray('' + option.key, val) > -1) ? 'selected="selected"' : '';
288 rendered += '<option value="' + esc(option.key) + '"' + selected + '>' + esc(option.value) + '</option>';
289 }
290 });
291 return rendered;
292 };
293
294 function chainSelect() {
295 var $form = $(this).closest('form'),
296 $target = $('select[data-name="' + $(this).data('target') + '"]', $form),
297 data = $target.data(),
298 val = $(this).val();
299 $target.prop('disabled', true);
300 if ($target.is('select.crm-chain-select-control')) {
301 $('select[data-name="' + $target.data('target') + '"]', $form).prop('disabled', true).blur();
302 }
303 if (!(val && val.length)) {
304 CRM.utils.setOptions($target.blur(), [], data.emptyPrompt);
305 } else {
306 $target.addClass('loading');
307 $.getJSON(CRM.url(data.callback), {_value: val}, function(vals) {
308 $target.prop('disabled', false).removeClass('loading');
309 CRM.utils.setOptions($target, vals || [], (vals && vals.length ? data.selectPrompt : data.nonePrompt));
310 });
311 }
312 }
313
314 /**
315 * Compare Form Input values against cached initial value.
316 *
317 * @return {Boolean} true if changes have been made.
318 */
319 CRM.utils.initialValueChanged = function(el) {
320 var isDirty = false;
321 $(':input:visible, .select2-container:visible+:input:hidden', el).not('[type=submit], [type=button], .crm-action-menu, :disabled').each(function () {
322 var
323 initialValue = $(this).data('crm-initial-value'),
324 currentValue = $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val();
325 // skip change of value for submit buttons
326 if (initialValue !== undefined && !_.isEqual(initialValue, currentValue)) {
327 isDirty = true;
328 }
329 });
330 return isDirty;
331 };
332
333 /**
334 * This provides defaults for ui.dialog which either need to be calculated or are different from global defaults
335 *
336 * @param settings
337 * @returns {*}
338 */
339 CRM.utils.adjustDialogDefaults = function(settings) {
340 settings = $.extend({width: '65%', height: '65%', modal: true}, settings || {});
341 // Support relative height
342 if (typeof settings.height === 'string' && settings.height.indexOf('%') > 0) {
343 settings.height = parseInt($(window).height() * (parseFloat(settings.height)/100), 10);
344 }
345 // Responsive adjustment - increase percent width on small screens
346 if (typeof settings.width === 'string' && settings.width.indexOf('%') > 0) {
347 var screenWidth = $(window).width(),
348 percentage = parseInt(settings.width.replace('%', ''), 10),
349 gap = 100-percentage;
350 if (screenWidth < 701) {
351 settings.width = '100%';
352 }
353 else if (screenWidth < 1400) {
354 settings.width = '' + parseInt(percentage+gap-((screenWidth - 700)/7*(gap)/100), 10) + '%';
355 }
356 }
357 return settings;
358 };
359
360 /**
361 * Wrapper for select2 initialization function; supplies defaults
362 * @param options object
363 */
364 $.fn.crmSelect2 = function(options) {
365 return $(this).each(function () {
366 var
367 $el = $(this),
368 settings = {allowClear: !$el.hasClass('required')};
369 // quickform doesn't support optgroups so here's a hack :(
370 $('option[value^=crm_optgroup]', this).each(function () {
371 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
372 $(this).remove();
373 });
374
375 // quickform does not support disabled option, so yet another hack to
376 // add disabled property for option values
377 $('option[value^=crm_disabled_opt]', this).attr('disabled', 'disabled');
378
379 // Defaults for single-selects
380 if ($el.is('select:not([multiple])')) {
381 settings.minimumResultsForSearch = 10;
382 if ($('option:first', this).val() === '') {
383 settings.placeholderOption = 'first';
384 }
385 }
386 $.extend(settings, $el.data('select-params') || {}, options || {});
387 if (settings.ajax) {
388 $el.addClass('crm-ajax-select');
389 }
390 $el.select2(settings);
391 });
392 };
393
394 /**
395 * @see CRM_Core_Form::addEntityRef for docs
396 * @param options object
397 */
398 $.fn.crmEntityRef = function(options) {
399 options = options || {};
400 options.select = options.select || {};
401 return $(this).each(function() {
402 var
403 $el = $(this).off('.crmEntity'),
404 entity = options.entity || $el.data('api-entity') || 'contact',
405 selectParams = {};
406 $el.data('api-entity', entity);
407 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
408 $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api));
409 $el.data('create-links', options.create || $el.data('create-links'));
410 $el.addClass('crm-form-entityref crm-' + entity.toLowerCase() + '-ref');
411 var settings = {
412 // Use select2 ajax helper instead of CRM.api3 because it provides more value
413 ajax: {
414 url: CRM.url('civicrm/ajax/rest'),
415 data: function (input, page_num) {
416 var params = getEntityRefApiParams($el);
417 params.input = input;
418 params.page_num = page_num;
419 return {
420 entity: $el.data('api-entity'),
421 action: 'getlist',
422 json: JSON.stringify(params)
423 };
424 },
425 results: function(data) {
426 return {more: data.more_results, results: data.values || []};
427 }
428 },
429 minimumInputLength: 1,
430 formatResult: CRM.utils.formatSelect2Result,
431 formatSelection: function(row) {
432 return (row.prefix !== undefined ? row.prefix + ' ' : '') + row.label + (row.suffix !== undefined ? ' ' + row.suffix : '');
433 },
434 escapeMarkup: function (m) {return m;},
435 initSelection: function($el, callback) {
436 var
437 multiple = !!$el.data('select-params').multiple,
438 val = $el.val(),
439 stored = $el.data('entity-value') || [];
440 if (val === '') {
441 return;
442 }
443 // If we already have this data, just return it
444 if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
445 callback(multiple ? stored : stored[0]);
446 } else {
447 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
448 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
449 callback(multiple ? result.values : result.values[0]);
450 // Trigger change (store data to avoid an infinite loop of lookups)
451 $el.data('entity-value', result.values).trigger('change');
452 });
453 }
454 }
455 };
456 // Create new items inline - works for tags
457 if ($el.data('create-links') && entity.toLowerCase() === 'tag') {
458 selectParams.createSearchChoice = function(term, data) {
459 if (!_.findKey(data, {label: term})) {
460 return {id: "0", term: term, label: term + ' (' + ts('new tag') + ')'};
461 }
462 };
463 selectParams.tokenSeparators = [','];
464 selectParams.createSearchChoicePosition = 'bottom';
465 $el.on('select2-selecting.crmEntity', function(e) {
466 if (e.val === "0") {
467 // Create a new term
468 e.object.label = e.object.term;
469 CRM.api3(entity, 'create', $.extend({name: e.object.term}, $el.data('api-params').params || {}))
470 .done(function(created) {
471 var
472 val = $el.select2('val'),
473 data = $el.select2('data'),
474 item = {id: created.id, label: e.object.term};
475 if (val === "0") {
476 $el.select2('data', item, true);
477 }
478 else if ($.isArray(val) && $.inArray("0", val) > -1) {
479 _.remove(data, {id: "0"});
480 data.push(item);
481 $el.select2('data', data, true);
482 }
483 });
484 }
485 });
486 }
487 else {
488 selectParams.formatInputTooShort = function() {
489 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
490 txt += renderEntityRefFilters($el) + renderEntityRefCreateLinks($el);
491 return txt;
492 };
493 selectParams.formatNoMatches = function() {
494 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
495 txt += renderEntityRefFilters($el) + renderEntityRefCreateLinks($el);
496 return txt;
497 };
498 $el.on('select2-open.crmEntity', function() {
499 var $el = $(this);
500 loadEntityRefFilterOptions($el);
501 $('#select2-drop')
502 .off('.crmEntity')
503 .on('click.crmEntity', 'a.crm-add-entity', function(e) {
504 $el.select2('close');
505 CRM.loadForm($(this).attr('href'), {
506 dialog: {width: 500, height: 220}
507 }).on('crmFormSuccess', function(e, data) {
508 if (data.status === 'success' && data.id) {
509 CRM.status(ts('%1 Created', {1: data.label}));
510 if ($el.select2('container').hasClass('select2-container-multi')) {
511 var selection = $el.select2('data');
512 selection.push(data);
513 $el.select2('data', selection, true);
514 } else {
515 $el.select2('data', data, true);
516 }
517 }
518 });
519 return false;
520 })
521 .on('change.crmEntity', 'select.crm-entityref-filter-value', function() {
522 var filter = $el.data('user-filter') || {};
523 filter.value = $(this).val();
524 $(this).toggleClass('active', !!filter.value);
525 $el.data('user-filter', filter);
526 if (filter.value) {
527 // Once a filter has been chosen, rerender create links and refocus the search box
528 $el.select2('close');
529 $el.select2('open');
530 }
531 })
532 .on('change.crmEntity', 'select.crm-entityref-filter-key', function() {
533 var filter = $el.data('user-filter') || {};
534 filter.key = $(this).val();
535 $(this).toggleClass('active', !!filter.key);
536 $el.data('user-filter', filter);
537 loadEntityRefFilterOptions($el);
538 });
539 });
540 }
541 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams));
542 });
543 };
544
545 /**
546 * Combine api-params with user-filter
547 * @param $el
548 * @returns {*}
549 */
550 function getEntityRefApiParams($el) {
551 var
552 params = $.extend({params: {}}, $el.data('api-params') || {}),
553 // Prevent original data from being modified - $.extend and _.clone don't cut it, they pass nested objects by reference!
554 combined = _.cloneDeep(params),
555 filter = $.extend({}, $el.data('user-filter') || {});
556 if (filter.key && filter.value) {
557 // Special case for contact type/sub-type combo
558 if (filter.key === 'contact_type' && (filter.value.indexOf('__') > 0)) {
559 combined.params.contact_type = filter.value.split('__')[0];
560 combined.params.contact_sub_type = filter.value.split('__')[1];
561 } else {
562 // Allow json-encoded api filters e.g. {"BETWEEN":[123,456]}
563 combined.params[filter.key] = filter.value.charAt(0) === '{' ? $.parseJSON(filter.value) : filter.value;
564 }
565 }
566 return combined;
567 }
568
569 function copyAttributes($source, $target, attributes) {
570 _.each(attributes, function(name) {
571 if ($source.attr(name)) {
572 $target.attr(name, $source.attr(name));
573 }
574 });
575 }
576
577 $.fn.crmDatepicker = function(options) {
578 return $(this).each(function() {
579 if ($(this).is('.crm-form-date-wrapper .crm-hidden-date')) {
580 // Already initialized
581 return;
582 }
583 var
584 $dataField = $(this).wrap('<span class="crm-form-date-wrapper" />'),
585 settings = $.extend({}, $dataField.data('datepicker') || {}, options || {}),
586 $dateField = $(),
587 $timeField = $(),
588 $clearLink = $();
589
590 if (settings.allowClear !== undefined ? settings.allowClear : !$dataField.hasClass('required')) {
591 $clearLink = $('<a class="crm-hover-button crm-clear-link" title="'+ ts('Clear') +'"><span class="icon ui-icon-close"></span></a>')
592 .insertAfter($dataField);
593 }
594 if (settings.time !== false) {
595 $timeField = $('<input>').insertAfter($dataField);
596 copyAttributes($dataField, $timeField, ['class', 'disabled']);
597 $timeField
598 .addClass('crm-form-text crm-form-time')
599 .attr('placeholder', $dataField.attr('time-placeholder') === undefined ? ts('Time') : $dataField.attr('time-placeholder'))
600 .change(updateDataField)
601 .timeEntry({
602 spinnerImage: '',
603 show24Hours: settings.time === true || settings.time === undefined ? CRM.config.timeIs24Hr : settings.time == '24'
604 });
605 }
606 if (settings.date !== false) {
607 $dateField = $('<input>').insertAfter($dataField);
608 copyAttributes($dataField, $dateField, ['placeholder', 'style', 'class', 'disabled']);
609 $dateField.addClass('crm-form-text crm-form-date');
610 settings.dateFormat = settings.dateFormat || CRM.config.dateInputFormat;
611 settings.changeMonth = _.includes('m', settings.dateFormat);
612 settings.changeYear = _.includes('y', settings.dateFormat);
613 $dateField.datepicker(settings).change(updateDataField);
614 }
615 // Rudimentary validation. TODO: Roll into use of jQUery validate and ui.datepicker.validation
616 function isValidDate() {
617 try {
618 $.datepicker.parseDate(settings.dateFormat, $dateField.val());
619 return true;
620 } catch (e) {
621 return false;
622 }
623 }
624 function updateInputFields(e, context) {
625 var val = $dataField.val(),
626 time = null;
627 if (context !== 'userInput' && context !== 'crmClear') {
628 if ($dateField.length) {
629 $dateField.datepicker('setDate', _.includes(val, '-') ? $.datepicker.parseDate('yy-mm-dd', val) : null);
630 }
631 if ($timeField.length) {
632 if (val.length === 8) {
633 time = val;
634 } else if (val.length === 19) {
635 time = val.split(' ')[1];
636 }
637 $timeField.timeEntry('setTime', time);
638 }
639 }
640 $clearLink.css('visibility', val ? 'visible' : 'hidden');
641 }
642 function updateDataField(e, context) {
643 // The crmClear event wipes all the field values anyway, so no need to respond
644 if (context !== 'crmClear') {
645 var val = '';
646 if ($dateField.val()) {
647 if (isValidDate()) {
648 val = $.datepicker.formatDate('yy-mm-dd', $dateField.datepicker('getDate'));
649 $dateField.removeClass('crm-error');
650 } else {
651 $dateField.addClass('crm-error');
652 }
653 }
654 if ($timeField.val()) {
655 val += (val ? ' ' : '') + $timeField.timeEntry('getTime').toTimeString().substr(0, 8);
656 }
657 $dataField.val(val).trigger('change', ['userInput']);
658 }
659 }
660 $dataField.hide().addClass('crm-hidden-date').on('change', updateInputFields);
661 updateInputFields();
662 });
663 };
664
665 CRM.utils.formatSelect2Result = function (row) {
666 var markup = '<div class="crm-select2-row">';
667 if (row.image !== undefined) {
668 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
669 }
670 else if (row.icon_class) {
671 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
672 }
673 markup += '<div><div class="crm-select2-row-label '+(row.label_class || '')+'">' +
674 (row.prefix !== undefined ? row.prefix + ' ' : '') + row.label + (row.suffix !== undefined ? ' ' + row.suffix : '') +
675 '</div>' +
676 '<div class="crm-select2-row-description">';
677 $.each(row.description || [], function(k, text) {
678 markup += '<p>' + text + '</p>';
679 });
680 markup += '</div></div></div>';
681 return markup;
682 };
683
684 function renderEntityRefCreateLinks($el) {
685 var
686 createLinks = $el.data('create-links'),
687 params = getEntityRefApiParams($el).params,
688 markup = '<div class="crm-entityref-links">';
689 if (!createLinks || $el.data('api-entity').toLowerCase() !== 'contact') {
690 return '';
691 }
692 if (createLinks === true) {
693 createLinks = params.contact_type ? _.where(CRM.config.entityRef.contactCreate, {type: params.contact_type}) : CRM.config.entityRef.contactCreate;
694 }
695 _.each(createLinks, function(link) {
696 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
697 if (link.type) {
698 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
699 }
700 markup += link.label + '</a>';
701 });
702 markup += '</div>';
703 return markup;
704 }
705
706 function getEntityRefFilters($el) {
707 var
708 entity = $el.data('api-entity').toLowerCase(),
709 filters = $.extend([], CRM.config.entityRef.filters[entity] || []),
710 filter = $el.data('user-filter') || {},
711 params = $.extend({params: {}}, $el.data('api-params') || {}).params,
712 result = [];
713 $.each(filters, function() {
714 if (typeof params[this.key] === 'undefined') {
715 result.push(this);
716 }
717 else if (this.key == 'contact_type' && typeof params.contact_sub_type === 'undefined') {
718 this.options = _.remove(this.options, function(option) {
719 return option.key.indexOf(params.contact_type + '__') === 0;
720 });
721 result.push(this);
722 }
723 });
724 return result;
725 }
726
727 function renderEntityRefFilters($el) {
728 var
729 filters = getEntityRefFilters($el),
730 filter = $el.data('user-filter') || {},
731 filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null;
732 if (!filters.length) {
733 return '';
734 }
735 var markup = '<div class="crm-entityref-filters">' +
736 '<select class="crm-entityref-filter-key' + (filter.key ? ' active' : '') + '">' +
737 '<option value="">' + ts('Refine search...') + '</option>' +
738 CRM.utils.renderOptions(filters, filter.key) +
739 '</select> &nbsp; ' +
740 '<select class="crm-entityref-filter-value' + (filter.key ? ' active"' : '"') + (filter.key ? '' : ' style="display:none;"') + '>' +
741 '<option value="">' + ts('- select -') + '</option>';
742 if (filterSpec && filterSpec.options) {
743 markup += CRM.utils.renderOptions(filterSpec.options, filter.value);
744 }
745 markup += '</select></div>';
746 return markup;
747 }
748
749 /**
750 * Fetch options for a filter (via ajax if necessary) and populate the appropriate select list
751 * @param $el
752 */
753 function loadEntityRefFilterOptions($el) {
754 var
755 filters = getEntityRefFilters($el),
756 filter = $el.data('user-filter') || {},
757 filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null,
758 $valField = $('.crm-entityref-filter-value', '#select2-drop');
759 if (filterSpec) {
760 $valField.show().val('');
761 if (filterSpec.options) {
762 CRM.utils.setOptions($valField, filterSpec.options, false, filter.value);
763 } else {
764 $valField.prop('disabled', true);
765 CRM.api3(filterSpec.entity || $el.data('api-entity'), 'getoptions', {field: filter.key, context: 'search', sequential: 1})
766 .done(function(result) {
767 var entity = $el.data('api-entity').toLowerCase(),
768 globalFilterSpec = _.find(CRM.config.entityRef.filters[entity], {key: filter.key}) || {};
769 // Store options globally so we don't have to look them up again
770 globalFilterSpec.options = result.values;
771 $valField.prop('disabled', false);
772 CRM.utils.setOptions($valField, result.values);
773 $valField.val(filter.value || '');
774 });
775 }
776 } else {
777 $valField.hide();
778 }
779 }
780
781 //CRM-15598 - Override url validator method to allow relative url's (e.g. /index.htm)
782 $.validator.addMethod("url", function(value, element) {
783 if (/^\//.test(value)) {
784 // Relative url: prepend dummy path for validation.
785 value = 'http://domain.tld' + value;
786 }
787 // From jQuery Validation Plugin v1.12.0
788 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);
789 });
790
791 /**
792 * Wrapper for jQuery validate initialization function; supplies defaults
793 */
794 $.fn.crmValidate = function(params) {
795 return $(this).each(function () {
796 var that = this,
797 settings = $.extend({}, CRM.validate._defaults, CRM.validate.params);
798 $(this).validate(settings);
799 // Call any post-initialization callbacks
800 if (CRM.validate.functions && CRM.validate.functions.length) {
801 $.each(CRM.validate.functions, function(i, func) {
802 func.call(that);
803 });
804 }
805 });
806 };
807
808 // Initialize widgets
809 $(document)
810 .on('crmLoad', function(e) {
811 $('table.row-highlight', e.target)
812 .off('.rowHighlight')
813 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) {
814 var filter, $table = $(this).closest('table');
815 if ($(this).hasClass('select-rows')) {
816 filter = $(this).prop('checked') ? ':not(:checked)' : ':checked';
817 $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
818 }
819 else {
820 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
821 if (data !== 'master-selected') {
822 $('input.select-rows', $table).prop('checked', $(".select-row:not(':checked')", $table).length < 1);
823 }
824 }
825 })
826 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
827 if ($("input:radio[name=radio_ts]").size() == 1) {
828 $("input:radio[name=radio_ts]").prop("checked", true);
829 }
830 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
831 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
832 $('select.crm-chain-select-control', e.target).off('.chainSelect').on('change.chainSelect', chainSelect);
833 // Cache Form Input initial values
834 $('form[data-warn-changes] :input', e.target).each(function() {
835 $(this).data('crm-initial-value', $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val());
836 });
837 })
838 .on('dialogopen', function(e) {
839 var $el = $(e.target);
840 // Modal dialogs should disable scrollbars
841 if ($el.dialog('option', 'modal')) {
842 $el.addClass('modal-dialog');
843 $('body').css({overflow: 'hidden'});
844 }
845 // Add resize button
846 if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) {
847 $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}));
848 $('.crm-dialog-titlebar-resize', $el.parent()).click(function(e) {
849 if ($el.data('origSize')) {
850 $el.dialog('option', $el.data('origSize'));
851 $el.data('origSize', null);
852 } else {
853 var menuHeight = $('#civicrm-menu').outerHeight();
854 $el.data('origSize', {
855 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
856 width: $el.dialog('option', 'width'),
857 height: $el.dialog('option', 'height')
858 });
859 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: {my: "top", at: "top+"+menuHeight, of: window}});
860 }
861 $el.trigger('dialogresize');
862 e.preventDefault();
863 });
864 }
865 })
866 .on('dialogclose', function(e) {
867 // Restore scrollbars when closing modal
868 if ($('.ui-dialog .modal-dialog:visible').not(e.target).length < 1) {
869 $('body').css({overflow: ''});
870 }
871 })
872 .on('submit', function(e) {
873 // CRM-14353 - disable changes warn when submitting a form
874 $('[data-warn-changes]').attr('data-warn-changes', 'false');
875 });
876
877 // CRM-14353 - Warn of unsaved changes for forms which have opted in
878 window.onbeforeunload = function() {
879 if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
880 return ts('You have unsaved changes.');
881 }
882 };
883
884 $.fn.crmtooltip = function () {
885 $(document)
886 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
887 $(this).addClass('crm-processed');
888 $(this).addClass('crm-tooltip-active');
889 var topDistance = e.pageY - $(window).scrollTop();
890 if (topDistance < 300 || topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
891 $(this).addClass('crm-tooltip-down');
892 }
893 if (!$(this).children('.crm-tooltip-wrapper').length) {
894 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
895 $(this).children().children('.crm-tooltip')
896 .html('<div class="crm-loading-element"></div>')
897 .load(this.href);
898 }
899 })
900 .on('mouseout', 'a.crm-summary-link', function () {
901 $(this).removeClass('crm-processed');
902 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
903 })
904 .on('click', 'a.crm-summary-link', false);
905 };
906
907 var helpDisplay, helpPrevious;
908 CRM.help = function (title, params, url) {
909 if (helpDisplay && helpDisplay.close) {
910 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
911 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
912 helpDisplay.close();
913 return;
914 }
915 helpDisplay.close();
916 }
917 helpPrevious = JSON.stringify(params);
918 params.class_name = 'CRM_Core_Page_Inline_Help';
919 params.type = 'page';
920 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
921 $.ajax(url || CRM.url('civicrm/ajax/inline'),
922 {
923 data: params,
924 dataType: 'html',
925 success: function (data) {
926 $('#crm-notification-container .crm-help .notify-content:last').html(data);
927 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
928 },
929 error: function () {
930 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
931 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
932 }
933 }
934 );
935 };
936 /**
937 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
938 */
939 CRM.status = function(options, deferred) {
940 // 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.
941 if (typeof options === 'string') {
942 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
943 }
944 var opts = $.extend({
945 start: ts('Saving...'),
946 success: ts('Saved'),
947 error: function(data) {
948 var msg = $.isPlainObject(data) && data.error_message;
949 CRM.alert(msg || ts('Sorry an error occurred and your information was not saved'), ts('Error'), 'error');
950 }
951 }, options || {});
952 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>')
953 .appendTo('body');
954 $msg.css('min-width', $msg.width());
955 function handle(status, data) {
956 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
957 if (endMsg) {
958 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg);
959 window.setTimeout(function() {
960 $msg.fadeOut('slow', function() {
961 $msg.remove();
962 });
963 }, 2000);
964 } else {
965 $msg.remove();
966 }
967 }
968 return (deferred || new $.Deferred())
969 .done(function(data) {
970 // If the server returns an error msg call the error handler
971 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
972 handle(status, data);
973 })
974 .fail(function(data) {
975 handle('error', data);
976 });
977 };
978
979 // Convert an Angular promise to a jQuery promise
980 CRM.toJqPromise = function(aPromise) {
981 var jqDeferred = $.Deferred();
982 aPromise.then(
983 function(data) { jqDeferred.resolve(data); },
984 function(data) { jqDeferred.reject(data); }
985 // should we also handle progress events?
986 );
987 return jqDeferred.promise();
988 };
989
990 CRM.toAPromise = function($q, jqPromise) {
991 var aDeferred = $q.defer();
992 jqPromise.then(
993 function(data) { aDeferred.resolve(data); },
994 function(data) { aDeferred.reject(data); }
995 // should we also handle progress events?
996 );
997 return aDeferred.promise;
998 };
999
1000 /**
1001 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1002 */
1003 CRM.alert = function (text, title, type, options) {
1004 type = type || 'alert';
1005 title = title || '';
1006 options = options || {};
1007 if ($('#crm-notification-container').length) {
1008 var params = {
1009 text: text,
1010 title: title,
1011 type: type
1012 };
1013 // By default, don't expire errors and messages containing links
1014 var extra = {
1015 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
1016 unique: true
1017 };
1018 options = $.extend(extra, options);
1019 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
1020 if (options.unique && options.unique !== '0') {
1021 $('#crm-notification-container .ui-notify-message').each(function () {
1022 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
1023 $('.icon.ui-notify-close', this).click();
1024 }
1025 });
1026 }
1027 return $('#crm-notification-container').notify('create', params, options);
1028 }
1029 else {
1030 if (title.length) {
1031 text = title + "\n" + text;
1032 }
1033 alert(text);
1034 return null;
1035 }
1036 };
1037
1038 /**
1039 * Close whichever alert contains the given node
1040 *
1041 * @param node
1042 */
1043 CRM.closeAlertByChild = function (node) {
1044 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
1045 };
1046
1047 /**
1048 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1049 */
1050 CRM.confirm = function (options) {
1051 var dialog, url, msg, buttons = [], settings = {
1052 title: ts('Confirm'),
1053 message: ts('Are you sure you want to continue?'),
1054 url: null,
1055 width: 'auto',
1056 height: 'auto',
1057 resizable: false,
1058 dialogClass: 'crm-container crm-confirm',
1059 close: function () {
1060 $(this).dialog('destroy').remove();
1061 },
1062 options: {
1063 no: ts('Cancel'),
1064 yes: ts('Continue')
1065 }
1066 };
1067 if (options && options.url) {
1068 settings.resizable = true;
1069 settings.height = '50%';
1070 }
1071 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
1072 settings = CRM.utils.adjustDialogDefaults(settings);
1073 if (!settings.buttons && $.isPlainObject(settings.options)) {
1074 $.each(settings.options, function(op, label) {
1075 buttons.push({
1076 text: label,
1077 'data-op': op,
1078 icons: {primary: op === 'no' ? 'ui-icon-close' : 'ui-icon-check'},
1079 click: function() {
1080 var event = $.Event('crmConfirm:' + op);
1081 $(this).trigger(event);
1082 if (!event.isDefaultPrevented()) {
1083 dialog.dialog('close');
1084 }
1085 }
1086 });
1087 });
1088 // Order buttons so that "no" goes on the right-hand side
1089 settings.buttons = _.sortBy(buttons, 'data-op').reverse();
1090 }
1091 url = settings.url;
1092 msg = url ? '' : settings.message;
1093 delete settings.options;
1094 delete settings.message;
1095 delete settings.url;
1096 dialog = $('<div class="crm-confirm-dialog"></div>').html(msg || '').dialog(settings);
1097 if ($.isFunction(options)) {
1098 dialog.on('crmConfirm:yes', options);
1099 }
1100 if (url) {
1101 CRM.loadPage(url, {target: dialog});
1102 }
1103 else {
1104 dialog.trigger('crmLoad');
1105 }
1106 return dialog;
1107 };
1108
1109 /** provides a local copy of ts for a domain */
1110 CRM.ts = function(domain) {
1111 return function(message, options) {
1112 if (domain) {
1113 options = $.extend(options || {}, {domain: domain});
1114 }
1115 return ts(message, options);
1116 };
1117 };
1118
1119 CRM.addStrings = function(domain, strings) {
1120 var bucket = (domain == 'civicrm' ? 'strings' : 'strings::' + domain);
1121 CRM[bucket] = CRM[bucket] || {};
1122 _.extend(CRM[bucket], strings);
1123 };
1124
1125 /**
1126 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1127 */
1128 $.fn.crmError = function (text, title, options) {
1129 title = title || '';
1130 text = text || '';
1131 options = options || {};
1132
1133 var extra = {
1134 expires: 0
1135 };
1136 if ($(this).length) {
1137 if (title === '') {
1138 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
1139 if (label.length) {
1140 label.addClass('crm-error');
1141 var $label = label.clone();
1142 if (text === '' && $('.crm-marker', $label).length > 0) {
1143 text = $('.crm-marker', $label).attr('title');
1144 }
1145 $('.crm-marker', $label).remove();
1146 title = $label.text();
1147 }
1148 }
1149 $(this).addClass('crm-error');
1150 }
1151 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
1152 if ($(this).length) {
1153 var ele = $(this);
1154 setTimeout(function () {
1155 ele.one('change', function () {
1156 if (msg && msg.close) msg.close();
1157 ele.removeClass('error');
1158 label.removeClass('crm-error');
1159 });
1160 }, 1000);
1161 }
1162 return msg;
1163 };
1164
1165 // Display system alerts through js notifications
1166 function messagesFromMarkup() {
1167 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
1168 var text, title = '';
1169 $(this).removeClass('status messages');
1170 var type = $(this).attr('class').split(' ')[0] || 'alert';
1171 type = type.replace('crm-', '');
1172 $('.icon', this).remove();
1173 if ($('.msg-text', this).length > 0) {
1174 text = $('.msg-text', this).html();
1175 title = $('.msg-title', this).html();
1176 }
1177 else {
1178 text = $(this).html();
1179 }
1180 var options = $(this).data('options') || {};
1181 $(this).remove();
1182 // Duplicates were already removed server-side
1183 options.unique = false;
1184 CRM.alert(text, title, type, options);
1185 });
1186 // Handle qf form errors
1187 $('form :input.error', this).one('blur', function() {
1188 $('.ui-notify-message.error a.ui-notify-close').click();
1189 $(this).removeClass('error');
1190 $(this).next('span.crm-error').remove();
1191 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
1192 .removeClass('crm-error')
1193 .find('.crm-error').removeClass('crm-error');
1194 });
1195 }
1196
1197 /**
1198 * Improve blockUI when used with jQuery dialog
1199 */
1200 var originalBlock = $.fn.block,
1201 originalUnblock = $.fn.unblock;
1202
1203 $.fn.block = function(opts) {
1204 if ($(this).is('.ui-dialog-content')) {
1205 originalBlock.call($(this).parents('.ui-dialog'), opts);
1206 return $(this);
1207 }
1208 return originalBlock.call(this, opts);
1209 };
1210 $.fn.unblock = function(opts) {
1211 if ($(this).is('.ui-dialog-content')) {
1212 originalUnblock.call($(this).parents('.ui-dialog'), opts);
1213 return $(this);
1214 }
1215 return originalUnblock.call(this, opts);
1216 };
1217
1218 // Preprocess all CRM ajax calls to display messages
1219 $(document).ajaxSuccess(function(event, xhr, settings) {
1220 try {
1221 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
1222 var response = $.parseJSON(xhr.responseText);
1223 if (typeof(response.crmMessages) == 'object') {
1224 $.each(response.crmMessages, function(n, msg) {
1225 CRM.alert(msg.text, msg.title, msg.type, msg.options);
1226 });
1227 }
1228 if (response.backtrace) {
1229 CRM.console('log', response.backtrace);
1230 }
1231 if (typeof response.deprecated === 'string') {
1232 CRM.console('warn', response.deprecated);
1233 }
1234 }
1235 }
1236 // Ignore errors thrown by parseJSON
1237 catch (e) {}
1238 });
1239
1240 $(function () {
1241 $.blockUI.defaults.message = null;
1242 $.blockUI.defaults.ignoreIfBlocked = true;
1243
1244 if ($('#crm-container').hasClass('crm-public')) {
1245 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container crm-public';
1246 }
1247
1248 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1249 $('.crm-container').trigger('crmLoad');
1250
1251 if ($('#crm-notification-container').length) {
1252 // Initialize notifications
1253 $('#crm-notification-container').notify();
1254 messagesFromMarkup.call($('#crm-container'));
1255 }
1256
1257 // Hide CiviCRM menubar when editor is fullscreen
1258 if (window.CKEDITOR) {
1259 CKEDITOR.on('instanceCreated', function (e) {
1260 e.editor.on('maximize', function (e) {
1261 $('#civicrm-menu').toggle(e.data === 2);
1262 });
1263 });
1264 }
1265
1266 $('body')
1267 // bind the event for image popup
1268 .on('click', 'a.crm-image-popup', function(e) {
1269 CRM.confirm({
1270 title: ts('Preview'),
1271 resizable: true,
1272 // Prevent overlap with the menubar
1273 maxHeight: $(window).height() - 30,
1274 position: {my: 'center', at: 'center center+15', of: window},
1275 message: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
1276 options: null
1277 });
1278 e.preventDefault();
1279 })
1280
1281 .on('click', function (event) {
1282 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1283 if ($(event.target).is('.btn-slide')) {
1284 $(event.target).addClass('btn-slide-active').find('.panel').show();
1285 }
1286 })
1287
1288 // Handle clear button for form elements
1289 .on('click', 'a.crm-clear-link', function() {
1290 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).trigger('change', ['crmClear']);
1291 $(this).siblings('input:text').val('').trigger('change', ['crmClear']);
1292 return false;
1293 })
1294 .on('change', 'input.crm-form-radio:checked', function() {
1295 $(this).siblings('.crm-clear-link').css({visibility: ''});
1296 })
1297
1298 // Allow normal clicking of links within accordions
1299 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
1300 e.stopPropagation();
1301 })
1302 // Handle accordions
1303 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
1304 if ($(this).parent().hasClass('collapsed')) {
1305 $(this).next().css('display', 'none').slideDown(200);
1306 }
1307 else {
1308 $(this).next().css('display', 'block').slideUp(200);
1309 }
1310 $(this).parent().toggleClass('collapsed');
1311 e.preventDefault();
1312 });
1313
1314 $().crmtooltip();
1315 });
1316 /**
1317 * @deprecated
1318 */
1319 $.fn.crmAccordions = function () {
1320 CRM.console('warn', 'Warning: $.crmAccordions was called. This function is deprecated and should not be used.');
1321 };
1322 /**
1323 * Collapse or expand an accordion
1324 * @param speed
1325 */
1326 $.fn.crmAccordionToggle = function (speed) {
1327 $(this).each(function () {
1328 if ($(this).hasClass('collapsed')) {
1329 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
1330 }
1331 else {
1332 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1333 }
1334 $(this).toggleClass('collapsed');
1335 });
1336 };
1337
1338 /**
1339 * Clientside currency formatting
1340 * @param number value
1341 * @param [optional] boolean onlyNumber - if true, we return formated amount without currency sign
1342 * @param [optional] string format - currency representation of the number 1234.56
1343 * @return string
1344 */
1345 var currencyTemplate;
1346 CRM.formatMoney = function(value, onlyNumber, format) {
1347 var decimal, separator, sign, i, j, result;
1348 if (value === 'init' && format) {
1349 currencyTemplate = format;
1350 return;
1351 }
1352 format = format || currencyTemplate;
1353 result = /1(.?)234(.?)56/.exec(format);
1354 if (result === null) {
1355 return 'Invalid format passed to CRM.formatMoney';
1356 }
1357 separator = result[1];
1358 decimal = result[2];
1359 sign = (value < 0) ? '-' : '';
1360 //extracting the absolute value of the integer part of the number and converting to string
1361 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
1362 j = ((j = i.length) > 3) ? j % 3 : 0;
1363 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) : '');
1364 if ( onlyNumber ) {
1365 return result;
1366 }
1367 return format.replace(/1.*234.*56/, result);
1368 };
1369
1370 CRM.console = function(method, title, msg) {
1371 if (window.console) {
1372 method = $.isFunction(console[method]) ? method : 'log';
1373 if (msg === undefined) {
1374 return console[method](title);
1375 } else {
1376 return console[method](title, msg);
1377 }
1378 }
1379 };
1380
1381 // Determine if a user has a given permission.
1382 // @see CRM_Core_Resources::addPermissions
1383 CRM.checkPerm = function(perm) {
1384 return CRM.permissions[perm];
1385 };
1386
1387 // Round while preserving sigfigs
1388 CRM.utils.sigfig = function(n, digits) {
1389 var len = ("" + n).length;
1390 var scale = Math.pow(10.0, len-digits);
1391 return Math.round(n / scale) * scale;
1392 };
1393 })(jQuery, _);