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