Case ui enhancements & code cleanup
[civicrm-core.git] / js / Common.js
1 // https://civicrm.org/licensing
2 var CRM = CRM || {};
3 var cj = jQuery;
4
5 /**
6 * Short-named function for string translation, defined in global scope so it's available everywhere.
7 *
8 * @param text string for translating
9 * @param params object key:value of additional parameters
10 *
11 * @return string
12 */
13 function ts(text, params) {
14 "use strict";
15 text = CRM.strings[text] || text;
16 if (typeof(params) === 'object') {
17 for (var i in params) {
18 if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') {
19 // sprintf emulation: escape % characters in the replacements to avoid conflicts
20 text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-'));
21 }
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 *
34 * @deprecated
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 ...)
38 */
39 function 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;
50 }
51 else {
52 alert('showBlocks array item not in .tpl = ' + showBlocks[i]);
53 }
54 }
55
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]);
65 }
66 }
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 *
73 * @deprecated
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
80 */
81 function 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("|");
93 var selectedOptionValue = cj('#' + trigger_field_id).val();
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 }
111 }
112 }
113 }
114
115 }
116 else {
117 if (field_type == 'radio') {
118 var target = target_element_id.split("|");
119 for (var j = 0; j < target.length; j++) {
120 if (cj('[name="' + trigger_field_id + '"]').is(':checked')) {
121 if (invert) {
122 cj('#' + target[j]).hide();
123 }
124 else {
125 cj('#' + target[j]).show();
126 }
127 }
128 else {
129 if (invert) {
130 cj('#' + target[j]).show();
131 }
132 else {
133 cj('#' + target[j]).hide();
134 }
135 }
136 }
137 }
138 }
139 }
140
141 /**
142 * Function to change button text and disable one it is clicked
143 * @deprecated
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
147 * @return bool
148 */
149 var submitcount = 0;
150 /* Changes button label on submit, and disables button after submit for newer browsers.
151 Puts up alert for older browsers. */
152 function 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;
170 }
171 }
172 }
173 /**
174 * @deprecated
175 */
176 function popUp(URL) {
177 day = new Date();
178 id = day.getTime();
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
182 /**
183 * Function to show / hide the row in optionFields
184 * @deprecated
185 * @param index string, element whose innerHTML is to hide else will show the hidden row.
186 */
187 function 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();
192 }
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;
201 }
202
203 CRM.utils = CRM.utils || {};
204 CRM.strings = CRM.strings || {};
205 CRM.validate = CRM.validate || {
206 params: {},
207 functions: []
208 };
209
210 (function ($, undefined) {
211 "use strict";
212
213 $.fn.select2.defaults.dropdownCssClass = 'crm-container';
214 // https://github.com/ivaynberg/select2/pull/2090
215 $.fn.select2.defaults.width = 'resolve';
216
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
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
226 * @param removePlaceholder bool
227 */
228 CRM.utils.setOptions = function($el, options, removePlaceholder) {
229 $el.each(function() {
230 var
231 $elect = $(this),
232 val = $elect.val() || [],
233 opts = removePlaceholder ? '' : '[value!=""]';
234 if (typeof(val) !== 'array') {
235 val = [val];
236 }
237 $elect.find('option' + opts).remove();
238 _.each(options, function(option) {
239 var selected = ($.inArray(''+option.key, val) > -1) ? 'selected="selected"' : '';
240 $elect.append('<option value="' + option.key + '"' + selected + '>' + option.value + '</option>');
241 });
242 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
243 });
244 };
245
246 /**
247 * Wrapper for select2 initialization function; supplies defaults
248 * @param options object
249 */
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 }
266 }
267 $el.select2($.extend(defaults, $el.data('select-params') || {}, options || {}));
268 });
269 };
270
271 /**
272 * @see CRM_Core_Form::addEntityRef for docs
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));
286 $el.data('create-links', options.create || $el.data('create-links'));
287 $el.addClass('crm-ajax-select crm-' + entity + '-ref');
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 },
306 minimumInputLength: 1,
307 formatResult: formatSelect2Result,
308 formatSelection: function(row) {
309 return row.label;
310 },
311 escapeMarkup: function (m) {return m;},
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 {
324 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
325 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
326 callback(multiple ? result.values : result.values[0])
327 });
328 }
329 }
330 };
331 if ($el.data('create-links')) {
332 selectParams.formatInputTooShort = function() {
333 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
334 if ($el.data('create-links')) {
335 txt += ' ' + ts('or') + '<br />' + formatSelect2CreateLinks($el);
336 }
337 return txt;
338 };
339 selectParams.formatNoMatches = function() {
340 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
341 return txt + '<br />' + formatSelect2CreateLinks($el);
342 };
343 $el.off('.createLinks').on('select2-open.createLinks', function() {
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) {
350 if (data.status === 'success' && data.id) {
351 CRM.status(ts('%1 Created', {1: data.label}));
352 if ($el.select2('container').hasClass('select2-container-multi')) {
353 var selection = $el.select2('data');
354 selection.push(data);
355 $el.select2('data', selection, true);
356 } else {
357 $el.select2('data', data, true);
358 }
359 }
360 });
361 return false;
362 });
363 });
364 }
365 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams));
366 });
367 };
368
369 function formatSelect2Result(row) {
370 var markup = '<div class="crm-select2-row">';
371 if (row.image !== undefined) {
372 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
373 }
374 else if (row.icon_class) {
375 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
376 }
377 markup += '<div><div class="crm-select2-row-label">' + row.label + '</div>';
378 markup += '<div class="crm-select2-row-description">';
379 $.each(row.description || [], function(k, text) {
380 markup += '<p>' + text + '</p>';
381 });
382 markup += '</div></div></div>';
383 return markup;
384 }
385
386 function formatSelect2CreateLinks($el) {
387 var
388 createLinks = $el.data('create-links'),
389 api = $el.data('api-params') || {},
390 type = api.params ? api.params.contact_type : null;
391 if (createLinks === true) {
392 createLinks = type ? _.where(CRM.profile.contactCreate, {type: type}) : CRM.profile.contactCreate;
393 }
394 var markup = '';
395 _.each(createLinks, function(link) {
396 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
397 if (link.type) {
398 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
399 }
400 markup += link.label + '</a>';
401 });
402 return markup;
403 }
404
405 // Initialize widgets
406 $(document)
407 .on('crmLoad', function(e) {
408 $('table.row-highlight', e.target)
409 .off('.rowHighlight')
410 .on('change.rowHighlight', 'input.select-row, input.select-rows', function () {
411 var target, table = $(this).closest('table');
412 if ($(this).hasClass('select-rows')) {
413 target = $('tbody tr', table);
414 $('input.select-row', table).prop('checked', $(this).prop('checked'));
415 }
416 else {
417 target = $(this).closest('tr');
418 $('input.select-rows', table).prop('checked', $(".select-row:not(':checked')", table).length < 1);
419 }
420 target.toggleClass('crm-row-selected', $(this).is(':checked'));
421 })
422 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
423 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
424 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
425 })
426 // Modal dialogs should disable scrollbars
427 .on('dialogopen', function(e) {
428 $(e.target).parent().addClass('crm-container');
429 if ($(e.target).dialog('option', 'modal')) {
430 $(e.target).addClass('modal-dialog');
431 $('body').css({overflow: 'hidden'});
432 }
433 })
434 .on('dialogclose', function(e) {
435 if ($('.ui-dialog .modal-dialog').not(e.target).length < 1) {
436 $('body').css({overflow: ''});
437 }
438 });
439
440 /**
441 * Function to make multiselect boxes behave as fields in small screens
442 */
443 function advmultiselectResize() {
444 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
445 if (amswidth < 700) {
446 $("form table.advmultiselect td").css('display', 'block');
447 }
448 else {
449 $("form table.advmultiselect td").css('display', 'table-cell');
450 }
451 var contactwidth = $('#crm-container #mainTabContainer').width();
452 if (contactwidth < 600) {
453 $('#crm-container #mainTabContainer').addClass('narrowpage');
454 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
455 if (index > 1) {
456 if (index % 2 == 0) {
457 $(this).parent().after('<tr class="narrowadded"></tr>');
458 }
459 var item = $(this);
460 $(this).parent().next().append(item);
461 }
462 });
463 }
464 else {
465 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
466 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
467 var nitem = $(this);
468 var parent = $(this).parent();
469 $(this).parent().prev().append(nitem);
470 if (parent.children().size() == 0) {
471 parent.remove();
472 }
473 });
474 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
475 }
476 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
477
478 if (cformwidth < 720) {
479 $('#crm-container .contact_basic_information-section').addClass('narrowform');
480 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
481 if (cformwidth < 480) {
482 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
483 }
484 else {
485 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
486 }
487 }
488 else {
489 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
490 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
491 }
492 }
493
494 advmultiselectResize();
495 $(window).resize(function () {
496 advmultiselectResize();
497 });
498
499 $.fn.crmtooltip = function () {
500 $(document)
501 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
502 $(this).addClass('crm-processed');
503 $(this).addClass('crm-tooltip-active');
504 var topDistance = e.pageY - $(window).scrollTop();
505 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
506 $(this).addClass('crm-tooltip-down');
507 }
508 if (!$(this).children('.crm-tooltip-wrapper').length) {
509 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
510 $(this).children().children('.crm-tooltip')
511 .html('<div class="crm-loading-element"></div>')
512 .load(this.href);
513 }
514 })
515 .on('mouseout', 'a.crm-summary-link', function () {
516 $(this).removeClass('crm-processed');
517 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
518 })
519 .on('click', 'a.crm-summary-link', false);
520 };
521
522 var helpDisplay, helpPrevious;
523 CRM.help = function (title, params, url) {
524 if (helpDisplay && helpDisplay.close) {
525 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
526 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
527 helpDisplay.close();
528 return;
529 }
530 helpDisplay.close();
531 }
532 helpPrevious = JSON.stringify(params);
533 params.class_name = 'CRM_Core_Page_Inline_Help';
534 params.type = 'page';
535 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
536 $.ajax(url || CRM.url('civicrm/ajax/inline'),
537 {
538 data: params,
539 dataType: 'html',
540 success: function (data) {
541 $('#crm-notification-container .crm-help .notify-content:last').html(data);
542 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
543 },
544 error: function () {
545 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
546 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
547 }
548 }
549 );
550 };
551 /**
552 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
553 */
554 CRM.status = function(options, deferred) {
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.
556 if (typeof options === 'string') {
557 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
558 }
559 var opts = $.extend({
560 start: ts('Saving...'),
561 success: ts('Saved'),
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()});
575 }, 2000);
576 } else {
577 $msg.remove();
578 }
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 });
589 };
590
591 /**
592 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
593 */
594 CRM.alert = function (text, title, type, options) {
595 type = type || 'alert';
596 title = title || '';
597 options = options || {};
598 if ($('#crm-notification-container').length) {
599 var params = {
600 text: text,
601 title: title,
602 type: type
603 };
604 // By default, don't expire errors and messages containing links
605 var extra = {
606 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
607 unique: true
608 };
609 options = $.extend(extra, options);
610 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
611 if (options.unique && options.unique !== '0') {
612 $('#crm-notification-container .ui-notify-message').each(function () {
613 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
614 $('.icon.ui-notify-close', this).click();
615 }
616 });
617 }
618 return $('#crm-notification-container').notify('create', params, options);
619 }
620 else {
621 if (title.length) {
622 text = title + "\n" + text;
623 }
624 alert(text);
625 return null;
626 }
627 };
628
629 /**
630 * Close whichever alert contains the given node
631 *
632 * @param node
633 */
634 CRM.closeAlertByChild = function (node) {
635 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
636 };
637
638 /**
639 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
640 */
641 CRM.confirm = function (buttons, options, cancelLabel) {
642 var dialog, callbacks = {};
643 cancelLabel = cancelLabel || ts('Cancel');
644 var settings = {
645 title: ts('Confirm Action'),
646 message: ts('Are you sure you want to continue?'),
647 resizable: false,
648 modal: true,
649 width: 'auto',
650 close: function () {
651 $(dialog).dialog('destroy').remove();
652 },
653 buttons: {}
654 };
655
656 settings.buttons[cancelLabel] = function () {
657 dialog.trigger('crmConfirmNo').dialog('close');
658 };
659 options = options || {};
660 $.extend(settings, options);
661 if ($.isFunction(buttons)) {
662 callbacks[ts('Continue')] = buttons;
663 }
664 else if (_.isString(buttons) || !buttons) {
665 callbacks[buttons || ts('Continue')] = function() {};
666 }
667 else {
668 callbacks = buttons;
669 }
670 $.each(callbacks, function (label, callback) {
671 settings.buttons[label] = function () {
672 dialog.trigger('crmConfirmYes');
673 if (callback.call(dialog) !== false) {
674 dialog.dialog('close');
675 }
676 };
677 });
678 dialog = $('<div class="crm-confirm-dialog"></div>')
679 .html(options.message)
680 .dialog(settings)
681 .trigger('crmLoad');
682 return dialog;
683 };
684
685 /**
686 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
687 */
688 $.fn.crmError = function (text, title, options) {
689 title = title || '';
690 text = text || '';
691 options = options || {};
692
693 var extra = {
694 expires: 0
695 };
696 if ($(this).length) {
697 if (title == '') {
698 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
699 if (label.length) {
700 label.addClass('crm-error');
701 var $label = label.clone();
702 if (text == '' && $('.crm-marker', $label).length > 0) {
703 text = $('.crm-marker', $label).attr('title');
704 }
705 $('.crm-marker', $label).remove();
706 title = $label.text();
707 }
708 }
709 $(this).addClass('error');
710 }
711 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
712 if ($(this).length) {
713 var ele = $(this);
714 setTimeout(function () {
715 ele.one('change', function () {
716 msg && msg.close && msg.close();
717 ele.removeClass('error');
718 label.removeClass('crm-error');
719 });
720 }, 1000);
721 }
722 return msg;
723 };
724
725 // Display system alerts through js notifications
726 function messagesFromMarkup() {
727 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
728 var text, title = '';
729 $(this).removeClass('status messages');
730 var type = $(this).attr('class').split(' ')[0] || 'alert';
731 type = type.replace('crm-', '');
732 $('.icon', this).remove();
733 if ($('.msg-text', this).length > 0) {
734 text = $('.msg-text', this).html();
735 title = $('.msg-title', this).html();
736 }
737 else {
738 text = $(this).html();
739 }
740 var options = $(this).data('options') || {};
741 $(this).remove();
742 // Duplicates were already removed server-side
743 options.unique = false;
744 CRM.alert(text, title, type, options);
745 });
746 // Handle qf form errors
747 $('form :input.error', this).one('blur', function() {
748 // ignore autocomplete fields
749 if ($(this).is('.ac_input')) {
750 return;
751 }
752
753 $('.ui-notify-message.error a.ui-notify-close').click();
754 $(this).removeClass('error');
755 $(this).next('span.crm-error').remove();
756 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
757 .removeClass('crm-error')
758 .find('.crm-error').removeClass('crm-error');
759 });
760 }
761
762 // Preprocess all cj ajax calls to display messages
763 $(document).ajaxSuccess(function(event, xhr, settings) {
764 try {
765 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
766 var response = $.parseJSON(xhr.responseText);
767 if (typeof(response.crmMessages) == 'object') {
768 $.each(response.crmMessages, function(n, msg) {
769 CRM.alert(msg.text, msg.title, msg.type, msg.options);
770 })
771 }
772 }
773 }
774 // Suppress errors
775 catch (e) {}
776 });
777
778 /**
779 * Temporary stub to get around name conflict with legacy jQuery.autocomplete plugin
780 * FIXME: Remove this before 4.5 release
781 */
782 $.widget('civi.crmAutocomplete', $.ui.autocomplete, {});
783
784 $(function () {
785 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
786 $('.crm-container').trigger('crmLoad');
787
788 if ($('#crm-notification-container').length) {
789 // Initialize notifications
790 $('#crm-notification-container').notify();
791 messagesFromMarkup.call($('#crm-container'));
792 }
793
794 // bind the event for image popup
795 $('body')
796 .on('click', 'a.crm-image-popup', function() {
797 var o = $('<div class="crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
798
799 CRM.confirm('',
800 {
801 title: ts('Preview'),
802 message: o
803 },
804 ts('Done')
805 );
806 return false;
807 })
808
809 .on('click', function (event) {
810 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
811 if ($(event.target).is('.btn-slide')) {
812 $(event.target).addClass('btn-slide-active').find('.panel').show();
813 }
814 })
815
816 // Handle clear button for form elements
817 .on('click', 'a.crm-clear-link', function() {
818 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
819 $(this).siblings('input:text').val('').change();
820 return false;
821 })
822 .on('change', 'input.crm-form-radio:checked', function() {
823 $(this).siblings('.crm-clear-link').css({visibility: ''});
824 });
825
826 $().crmtooltip();
827 });
828
829 $.fn.crmAccordions = function (speed) {
830 var container = $(this).length > 0 ? $(this) : $('.crm-container');
831 speed = speed === undefined ? 200 : speed;
832 container
833 .off('click.crmAccordions')
834 // Allow normal clicking of links
835 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
836 e.stopPropagation && e.stopPropagation();
837 })
838 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
839 if ($(this).parent().hasClass('collapsed')) {
840 $(this).next().css('display', 'none').slideDown(speed);
841 }
842 else {
843 $(this).next().css('display', 'block').slideUp(speed);
844 }
845 $(this).parent().toggleClass('collapsed');
846 return false;
847 });
848 };
849 $.fn.crmAccordionToggle = function (speed) {
850 $(this).each(function () {
851 if ($(this).hasClass('collapsed')) {
852 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
853 }
854 else {
855 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
856 }
857 $(this).toggleClass('collapsed');
858 });
859 };
860
861 /**
862 * Clientside currency formatting
863 * @param value
864 * @param format - currency representation of the number 1234.56
865 * @return string
866 * @see CRM_Core_Resources::addCoreResources
867 */
868 var currencyTemplate;
869 CRM.formatMoney = function(value, format) {
870 var decimal, separator, sign, i, j, result;
871 if (value === 'init' && format) {
872 currencyTemplate = format;
873 return;
874 }
875 format = format || currencyTemplate;
876 result = /1(.?)234(.?)56/.exec(format);
877 if (result === null) {
878 return 'Invalid format passed to CRM.formatMoney';
879 }
880 separator = result[1];
881 decimal = result[2];
882 sign = (value < 0) ? '-' : '';
883 //extracting the absolute value of the integer part of the number and converting to string
884 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
885 j = ((j = i.length) > 3) ? j % 3 : 0;
886 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) : '');
887 return format.replace(/1.*234.*56/, result);
888 };
889 })(jQuery);