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