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