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