CRM-15598 - Allow relative URL's for Link custom fields
[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 // Defaults for single-selects
313 if ($el.is('select:not([multiple])')) {
314 settings.minimumResultsForSearch = 10;
315 if ($('option:first', this).val() === '') {
316 settings.placeholderOption = 'first';
317 }
318 }
319 $.extend(settings, $el.data('select-params') || {}, options || {});
320 if (settings.ajax) {
321 $el.addClass('crm-ajax-select');
322 }
323 $el.select2(settings);
324 });
325 };
326
327 /**
328 * @see CRM_Core_Form::addEntityRef for docs
329 * @param options object
330 */
331 $.fn.crmEntityRef = function(options) {
332 options = options || {};
333 options.select = options.select || {};
334 return $(this).each(function() {
335 var
336 $el = $(this).off('.crmEntity'),
337 entity = options.entity || $el.data('api-entity') || 'contact',
338 selectParams = {};
339 $el.data('api-entity', entity);
340 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
341 $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api));
342 $el.data('create-links', options.create || $el.data('create-links'));
343 $el.addClass('crm-form-entityref crm-' + entity.toLowerCase() + '-ref');
344 var settings = {
345 // Use select2 ajax helper instead of CRM.api3 because it provides more value
346 ajax: {
347 url: CRM.url('civicrm/ajax/rest'),
348 data: function (input, page_num) {
349 var params = getEntityRefApiParams($el);
350 params.input = input;
351 params.page_num = page_num;
352 return {
353 entity: $el.data('api-entity'),
354 action: 'getlist',
355 json: JSON.stringify(params)
356 };
357 },
358 results: function(data) {
359 return {more: data.more_results, results: data.values || []};
360 }
361 },
362 minimumInputLength: 1,
363 formatResult: CRM.utils.formatSelect2Result,
364 formatSelection: function(row) {
365 return row.label;
366 },
367 escapeMarkup: function (m) {return m;},
368 initSelection: function($el, callback) {
369 var
370 multiple = !!$el.data('select-params').multiple,
371 val = $el.val(),
372 stored = $el.data('entity-value') || [];
373 if (val === '') {
374 return;
375 }
376 // If we already have this data, just return it
377 if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
378 callback(multiple ? stored : stored[0]);
379 } else {
380 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
381 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
382 callback(multiple ? result.values : result.values[0]);
383 // Trigger change (store data to avoid an infinite loop of lookups)
384 $el.data('entity-value', result.values).trigger('change');
385 });
386 }
387 }
388 };
389 // Create new items inline - works for tags
390 if ($el.data('create-links') && entity.toLowerCase() === 'tag') {
391 selectParams.createSearchChoice = function(term, data) {
392 if (!_.findKey(data, {label: term})) {
393 return {id: "0", term: term, label: term + ' (' + ts('new tag') + ')'};
394 }
395 };
396 selectParams.tokenSeparators = [','];
397 selectParams.createSearchChoicePosition = 'bottom';
398 $el.on('select2-selecting.crmEntity', function(e) {
399 if (e.val === "0") {
400 // Create a new term
401 e.object.label = e.object.term;
402 CRM.api3(entity, 'create', $.extend({name: e.object.term}, $el.data('api-params').params || {}))
403 .done(function(created) {
404 var
405 val = $el.select2('val'),
406 data = $el.select2('data'),
407 item = {id: created.id, label: e.object.term};
408 if (val === "0") {
409 $el.select2('data', item, true);
410 }
411 else if ($.isArray(val) && $.inArray("0", val) > -1) {
412 _.remove(data, {id: "0"});
413 data.push(item);
414 $el.select2('data', data, true);
415 }
416 });
417 }
418 });
419 }
420 else {
421 selectParams.formatInputTooShort = function() {
422 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
423 txt += renderEntityRefFilters($el) + renderEntityRefCreateLinks($el);
424 return txt;
425 };
426 selectParams.formatNoMatches = function() {
427 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
428 txt += renderEntityRefFilters($el) + renderEntityRefCreateLinks($el);
429 return txt;
430 };
431 $el.on('select2-open.crmEntity', function() {
432 var $el = $(this);
433 loadEntityRefFilterOptions($el);
434 $('#select2-drop')
435 .off('.crmEntity')
436 .on('click.crmEntity', 'a.crm-add-entity', function(e) {
437 $el.select2('close');
438 CRM.loadForm($(this).attr('href'), {
439 dialog: {width: 500, height: 'auto'}
440 }).on('crmFormSuccess', function(e, data) {
441 if (data.status === 'success' && data.id) {
442 CRM.status(ts('%1 Created', {1: data.label}));
443 if ($el.select2('container').hasClass('select2-container-multi')) {
444 var selection = $el.select2('data');
445 selection.push(data);
446 $el.select2('data', selection, true);
447 } else {
448 $el.select2('data', data, true);
449 }
450 }
451 });
452 return false;
453 })
454 .on('change.crmEntity', 'select.crm-entityref-filter-value', function() {
455 var filter = $el.data('user-filter') || {};
456 filter.value = $(this).val();
457 $(this).toggleClass('active', !!filter.value);
458 $el.data('user-filter', filter);
459 if (filter.value) {
460 // Once a filter has been chosen, rerender create links and refocus the search box
461 $el.select2('close');
462 $el.select2('open');
463 }
464 })
465 .on('change.crmEntity', 'select.crm-entityref-filter-key', function() {
466 var filter = $el.data('user-filter') || {};
467 filter.key = $(this).val();
468 $(this).toggleClass('active', !!filter.key);
469 $el.data('user-filter', filter);
470 loadEntityRefFilterOptions($el);
471 });
472 });
473 }
474 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams));
475 });
476 };
477
478 /**
479 * Combine api-params with user-filter
480 * @param $el
481 * @returns {*}
482 */
483 function getEntityRefApiParams($el) {
484 var
485 params = $.extend({params: {}}, $el.data('api-params') || {}),
486 // Prevent original data from being modified - $.extend and _.clone don't cut it, they pass nested objects by reference!
487 combined = _.cloneDeep(params),
488 filter = $.extend({}, $el.data('user-filter') || {});
489 if (filter.key && filter.value) {
490 // Special case for contact type/sub-type combo
491 if (filter.key === 'contact_type' && (filter.value.indexOf('.') > 0)) {
492 combined.params.contact_type = filter.value.split('.')[0];
493 combined.params.contact_sub_type = filter.value.split('.')[1];
494 } else {
495 // Allow json-encoded api filters e.g. {"BETWEEN":[123,456]}
496 combined.params[filter.key] = filter.value.charAt(0) === '{' ? $.parseJSON(filter.value) : filter.value;
497 }
498 }
499 return combined;
500 }
501
502 CRM.utils.formatSelect2Result = function (row) {
503 var markup = '<div class="crm-select2-row">';
504 if (row.image !== undefined) {
505 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
506 }
507 else if (row.icon_class) {
508 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
509 }
510 markup += '<div><div class="crm-select2-row-label '+(row.label_class || '')+'">' + row.label + '</div>';
511 markup += '<div class="crm-select2-row-description">';
512 $.each(row.description || [], function(k, text) {
513 markup += '<p>' + text + '</p>';
514 });
515 markup += '</div></div></div>';
516 return markup;
517 };
518
519 function renderEntityRefCreateLinks($el) {
520 var
521 createLinks = $el.data('create-links'),
522 params = getEntityRefApiParams($el).params,
523 markup = '<div class="crm-entityref-links">';
524 if (!createLinks || $el.data('api-entity').toLowerCase() !== 'contact') {
525 return '';
526 }
527 if (createLinks === true) {
528 createLinks = params.contact_type ? _.where(CRM.config.entityRef.contactCreate, {type: params.contact_type}) : CRM.config.entityRef.contactCreate;
529 }
530 _.each(createLinks, function(link) {
531 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
532 if (link.type) {
533 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
534 }
535 markup += link.label + '</a>';
536 });
537 markup += '</div>';
538 return markup;
539 }
540
541 function getEntityRefFilters($el) {
542 var
543 entity = $el.data('api-entity').toLowerCase(),
544 filters = $.extend([], CRM.config.entityRef.filters[entity] || []),
545 filter = $el.data('user-filter') || {},
546 params = $.extend({params: {}}, $el.data('api-params') || {}).params,
547 result = [];
548 $.each(filters, function() {
549 if (typeof params[this.key] === 'undefined') {
550 result.push(this);
551 }
552 else if (this.key == 'contact_type' && typeof params.contact_sub_type === 'undefined') {
553 this.options = _.remove(this.options, function(option) {
554 return option.key.indexOf(params.contact_type + '.') === 0;
555 });
556 result.push(this);
557 }
558 });
559 return result;
560 }
561
562 function renderEntityRefFilters($el) {
563 var
564 filters = getEntityRefFilters($el),
565 filter = $el.data('user-filter') || {},
566 filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null;
567 if (!filters.length) {
568 return '';
569 }
570 var markup = '<div class="crm-entityref-filters">' +
571 '<select class="crm-entityref-filter-key' + (filter.key ? ' active' : '') + '">' +
572 '<option value="">' + ts('Refine search...') + '</option>' +
573 CRM.utils.renderOptions(filters, filter.key) +
574 '</select> &nbsp; ' +
575 '<select class="crm-entityref-filter-value' + (filter.key ? ' active"' : '"') + (filter.key ? '' : ' style="display:none;"') + '>' +
576 '<option value="">' + ts('- select -') + '</option>';
577 if (filterSpec && filterSpec.options) {
578 markup += CRM.utils.renderOptions(filterSpec.options, filter.value);
579 }
580 markup += '</select></div>';
581 return markup;
582 }
583
584 /**
585 * Fetch options for a filter (via ajax if necessary) and populate the appropriate select list
586 * @param $el
587 */
588 function loadEntityRefFilterOptions($el) {
589 var
590 filters = getEntityRefFilters($el),
591 filter = $el.data('user-filter') || {},
592 filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null,
593 $valField = $('.crm-entityref-filter-value', '#select2-drop');
594 if (filterSpec) {
595 $valField.show().val('');
596 if (filterSpec.options) {
597 CRM.utils.setOptions($valField, filterSpec.options, false, filter.value);
598 } else {
599 $valField.prop('disabled', true);
600 CRM.api3(filterSpec.entity || $el.data('api-entity'), 'getoptions', {field: filter.key, sequential: 1})
601 .done(function(result) {
602 var entity = $el.data('api-entity').toLowerCase(),
603 globalFilterSpec = _.find(CRM.config.entityRef.filters[entity], {key: filter.key}) || {};
604 // Store options globally so we don't have to look them up again
605 globalFilterSpec.options = result.values;
606 $valField.prop('disabled', false);
607 CRM.utils.setOptions($valField, result.values);
608 $valField.val(filter.value || '');
609 });
610 }
611 } else {
612 $valField.hide();
613 }
614 }
615
616 //CRM-15598 - Override url validator method to allow relative url's (e.g. /index.htm)
617 $.validator.addMethod("url", function(value, element) {
618 if (/^\//.test(value)) {
619 // Relative url: prepend dummy path for validation.
620 value = 'http://domain.tld' + value;
621 }
622 // From jQuery Validation Plugin v1.12.0
623 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);
624 });
625
626 /**
627 * Wrapper for jQuery validate initialization function; supplies defaults
628 */
629 $.fn.crmValidate = function(params) {
630 return $(this).each(function () {
631 var that = this,
632 settings = $.extend({}, CRM.validate._defaults, CRM.validate.params);
633 $(this).validate(settings);
634 // Call any post-initialization callbacks
635 if (CRM.validate.functions && CRM.validate.functions.length) {
636 $.each(CRM.validate.functions, function(i, func) {
637 func.call(that);
638 });
639 }
640 });
641 };
642
643 // Initialize widgets
644 $(document)
645 .on('crmLoad', function(e) {
646 $('table.row-highlight', e.target)
647 .off('.rowHighlight')
648 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) {
649 var filter, $table = $(this).closest('table');
650 if ($(this).hasClass('select-rows')) {
651 filter = $(this).prop('checked') ? ':not(:checked)' : ':checked';
652 $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
653 }
654 else {
655 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
656 if (data !== 'master-selected') {
657 $('input.select-rows', $table).prop('checked', $(".select-row:not(':checked')", $table).length < 1);
658 }
659 }
660 })
661 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
662 if ($("input:radio[name=radio_ts]").size() == 1) {
663 $("input:radio[name=radio_ts]").prop("checked", true);
664 }
665 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
666 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
667 $('select.crm-chain-select-control', e.target).off('.chainSelect').on('change.chainSelect', chainSelect);
668 // Cache Form Input initial values
669 $('form[data-warn-changes] :input', e.target).each(function() {
670 $(this).data('crm-initial-value', $(this).val());
671 });
672 })
673 .on('dialogopen', function(e) {
674 var $el = $(e.target);
675 // Modal dialogs should disable scrollbars
676 if ($el.dialog('option', 'modal')) {
677 $el.addClass('modal-dialog');
678 $('body').css({overflow: 'hidden'});
679 }
680 // Add resize button
681 if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) {
682 $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}));
683 $('.crm-dialog-titlebar-resize', $el.parent()).click(function(e) {
684 if ($el.data('origSize')) {
685 $el.dialog('option', $el.data('origSize'));
686 $el.data('origSize', null);
687 } else {
688 var menuHeight = $('#civicrm-menu').outerHeight();
689 $el.data('origSize', {
690 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
691 width: $el.dialog('option', 'width'),
692 height: $el.dialog('option', 'height')
693 });
694 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: {my: "top", at: "top+"+menuHeight, of: window}});
695 }
696 e.preventDefault();
697 });
698 }
699 })
700 .on('dialogclose', function(e) {
701 // Restore scrollbars when closing modal
702 if ($('.ui-dialog .modal-dialog:visible').not(e.target).length < 1) {
703 $('body').css({overflow: ''});
704 }
705 })
706 .on('submit', function(e) {
707 // CRM-14353 - disable changes warn when submitting a form
708 $('[data-warn-changes]').attr('data-warn-changes', 'false');
709 })
710 ;
711
712 // CRM-14353 - Warn of unsaved changes for forms which have opted in
713 window.onbeforeunload = function() {
714 if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
715 return ts('You have unsaved changes.');
716 }
717 };
718
719 /**
720 * Function to make multiselect boxes behave as fields in small screens
721 */
722 function advmultiselectResize() {
723 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
724 if (amswidth < 700) {
725 $("form table.advmultiselect td").css('display', 'block');
726 }
727 else {
728 $("form table.advmultiselect td").css('display', 'table-cell');
729 }
730 var contactwidth = $('#crm-container #mainTabContainer').width();
731 if (contactwidth < 600) {
732 $('#crm-container #mainTabContainer').addClass('narrowpage');
733 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
734 if (index > 1) {
735 if (index % 2 == 0) {
736 $(this).parent().after('<tr class="narrowadded"></tr>');
737 }
738 var item = $(this);
739 $(this).parent().next().append(item);
740 }
741 });
742 }
743 else {
744 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
745 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
746 var nitem = $(this);
747 var parent = $(this).parent();
748 $(this).parent().prev().append(nitem);
749 if (parent.children().size() == 0) {
750 parent.remove();
751 }
752 });
753 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
754 }
755 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
756
757 if (cformwidth < 720) {
758 $('#crm-container .contact_basic_information-section').addClass('narrowform');
759 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
760 if (cformwidth < 480) {
761 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
762 }
763 else {
764 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
765 }
766 }
767 else {
768 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
769 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
770 }
771 }
772
773 advmultiselectResize();
774 $(window).resize(advmultiselectResize);
775
776 $.fn.crmtooltip = function () {
777 $(document)
778 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
779 $(this).addClass('crm-processed');
780 $(this).addClass('crm-tooltip-active');
781 var topDistance = e.pageY - $(window).scrollTop();
782 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
783 $(this).addClass('crm-tooltip-down');
784 }
785 if (!$(this).children('.crm-tooltip-wrapper').length) {
786 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
787 $(this).children().children('.crm-tooltip')
788 .html('<div class="crm-loading-element"></div>')
789 .load(this.href);
790 }
791 })
792 .on('mouseout', 'a.crm-summary-link', function () {
793 $(this).removeClass('crm-processed');
794 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
795 })
796 .on('click', 'a.crm-summary-link', false);
797 };
798
799 var helpDisplay, helpPrevious;
800 CRM.help = function (title, params, url) {
801 if (helpDisplay && helpDisplay.close) {
802 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
803 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
804 helpDisplay.close();
805 return;
806 }
807 helpDisplay.close();
808 }
809 helpPrevious = JSON.stringify(params);
810 params.class_name = 'CRM_Core_Page_Inline_Help';
811 params.type = 'page';
812 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
813 $.ajax(url || CRM.url('civicrm/ajax/inline'),
814 {
815 data: params,
816 dataType: 'html',
817 success: function (data) {
818 $('#crm-notification-container .crm-help .notify-content:last').html(data);
819 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
820 },
821 error: function () {
822 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
823 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
824 }
825 }
826 );
827 };
828 /**
829 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
830 */
831 CRM.status = function(options, deferred) {
832 // 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.
833 if (typeof options === 'string') {
834 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
835 }
836 var opts = $.extend({
837 start: ts('Saving...'),
838 success: ts('Saved'),
839 error: function() {
840 CRM.alert(ts('Sorry an error occurred and your information was not saved'), ts('Error'));
841 }
842 }, options || {});
843 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>')
844 .appendTo('body');
845 $msg.css('min-width', $msg.width());
846 function handle(status, data) {
847 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
848 if (endMsg) {
849 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg);
850 window.setTimeout(function() {
851 $msg.fadeOut('slow', function() {$msg.remove()});
852 }, 2000);
853 } else {
854 $msg.remove();
855 }
856 }
857 return (deferred || new $.Deferred())
858 .done(function(data) {
859 // If the server returns an error msg call the error handler
860 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
861 handle(status, data);
862 })
863 .fail(function(data) {
864 handle('error', data);
865 });
866 };
867
868 /**
869 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
870 */
871 CRM.alert = function (text, title, type, options) {
872 type = type || 'alert';
873 title = title || '';
874 options = options || {};
875 if ($('#crm-notification-container').length) {
876 var params = {
877 text: text,
878 title: title,
879 type: type
880 };
881 // By default, don't expire errors and messages containing links
882 var extra = {
883 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
884 unique: true
885 };
886 options = $.extend(extra, options);
887 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
888 if (options.unique && options.unique !== '0') {
889 $('#crm-notification-container .ui-notify-message').each(function () {
890 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
891 $('.icon.ui-notify-close', this).click();
892 }
893 });
894 }
895 return $('#crm-notification-container').notify('create', params, options);
896 }
897 else {
898 if (title.length) {
899 text = title + "\n" + text;
900 }
901 alert(text);
902 return null;
903 }
904 };
905
906 /**
907 * Close whichever alert contains the given node
908 *
909 * @param node
910 */
911 CRM.closeAlertByChild = function (node) {
912 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
913 };
914
915 /**
916 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
917 */
918 CRM.confirm = function (options) {
919 var dialog, url, msg, buttons = [], settings = {
920 title: ts('Confirm'),
921 message: ts('Are you sure you want to continue?'),
922 url: null,
923 width: 'auto',
924 modal: true,
925 resizable: false,
926 dialogClass: 'crm-container crm-confirm',
927 close: function () {
928 $(this).dialog('destroy').remove();
929 },
930 options: {
931 no: ts('Cancel'),
932 yes: ts('Continue')
933 }
934 };
935 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
936 if (!settings.buttons && $.isPlainObject(settings.options)) {
937 $.each(settings.options, function(op, label) {
938 buttons.push({
939 text: label,
940 'data-op': op,
941 icons: {primary: op === 'no' ? 'ui-icon-close' : 'ui-icon-check'},
942 click: function() {
943 var event = $.Event('crmConfirm:' + op);
944 $(this).trigger(event);
945 if (!event.isDefaultPrevented()) {
946 dialog.dialog('close');
947 }
948 }
949 });
950 });
951 // Order buttons so that "no" goes on the right-hand side
952 settings.buttons = _.sortBy(buttons, 'data-op').reverse();
953 }
954 url = settings.url;
955 msg = url ? '' : settings.message;
956 delete settings.options;
957 delete settings.message;
958 delete settings.url;
959 dialog = $('<div class="crm-confirm-dialog"></div>').html(msg || '').dialog(settings);
960 if ($.isFunction(options)) {
961 dialog.on('crmConfirm:yes', options);
962 }
963 if (url) {
964 CRM.loadPage(url, {target: dialog});
965 }
966 else {
967 dialog.trigger('crmLoad');
968 }
969 return dialog;
970 };
971
972 /** provides a local copy of ts for a domain */
973 CRM.ts = function(domain) {
974 return function(message, options) {
975 if (domain) {
976 options = $.extend(options || {}, {domain: domain});
977 }
978 return ts(message, options);
979 };
980 };
981
982 /**
983 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
984 */
985 $.fn.crmError = function (text, title, options) {
986 title = title || '';
987 text = text || '';
988 options = options || {};
989
990 var extra = {
991 expires: 0
992 };
993 if ($(this).length) {
994 if (title == '') {
995 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
996 if (label.length) {
997 label.addClass('crm-error');
998 var $label = label.clone();
999 if (text == '' && $('.crm-marker', $label).length > 0) {
1000 text = $('.crm-marker', $label).attr('title');
1001 }
1002 $('.crm-marker', $label).remove();
1003 title = $label.text();
1004 }
1005 }
1006 $(this).addClass('error');
1007 }
1008 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
1009 if ($(this).length) {
1010 var ele = $(this);
1011 setTimeout(function () {
1012 ele.one('change', function () {
1013 msg && msg.close && msg.close();
1014 ele.removeClass('error');
1015 label.removeClass('crm-error');
1016 });
1017 }, 1000);
1018 }
1019 return msg;
1020 };
1021
1022 // Display system alerts through js notifications
1023 function messagesFromMarkup() {
1024 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
1025 var text, title = '';
1026 $(this).removeClass('status messages');
1027 var type = $(this).attr('class').split(' ')[0] || 'alert';
1028 type = type.replace('crm-', '');
1029 $('.icon', this).remove();
1030 if ($('.msg-text', this).length > 0) {
1031 text = $('.msg-text', this).html();
1032 title = $('.msg-title', this).html();
1033 }
1034 else {
1035 text = $(this).html();
1036 }
1037 var options = $(this).data('options') || {};
1038 $(this).remove();
1039 // Duplicates were already removed server-side
1040 options.unique = false;
1041 CRM.alert(text, title, type, options);
1042 });
1043 // Handle qf form errors
1044 $('form :input.error', this).one('blur', function() {
1045 $('.ui-notify-message.error a.ui-notify-close').click();
1046 $(this).removeClass('error');
1047 $(this).next('span.crm-error').remove();
1048 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
1049 .removeClass('crm-error')
1050 .find('.crm-error').removeClass('crm-error');
1051 });
1052 }
1053
1054 /**
1055 * Improve blockUI when used with jQuery dialog
1056 */
1057 var originalBlock = $.fn.block,
1058 originalUnblock = $.fn.unblock;
1059
1060 $.fn.block = function(opts) {
1061 if ($(this).is('.ui-dialog-content')) {
1062 originalBlock.call($(this).parents('.ui-dialog'), opts);
1063 return $(this);
1064 }
1065 return originalBlock.call(this, opts);
1066 };
1067 $.fn.unblock = function(opts) {
1068 if ($(this).is('.ui-dialog-content')) {
1069 originalUnblock.call($(this).parents('.ui-dialog'), opts);
1070 return $(this);
1071 }
1072 return originalUnblock.call(this, opts);
1073 };
1074
1075 // Preprocess all CRM ajax calls to display messages
1076 $(document).ajaxSuccess(function(event, xhr, settings) {
1077 try {
1078 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
1079 var response = $.parseJSON(xhr.responseText);
1080 if (typeof(response.crmMessages) == 'object') {
1081 $.each(response.crmMessages, function(n, msg) {
1082 CRM.alert(msg.text, msg.title, msg.type, msg.options);
1083 })
1084 }
1085 if (response.backtrace) {
1086 CRM.console('log', response.backtrace);
1087 }
1088 if (typeof response.deprecated === 'string') {
1089 CRM.console('warn', response.deprecated);
1090 }
1091 }
1092 }
1093 // Ignore errors thrown by parseJSON
1094 catch (e) {}
1095 });
1096
1097 $(function () {
1098 $.blockUI.defaults.message = null;
1099 $.blockUI.defaults.ignoreIfBlocked = true;
1100
1101 if ($('#crm-container').hasClass('crm-public')) {
1102 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container crm-public';
1103 }
1104
1105 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1106 $('.crm-container').trigger('crmLoad');
1107
1108 if ($('#crm-notification-container').length) {
1109 // Initialize notifications
1110 $('#crm-notification-container').notify();
1111 messagesFromMarkup.call($('#crm-container'));
1112 }
1113
1114 $('body')
1115 // bind the event for image popup
1116 .on('click', 'a.crm-image-popup', function(e) {
1117 CRM.confirm({
1118 title: ts('Preview'),
1119 resizable: true,
1120 message: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
1121 options: null
1122 });
1123 e.preventDefault();
1124 })
1125
1126 .on('click', function (event) {
1127 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1128 if ($(event.target).is('.btn-slide')) {
1129 $(event.target).addClass('btn-slide-active').find('.panel').show();
1130 }
1131 })
1132
1133 // Handle clear button for form elements
1134 .on('click', 'a.crm-clear-link', function() {
1135 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
1136 $(this).siblings('input:text').val('').change();
1137 return false;
1138 })
1139 .on('change', 'input.crm-form-radio:checked', function() {
1140 $(this).siblings('.crm-clear-link').css({visibility: ''});
1141 })
1142
1143 // Allow normal clicking of links within accordions
1144 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
1145 e.stopPropagation();
1146 })
1147 // Handle accordions
1148 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
1149 if ($(this).parent().hasClass('collapsed')) {
1150 $(this).next().css('display', 'none').slideDown(200);
1151 }
1152 else {
1153 $(this).next().css('display', 'block').slideUp(200);
1154 }
1155 $(this).parent().toggleClass('collapsed');
1156 e.preventDefault();
1157 });
1158
1159 $().crmtooltip();
1160 });
1161 /**
1162 * @deprecated
1163 */
1164 $.fn.crmAccordions = function () {};
1165 /**
1166 * Collapse or expand an accordion
1167 * @param speed
1168 */
1169 $.fn.crmAccordionToggle = function (speed) {
1170 $(this).each(function () {
1171 if ($(this).hasClass('collapsed')) {
1172 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
1173 }
1174 else {
1175 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1176 }
1177 $(this).toggleClass('collapsed');
1178 });
1179 };
1180
1181 /**
1182 * Clientside currency formatting
1183 * @param number value
1184 * @param [optional] string format - currency representation of the number 1234.56
1185 * @return string
1186 */
1187 var currencyTemplate;
1188 CRM.formatMoney = function(value, format) {
1189 var decimal, separator, sign, i, j, result;
1190 if (value === 'init' && format) {
1191 currencyTemplate = format;
1192 return;
1193 }
1194 format = format || currencyTemplate;
1195 result = /1(.?)234(.?)56/.exec(format);
1196 if (result === null) {
1197 return 'Invalid format passed to CRM.formatMoney';
1198 }
1199 separator = result[1];
1200 decimal = result[2];
1201 sign = (value < 0) ? '-' : '';
1202 //extracting the absolute value of the integer part of the number and converting to string
1203 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
1204 j = ((j = i.length) > 3) ? j % 3 : 0;
1205 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) : '');
1206 return format.replace(/1.*234.*56/, result);
1207 };
1208
1209 CRM.console = function(method, title, msg) {
1210 if (window.console) {
1211 method = $.isFunction(console[method]) ? method : 'log';
1212 if (msg === undefined) {
1213 return console[method](title);
1214 } else {
1215 return console[method](title, msg);
1216 }
1217 }
1218 };
1219 })(jQuery, _);