Merge pull request #2726 from pratik-joshi/CRM-13973-qa
[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 /**
175 * Function to show / hide the row in optionFields
176 * @deprecated
177 * @param index string, element whose innerHTML is to hide else will show the hidden row.
178 */
179 function showHideRow(index) {
180 if (index) {
181 cj('tr#optionField_' + index).hide();
182 if (cj('table#optionField tr:hidden:first').length) {
183 cj('div#optionFieldLink').show();
184 }
185 }
186 else {
187 cj('table#optionField tr:hidden:first').show();
188 if (!cj('table#optionField tr:hidden:last').length) {
189 cj('div#optionFieldLink').hide();
190 }
191 }
192 return false;
193 }
194
195 CRM.utils = CRM.utils || {};
196 CRM.strings = CRM.strings || {};
197 CRM.validate = CRM.validate || {
198 params: {},
199 functions: []
200 };
201
202 (function ($, undefined) {
203 "use strict";
204
205 // Theme classes for unattached elements
206 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container';
207
208 // https://github.com/ivaynberg/select2/pull/2090
209 $.fn.select2.defaults.width = 'resolve';
210
211 // Workaround for https://github.com/ivaynberg/select2/issues/1246
212 $.ui.dialog.prototype._allowInteraction = function(e) {
213 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop').length;
214 };
215
216 /**
217 * Populate a select list, overwriting the existing options except for the placeholder.
218 * @param $el jquery collection - 1 or more select elements
219 * @param options array in format returned by api.getoptions
220 * @param removePlaceholder bool
221 */
222 CRM.utils.setOptions = function($el, options, removePlaceholder) {
223 $el.each(function() {
224 var
225 $elect = $(this),
226 val = $elect.val() || [],
227 opts = removePlaceholder ? '' : '[value!=""]';
228 if (typeof(val) !== 'array') {
229 val = [val];
230 }
231 $elect.find('option' + opts).remove();
232 _.each(options, function(option) {
233 var selected = ($.inArray(''+option.key, val) > -1) ? 'selected="selected"' : '';
234 $elect.append('<option value="' + option.key + '"' + selected + '>' + option.value + '</option>');
235 });
236 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
237 });
238 };
239
240 /**
241 * Wrapper for select2 initialization function; supplies defaults
242 * @param options object
243 */
244 $.fn.crmSelect2 = function(options) {
245 return $(this).each(function () {
246 var
247 $el = $(this),
248 defaults = {allowClear: !$el.hasClass('required')};
249 // quickform doesn't support optgroups so here's a hack :(
250 $('option[value^=crm_optgroup]', this).each(function () {
251 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
252 $(this).remove();
253 });
254 // Defaults for single-selects
255 if ($el.is('select:not([multiple])')) {
256 defaults.minimumResultsForSearch = 10;
257 if ($('option:first', this).val() === '') {
258 defaults.placeholderOption = 'first';
259 }
260 }
261 $el.select2($.extend(defaults, $el.data('select-params') || {}, options || {}));
262 });
263 };
264
265 /**
266 * @see CRM_Core_Form::addEntityRef for docs
267 * @param options object
268 */
269 $.fn.crmEntityRef = function(options) {
270 options = options || {};
271 options.select = options.select || {};
272 return $(this).each(function() {
273 var
274 $el = $(this),
275 entity = options.entity || $el.data('api-entity') || 'contact',
276 selectParams = {};
277 $el.data('api-entity', entity);
278 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
279 $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api));
280 $el.data('create-links', options.create || $el.data('create-links'));
281 $el.addClass('crm-ajax-select crm-' + entity + '-ref');
282 var settings = {
283 // Use select2 ajax helper instead of CRM.api because it provides more value
284 ajax: {
285 url: CRM.url('civicrm/ajax/rest'),
286 data: function (input, page_num) {
287 var params = $el.data('api-params') || {};
288 params.input = input;
289 params.page_num = page_num;
290 return {
291 entity: $el.data('api-entity'),
292 action: 'getlist',
293 json: JSON.stringify(params)
294 };
295 },
296 results: function(data) {
297 return {more: data.more_results, results: data.values || []};
298 }
299 },
300 minimumInputLength: 1,
301 formatResult: formatSelect2Result,
302 formatSelection: function(row) {
303 return row.label;
304 },
305 escapeMarkup: function (m) {return m;},
306 initSelection: function($el, callback) {
307 var
308 multiple = !!$el.data('select-params').multiple,
309 val = $el.val(),
310 stored = $el.data('entity-value') || [];
311 if (val === '') {
312 return;
313 }
314 // If we already have this data, just return it
315 if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
316 callback(multiple ? stored : stored[0]);
317 } else {
318 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
319 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
320 callback(multiple ? result.values : result.values[0])
321 });
322 }
323 }
324 };
325 if ($el.data('create-links')) {
326 selectParams.formatInputTooShort = function() {
327 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
328 if ($el.data('create-links')) {
329 txt += ' ' + ts('or') + '<br />' + formatSelect2CreateLinks($el);
330 }
331 return txt;
332 };
333 selectParams.formatNoMatches = function() {
334 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
335 return txt + '<br />' + formatSelect2CreateLinks($el);
336 };
337 $el.off('.createLinks').on('select2-open.createLinks', function() {
338 var $el = $(this);
339 $('#select2-drop').off('.crmEntity').on('click.crmEntity', 'a.crm-add-entity', function(e) {
340 $el.select2('close');
341 CRM.loadForm($(this).attr('href'), {
342 dialog: {width: 500, height: 'auto'}
343 }).on('crmFormSuccess', function(e, data) {
344 if (data.status === 'success' && data.id) {
345 CRM.status(ts('%1 Created', {1: data.label}));
346 if ($el.select2('container').hasClass('select2-container-multi')) {
347 var selection = $el.select2('data');
348 selection.push(data);
349 $el.select2('data', selection, true);
350 } else {
351 $el.select2('data', data, true);
352 }
353 }
354 });
355 return false;
356 });
357 });
358 }
359 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams));
360 });
361 };
362
363 function formatSelect2Result(row) {
364 var markup = '<div class="crm-select2-row">';
365 if (row.image !== undefined) {
366 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
367 }
368 else if (row.icon_class) {
369 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
370 }
371 markup += '<div><div class="crm-select2-row-label">' + row.label + '</div>';
372 markup += '<div class="crm-select2-row-description">';
373 $.each(row.description || [], function(k, text) {
374 markup += '<p>' + text + '</p>';
375 });
376 markup += '</div></div></div>';
377 return markup;
378 }
379
380 function formatSelect2CreateLinks($el) {
381 var
382 createLinks = $el.data('create-links'),
383 api = $el.data('api-params') || {},
384 type = api.params ? api.params.contact_type : null;
385 if (createLinks === true) {
386 createLinks = type ? _.where(CRM.profile.contactCreate, {type: type}) : CRM.profile.contactCreate;
387 }
388 var markup = '';
389 _.each(createLinks, function(link) {
390 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
391 if (link.type) {
392 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
393 }
394 markup += link.label + '</a>';
395 });
396 return markup;
397 }
398
399 // Initialize widgets
400 $(document)
401 .on('crmLoad', function(e) {
402 $('table.row-highlight', e.target)
403 .off('.rowHighlight')
404 .on('change.rowHighlight', 'input.select-row, input.select-rows', function () {
405 var target, table = $(this).closest('table');
406 if ($(this).hasClass('select-rows')) {
407 target = $('tbody tr', table);
408 $('input.select-row', table).prop('checked', $(this).prop('checked'));
409 }
410 else {
411 target = $(this).closest('tr');
412 $('input.select-rows', table).prop('checked', $(".select-row:not(':checked')", table).length < 1);
413 }
414 target.toggleClass('crm-row-selected', $(this).is(':checked'));
415 })
416 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
417 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
418 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
419 })
420 // Modal dialogs should disable scrollbars
421 .on('dialogopen', function(e) {
422 if ($(e.target).dialog('option', 'modal')) {
423 $(e.target).addClass('modal-dialog');
424 $('body').css({overflow: 'hidden'});
425 }
426 })
427 .on('dialogclose', function(e) {
428 if ($('.ui-dialog .modal-dialog').not(e.target).length < 1) {
429 $('body').css({overflow: ''});
430 }
431 });
432
433 /**
434 * Function to make multiselect boxes behave as fields in small screens
435 */
436 function advmultiselectResize() {
437 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
438 if (amswidth < 700) {
439 $("form table.advmultiselect td").css('display', 'block');
440 }
441 else {
442 $("form table.advmultiselect td").css('display', 'table-cell');
443 }
444 var contactwidth = $('#crm-container #mainTabContainer').width();
445 if (contactwidth < 600) {
446 $('#crm-container #mainTabContainer').addClass('narrowpage');
447 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
448 if (index > 1) {
449 if (index % 2 == 0) {
450 $(this).parent().after('<tr class="narrowadded"></tr>');
451 }
452 var item = $(this);
453 $(this).parent().next().append(item);
454 }
455 });
456 }
457 else {
458 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
459 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
460 var nitem = $(this);
461 var parent = $(this).parent();
462 $(this).parent().prev().append(nitem);
463 if (parent.children().size() == 0) {
464 parent.remove();
465 }
466 });
467 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
468 }
469 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
470
471 if (cformwidth < 720) {
472 $('#crm-container .contact_basic_information-section').addClass('narrowform');
473 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
474 if (cformwidth < 480) {
475 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
476 }
477 else {
478 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
479 }
480 }
481 else {
482 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
483 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
484 }
485 }
486
487 advmultiselectResize();
488 $(window).resize(function () {
489 advmultiselectResize();
490 });
491
492 $.fn.crmtooltip = function () {
493 $(document)
494 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
495 $(this).addClass('crm-processed');
496 $(this).addClass('crm-tooltip-active');
497 var topDistance = e.pageY - $(window).scrollTop();
498 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
499 $(this).addClass('crm-tooltip-down');
500 }
501 if (!$(this).children('.crm-tooltip-wrapper').length) {
502 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
503 $(this).children().children('.crm-tooltip')
504 .html('<div class="crm-loading-element"></div>')
505 .load(this.href);
506 }
507 })
508 .on('mouseout', 'a.crm-summary-link', function () {
509 $(this).removeClass('crm-processed');
510 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
511 })
512 .on('click', 'a.crm-summary-link', false);
513 };
514
515 var helpDisplay, helpPrevious;
516 CRM.help = function (title, params, url) {
517 if (helpDisplay && helpDisplay.close) {
518 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
519 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
520 helpDisplay.close();
521 return;
522 }
523 helpDisplay.close();
524 }
525 helpPrevious = JSON.stringify(params);
526 params.class_name = 'CRM_Core_Page_Inline_Help';
527 params.type = 'page';
528 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
529 $.ajax(url || CRM.url('civicrm/ajax/inline'),
530 {
531 data: params,
532 dataType: 'html',
533 success: function (data) {
534 $('#crm-notification-container .crm-help .notify-content:last').html(data);
535 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
536 },
537 error: function () {
538 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
539 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
540 }
541 }
542 );
543 };
544 /**
545 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
546 */
547 CRM.status = function(options, deferred) {
548 // 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.
549 if (typeof options === 'string') {
550 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
551 }
552 var opts = $.extend({
553 start: ts('Saving...'),
554 success: ts('Saved'),
555 error: function() {
556 CRM.alert(ts('Sorry an error occurred and your information was not saved'), ts('Error'));
557 }
558 }, options || {});
559 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>')
560 .appendTo('body');
561 $msg.css('min-width', $msg.width());
562 function handle(status, data) {
563 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
564 if (endMsg) {
565 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg);
566 window.setTimeout(function() {
567 $msg.fadeOut('slow', function() {$msg.remove()});
568 }, 2000);
569 } else {
570 $msg.remove();
571 }
572 }
573 return (deferred || new $.Deferred())
574 .done(function(data) {
575 // If the server returns an error msg call the error handler
576 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
577 handle(status, data);
578 })
579 .fail(function(data) {
580 handle('error', data);
581 });
582 };
583
584 /**
585 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
586 */
587 CRM.alert = function (text, title, type, options) {
588 type = type || 'alert';
589 title = title || '';
590 options = options || {};
591 if ($('#crm-notification-container').length) {
592 var params = {
593 text: text,
594 title: title,
595 type: type
596 };
597 // By default, don't expire errors and messages containing links
598 var extra = {
599 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
600 unique: true
601 };
602 options = $.extend(extra, options);
603 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
604 if (options.unique && options.unique !== '0') {
605 $('#crm-notification-container .ui-notify-message').each(function () {
606 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
607 $('.icon.ui-notify-close', this).click();
608 }
609 });
610 }
611 return $('#crm-notification-container').notify('create', params, options);
612 }
613 else {
614 if (title.length) {
615 text = title + "\n" + text;
616 }
617 alert(text);
618 return null;
619 }
620 };
621
622 /**
623 * Close whichever alert contains the given node
624 *
625 * @param node
626 */
627 CRM.closeAlertByChild = function (node) {
628 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
629 };
630
631 /**
632 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
633 */
634 CRM.confirm = function (buttons, options, cancelLabel) {
635 var dialog, callbacks = {};
636 cancelLabel = cancelLabel || ts('Cancel');
637 var settings = {
638 title: ts('Confirm Action'),
639 message: ts('Are you sure you want to continue?'),
640 resizable: false,
641 modal: true,
642 width: 'auto',
643 close: function () {
644 $(dialog).dialog('destroy').remove();
645 },
646 buttons: {}
647 };
648
649 settings.buttons[cancelLabel] = function () {
650 dialog.trigger('crmConfirmNo').dialog('close');
651 };
652 options = options || {};
653 $.extend(settings, options);
654 if ($.isFunction(buttons)) {
655 callbacks[ts('Continue')] = buttons;
656 }
657 else if (_.isString(buttons) || !buttons) {
658 callbacks[buttons || ts('Continue')] = function() {};
659 }
660 else {
661 callbacks = buttons;
662 }
663 $.each(callbacks, function (label, callback) {
664 settings.buttons[label] = function () {
665 dialog.trigger('crmConfirmYes');
666 if (callback.call(dialog) !== false) {
667 dialog.dialog('close');
668 }
669 };
670 });
671 dialog = $('<div class="crm-confirm-dialog"></div>')
672 .html(options.message)
673 .dialog(settings)
674 .trigger('crmLoad');
675 return dialog;
676 };
677
678 /**
679 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
680 */
681 $.fn.crmError = function (text, title, options) {
682 title = title || '';
683 text = text || '';
684 options = options || {};
685
686 var extra = {
687 expires: 0
688 };
689 if ($(this).length) {
690 if (title == '') {
691 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
692 if (label.length) {
693 label.addClass('crm-error');
694 var $label = label.clone();
695 if (text == '' && $('.crm-marker', $label).length > 0) {
696 text = $('.crm-marker', $label).attr('title');
697 }
698 $('.crm-marker', $label).remove();
699 title = $label.text();
700 }
701 }
702 $(this).addClass('error');
703 }
704 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
705 if ($(this).length) {
706 var ele = $(this);
707 setTimeout(function () {
708 ele.one('change', function () {
709 msg && msg.close && msg.close();
710 ele.removeClass('error');
711 label.removeClass('crm-error');
712 });
713 }, 1000);
714 }
715 return msg;
716 };
717
718 // Display system alerts through js notifications
719 function messagesFromMarkup() {
720 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
721 var text, title = '';
722 $(this).removeClass('status messages');
723 var type = $(this).attr('class').split(' ')[0] || 'alert';
724 type = type.replace('crm-', '');
725 $('.icon', this).remove();
726 if ($('.msg-text', this).length > 0) {
727 text = $('.msg-text', this).html();
728 title = $('.msg-title', this).html();
729 }
730 else {
731 text = $(this).html();
732 }
733 var options = $(this).data('options') || {};
734 $(this).remove();
735 // Duplicates were already removed server-side
736 options.unique = false;
737 CRM.alert(text, title, type, options);
738 });
739 // Handle qf form errors
740 $('form :input.error', this).one('blur', function() {
741 // ignore autocomplete fields
742 if ($(this).is('.ac_input')) {
743 return;
744 }
745
746 $('.ui-notify-message.error a.ui-notify-close').click();
747 $(this).removeClass('error');
748 $(this).next('span.crm-error').remove();
749 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
750 .removeClass('crm-error')
751 .find('.crm-error').removeClass('crm-error');
752 });
753 }
754
755 // Preprocess all cj ajax calls to display messages
756 $(document).ajaxSuccess(function(event, xhr, settings) {
757 try {
758 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
759 var response = $.parseJSON(xhr.responseText);
760 if (typeof(response.crmMessages) == 'object') {
761 $.each(response.crmMessages, function(n, msg) {
762 CRM.alert(msg.text, msg.title, msg.type, msg.options);
763 })
764 }
765 }
766 }
767 // Suppress errors
768 catch (e) {}
769 });
770
771 /**
772 * Temporary stub to get around name conflict with legacy jQuery.autocomplete plugin
773 * FIXME: Remove this before 4.5 release
774 */
775 $.widget('civi.crmAutocomplete', $.ui.autocomplete, {});
776
777 $(function () {
778 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
779 $('.crm-container').trigger('crmLoad');
780
781 if ($('#crm-notification-container').length) {
782 // Initialize notifications
783 $('#crm-notification-container').notify();
784 messagesFromMarkup.call($('#crm-container'));
785 }
786
787 // bind the event for image popup
788 $('body')
789 .on('click', 'a.crm-image-popup', function() {
790 var o = $('<div class="crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
791
792 CRM.confirm('',
793 {
794 title: ts('Preview'),
795 message: o
796 },
797 ts('Done')
798 );
799 return false;
800 })
801
802 .on('click', function (event) {
803 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
804 if ($(event.target).is('.btn-slide')) {
805 $(event.target).addClass('btn-slide-active').find('.panel').show();
806 }
807 })
808
809 // Handle clear button for form elements
810 .on('click', 'a.crm-clear-link', function() {
811 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
812 $(this).siblings('input:text').val('').change();
813 return false;
814 })
815 .on('change', 'input.crm-form-radio:checked', function() {
816 $(this).siblings('.crm-clear-link').css({visibility: ''});
817 });
818
819 $().crmtooltip();
820 });
821
822 $.fn.crmAccordions = function (speed) {
823 var container = $(this).length > 0 ? $(this) : $('.crm-container');
824 speed = speed === undefined ? 200 : speed;
825 container
826 .off('click.crmAccordions')
827 // Allow normal clicking of links
828 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
829 e.stopPropagation && e.stopPropagation();
830 })
831 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
832 if ($(this).parent().hasClass('collapsed')) {
833 $(this).next().css('display', 'none').slideDown(speed);
834 }
835 else {
836 $(this).next().css('display', 'block').slideUp(speed);
837 }
838 $(this).parent().toggleClass('collapsed');
839 return false;
840 });
841 };
842 $.fn.crmAccordionToggle = function (speed) {
843 $(this).each(function () {
844 if ($(this).hasClass('collapsed')) {
845 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
846 }
847 else {
848 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
849 }
850 $(this).toggleClass('collapsed');
851 });
852 };
853
854 /**
855 * Clientside currency formatting
856 * @param value
857 * @param format - currency representation of the number 1234.56
858 * @return string
859 * @see CRM_Core_Resources::addCoreResources
860 */
861 var currencyTemplate;
862 CRM.formatMoney = function(value, format) {
863 var decimal, separator, sign, i, j, result;
864 if (value === 'init' && format) {
865 currencyTemplate = format;
866 return;
867 }
868 format = format || currencyTemplate;
869 result = /1(.?)234(.?)56/.exec(format);
870 if (result === null) {
871 return 'Invalid format passed to CRM.formatMoney';
872 }
873 separator = result[1];
874 decimal = result[2];
875 sign = (value < 0) ? '-' : '';
876 //extracting the absolute value of the integer part of the number and converting to string
877 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
878 j = ((j = i.length) > 3) ? j % 3 : 0;
879 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) : '');
880 return format.replace(/1.*234.*56/, result);
881 };
882 })(jQuery);