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