Add phpdoc comment to random recipients function
[civicrm-core.git] / js / Common.js
CommitLineData
353ea873 1// https://civicrm.org/licensing
6a488035 2var CRM = CRM || {};
4b513f23
CW
3var cj = CRM.$ = jQuery;
4CRM._ = _;
6a488035
TO
5
6/**
7 * Short-named function for string translation, defined in global scope so it's available everywhere.
8 *
353ea873
CW
9 * @param text string for translating
10 * @param params object key:value of additional parameters
6a488035 11 *
353ea873 12 * @return string
6a488035
TO
13 */
14function ts(text, params) {
7553cf23 15 "use strict";
6a488035 16 text = CRM.strings[text] || text;
2788147f 17 if (typeof(params) === 'object') {
6a488035 18 for (var i in params) {
32155ad6 19 if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') {
2788147f 20 // sprintf emulation: escape % characters in the replacements to avoid conflicts
32155ad6 21 text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-'));
2788147f 22 }
6a488035
TO
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 *
353ea873 35 * @deprecated
6a488035
TO
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 ...)
6a488035 39 */
0f5816a6
KJ
40function 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;
6a488035 51 }
0f5816a6
KJ
52 else {
53 alert('showBlocks array item not in .tpl = ' + showBlocks[i]);
54 }
55 }
6a488035 56
0f5816a6
KJ
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]);
6a488035 66 }
0f5816a6 67 }
6a488035
TO
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 *
353ea873 74 * @deprecated
6a488035
TO
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
0f5816a6
KJ
81 */
82function showHideByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, invert) {
83 if (target_element_type == null) {
84 var target_element_type = 'block';
85 }
86 else {
87 if (target_element_type == 'table-row') {
88 var target_element_type = '';
89 }
90 }
91
92 if (field_type == 'select') {
93 var trigger = trigger_value.split("|");
24cc4545 94 var selectedOptionValue = cj('#' + trigger_field_id).val();
0f5816a6
KJ
95
96 var target = target_element_id.split("|");
97 for (var j = 0; j < target.length; j++) {
98 if (invert) {
99 cj('#' + target[j]).show();
100 }
101 else {
102 cj('#' + target[j]).hide();
103 }
104 for (var i = 0; i < trigger.length; i++) {
105 if (selectedOptionValue == trigger[i]) {
106 if (invert) {
107 cj('#' + target[j]).hide();
108 }
109 else {
110 cj('#' + target[j]).show();
111 }
6a488035 112 }
0f5816a6
KJ
113 }
114 }
6a488035 115
0f5816a6
KJ
116 }
117 else {
118 if (field_type == 'radio') {
119 var target = target_element_id.split("|");
120 for (var j = 0; j < target.length; j++) {
24cc4545 121 if (cj('[name="' + trigger_field_id + '"]').is(':checked')) {
0f5816a6
KJ
122 if (invert) {
123 cj('#' + target[j]).hide();
124 }
125 else {
126 cj('#' + target[j]).show();
127 }
6a488035 128 }
0f5816a6
KJ
129 else {
130 if (invert) {
131 cj('#' + target[j]).show();
132 }
133 else {
134 cj('#' + target[j]).hide();
135 }
136 }
137 }
6a488035 138 }
0f5816a6 139 }
6a488035
TO
140}
141
6a488035
TO
142/**
143 * Function to change button text and disable one it is clicked
353ea873 144 * @deprecated
6a488035
TO
145 * @param obj object - the button clicked
146 * @param formID string - the id of the form being submitted
147 * @param string procText - button text after user clicks it
353ea873 148 * @return bool
6a488035 149 */
0f5816a6 150var submitcount = 0;
c6edd786 151/* Changes button label on submit, and disables button after submit for newer browsers.
152 Puts up alert for older browsers. */
0f5816a6
KJ
153function submitOnce(obj, formId, procText) {
154 // if named button clicked, change text
155 if (obj.value != null) {
156 obj.value = procText + " ...";
157 }
158 if (document.getElementById) { // disable submit button for newer browsers
159 obj.disabled = true;
160 document.getElementById(formId).submit();
161 return true;
162 }
163 else { // for older browsers
164 if (submitcount == 0) {
165 submitcount++;
166 return true;
167 }
168 else {
169 alert("Your request is currently being processed ... Please wait.");
170 return false;
6a488035 171 }
0f5816a6 172 }
6a488035 173}
6a488035 174
6a488035
TO
175/**
176 * Function to show / hide the row in optionFields
353ea873
CW
177 * @deprecated
178 * @param index string, element whose innerHTML is to hide else will show the hidden row.
6a488035 179 */
0f5816a6
KJ
180function showHideRow(index) {
181 if (index) {
182 cj('tr#optionField_' + index).hide();
183 if (cj('table#optionField tr:hidden:first').length) {
184 cj('div#optionFieldLink').show();
6a488035 185 }
0f5816a6
KJ
186 }
187 else {
188 cj('table#optionField tr:hidden:first').show();
189 if (!cj('table#optionField tr:hidden:last').length) {
190 cj('div#optionFieldLink').hide();
191 }
192 }
193 return false;
6a488035
TO
194}
195
475e9f44 196CRM.utils = CRM.utils || {};
6a488035 197CRM.strings = CRM.strings || {};
6a488035 198
4b513f23 199(function ($, _, undefined) {
7553cf23 200 "use strict";
d664f648 201
3f586963
CW
202 // Theme classes for unattached elements
203 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container';
204
47f21f3a
CW
205 // https://github.com/ivaynberg/select2/pull/2090
206 $.fn.select2.defaults.width = 'resolve';
207
e20523a8
CW
208 // Workaround for https://github.com/ivaynberg/select2/issues/1246
209 $.ui.dialog.prototype._allowInteraction = function(e) {
210 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop').length;
211 };
212
475e9f44
CW
213 /**
214 * Populate a select list, overwriting the existing options except for the placeholder.
215 * @param $el jquery collection - 1 or more select elements
216 * @param options array in format returned by api.getoptions
23e8a31b 217 * @param removePlaceholder bool
475e9f44 218 */
23e8a31b 219 CRM.utils.setOptions = function($el, options, removePlaceholder) {
475e9f44
CW
220 $el.each(function() {
221 var
222 $elect = $(this),
23e8a31b
CW
223 val = $elect.val() || [],
224 opts = removePlaceholder ? '' : '[value!=""]';
46ed212b 225 if (!$.isArray(val)) {
475e9f44
CW
226 val = [val];
227 }
23e8a31b 228 $elect.find('option' + opts).remove();
e6f4ac36 229 _.each(options, function(option) {
475e9f44
CW
230 var selected = ($.inArray(''+option.key, val) > -1) ? 'selected="selected"' : '';
231 $elect.append('<option value="' + option.key + '"' + selected + '>' + option.value + '</option>');
232 });
e6f4ac36 233 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
475e9f44
CW
234 });
235 };
236
3e201321 237/**
238 * Compare Form Input values against cached initial value.
88e9380e
CW
239 *
240 * @return {Boolean} true if changes have been made.
3e201321 241 */
242 CRM.utils.initialValueChanged = function(el) {
88e9380e 243 var isDirty = false;
18469bf2 244 $(':input:visible, .select2-container:visible+:input.select2-offscreen', el).not('[type=submit], [type=button], .crm-action-menu').each(function () {
88e9380e 245 var initialValue = $(this).data('crm-initial-value');
3c0624e2 246 // skip change of value for submit buttons
bf7a4fbc 247 if (initialValue !== undefined && !_.isEqual(initialValue, $(this).val())) {
88e9380e
CW
248 isDirty = true;
249 }
3e201321 250 });
251 return isDirty;
8d36b801 252 };
3e201321 253
7ba7f3a0 254 /**
255 * Wrapper for toggle function which is deprecated in from jQuery 1.8;
256 * @param fn1,fn2 handlers
257 */
258
259 $.fn.toggleClick = function( fn1, fn2 ) {
260 // Don't mess with animation or css toggles
261 if ( !$.isFunction( fn1 ) || !$.isFunction( fn2 ) ) {
262 return;
263 }
264 // migrateWarn("jQuery.fn.toggle(handler, handler...) is deprecated");
265 // Save reference to arguments for access in closure
266 var args = arguments,
267 guid = fn1.guid || $.guid++,
268 i = 0,
269 toggler = function( event ) {
270 // Figure out which function to execute
271 var lastToggle = ( $._data( this, "lastToggle" + fn1.guid ) || 0 ) % i;
272 $._data( this, "lastToggle" + fn1.guid, lastToggle + 1 );
273 // Make sure that clicks stop
274 event.preventDefault();
275 // and execute the function
276 return args[ lastToggle ].apply( this, arguments ) || false;
277 };
278 // link all the functions, so any of them can unbind this click handler
279 toggler.guid = guid;
280 while ( i < args.length ) {
281 args[ i++ ].guid = guid;
282 }
283 return this.click( toggler );
284 };
285
ba4fb2b2 286 /**
353ea873 287 * Wrapper for select2 initialization function; supplies defaults
a88cf11a 288 * @param options object
ba4fb2b2 289 */
a88cf11a
CW
290 $.fn.crmSelect2 = function(options) {
291 return $(this).each(function () {
292 var
293 $el = $(this),
a243158e 294 settings = {allowClear: !$el.hasClass('required')};
a88cf11a
CW
295 // quickform doesn't support optgroups so here's a hack :(
296 $('option[value^=crm_optgroup]', this).each(function () {
297 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
298 $(this).remove();
299 });
300 // Defaults for single-selects
301 if ($el.is('select:not([multiple])')) {
a243158e 302 settings.minimumResultsForSearch = 10;
a88cf11a 303 if ($('option:first', this).val() === '') {
a243158e 304 settings.placeholderOption = 'first';
a88cf11a 305 }
ba4fb2b2 306 }
a243158e
CW
307 $.extend(settings, $el.data('select-params') || {}, options || {});
308 if (settings.ajax) {
309 $el.addClass('crm-ajax-select');
310 }
311 $el.select2(settings);
a88cf11a
CW
312 });
313 };
314
315 /**
353ea873 316 * @see CRM_Core_Form::addEntityRef for docs
a88cf11a
CW
317 * @param options object
318 */
319 $.fn.crmEntityRef = function(options) {
320 options = options || {};
321 options.select = options.select || {};
322 return $(this).each(function() {
323 var
4c993609 324 $el = $(this).off('.crmEntity'),
a88cf11a
CW
325 entity = options.entity || $el.data('api-entity') || 'contact',
326 selectParams = {};
327 $el.data('api-entity', entity);
328 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
329 $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api));
a4799f04 330 $el.data('create-links', options.create || $el.data('create-links'));
a243158e 331 $el.addClass('crm-form-entityref crm-' + entity + '-ref');
ba4fb2b2
CW
332 var settings = {
333 // Use select2 ajax helper instead of CRM.api because it provides more value
334 ajax: {
335 url: CRM.url('civicrm/ajax/rest'),
336 data: function (input, page_num) {
337 var params = $el.data('api-params') || {};
338 params.input = input;
339 params.page_num = page_num;
340 return {
341 entity: $el.data('api-entity'),
342 action: 'getlist',
343 json: JSON.stringify(params)
344 };
345 },
346 results: function(data) {
347 return {more: data.more_results, results: data.values || []};
348 }
349 },
a88cf11a 350 minimumInputLength: 1,
3c0b6a40 351 formatResult: CRM.utils.formatSelect2Result,
ba4fb2b2
CW
352 formatSelection: function(row) {
353 return row.label;
354 },
355 escapeMarkup: function (m) {return m;},
a88cf11a
CW
356 initSelection: function($el, callback) {
357 var
358 multiple = !!$el.data('select-params').multiple,
359 val = $el.val(),
360 stored = $el.data('entity-value') || [];
361 if (val === '') {
362 return;
363 }
364 // If we already have this data, just return it
365 if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
366 callback(multiple ? stored : stored[0]);
367 } else {
78b203e5 368 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
a88cf11a 369 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
d2b4810b
CW
370 callback(multiple ? result.values : result.values[0]);
371 // Trigger change (store data to avoid an infinite loop of lookups)
372 $el.data('entity-value', result.values).trigger('change');
a88cf11a
CW
373 });
374 }
ba4fb2b2
CW
375 }
376 };
4c993609 377 if ($el.data('create-links') && entity.toLowerCase() === 'contact') {
a88cf11a
CW
378 selectParams.formatInputTooShort = function() {
379 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
4e56e743 380 if ($el.data('create-links') && CRM.profileCreate) {
a4799f04 381 txt += ' ' + ts('or') + '<br />' + formatSelect2CreateLinks($el);
ba4fb2b2
CW
382 }
383 return txt;
384 };
a88cf11a 385 selectParams.formatNoMatches = function() {
ba4fb2b2 386 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
4e56e743 387 return txt + (CRM.profileCreate ? ('<br />' + formatSelect2CreateLinks($el)) : '');
ba4fb2b2 388 };
4c993609 389 $el.on('select2-open.crmEntity', function() {
ba4fb2b2
CW
390 var $el = $(this);
391 $('#select2-drop').off('.crmEntity').on('click.crmEntity', 'a.crm-add-entity', function(e) {
392 $el.select2('close');
393 CRM.loadForm($(this).attr('href'), {
394 dialog: {width: 500, height: 'auto'}
395 }).on('crmFormSuccess', function(e, data) {
c92f6436 396 if (data.status === 'success' && data.id) {
e11b84ce 397 CRM.status(ts('%1 Created', {1: data.label}));
c92f6436
CW
398 if ($el.select2('container').hasClass('select2-container-multi')) {
399 var selection = $el.select2('data');
400 selection.push(data);
401 $el.select2('data', selection, true);
402 } else {
403 $el.select2('data', data, true);
404 }
ba4fb2b2
CW
405 }
406 });
407 return false;
408 });
409 });
410 }
4c993609
CW
411 // Create new items inline - works for tags
412 else if ($el.data('create-links')) {
413 selectParams.createSearchChoice = function(term, data) {
414 if (!_.findKey(data, {label: term})) {
415 return {id: "0", term: term, label: term + ' (' + ts('new tag') + ')'};
416 }
417 };
e4f4dc22 418 selectParams.tokenSeparators = [','];
4c993609
CW
419 selectParams.createSearchChoicePosition = 'bottom';
420 }
421 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams))
422 .on('select2-selecting.crmEntity', function(e) {
423 if (e.val === "0") {
424 e.object.label = e.object.term;
425 CRM.api3(entity, 'create', $.extend({name: e.object.term}, $el.data('api-params').params || {}))
426 .done(function(created) {
427 var
428 multiple = !!$el.data('select-params').multiple,
429 val = $el.select2('val'),
430 data = $el.select2('data'),
431 item = {id: created.id, label: e.object.term};
432 if (val === "0") {
e4f4dc22 433 $el.select2('data', item, true);
4c993609
CW
434 }
435 else if ($.isArray(val) && $.inArray("0", val) > -1) {
436 _.remove(data, {id: "0"});
437 data.push(item);
e4f4dc22 438 $el.select2('data', data, true);
4c993609
CW
439 }
440 });
441 }
442 });
a88cf11a 443 });
ba4fb2b2
CW
444 };
445
3c0b6a40 446 CRM.utils.formatSelect2Result = function (row) {
88881f79 447 var markup = '<div class="crm-select2-row">';
ff88d165 448 if (row.image !== undefined) {
88881f79 449 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
ff88d165 450 }
54bee7df 451 else if (row.icon_class) {
88881f79 452 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
54bee7df 453 }
3c0b6a40 454 markup += '<div><div class="crm-select2-row-label '+(row.label_class || '')+'">' + row.label + '</div>';
88881f79
CW
455 markup += '<div class="crm-select2-row-description">';
456 $.each(row.description || [], function(k, text) {
457 markup += '<p>' + text + '</p>';
458 });
459 markup += '</div></div></div>';
ff88d165 460 return markup;
3c0b6a40 461 };
a4799f04
CW
462
463 function formatSelect2CreateLinks($el) {
464 var
465 createLinks = $el.data('create-links'),
466 api = $el.data('api-params') || {},
467 type = api.params ? api.params.contact_type : null;
468 if (createLinks === true) {
4e56e743 469 createLinks = type ? _.where(CRM.profileCreate, {type: type}) : CRM.profileCreate;
a4799f04 470 }
79ae07d9 471 var markup = '';
a4799f04 472 _.each(createLinks, function(link) {
79ae07d9 473 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
a4799f04
CW
474 if (link.type) {
475 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
79ae07d9
CW
476 }
477 markup += link.label + '</a>';
478 });
479 return markup;
a4799f04 480 }
ff88d165 481
3d527838
CW
482 /**
483 * Wrapper for jQuery validate initialization function; supplies defaults
484 * @param options object
485 */
486 $.fn.crmValidate = function(params) {
487 return $(this).each(function () {
488 var that = this,
489 settings = $.extend({}, CRM.validate._defaults, CRM.validate.params);
490 $(this).validate(settings);
491 // Call any post-initialization callbacks
492 if (CRM.validate.functions && CRM.validate.functions.length) {
493 $.each(CRM.validate.functions, function(i, func) {
494 func.call(that);
495 });
496 }
497 });
498 }
499
f7b92fcd 500 // Initialize widgets
eb90857a
CW
501 $(document)
502 .on('crmLoad', function(e) {
503 $('table.row-highlight', e.target)
504 .off('.rowHighlight')
7e13d44e
CW
505 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) {
506 var filter, $table = $(this).closest('table');
eb90857a 507 if ($(this).hasClass('select-rows')) {
7e13d44e
CW
508 filter = $(this).prop('checked') ? ':not(:checked)' : ':checked';
509 $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
eb90857a
CW
510 }
511 else {
7e13d44e
CW
512 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
513 if (data !== 'master-selected') {
514 $('input.select-rows', $table).prop('checked', $(".select-row:not(':checked')", $table).length < 1);
515 }
eb90857a 516 }
eb90857a
CW
517 })
518 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
5f34e50b
CW
519 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
520 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
3e201321 521 // Cache Form Input initial values
88e9380e 522 $('form[data-warn-changes] :input', e.target).each(function() {
329758bb 523 $(this).data('crm-initial-value', $(this).val());
3e201321 524 });
eb90857a 525 })
eb90857a 526 .on('dialogopen', function(e) {
f292709b
CW
527 var $el = $(e.target);
528 // Modal dialogs should disable scrollbars
529 if ($el.dialog('option', 'modal')) {
530 $el.addClass('modal-dialog');
eb90857a
CW
531 $('body').css({overflow: 'hidden'});
532 }
f292709b
CW
533 $el.parent().find('.ui-dialog-titlebar-close').attr('title', ts('Close'));
534 // Add resize button
a243158e 535 if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) {
77a8d7f9 536 $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
537 $('.crm-dialog-titlebar-resize', $el.parent()).click(function(e) {
538 if ($el.data('origSize')) {
539 $el.dialog('option', $el.data('origSize'));
540 $el.data('origSize', null);
541 } else {
542 $el.data('origSize', {
f2f191fe 543 position: {my: 'center', at: 'center', of: window},
f292709b
CW
544 width: $el.dialog('option', 'width'),
545 height: $el.dialog('option', 'height')
546 });
547 var menuHeight = $('#civicrm-menu').height();
f2f191fe 548 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: {my: "top", at: "top+"+menuHeight, of: window}});
f292709b
CW
549 }
550 e.preventDefault();
551 });
552 }
eb90857a
CW
553 })
554 .on('dialogclose', function(e) {
f292709b 555 // Restore scrollbars when closing modal
5a6148a0 556 if ($('.ui-dialog .modal-dialog:visible').not(e.target).length < 1) {
eb90857a
CW
557 $('body').css({overflow: ''});
558 }
afc021d8 559 })
560 .on('submit', function(e) {
f582fc8f 561 // CRM-14353 - disable changes warn when submitting a form
abb6e044 562 $('[data-warn-changes]').attr('data-warn-changes', 'false');
afc021d8 563 })
f582fc8f
CW
564 ;
565
566 // CRM-14353 - Warn of unsaved changes for forms which have opted in
567 window.onbeforeunload = function() {
18469bf2 568 if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
f582fc8f
CW
569 return ts('You have unsaved changes.');
570 }
571 };
148c4e8d
CW
572
573 /**
574 * Function to make multiselect boxes behave as fields in small screens
575 */
576 function advmultiselectResize() {
577 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
578 if (amswidth < 700) {
579 $("form table.advmultiselect td").css('display', 'block');
0f5816a6
KJ
580 }
581 else {
148c4e8d
CW
582 $("form table.advmultiselect td").css('display', 'table-cell');
583 }
584 var contactwidth = $('#crm-container #mainTabContainer').width();
585 if (contactwidth < 600) {
586 $('#crm-container #mainTabContainer').addClass('narrowpage');
0f5816a6 587 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
148c4e8d 588 if (index > 1) {
0f5816a6 589 if (index % 2 == 0) {
148c4e8d
CW
590 $(this).parent().after('<tr class="narrowadded"></tr>');
591 }
592 var item = $(this);
593 $(this).parent().next().append(item);
594 }
595 });
0f5816a6
KJ
596 }
597 else {
148c4e8d 598 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
0f5816a6 599 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
148c4e8d
CW
600 var nitem = $(this);
601 var parent = $(this).parent();
602 $(this).parent().prev().append(nitem);
0f5816a6 603 if (parent.children().size() == 0) {
148c4e8d
CW
604 parent.remove();
605 }
606 });
607 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
608 }
609 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
0f5816a6 610
148c4e8d
CW
611 if (cformwidth < 720) {
612 $('#crm-container .contact_basic_information-section').addClass('narrowform');
613 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
614 if (cformwidth < 480) {
615 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
0f5816a6
KJ
616 }
617 else {
148c4e8d
CW
618 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
619 }
0f5816a6
KJ
620 }
621 else {
148c4e8d
CW
622 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
623 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
624 }
625 }
0f5816a6 626
148c4e8d 627 advmultiselectResize();
0f5816a6 628 $(window).resize(function () {
6a488035
TO
629 advmultiselectResize();
630 });
631
0f5816a6 632 $.fn.crmtooltip = function () {
2c29c2ac
RN
633 $(document)
634 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
635 $(this).addClass('crm-processed');
e24b17b9
CW
636 $(this).addClass('crm-tooltip-active');
637 var topDistance = e.pageY - $(window).scrollTop();
638 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
639 $(this).addClass('crm-tooltip-down');
640 }
641 if (!$(this).children('.crm-tooltip-wrapper').length) {
6a488035
TO
642 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
643 $(this).children().children('.crm-tooltip')
644 .html('<div class="crm-loading-element"></div>')
645 .load(this.href);
646 }
647 })
2c29c2ac
RN
648 .on('mouseout', 'a.crm-summary-link', function () {
649 $(this).removeClass('crm-processed');
e24b17b9
CW
650 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
651 })
2c29c2ac 652 .on('click', 'a.crm-summary-link', false);
6a488035
TO
653 };
654
b0ca6188 655 var helpDisplay, helpPrevious;
8e3272a1 656 CRM.help = function (title, params, url) {
55a93b02 657 if (helpDisplay && helpDisplay.close) {
b0ca6188 658 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
55a93b02
CW
659 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
660 helpDisplay.close();
b0ca6188
CW
661 return;
662 }
55a93b02 663 helpDisplay.close();
b0ca6188
CW
664 }
665 helpPrevious = JSON.stringify(params);
6a488035
TO
666 params.class_name = 'CRM_Core_Page_Inline_Help';
667 params.type = 'page';
b0ca6188 668 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
8e3272a1 669 $.ajax(url || CRM.url('civicrm/ajax/inline'),
6a488035
TO
670 {
671 data: params,
672 dataType: 'html',
e24b17b9 673 success: function (data) {
6a488035
TO
674 $('#crm-notification-container .crm-help .notify-content:last').html(data);
675 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
676 },
e24b17b9 677 error: function () {
6a488035
TO
678 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
679 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
680 }
681 }
682 );
683 };
8960d9b9 684 /**
7442e8f6 685 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
8960d9b9 686 */
1b2475e1 687 CRM.status = function(options, deferred) {
9a7ef94f 688 // 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
689 if (typeof options === 'string') {
690 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
8960d9b9 691 }
1b2475e1
CW
692 var opts = $.extend({
693 start: ts('Saving...'),
9a7ef94f 694 success: ts('Saved'),
1b2475e1
CW
695 error: function() {
696 CRM.alert(ts('Sorry an error occurred and your information was not saved'), ts('Error'));
697 }
698 }, options || {});
699 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>')
700 .appendTo('body');
701 $msg.css('min-width', $msg.width());
702 function handle(status, data) {
703 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
704 if (endMsg) {
705 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg);
706 window.setTimeout(function() {
707 $msg.fadeOut('slow', function() {$msg.remove()});
4bad157e
CW
708 }, 2000);
709 } else {
1b2475e1 710 $msg.remove();
4bad157e 711 }
1b2475e1
CW
712 }
713 return (deferred || new $.Deferred())
714 .done(function(data) {
715 // If the server returns an error msg call the error handler
716 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
717 handle(status, data);
718 })
719 .fail(function(data) {
720 handle('error', data);
721 });
8960d9b9 722 };
6a488035
TO
723
724 /**
7442e8f6 725 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 726 */
0f5816a6 727 CRM.alert = function (text, title, type, options) {
6a488035
TO
728 type = type || 'alert';
729 title = title || '';
730 options = options || {};
731 if ($('#crm-notification-container').length) {
732 var params = {
733 text: text,
734 title: title,
735 type: type
736 };
737 // By default, don't expire errors and messages containing links
738 var extra = {
739 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
740 unique: true
741 };
742 options = $.extend(extra, options);
e24b17b9 743 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
6a488035 744 if (options.unique && options.unique !== '0') {
0f5816a6 745 $('#crm-notification-container .ui-notify-message').each(function () {
6a488035
TO
746 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
747 $('.icon.ui-notify-close', this).click();
748 }
749 });
750 }
751 return $('#crm-notification-container').notify('create', params, options);
752 }
753 else {
754 if (title.length) {
755 text = title + "\n" + text;
756 }
757 alert(text);
758 return null;
759 }
e24b17b9 760 };
6a488035
TO
761
762 /**
763 * Close whichever alert contains the given node
764 *
765 * @param node
766 */
0f5816a6 767 CRM.closeAlertByChild = function (node) {
6a488035 768 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
e24b17b9 769 };
6a488035
TO
770
771 /**
7442e8f6 772 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 773 */
5fb83680
CW
774 CRM.confirm = function (options) {
775 var dialog, settings = {
7553cf23
CW
776 title: ts('Confirm Action'),
777 message: ts('Are you sure you want to continue?'),
0d5f99d4 778 width: 'auto',
5fb83680 779 modal: true,
a243158e 780 resizable: false,
5fb83680 781 dialogClass: 'crm-container crm-confirm',
0f5816a6 782 close: function () {
5fb83680 783 $(this).dialog('destroy').remove();
0f5816a6 784 },
5fb83680
CW
785 options: {
786 no: ts('Cancel'),
787 yes: ts('Continue')
788 }
0f5816a6 789 };
5fb83680
CW
790 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
791 if (!settings.buttons && $.isPlainObject(settings.options)) {
792 settings.buttons = [];
793 $.each(settings.options, function(key, label) {
794 settings.buttons.push({
795 text: label,
796 click: function() {
797 var event = $.Event('crmConfirm:' + key);
798 $(this).trigger(event);
799 if (!event.isDefaultPrevented()) {
800 dialog.dialog('close');
801 }
802 }
803 });
804 });
2a06342c 805 }
5fb83680
CW
806 dialog = $('<div class="crm-confirm-dialog"></div>').html(settings.message);
807 delete settings.options;
808 delete settings.message;
809 if ($.isFunction(options)) {
810 dialog.on('crmConfirm:yes', options);
7553cf23 811 }
5fb83680 812 return dialog.dialog(settings).trigger('crmLoad');
e24b17b9 813 };
6a488035 814
ed7225e6
CW
815 /** provides a local copy of ts for a domain */
816 CRM.ts = function(domain) {
817 return function(message, options) {
818 if (domain) {
819 options = $.extend(options || {}, {domain: domain});
820 }
f97524d9
TO
821 return ts(message, options);
822 };
f97524d9
TO
823 };
824
6a488035 825 /**
7442e8f6 826 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 827 */
0f5816a6 828 $.fn.crmError = function (text, title, options) {
6a488035
TO
829 title = title || '';
830 text = text || '';
831 options = options || {};
832
833 var extra = {
834 expires: 0
835 };
836 if ($(this).length) {
837 if (title == '') {
838 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
839 if (label.length) {
840 label.addClass('crm-error');
841 var $label = label.clone();
842 if (text == '' && $('.crm-marker', $label).length > 0) {
843 text = $('.crm-marker', $label).attr('title');
844 }
845 $('.crm-marker', $label).remove();
846 title = $label.text();
847 }
848 }
849 $(this).addClass('error');
850 }
851 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
852 if ($(this).length) {
853 var ele = $(this);
0f5816a6
KJ
854 setTimeout(function () {
855 ele.one('change', function () {
856 msg && msg.close && msg.close();
857 ele.removeClass('error');
858 label.removeClass('crm-error');
859 });
860 }, 1000);
6a488035
TO
861 }
862 return msg;
e24b17b9 863 };
6a488035
TO
864
865 // Display system alerts through js notifications
866 function messagesFromMarkup() {
0f5816a6 867 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
e24b17b9 868 var text, title = '';
6a488035
TO
869 $(this).removeClass('status messages');
870 var type = $(this).attr('class').split(' ')[0] || 'alert';
871 type = type.replace('crm-', '');
872 $('.icon', this).remove();
6a488035 873 if ($('.msg-text', this).length > 0) {
e24b17b9 874 text = $('.msg-text', this).html();
6a488035
TO
875 title = $('.msg-title', this).html();
876 }
877 else {
e24b17b9 878 text = $(this).html();
6a488035
TO
879 }
880 var options = $(this).data('options') || {};
881 $(this).remove();
882 // Duplicates were already removed server-side
883 options.unique = false;
884 CRM.alert(text, title, type, options);
885 });
886 // Handle qf form errors
887 $('form :input.error', this).one('blur', function() {
888 $('.ui-notify-message.error a.ui-notify-close').click();
889 $(this).removeClass('error');
890 $(this).next('span.crm-error').remove();
891 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
892 .removeClass('crm-error')
893 .find('.crm-error').removeClass('crm-error');
894 });
895 }
896
03a7ec8f
CW
897 // Preprocess all cj ajax calls to display messages
898 $(document).ajaxSuccess(function(event, xhr, settings) {
899 try {
900 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
901 var response = $.parseJSON(xhr.responseText);
902 if (typeof(response.crmMessages) == 'object') {
903 $.each(response.crmMessages, function(n, msg) {
904 CRM.alert(msg.text, msg.title, msg.type, msg.options);
905 })
906 }
907 }
908 }
909 // Suppress errors
910 catch (e) {}
911 });
912
0f5816a6 913 $(function () {
fdeb4de2
CW
914 $.blockUI.defaults.message = null;
915
205bb8ae 916 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
8547369d 917 $('.crm-container').trigger('crmLoad');
205bb8ae 918
ef3309b6 919 if ($('#crm-notification-container').length) {
6a488035
TO
920 // Initialize notifications
921 $('#crm-notification-container').notify();
922 messagesFromMarkup.call($('#crm-container'));
6a488035 923 }
ebb9197b 924
475e9f44 925 $('body')
5fb83680
CW
926 // bind the event for image popup
927 .on('click', 'a.crm-image-popup', function(e) {
928 CRM.confirm({
929 title: ts('Preview'),
a243158e 930 resizable: true,
5fb83680
CW
931 message: '<div class="crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>',
932 options: null
933 });
934 e.preventDefault();
475e9f44 935 })
ebb9197b 936
475e9f44
CW
937 .on('click', function (event) {
938 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
939 if ($(event.target).is('.btn-slide')) {
940 $(event.target).addClass('btn-slide-active').find('.panel').show();
941 }
942 })
d664f648 943
4a143c04
CW
944 // Handle clear button for form elements
945 .on('click', 'a.crm-clear-link', function() {
946 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
bcb4280c 947 $(this).siblings('input:text').val('').change();
4a143c04
CW
948 return false;
949 })
950 .on('change', 'input.crm-form-radio:checked', function() {
951 $(this).siblings('.crm-clear-link').css({visibility: ''});
843bfb07 952 })
6a488035 953
843bfb07 954 // Allow normal clicking of links within accordions
cf021bc5 955 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
843bfb07 956 e.stopPropagation();
cf021bc5 957 })
843bfb07
CW
958 // Handle accordions
959 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
6a488035 960 if ($(this).parent().hasClass('collapsed')) {
843bfb07 961 $(this).next().css('display', 'none').slideDown(200);
6a488035
TO
962 }
963 else {
843bfb07 964 $(this).next().css('display', 'block').slideUp(200);
6a488035
TO
965 }
966 $(this).parent().toggleClass('collapsed');
843bfb07 967 e.preventDefault();
6a488035 968 });
843bfb07
CW
969
970 $().crmtooltip();
971 });
972 /**
973 * @deprecated
974 */
975 $.fn.crmAccordions = function () {};
976 /**
977 * Collapse or expand an accordion
978 * @param speed
979 */
0f5816a6
KJ
980 $.fn.crmAccordionToggle = function (speed) {
981 $(this).each(function () {
6a488035
TO
982 if ($(this).hasClass('collapsed')) {
983 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
984 }
985 else {
986 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
987 }
988 $(this).toggleClass('collapsed');
989 });
990 };
5ec182d9
CW
991
992 /**
993 * Clientside currency formatting
994 * @param value
3bdb644f 995 * @param format - currency representation of the number 1234.56
5ec182d9 996 * @return string
3bdb644f 997 * @see CRM_Core_Resources::addCoreResources
5ec182d9
CW
998 */
999 var currencyTemplate;
1000 CRM.formatMoney = function(value, format) {
1001 var decimal, separator, sign, i, j, result;
1002 if (value === 'init' && format) {
1003 currencyTemplate = format;
1004 return;
1005 }
1006 format = format || currencyTemplate;
1007 result = /1(.?)234(.?)56/.exec(format);
1008 if (result === null) {
1009 return 'Invalid format passed to CRM.formatMoney';
1010 }
1011 separator = result[1];
1012 decimal = result[2];
1013 sign = (value < 0) ? '-' : '';
1014 //extracting the absolute value of the integer part of the number and converting to string
1015 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
5ec182d9
CW
1016 j = ((j = i.length) > 3) ? j % 3 : 0;
1017 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) : '');
1018 return format.replace(/1.*234.*56/, result);
1019 };
4b513f23 1020})(jQuery, _);