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