Merge pull request #2664 from colemanw/tabs
[civicrm-core.git] / js / Common.js
CommitLineData
353ea873 1// https://civicrm.org/licensing
6a488035
TO
2var CRM = CRM || {};
3var cj = jQuery;
4
5/**
6 * Short-named function for string translation, defined in global scope so it's available everywhere.
7 *
353ea873
CW
8 * @param text string for translating
9 * @param params object key:value of additional parameters
6a488035 10 *
353ea873 11 * @return string
6a488035
TO
12 */
13function ts(text, params) {
7553cf23 14 "use strict";
6a488035 15 text = CRM.strings[text] || text;
2788147f 16 if (typeof(params) === 'object') {
6a488035 17 for (var i in params) {
32155ad6 18 if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') {
2788147f 19 // sprintf emulation: escape % characters in the replacements to avoid conflicts
32155ad6 20 text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-'));
2788147f 21 }
6a488035
TO
22 }
23 return text.replace(/%-crmescaped-/g, '%');
24 }
25 return text;
26}
27
28/**
29 * This function is called by default at the bottom of template files which have forms that have
30 * conditionally displayed/hidden sections and elements. The PHP is responsible for generating
31 * a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to
32 * this function.
33 *
353ea873 34 * @deprecated
6a488035
TO
35 * @param showBlocks Array of element Id's to be displayed
36 * @param hideBlocks Array of element Id's to be hidden
37 * @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...)
6a488035 38 */
0f5816a6
KJ
39function on_load_init_blocks(showBlocks, hideBlocks, elementType) {
40 if (elementType == null) {
41 var elementType = 'block';
42 }
43
44 /* This loop is used to display the blocks whose IDs are present within the showBlocks array */
45 for (var i = 0; i < showBlocks.length; i++) {
46 var myElement = document.getElementById(showBlocks[i]);
47 /* getElementById returns null if element id doesn't exist in the document */
48 if (myElement != null) {
49 myElement.style.display = elementType;
6a488035 50 }
0f5816a6
KJ
51 else {
52 alert('showBlocks array item not in .tpl = ' + showBlocks[i]);
53 }
54 }
6a488035 55
0f5816a6
KJ
56 /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
57 for (var i = 0; i < hideBlocks.length; i++) {
58 var myElement = document.getElementById(hideBlocks[i]);
59 /* getElementById returns null if element id doesn't exist in the document */
60 if (myElement != null) {
61 myElement.style.display = 'none';
62 }
63 else {
64 alert('showBlocks array item not in .tpl = ' + hideBlocks[i]);
6a488035 65 }
0f5816a6 66 }
6a488035
TO
67}
68
69/**
70 * This function is called when we need to show or hide a related form element (target_element)
71 * based on the value (trigger_value) of another form field (trigger_field).
72 *
353ea873 73 * @deprecated
6a488035
TO
74 * @param trigger_field_id HTML id of field whose onchange is the trigger
75 * @param trigger_value List of integers - option value(s) which trigger show-element action for target_field
76 * @param target_element_id HTML id of element to be shown or hidden
77 * @param target_element_type Type of element to be shown or hidden ('block' or 'table-row')
78 * @param field_type Type of element radio/select
79 * @param invert Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match
0f5816a6
KJ
80 */
81function showHideByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, invert) {
82 if (target_element_type == null) {
83 var target_element_type = 'block';
84 }
85 else {
86 if (target_element_type == 'table-row') {
87 var target_element_type = '';
88 }
89 }
90
91 if (field_type == 'select') {
92 var trigger = trigger_value.split("|");
24cc4545 93 var selectedOptionValue = cj('#' + trigger_field_id).val();
0f5816a6
KJ
94
95 var target = target_element_id.split("|");
96 for (var j = 0; j < target.length; j++) {
97 if (invert) {
98 cj('#' + target[j]).show();
99 }
100 else {
101 cj('#' + target[j]).hide();
102 }
103 for (var i = 0; i < trigger.length; i++) {
104 if (selectedOptionValue == trigger[i]) {
105 if (invert) {
106 cj('#' + target[j]).hide();
107 }
108 else {
109 cj('#' + target[j]).show();
110 }
6a488035 111 }
0f5816a6
KJ
112 }
113 }
6a488035 114
0f5816a6
KJ
115 }
116 else {
117 if (field_type == 'radio') {
118 var target = target_element_id.split("|");
119 for (var j = 0; j < target.length; j++) {
24cc4545 120 if (cj('[name="' + trigger_field_id + '"]').is(':checked')) {
0f5816a6
KJ
121 if (invert) {
122 cj('#' + target[j]).hide();
123 }
124 else {
125 cj('#' + target[j]).show();
126 }
6a488035 127 }
0f5816a6
KJ
128 else {
129 if (invert) {
130 cj('#' + target[j]).show();
131 }
132 else {
133 cj('#' + target[j]).hide();
134 }
135 }
136 }
6a488035 137 }
0f5816a6 138 }
6a488035
TO
139}
140
6a488035
TO
141/**
142 * Function to change button text and disable one it is clicked
353ea873 143 * @deprecated
6a488035
TO
144 * @param obj object - the button clicked
145 * @param formID string - the id of the form being submitted
146 * @param string procText - button text after user clicks it
353ea873 147 * @return bool
6a488035 148 */
0f5816a6 149var submitcount = 0;
c6edd786 150/* Changes button label on submit, and disables button after submit for newer browsers.
151 Puts up alert for older browsers. */
0f5816a6
KJ
152function submitOnce(obj, formId, procText) {
153 // if named button clicked, change text
154 if (obj.value != null) {
155 obj.value = procText + " ...";
156 }
157 if (document.getElementById) { // disable submit button for newer browsers
158 obj.disabled = true;
159 document.getElementById(formId).submit();
160 return true;
161 }
162 else { // for older browsers
163 if (submitcount == 0) {
164 submitcount++;
165 return true;
166 }
167 else {
168 alert("Your request is currently being processed ... Please wait.");
169 return false;
6a488035 170 }
0f5816a6 171 }
6a488035 172}
353ea873
CW
173/**
174 * @deprecated
175 */
6a488035
TO
176function popUp(URL) {
177 day = new Date();
0f5816a6 178 id = day.getTime();
6a488035
TO
179 eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=640,height=420,left = 202,top = 184');");
180}
181
6a488035
TO
182/**
183 * Function to show / hide the row in optionFields
353ea873
CW
184 * @deprecated
185 * @param index string, element whose innerHTML is to hide else will show the hidden row.
6a488035 186 */
0f5816a6
KJ
187function showHideRow(index) {
188 if (index) {
189 cj('tr#optionField_' + index).hide();
190 if (cj('table#optionField tr:hidden:first').length) {
191 cj('div#optionFieldLink').show();
6a488035 192 }
0f5816a6
KJ
193 }
194 else {
195 cj('table#optionField tr:hidden:first').show();
196 if (!cj('table#optionField tr:hidden:last').length) {
197 cj('div#optionFieldLink').hide();
198 }
199 }
200 return false;
6a488035
TO
201}
202
475e9f44 203CRM.utils = CRM.utils || {};
6a488035
TO
204CRM.strings = CRM.strings || {};
205CRM.validate = CRM.validate || {
206 params: {},
207 functions: []
208};
209
0f5816a6 210(function ($, undefined) {
7553cf23 211 "use strict";
d664f648 212
23e8a31b 213 $.fn.select2.defaults.dropdownCssClass = 'crm-container';
47f21f3a
CW
214 // https://github.com/ivaynberg/select2/pull/2090
215 $.fn.select2.defaults.width = 'resolve';
216
e20523a8
CW
217 // Workaround for https://github.com/ivaynberg/select2/issues/1246
218 $.ui.dialog.prototype._allowInteraction = function(e) {
219 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop').length;
220 };
221
475e9f44
CW
222 /**
223 * Populate a select list, overwriting the existing options except for the placeholder.
224 * @param $el jquery collection - 1 or more select elements
225 * @param options array in format returned by api.getoptions
23e8a31b 226 * @param removePlaceholder bool
475e9f44 227 */
23e8a31b 228 CRM.utils.setOptions = function($el, options, removePlaceholder) {
475e9f44
CW
229 $el.each(function() {
230 var
231 $elect = $(this),
23e8a31b
CW
232 val = $elect.val() || [],
233 opts = removePlaceholder ? '' : '[value!=""]';
475e9f44
CW
234 if (typeof(val) !== 'array') {
235 val = [val];
236 }
23e8a31b 237 $elect.find('option' + opts).remove();
e6f4ac36 238 _.each(options, function(option) {
475e9f44
CW
239 var selected = ($.inArray(''+option.key, val) > -1) ? 'selected="selected"' : '';
240 $elect.append('<option value="' + option.key + '"' + selected + '>' + option.value + '</option>');
241 });
e6f4ac36 242 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
475e9f44
CW
243 });
244 };
245
ba4fb2b2 246 /**
353ea873 247 * Wrapper for select2 initialization function; supplies defaults
a88cf11a 248 * @param options object
ba4fb2b2 249 */
a88cf11a
CW
250 $.fn.crmSelect2 = function(options) {
251 return $(this).each(function () {
252 var
253 $el = $(this),
254 defaults = {allowClear: !$el.hasClass('required')};
255 // quickform doesn't support optgroups so here's a hack :(
256 $('option[value^=crm_optgroup]', this).each(function () {
257 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
258 $(this).remove();
259 });
260 // Defaults for single-selects
261 if ($el.is('select:not([multiple])')) {
262 defaults.minimumResultsForSearch = 10;
263 if ($('option:first', this).val() === '') {
264 defaults.placeholderOption = 'first';
265 }
ba4fb2b2 266 }
a88cf11a
CW
267 $el.select2($.extend(defaults, $el.data('select-params') || {}, options || {}));
268 });
269 };
270
271 /**
353ea873 272 * @see CRM_Core_Form::addEntityRef for docs
a88cf11a
CW
273 * @param options object
274 */
275 $.fn.crmEntityRef = function(options) {
276 options = options || {};
277 options.select = options.select || {};
278 return $(this).each(function() {
279 var
280 $el = $(this),
281 entity = options.entity || $el.data('api-entity') || 'contact',
282 selectParams = {};
283 $el.data('api-entity', entity);
284 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
285 $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api));
a4799f04 286 $el.data('create-links', options.create || $el.data('create-links'));
a88cf11a 287 $el.addClass('crm-ajax-select crm-' + entity + '-ref');
ba4fb2b2
CW
288 var settings = {
289 // Use select2 ajax helper instead of CRM.api because it provides more value
290 ajax: {
291 url: CRM.url('civicrm/ajax/rest'),
292 data: function (input, page_num) {
293 var params = $el.data('api-params') || {};
294 params.input = input;
295 params.page_num = page_num;
296 return {
297 entity: $el.data('api-entity'),
298 action: 'getlist',
299 json: JSON.stringify(params)
300 };
301 },
302 results: function(data) {
303 return {more: data.more_results, results: data.values || []};
304 }
305 },
a88cf11a 306 minimumInputLength: 1,
a4799f04 307 formatResult: formatSelect2Result,
ba4fb2b2
CW
308 formatSelection: function(row) {
309 return row.label;
310 },
311 escapeMarkup: function (m) {return m;},
a88cf11a
CW
312 initSelection: function($el, callback) {
313 var
314 multiple = !!$el.data('select-params').multiple,
315 val = $el.val(),
316 stored = $el.data('entity-value') || [];
317 if (val === '') {
318 return;
319 }
320 // If we already have this data, just return it
321 if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
322 callback(multiple ? stored : stored[0]);
323 } else {
78b203e5 324 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
a88cf11a
CW
325 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
326 callback(multiple ? result.values : result.values[0])
327 });
328 }
ba4fb2b2
CW
329 }
330 };
331 if ($el.data('create-links')) {
a88cf11a
CW
332 selectParams.formatInputTooShort = function() {
333 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
a4799f04
CW
334 if ($el.data('create-links')) {
335 txt += ' ' + ts('or') + '<br />' + formatSelect2CreateLinks($el);
ba4fb2b2
CW
336 }
337 return txt;
338 };
a88cf11a 339 selectParams.formatNoMatches = function() {
ba4fb2b2 340 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
a4799f04 341 return txt + '<br />' + formatSelect2CreateLinks($el);
ba4fb2b2 342 };
a88cf11a 343 $el.off('.createLinks').on('select2-open.createLinks', function() {
ba4fb2b2
CW
344 var $el = $(this);
345 $('#select2-drop').off('.crmEntity').on('click.crmEntity', 'a.crm-add-entity', function(e) {
346 $el.select2('close');
347 CRM.loadForm($(this).attr('href'), {
348 dialog: {width: 500, height: 'auto'}
349 }).on('crmFormSuccess', function(e, data) {
c92f6436
CW
350 if (data.status === 'success' && data.id) {
351 if ($el.select2('container').hasClass('select2-container-multi')) {
352 var selection = $el.select2('data');
353 selection.push(data);
354 $el.select2('data', selection, true);
355 } else {
356 $el.select2('data', data, true);
357 }
ba4fb2b2
CW
358 }
359 });
360 return false;
361 });
362 });
363 }
a88cf11a
CW
364 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams));
365 });
ba4fb2b2
CW
366 };
367
a4799f04 368 function formatSelect2Result(row) {
88881f79 369 var markup = '<div class="crm-select2-row">';
ff88d165 370 if (row.image !== undefined) {
88881f79 371 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
ff88d165 372 }
54bee7df 373 else if (row.icon_class) {
88881f79 374 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
54bee7df 375 }
88881f79
CW
376 markup += '<div><div class="crm-select2-row-label">' + row.label + '</div>';
377 markup += '<div class="crm-select2-row-description">';
378 $.each(row.description || [], function(k, text) {
379 markup += '<p>' + text + '</p>';
380 });
381 markup += '</div></div></div>';
ff88d165 382 return markup;
a4799f04
CW
383 }
384
385 function formatSelect2CreateLinks($el) {
386 var
387 createLinks = $el.data('create-links'),
388 api = $el.data('api-params') || {},
389 type = api.params ? api.params.contact_type : null;
390 if (createLinks === true) {
391 createLinks = type ? _.where(CRM.profile.contactCreate, {type: type}) : CRM.profile.contactCreate;
392 }
79ae07d9 393 var markup = '';
a4799f04 394 _.each(createLinks, function(link) {
79ae07d9 395 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
a4799f04
CW
396 if (link.type) {
397 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
79ae07d9
CW
398 }
399 markup += link.label + '</a>';
400 });
401 return markup;
a4799f04 402 }
ff88d165 403
f7b92fcd 404 // Initialize widgets
eb90857a
CW
405 $(document)
406 .on('crmLoad', function(e) {
407 $('table.row-highlight', e.target)
408 .off('.rowHighlight')
409 .on('change.rowHighlight', 'input.select-row, input.select-rows', function () {
410 var target, table = $(this).closest('table');
411 if ($(this).hasClass('select-rows')) {
412 target = $('tbody tr', table);
413 $('input.select-row', table).prop('checked', $(this).prop('checked'));
414 }
415 else {
416 target = $(this).closest('tr');
417 $('input.select-rows', table).prop('checked', $(".select-row:not(':checked')", table).length < 1);
418 }
419 target.toggleClass('crm-row-selected', $(this).is(':checked'));
420 })
421 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
422 $('.crm-select2:not(.select2-offscreen)', e.target).crmSelect2();
423 $('.crm-form-entityref:not(.select2-offscreen)', e.target).crmEntityRef();
424 })
425 // Modal dialogs should disable scrollbars
426 .on('dialogopen', function(e) {
427 if ($(e.target).dialog('option', 'modal')) {
428 $(e.target).addClass('modal-dialog');
429 $('body').css({overflow: 'hidden'});
430 }
431 })
432 .on('dialogclose', function(e) {
e0fb89c1 433 if ($('.ui-dialog .modal-dialog').not(e.target).length < 1) {
eb90857a
CW
434 $('body').css({overflow: ''});
435 }
436 });
148c4e8d
CW
437
438 /**
439 * Function to make multiselect boxes behave as fields in small screens
440 */
441 function advmultiselectResize() {
442 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
443 if (amswidth < 700) {
444 $("form table.advmultiselect td").css('display', 'block');
0f5816a6
KJ
445 }
446 else {
148c4e8d
CW
447 $("form table.advmultiselect td").css('display', 'table-cell');
448 }
449 var contactwidth = $('#crm-container #mainTabContainer').width();
450 if (contactwidth < 600) {
451 $('#crm-container #mainTabContainer').addClass('narrowpage');
0f5816a6 452 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
148c4e8d 453 if (index > 1) {
0f5816a6 454 if (index % 2 == 0) {
148c4e8d
CW
455 $(this).parent().after('<tr class="narrowadded"></tr>');
456 }
457 var item = $(this);
458 $(this).parent().next().append(item);
459 }
460 });
0f5816a6
KJ
461 }
462 else {
148c4e8d 463 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
0f5816a6 464 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
148c4e8d
CW
465 var nitem = $(this);
466 var parent = $(this).parent();
467 $(this).parent().prev().append(nitem);
0f5816a6 468 if (parent.children().size() == 0) {
148c4e8d
CW
469 parent.remove();
470 }
471 });
472 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
473 }
474 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
0f5816a6 475
148c4e8d
CW
476 if (cformwidth < 720) {
477 $('#crm-container .contact_basic_information-section').addClass('narrowform');
478 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
479 if (cformwidth < 480) {
480 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
0f5816a6
KJ
481 }
482 else {
148c4e8d
CW
483 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
484 }
0f5816a6
KJ
485 }
486 else {
148c4e8d
CW
487 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
488 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
489 }
490 }
0f5816a6 491
148c4e8d 492 advmultiselectResize();
0f5816a6 493 $(window).resize(function () {
6a488035
TO
494 advmultiselectResize();
495 });
496
0f5816a6 497 $.fn.crmtooltip = function () {
2c29c2ac
RN
498 $(document)
499 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
500 $(this).addClass('crm-processed');
e24b17b9
CW
501 $(this).addClass('crm-tooltip-active');
502 var topDistance = e.pageY - $(window).scrollTop();
503 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
504 $(this).addClass('crm-tooltip-down');
505 }
506 if (!$(this).children('.crm-tooltip-wrapper').length) {
6a488035
TO
507 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
508 $(this).children().children('.crm-tooltip')
509 .html('<div class="crm-loading-element"></div>')
510 .load(this.href);
511 }
512 })
2c29c2ac
RN
513 .on('mouseout', 'a.crm-summary-link', function () {
514 $(this).removeClass('crm-processed');
e24b17b9
CW
515 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
516 })
2c29c2ac 517 .on('click', 'a.crm-summary-link', false);
6a488035
TO
518 };
519
b0ca6188 520 var helpDisplay, helpPrevious;
8e3272a1 521 CRM.help = function (title, params, url) {
55a93b02 522 if (helpDisplay && helpDisplay.close) {
b0ca6188 523 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
55a93b02
CW
524 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
525 helpDisplay.close();
b0ca6188
CW
526 return;
527 }
55a93b02 528 helpDisplay.close();
b0ca6188
CW
529 }
530 helpPrevious = JSON.stringify(params);
6a488035
TO
531 params.class_name = 'CRM_Core_Page_Inline_Help';
532 params.type = 'page';
b0ca6188 533 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
8e3272a1 534 $.ajax(url || CRM.url('civicrm/ajax/inline'),
6a488035
TO
535 {
536 data: params,
537 dataType: 'html',
e24b17b9 538 success: function (data) {
6a488035
TO
539 $('#crm-notification-container .crm-help .notify-content:last').html(data);
540 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
541 },
e24b17b9 542 error: function () {
6a488035
TO
543 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
544 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
545 }
546 }
547 );
548 };
8960d9b9 549 /**
1b2475e1 550 * @param options object|string
8960d9b9
CW
551 * @param deferred optional jQuery deferred object
552 * @return jQuery deferred object - if not supplied a new one will be created
553 */
1b2475e1 554 CRM.status = function(options, deferred) {
9a7ef94f 555 // 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
556 if (typeof options === 'string') {
557 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
8960d9b9 558 }
1b2475e1
CW
559 var opts = $.extend({
560 start: ts('Saving...'),
9a7ef94f 561 success: ts('Saved'),
1b2475e1
CW
562 error: function() {
563 CRM.alert(ts('Sorry an error occurred and your information was not saved'), ts('Error'));
564 }
565 }, options || {});
566 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>')
567 .appendTo('body');
568 $msg.css('min-width', $msg.width());
569 function handle(status, data) {
570 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
571 if (endMsg) {
572 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg);
573 window.setTimeout(function() {
574 $msg.fadeOut('slow', function() {$msg.remove()});
4bad157e
CW
575 }, 2000);
576 } else {
1b2475e1 577 $msg.remove();
4bad157e 578 }
1b2475e1
CW
579 }
580 return (deferred || new $.Deferred())
581 .done(function(data) {
582 // If the server returns an error msg call the error handler
583 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
584 handle(status, data);
585 })
586 .fail(function(data) {
587 handle('error', data);
588 });
8960d9b9 589 };
6a488035
TO
590
591 /**
592 * @param string text Displayable message
593 * @param string title Displayable title
594 * @param string type 'alert'|'info'|'success'|'error' (default: 'alert')
595 * @param {object} options
596 * @return {*}
597 * @see http://wiki.civicrm.org/confluence/display/CRM/Notifications+in+CiviCRM
598 */
0f5816a6 599 CRM.alert = function (text, title, type, options) {
6a488035
TO
600 type = type || 'alert';
601 title = title || '';
602 options = options || {};
603 if ($('#crm-notification-container').length) {
604 var params = {
605 text: text,
606 title: title,
607 type: type
608 };
609 // By default, don't expire errors and messages containing links
610 var extra = {
611 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
612 unique: true
613 };
614 options = $.extend(extra, options);
e24b17b9 615 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
6a488035 616 if (options.unique && options.unique !== '0') {
0f5816a6 617 $('#crm-notification-container .ui-notify-message').each(function () {
6a488035
TO
618 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
619 $('.icon.ui-notify-close', this).click();
620 }
621 });
622 }
623 return $('#crm-notification-container').notify('create', params, options);
624 }
625 else {
626 if (title.length) {
627 text = title + "\n" + text;
628 }
629 alert(text);
630 return null;
631 }
e24b17b9 632 };
6a488035
TO
633
634 /**
635 * Close whichever alert contains the given node
636 *
637 * @param node
638 */
0f5816a6 639 CRM.closeAlertByChild = function (node) {
6a488035 640 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
e24b17b9 641 };
6a488035
TO
642
643 /**
644 * Prompt the user for confirmation.
645 *
7553cf23
CW
646 * @param buttons {object|function} key|value pairs where key == button label and value == callback function
647 * passing in a function instead of an object is a shortcut for a sinlgle button labeled "Continue"
648 * @param options {object|void} Override defaults, keys include 'title', 'message',
649 * see jQuery.dialog for full list of available params
ebb5fc58 650 * @param cancelLabel {string}
6a488035 651 */
706cff6d 652 CRM.confirm = function (buttons, options, cancelLabel) {
7553cf23 653 var dialog, callbacks = {};
706cff6d 654 cancelLabel = cancelLabel || ts('Cancel');
7553cf23
CW
655 var settings = {
656 title: ts('Confirm Action'),
657 message: ts('Are you sure you want to continue?'),
6a488035
TO
658 resizable: false,
659 modal: true,
0d5f99d4 660 width: 'auto',
0f5816a6
KJ
661 close: function () {
662 $(dialog).remove();
663 },
7553cf23
CW
664 buttons: {}
665 };
706cff6d
KJ
666
667 settings.buttons[cancelLabel] = function () {
0f5816a6
KJ
668 dialog.dialog('close');
669 };
7553cf23
CW
670 options = options || {};
671 $.extend(settings, options);
672 if (typeof(buttons) === 'function') {
673 callbacks[ts('Continue')] = buttons;
0f5816a6
KJ
674 }
675 else {
7553cf23
CW
676 callbacks = buttons;
677 }
0f5816a6
KJ
678 $.each(callbacks, function (label, callback) {
679 settings.buttons[label] = function () {
ebb5fc58
CW
680 if (callback.call(dialog) !== false) {
681 dialog.dialog('close');
682 }
e24b17b9 683 };
6a488035 684 });
7553cf23
CW
685 dialog = $('<div class="crm-container crm-confirm-dialog"></div>')
686 .html(options.message)
687 .appendTo('body')
688 .dialog(settings);
689 return dialog;
e24b17b9 690 };
6a488035
TO
691
692 /**
693 * Sets an error message
694 * If called for a form item, title and removal condition will be handled automatically
695 */
0f5816a6 696 $.fn.crmError = function (text, title, options) {
6a488035
TO
697 title = title || '';
698 text = text || '';
699 options = options || {};
700
701 var extra = {
702 expires: 0
703 };
704 if ($(this).length) {
705 if (title == '') {
706 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
707 if (label.length) {
708 label.addClass('crm-error');
709 var $label = label.clone();
710 if (text == '' && $('.crm-marker', $label).length > 0) {
711 text = $('.crm-marker', $label).attr('title');
712 }
713 $('.crm-marker', $label).remove();
714 title = $label.text();
715 }
716 }
717 $(this).addClass('error');
718 }
719 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
720 if ($(this).length) {
721 var ele = $(this);
0f5816a6
KJ
722 setTimeout(function () {
723 ele.one('change', function () {
724 msg && msg.close && msg.close();
725 ele.removeClass('error');
726 label.removeClass('crm-error');
727 });
728 }, 1000);
6a488035
TO
729 }
730 return msg;
e24b17b9 731 };
6a488035
TO
732
733 // Display system alerts through js notifications
734 function messagesFromMarkup() {
0f5816a6 735 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
e24b17b9 736 var text, title = '';
6a488035
TO
737 $(this).removeClass('status messages');
738 var type = $(this).attr('class').split(' ')[0] || 'alert';
739 type = type.replace('crm-', '');
740 $('.icon', this).remove();
6a488035 741 if ($('.msg-text', this).length > 0) {
e24b17b9 742 text = $('.msg-text', this).html();
6a488035
TO
743 title = $('.msg-title', this).html();
744 }
745 else {
e24b17b9 746 text = $(this).html();
6a488035
TO
747 }
748 var options = $(this).data('options') || {};
749 $(this).remove();
750 // Duplicates were already removed server-side
751 options.unique = false;
752 CRM.alert(text, title, type, options);
753 });
754 // Handle qf form errors
755 $('form :input.error', this).one('blur', function() {
ef04c554 756 // ignore autocomplete fields
23246a80 757 if ($(this).is('.ac_input')) {
758 return;
759 }
ef04c554 760
6a488035
TO
761 $('.ui-notify-message.error a.ui-notify-close').click();
762 $(this).removeClass('error');
763 $(this).next('span.crm-error').remove();
764 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
765 .removeClass('crm-error')
766 .find('.crm-error').removeClass('crm-error');
767 });
768 }
769
23223213 770 $.widget('civi.crmSnippet', {
205bb8ae 771 options: {
a73f25bb 772 url: null,
205bb8ae
CW
773 block: true,
774 crmForm: null
775 },
c02f8fc4 776 _originalContent: null,
fa3a5fe2
CW
777 _originalUrl: null,
778 isOriginalUrl: function() {
0906345e
CW
779 var
780 args = {},
781 same = true,
782 newUrl = this._formatUrl(this.options.url),
783 oldUrl = this._formatUrl(this._originalUrl);
fa3a5fe2 784 // Compare path
0906345e 785 if (newUrl.split('?')[0] !== oldUrl.split('?')[0]) {
fa3a5fe2
CW
786 return false;
787 }
788 // Compare arguments
0906345e 789 $.each(newUrl.split('?')[1].split('&'), function(k, v) {
fa3a5fe2
CW
790 var arg = v.split('=');
791 args[arg[0]] = arg[1];
792 });
0906345e 793 $.each(oldUrl.split('?')[1].split('&'), function(k, v) {
fa3a5fe2
CW
794 var arg = v.split('=');
795 if (args[arg[0]] !== undefined && arg[1] !== args[arg[0]]) {
796 same = false;
797 }
798 });
799 return same;
800 },
801 resetUrl: function() {
802 this.options.url = this._originalUrl;
803 },
205bb8ae 804 _create: function() {
205bb8ae
CW
805 this.element.addClass('crm-ajax-container');
806 if (!this.element.is('.crm-container *')) {
807 this.element.addClass('crm-container');
808 }
4a140040 809 this._handleOrderLinks();
5d92a7e7
CW
810 // Set default if not supplied
811 this.options.url = this.options.url || document.location.href;
fa3a5fe2 812 this._originalUrl = this.options.url;
205bb8ae
CW
813 },
814 _onFailure: function(data) {
815 this.options.block && this.element.unblock();
816 this.element.trigger('crmAjaxFail', data);
817 CRM.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
818 },
819 _formatUrl: function(url) {
0906345e
CW
820 // Strip hash
821 url = url.split('#')[0];
205bb8ae
CW
822 // Add snippet argument to url
823 if (url.search(/[&?]snippet=/) < 0) {
fc05b8da 824 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
8547369d
CW
825 } else {
826 url = url.replace(/snippet=[^&]*/, 'snippet=json');
205bb8ae
CW
827 }
828 return url;
829 },
d6539f93 830 // Hack to deal with civicrm legacy sort functionality
4a140040
CW
831 _handleOrderLinks: function() {
832 var that = this;
833 $('a.crm-weight-arrow', that.element).click(function(e) {
834 that.options.block && that.element.block();
835 $.getJSON(that._formatUrl(this.href)).done(function() {
836 that.refresh();
837 });
838 e.stopImmediatePropagation();
839 return false;
840 });
841 },
205bb8ae
CW
842 refresh: function() {
843 var that = this;
844 var url = this._formatUrl(this.options.url);
4a140040 845 this.options.block && $('.blockOverlay', this.element).length < 1 && this.element.block();
205bb8ae
CW
846 $.getJSON(url, function(data) {
847 if (typeof(data) != 'object' || typeof(data.content) != 'string') {
848 that._onFailure(data);
849 return;
850 }
851 data.url = url;
c02f8fc4
CW
852 that.element.trigger('crmBeforeLoad', data);
853 if (that._originalContent === null) {
854 that._originalContent = that.element.contents().detach();
855 }
856 that.element.html(data.content);
4a140040
CW
857 that._handleOrderLinks();
858 that.element.trigger('crmLoad', data);
205bb8ae
CW
859 that.options.crmForm && that.element.trigger('crmFormLoad', data);
860 }).fail(function() {
861 that._onFailure();
862 });
4b628e67
CW
863 },
864 _destroy: function() {
865 this.element.removeClass('crm-ajax-container');
c02f8fc4
CW
866 if (this._originalContent !== null) {
867 this.element.empty().append(this._originalContent);
868 }
205bb8ae
CW
869 }
870 });
871
0e017a41 872 var dialogCount = 0;
d4e4e9df 873 CRM.loadPage = function(url, options) {
d4e4e9df 874 var settings = {
0e017a41 875 target: '#crm-ajax-dialog-' + (dialogCount++),
8547369d
CW
876 dialog: false
877 };
878 if (!options || !options.target) {
879 settings.dialog = {
d4e4e9df 880 modal: true,
f84151fd 881 width: '65%',
eb90857a 882 height: parseInt($(window).height() * .75)
8547369d
CW
883 };
884 }
205bb8ae 885 options && $.extend(true, settings, options);
0e017a41 886 settings.url = url;
83df6b4a 887 // Create new dialog
8547369d 888 if (settings.dialog) {
205bb8ae 889 $('<div id="'+ settings.target.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings.dialog);
eb90857a
CW
890 $(settings.target).on('dialogclose', function() {
891 $(this).dialog('destroy').remove();
892 });
d4e4e9df 893 }
205bb8ae 894 if (settings.dialog && !settings.dialog.title) {
cbc9c3b2
CW
895 $(settings.target).on('crmLoad', function(e, data) {
896 if (e.target === $(settings.target)[0] && data && data.title) {
897 $(this).dialog('option', 'title', data.title);
898 }
205bb8ae
CW
899 });
900 }
5d92a7e7
CW
901 $(settings.target).crmSnippet(settings).crmSnippet('refresh');
902 return $(settings.target);
d4e4e9df
CW
903 };
904
905 CRM.loadForm = function(url, options) {
d4e4e9df 906 var settings = {
205bb8ae
CW
907 crmForm: {
908 ajaxForm: {},
205bb8ae
CW
909 autoClose: true,
910 validate: true,
911 refreshAction: ['next_new', 'submit_savenext'],
912 cancelButton: '.cancel.form-submit',
23223213 913 openInline: 'a.button:not("[href=#], .no-popup")',
205bb8ae
CW
914 onCancel: function(event) {},
915 onError: function(data) {
916 var $el = $(this);
5d92a7e7 917 $el.html(data.content).trigger('crmLoad', data).trigger('crmFormLoad', data).trigger('crmFormError', data);
205bb8ae
CW
918 if (typeof(data.errors) == 'object') {
919 $.each(data.errors, function(formElement, msg) {
920 $('[name="'+formElement+'"]', $el).crmError(msg);
921 });
922 }
d4e4e9df 923 }
d4e4e9df
CW
924 }
925 };
a10432db
CW
926 // Hack to make delete dialogs smaller
927 if (url.indexOf('/delete') > 0 || url.indexOf('action=delete') > 0) {
928 settings.dialog = {
929 width: 400,
930 height: 300
931 };
932 }
205bb8ae
CW
933 // Move options that belong to crmForm. Others will be passed through to crmSnippet
934 options && $.each(options, function(key, value) {
935 if (typeof(settings.crmForm[key]) !== 'undefined') {
936 settings.crmForm[key] = value;
937 }
938 else {
939 settings[key] = value;
940 }
941 });
205bb8ae
CW
942
943 var widget = CRM.loadPage(url, settings);
944
945 widget.on('crmFormLoad', function(event, data) {
946 var $el = $(this);
660c46f3 947 var settings = $el.crmSnippet('option', 'crmForm');
205bb8ae
CW
948 settings.cancelButton && $(settings.cancelButton, this).click(function(event) {
949 var returnVal = settings.onCancel.call($el, event);
950 if (returnVal !== false) {
951 $el.trigger('crmFormCancel', event);
660c46f3 952 if ($el.data('uiDialog') && settings.autoClose) {
fa3a5fe2
CW
953 $el.dialog('close');
954 }
955 else if (!settings.autoClose) {
956 $el.crmSnippet('resetUrl').crmSnippet('refresh');
957 }
0e017a41 958 }
205bb8ae
CW
959 return returnVal === false;
960 });
d4e4e9df 961 if (settings.validate) {
0e017a41 962 $("form", this).validate(typeof(settings.validate) == 'object' ? settings.validate : CRM.validate.params);
d4e4e9df 963 }
205bb8ae 964 $("form", this).ajaxForm($.extend({
fa3a5fe2 965 url: data.url.replace(/reset=1[&]?/, ''),
d4e4e9df
CW
966 dataType: 'json',
967 success: function(response) {
34866662 968 if (response.status !== 'form_error') {
36876f55 969 $el.crmSnippet('option', 'block') && $el.unblock();
205bb8ae 970 $el.trigger('crmFormSuccess', response);
0e017a41 971 // Reset form for e.g. "save and new"
d6539f93 972 if (response.userContext && settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0) {
205bb8ae 973 $el.crmSnippet('option', 'url', response.userContext).crmSnippet('refresh');
0e017a41 974 }
660c46f3 975 else if ($el.data('uiDialog') && settings.autoClose) {
205bb8ae 976 $el.dialog('close');
83df6b4a 977 }
d6539f93
CW
978 else if (settings.autoClose === false) {
979 $el.crmSnippet('resetUrl').crmSnippet('refresh');
980 }
d4e4e9df
CW
981 }
982 else {
25bbc4c0 983 response.url = data.url;
205bb8ae 984 settings.onError.call($el, response);
d4e4e9df 985 }
23223213
CW
986 },
987 beforeSerialize: function(form, options) {
988 if (window.CKEDITOR && window.CKEDITOR.instances) {
a10432db
CW
989 $.each(CKEDITOR.instances, function() {
990 this.updateElement && this.updateElement();
991 });
23223213 992 }
83df6b4a 993 },
205bb8ae 994 beforeSubmit: function(submission) {
36876f55 995 $el.crmSnippet('option', 'block') && $el.block();
205bb8ae 996 $el.trigger('crmFormSubmit', submission);
d4e4e9df 997 }
205bb8ae 998 }, settings.ajaxForm));
fa3a5fe2
CW
999 if (settings.openInline) {
1000 settings.autoClose = $el.crmSnippet('isOriginalUrl');
1001 $(settings.openInline, this).click(function(event) {
1002 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
1003 return false;
1004 });
1005 }
81c81624
CW
1006 // For convenience, focus the first field
1007 $('input[type=text], textarea, select', this).filter(':visible').first().focus();
205bb8ae
CW
1008 });
1009 return widget;
d4e4e9df
CW
1010 };
1011
03a7ec8f
CW
1012 // Preprocess all cj ajax calls to display messages
1013 $(document).ajaxSuccess(function(event, xhr, settings) {
1014 try {
1015 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
1016 var response = $.parseJSON(xhr.responseText);
1017 if (typeof(response.crmMessages) == 'object') {
1018 $.each(response.crmMessages, function(n, msg) {
1019 CRM.alert(msg.text, msg.title, msg.type, msg.options);
1020 })
1021 }
1022 }
1023 }
1024 // Suppress errors
1025 catch (e) {}
1026 });
1027
7cb72342
CW
1028 /**
1029 * Temporary stub to get around name conflict with legacy jQuery.autocomplete plugin
1030 */
1031 $.widget('civi.crmAutocomplete', $.ui.autocomplete, {});
1032
0f5816a6 1033 $(function () {
205bb8ae 1034 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
8547369d 1035 $('.crm-container').trigger('crmLoad');
205bb8ae 1036
ef3309b6 1037 if ($('#crm-notification-container').length) {
6a488035
TO
1038 // Initialize notifications
1039 $('#crm-notification-container').notify();
1040 messagesFromMarkup.call($('#crm-container'));
6a488035 1041 }
ebb9197b
C
1042
1043 // bind the event for image popup
475e9f44
CW
1044 $('body')
1045 .on('click', 'a.crm-image-popup', function() {
1046 var o = $('<div class="crm-container crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
1047
1048 CRM.confirm('',
1049 {
1050 title: ts('Preview'),
1051 message: o
1052 },
1053 ts('Done')
1054 );
1055 return false;
1056 })
ebb9197b 1057
475e9f44
CW
1058 .on('click', function (event) {
1059 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1060 if ($(event.target).is('.btn-slide')) {
1061 $(event.target).addClass('btn-slide-active').find('.panel').show();
1062 }
1063 })
d664f648 1064
87831073 1065 .on('click', 'a.crm-option-edit-link', function() {
78b203e5
CW
1066 var
1067 link = $(this),
1068 optionsChanged = false;
87831073 1069 CRM.loadForm(this.href, {openInline: 'a:not("[href=#], .no-popup")'})
78b203e5
CW
1070 .on('crmFormSuccess', function() {
1071 optionsChanged = true;
1072 })
475e9f44 1073 .on('dialogclose', function() {
78b203e5
CW
1074 if (optionsChanged) {
1075 link.trigger('crmOptionsEdited');
1076 var $elects = $('select[data-option-edit-path="' + link.data('option-edit-path') + '"]');
1077 if ($elects.data('api-entity') && $elects.data('api-field')) {
1078 CRM.api3($elects.data('api-entity'), 'getoptions', {sequential: 1, field: $elects.data('api-field')})
1079 .done(function (data) {
1080 CRM.utils.setOptions($elects, data.values);
1081 });
1082 }
87831073 1083 }
475e9f44
CW
1084 });
1085 return false;
4a143c04
CW
1086 })
1087 // Handle clear button for form elements
1088 .on('click', 'a.crm-clear-link', function() {
1089 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
bcb4280c 1090 $(this).siblings('input:text').val('').change();
4a143c04
CW
1091 return false;
1092 })
1093 .on('change', 'input.crm-form-radio:checked', function() {
1094 $(this).siblings('.crm-clear-link').css({visibility: ''});
475e9f44 1095 });
d664f648 1096 $().crmtooltip();
6a488035
TO
1097 });
1098
0f5816a6 1099 $.fn.crmAccordions = function (speed) {
cf021bc5
CW
1100 var container = $(this).length > 0 ? $(this) : $('.crm-container');
1101 speed = speed === undefined ? 200 : speed;
1102 container
1103 .off('click.crmAccordions')
6a488035 1104 // Allow normal clicking of links
cf021bc5 1105 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
6a488035 1106 e.stopPropagation && e.stopPropagation();
cf021bc5
CW
1107 })
1108 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
6a488035
TO
1109 if ($(this).parent().hasClass('collapsed')) {
1110 $(this).next().css('display', 'none').slideDown(speed);
1111 }
1112 else {
1113 $(this).next().css('display', 'block').slideUp(speed);
1114 }
1115 $(this).parent().toggleClass('collapsed');
1116 return false;
1117 });
6a488035 1118 };
0f5816a6
KJ
1119 $.fn.crmAccordionToggle = function (speed) {
1120 $(this).each(function () {
6a488035
TO
1121 if ($(this).hasClass('collapsed')) {
1122 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
1123 }
1124 else {
1125 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1126 }
1127 $(this).toggleClass('collapsed');
1128 });
1129 };
5ec182d9
CW
1130
1131 /**
1132 * Clientside currency formatting
1133 * @param value
3bdb644f 1134 * @param format - currency representation of the number 1234.56
5ec182d9 1135 * @return string
3bdb644f 1136 * @see CRM_Core_Resources::addCoreResources
5ec182d9
CW
1137 */
1138 var currencyTemplate;
1139 CRM.formatMoney = function(value, format) {
1140 var decimal, separator, sign, i, j, result;
1141 if (value === 'init' && format) {
1142 currencyTemplate = format;
1143 return;
1144 }
1145 format = format || currencyTemplate;
1146 result = /1(.?)234(.?)56/.exec(format);
1147 if (result === null) {
1148 return 'Invalid format passed to CRM.formatMoney';
1149 }
1150 separator = result[1];
1151 decimal = result[2];
1152 sign = (value < 0) ? '-' : '';
1153 //extracting the absolute value of the integer part of the number and converting to string
1154 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
5ec182d9
CW
1155 j = ((j = i.length) > 3) ? j % 3 : 0;
1156 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) : '');
1157 return format.replace(/1.*234.*56/, result);
1158 };
6a488035 1159})(jQuery);