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