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