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