37f299e93df3fd27a033b5c017ac8a1a2eed01d3
[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 = document.getElementById(trigger_field_id).options[document.getElementById(trigger_field_id).selectedIndex].value;
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 (document.getElementsByName(trigger_field_id)[0].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 * reset all the radio buttons with a given name
176 *
177 * @param string fieldName
178 * @param object form
179 * @return null
180 */
181 function unselectRadio(fieldName, form) {
182 for (i = 0; i < document.forms[form].elements.length; i++) {
183 if (document.forms[form].elements[i].name == fieldName) {
184 document.forms[form].elements[i].checked = false;
185 }
186 }
187 return;
188 }
189
190 /**
191 * Function to change button text and disable one it is clicked
192 *
193 * @param obj object - the button clicked
194 * @param formID string - the id of the form being submitted
195 * @param string procText - button text after user clicks it
196 * @return null
197 */
198 var submitcount = 0;
199 /* Changes button label on submit, and disables button after submit for newer browsers.
200 Puts up alert for older browsers. */
201 function submitOnce(obj, formId, procText) {
202 // if named button clicked, change text
203 if (obj.value != null) {
204 obj.value = procText + " ...";
205 }
206 if (document.getElementById) { // disable submit button for newer browsers
207 obj.disabled = true;
208 document.getElementById(formId).submit();
209 return true;
210 }
211 else { // for older browsers
212 if (submitcount == 0) {
213 submitcount++;
214 return true;
215 }
216 else {
217 alert("Your request is currently being processed ... Please wait.");
218 return false;
219 }
220 }
221 }
222
223 function popUp(URL) {
224 day = new Date();
225 id = day.getTime();
226 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');");
227 }
228
229 /**
230 * Function to show / hide the row in optionFields
231 *
232 * @param element name index, that whose innerHTML is to hide else will show the hidden row.
233 */
234 function showHideRow(index) {
235 if (index) {
236 cj('tr#optionField_' + index).hide();
237 if (cj('table#optionField tr:hidden:first').length) {
238 cj('div#optionFieldLink').show();
239 }
240 }
241 else {
242 cj('table#optionField tr:hidden:first').show();
243 if (!cj('table#optionField tr:hidden:last').length) {
244 cj('div#optionFieldLink').hide();
245 }
246 }
247 return false;
248 }
249
250 CRM.strings = CRM.strings || {};
251 CRM.validate = CRM.validate || {
252 params: {},
253 functions: []
254 };
255
256 (function ($, undefined) {
257 "use strict";
258
259 // Set select2 defaults
260 $.fn.select2.defaults.minimumResultsForSearch = 10;
261 // https://github.com/ivaynberg/select2/pull/2090
262 $.fn.select2.defaults.width = 'resolve';
263
264 // Workaround for https://github.com/ivaynberg/select2/issues/1246
265 $.ui.dialog.prototype._allowInteraction = function(e) {
266 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop').length;
267 };
268
269 // Initialize widgets
270 $(document).on('crmLoad', function(e) {
271 $('table.row-highlight', e.target)
272 .off('.rowHighlight')
273 .on('change.rowHighlight', 'input.select-row, input.select-rows', function () {
274 var target, table = $(this).closest('table');
275 if ($(this).hasClass('select-rows')) {
276 target = $('tbody tr', table);
277 $('input.select-row', table).prop('checked', $(this).prop('checked'));
278 }
279 else {
280 target = $(this).closest('tr');
281 $('input.select-rows', table).prop('checked', $(".select-row:not(':checked')", table).length < 1);
282 }
283 target.toggleClass('crm-row-selected', $(this).is(':checked'));
284 })
285 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
286 $('.crm-select2', e.target).each(function() {
287 // quickform doesn't support optgroups so here's a hack :(
288 $('option[value^=crm_optgroup]', this).each(function() {
289 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
290 $(this).remove();
291 });
292 var options = $(this).data('select-params') || {};
293 // Set placeholder from markup if not specified
294 if ($(this).is('select:not([multiple])')) {
295 options.allowClear = options.allowClear !== undefined ? options.allowClear : !($(this).hasClass('required'));
296 if (options.placeHolder === undefined && $('option:first', this).val() === '') {
297 options.placeholderOption = 'first';
298 }
299 }
300 // Api-based searching
301 if ($(this).data('api-params')) {
302 $(this).addClass('crm-ajax-select')
303 options.query = function(info) {
304 var api = $(info.element).data('api-params');
305 var params = api.params || {};
306 params[api.search] = info.term;
307 CRM.api3(api.entity, api.action, params).done(function(data) {
308 var results = {context: info.context, results: []};
309 if (typeof(data.values) === 'object') {
310 $.each(data.values, function(k, v) {
311 results.results.push({id: v[api.key], text: v[api.label]});
312 });
313 }
314 info.callback(results);
315 });
316 };
317 options.initSelection = function(el, callback) {
318 callback(el.data('entity-value'));
319 };
320 }
321 $(this).select2(options).removeClass('crm-select2');
322 });
323 });
324
325 /**
326 * Function to make multiselect boxes behave as fields in small screens
327 */
328 function advmultiselectResize() {
329 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
330 if (amswidth < 700) {
331 $("form table.advmultiselect td").css('display', 'block');
332 }
333 else {
334 $("form table.advmultiselect td").css('display', 'table-cell');
335 }
336 var contactwidth = $('#crm-container #mainTabContainer').width();
337 if (contactwidth < 600) {
338 $('#crm-container #mainTabContainer').addClass('narrowpage');
339 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
340 if (index > 1) {
341 if (index % 2 == 0) {
342 $(this).parent().after('<tr class="narrowadded"></tr>');
343 }
344 var item = $(this);
345 $(this).parent().next().append(item);
346 }
347 });
348 }
349 else {
350 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
351 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
352 var nitem = $(this);
353 var parent = $(this).parent();
354 $(this).parent().prev().append(nitem);
355 if (parent.children().size() == 0) {
356 parent.remove();
357 }
358 });
359 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
360 }
361 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
362
363 if (cformwidth < 720) {
364 $('#crm-container .contact_basic_information-section').addClass('narrowform');
365 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
366 if (cformwidth < 480) {
367 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
368 }
369 else {
370 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
371 }
372 }
373 else {
374 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
375 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
376 }
377 }
378
379 advmultiselectResize();
380 $(window).resize(function () {
381 advmultiselectResize();
382 });
383
384 $.fn.crmtooltip = function () {
385 $(document)
386 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
387 $(this).addClass('crm-processed');
388 $(this).addClass('crm-tooltip-active');
389 var topDistance = e.pageY - $(window).scrollTop();
390 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
391 $(this).addClass('crm-tooltip-down');
392 }
393 if (!$(this).children('.crm-tooltip-wrapper').length) {
394 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
395 $(this).children().children('.crm-tooltip')
396 .html('<div class="crm-loading-element"></div>')
397 .load(this.href);
398 }
399 })
400 .on('mouseout', 'a.crm-summary-link', function () {
401 $(this).removeClass('crm-processed');
402 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
403 })
404 .on('click', 'a.crm-summary-link', false);
405 };
406
407 var h;
408 CRM.help = function (title, params, url) {
409 h && h.close && h.close();
410 var options = {
411 expires: 0
412 };
413 h = CRM.alert('...', title, 'crm-help crm-msg-loading', options);
414 params.class_name = 'CRM_Core_Page_Inline_Help';
415 params.type = 'page';
416 $.ajax(url || CRM.url('civicrm/ajax/inline'),
417 {
418 data: params,
419 dataType: 'html',
420 success: function (data) {
421 $('#crm-notification-container .crm-help .notify-content:last').html(data);
422 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
423 },
424 error: function () {
425 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
426 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
427 }
428 }
429 );
430 };
431 /**
432 * @param startMsg string
433 * @param endMsg string|function
434 * @param deferred optional jQuery deferred object
435 * @return jQuery deferred object - if not supplied a new one will be created
436 */
437 var fadeOut;
438 CRM.status = function(startMsg, endMsg, deferred) {
439 var $bar = $('#civicrm-menu');
440 if (!$bar.length) {
441 console && console.log && console.log('CRM.status called on a page with no menubar');
442 return;
443 }
444 $('.crm-menubar-status-container', $bar).remove();
445 fadeOut && window.clearTimeout(fadeOut);
446 $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>');
447 $('.crm-menubar-status-container', $bar).css('min-width', $('.crm-menubar-status-container', $bar).width());
448 deferred || (deferred = new $.Deferred());
449 deferred.done(function(data) {
450 var msg = typeof(endMsg) === 'function' ? endMsg(data) : endMsg;
451 $('.crm-menubar-status-container', $bar).removeClass('status-busy').addClass('status-done').show().find('.crm-menubar-status-msg').html(msg);
452 if (msg) {
453 fadeOut = window.setTimeout(function() {
454 $('.crm-menubar-status-container', $bar).fadeOut('slow');
455 }, 2000);
456 } else {
457 $('.crm-menubar-status-container', $bar).hide();
458 }
459 });
460 return deferred;
461 };
462
463 /**
464 * @param string text Displayable message
465 * @param string title Displayable title
466 * @param string type 'alert'|'info'|'success'|'error' (default: 'alert')
467 * @param {object} options
468 * @return {*}
469 * @see http://wiki.civicrm.org/confluence/display/CRM/Notifications+in+CiviCRM
470 */
471 CRM.alert = function (text, title, type, options) {
472 type = type || 'alert';
473 title = title || '';
474 options = options || {};
475 if ($('#crm-notification-container').length) {
476 var params = {
477 text: text,
478 title: title,
479 type: type
480 };
481 // By default, don't expire errors and messages containing links
482 var extra = {
483 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
484 unique: true
485 };
486 options = $.extend(extra, options);
487 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
488 if (options.unique && options.unique !== '0') {
489 $('#crm-notification-container .ui-notify-message').each(function () {
490 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
491 $('.icon.ui-notify-close', this).click();
492 }
493 });
494 }
495 return $('#crm-notification-container').notify('create', params, options);
496 }
497 else {
498 if (title.length) {
499 text = title + "\n" + text;
500 }
501 alert(text);
502 return null;
503 }
504 };
505
506 /**
507 * Close whichever alert contains the given node
508 *
509 * @param node
510 */
511 CRM.closeAlertByChild = function (node) {
512 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
513 };
514
515 /**
516 * Prompt the user for confirmation.
517 *
518 * @param buttons {object|function} key|value pairs where key == button label and value == callback function
519 * passing in a function instead of an object is a shortcut for a sinlgle button labeled "Continue"
520 * @param options {object|void} Override defaults, keys include 'title', 'message',
521 * see jQuery.dialog for full list of available params
522 */
523 CRM.confirm = function (buttons, options, cancelLabel) {
524 var dialog, callbacks = {};
525 cancelLabel = cancelLabel || ts('Cancel');
526 var settings = {
527 title: ts('Confirm Action'),
528 message: ts('Are you sure you want to continue?'),
529 resizable: false,
530 modal: true,
531 width: 'auto',
532 close: function () {
533 $(dialog).remove();
534 },
535 buttons: {}
536 };
537
538 settings.buttons[cancelLabel] = function () {
539 dialog.dialog('close');
540 };
541 options = options || {};
542 $.extend(settings, options);
543 if (typeof(buttons) === 'function') {
544 callbacks[ts('Continue')] = buttons;
545 }
546 else {
547 callbacks = buttons;
548 }
549 $.each(callbacks, function (label, callback) {
550 settings.buttons[label] = function () {
551 callback.call(dialog);
552 dialog.dialog('close');
553 };
554 });
555 dialog = $('<div class="crm-container crm-confirm-dialog"></div>')
556 .html(options.message)
557 .appendTo('body')
558 .dialog(settings);
559 return dialog;
560 };
561
562 /**
563 * Sets an error message
564 * If called for a form item, title and removal condition will be handled automatically
565 */
566 $.fn.crmError = function (text, title, options) {
567 title = title || '';
568 text = text || '';
569 options = options || {};
570
571 var extra = {
572 expires: 0
573 };
574 if ($(this).length) {
575 if (title == '') {
576 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
577 if (label.length) {
578 label.addClass('crm-error');
579 var $label = label.clone();
580 if (text == '' && $('.crm-marker', $label).length > 0) {
581 text = $('.crm-marker', $label).attr('title');
582 }
583 $('.crm-marker', $label).remove();
584 title = $label.text();
585 }
586 }
587 $(this).addClass('error');
588 }
589 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
590 if ($(this).length) {
591 var ele = $(this);
592 setTimeout(function () {
593 ele.one('change', function () {
594 msg && msg.close && msg.close();
595 ele.removeClass('error');
596 label.removeClass('crm-error');
597 });
598 }, 1000);
599 }
600 return msg;
601 };
602
603 // Display system alerts through js notifications
604 function messagesFromMarkup() {
605 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
606 var text, title = '';
607 $(this).removeClass('status messages');
608 var type = $(this).attr('class').split(' ')[0] || 'alert';
609 type = type.replace('crm-', '');
610 $('.icon', this).remove();
611 if ($('.msg-text', this).length > 0) {
612 text = $('.msg-text', this).html();
613 title = $('.msg-title', this).html();
614 }
615 else {
616 text = $(this).html();
617 }
618 var options = $(this).data('options') || {};
619 $(this).remove();
620 // Duplicates were already removed server-side
621 options.unique = false;
622 CRM.alert(text, title, type, options);
623 });
624 // Handle qf form errors
625 $('form :input.error', this).one('blur', function() {
626 // ignore autocomplete fields
627 if ($(this).is('.ac_input')) {
628 return;
629 }
630
631 $('.ui-notify-message.error a.ui-notify-close').click();
632 $(this).removeClass('error');
633 $(this).next('span.crm-error').remove();
634 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
635 .removeClass('crm-error')
636 .find('.crm-error').removeClass('crm-error');
637 });
638 }
639
640 $.widget('civi.crmSnippet', {
641 options: {
642 url: null,
643 block: true,
644 crmForm: null
645 },
646 _originalContent: null,
647 _originalUrl: null,
648 isOriginalUrl: function() {
649 var
650 args = {},
651 same = true,
652 newUrl = this._formatUrl(this.options.url),
653 oldUrl = this._formatUrl(this._originalUrl);
654 // Compare path
655 if (newUrl.split('?')[0] !== oldUrl.split('?')[0]) {
656 return false;
657 }
658 // Compare arguments
659 $.each(newUrl.split('?')[1].split('&'), function(k, v) {
660 var arg = v.split('=');
661 args[arg[0]] = arg[1];
662 });
663 $.each(oldUrl.split('?')[1].split('&'), function(k, v) {
664 var arg = v.split('=');
665 if (args[arg[0]] !== undefined && arg[1] !== args[arg[0]]) {
666 same = false;
667 }
668 });
669 return same;
670 },
671 resetUrl: function() {
672 this.options.url = this._originalUrl;
673 },
674 _create: function() {
675 this.element.addClass('crm-ajax-container');
676 if (!this.element.is('.crm-container *')) {
677 this.element.addClass('crm-container');
678 }
679 this._handleOrderLinks();
680 // Set default if not supplied
681 this.options.url = this.options.url || document.location.href;
682 this._originalUrl = this.options.url;
683 },
684 _onFailure: function(data) {
685 this.options.block && this.element.unblock();
686 this.element.trigger('crmAjaxFail', data);
687 CRM.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
688 },
689 _formatUrl: function(url) {
690 // Strip hash
691 url = url.split('#')[0];
692 // Add snippet argument to url
693 if (url.search(/[&?]snippet=/) < 0) {
694 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
695 } else {
696 url = url.replace(/snippet=[^&]*/, 'snippet=json');
697 }
698 return url;
699 },
700 // Hack to deal with civicrm legacy sort functionality
701 _handleOrderLinks: function() {
702 var that = this;
703 $('a.crm-weight-arrow', that.element).click(function(e) {
704 that.options.block && that.element.block();
705 $.getJSON(that._formatUrl(this.href)).done(function() {
706 that.refresh();
707 });
708 e.stopImmediatePropagation();
709 return false;
710 });
711 },
712 refresh: function() {
713 var that = this;
714 var url = this._formatUrl(this.options.url);
715 this.options.block && $('.blockOverlay', this.element).length < 1 && this.element.block();
716 $.getJSON(url, function(data) {
717 if (typeof(data) != 'object' || typeof(data.content) != 'string') {
718 that._onFailure(data);
719 return;
720 }
721 data.url = url;
722 that.element.trigger('crmBeforeLoad', data);
723 if (that._originalContent === null) {
724 that._originalContent = that.element.contents().detach();
725 }
726 that.element.html(data.content);
727 that._handleOrderLinks();
728 that.element.trigger('crmLoad', data);
729 that.options.crmForm && that.element.trigger('crmFormLoad', data);
730 }).fail(function() {
731 that._onFailure();
732 });
733 },
734 _destroy: function() {
735 this.element.removeClass('crm-ajax-container');
736 if (this._originalContent !== null) {
737 this.element.empty().append(this._originalContent);
738 }
739 }
740 });
741
742 var dialogCount = 0;
743 CRM.loadPage = function(url, options) {
744 var settings = {
745 target: '#crm-ajax-dialog-' + (dialogCount++),
746 dialog: false
747 };
748 if (!options || !options.target) {
749 settings.dialog = {
750 modal: true,
751 width: '65%',
752 height: parseInt($(window).height() * .75),
753 close: function() {
754 $(this).dialog('destroy').remove();
755 }
756 };
757 }
758 options && $.extend(true, settings, options);
759 settings.url = url;
760 // Create new dialog
761 if (settings.dialog) {
762 $('<div id="'+ settings.target.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings.dialog);
763 }
764 if (settings.dialog && !settings.dialog.title) {
765 $(settings.target).on('crmLoad', function(event, data) {
766 data.title && $(this).dialog('option', 'title', data.title);
767 });
768 }
769 $(settings.target).crmSnippet(settings).crmSnippet('refresh');
770 return $(settings.target);
771 };
772
773 CRM.loadForm = function(url, options) {
774 var settings = {
775 crmForm: {
776 ajaxForm: {},
777 autoClose: true,
778 validate: true,
779 refreshAction: ['next_new', 'submit_savenext'],
780 cancelButton: '.cancel.form-submit',
781 openInline: 'a.button:not("[href=#], .no-popup")',
782 onCancel: function(event) {},
783 onError: function(data) {
784 var $el = $(this);
785 $el.html(data.content).trigger('crmLoad', data).trigger('crmFormLoad', data).trigger('crmFormError', data);
786 if (typeof(data.errors) == 'object') {
787 $.each(data.errors, function(formElement, msg) {
788 $('[name="'+formElement+'"]', $el).crmError(msg);
789 });
790 }
791 }
792 }
793 };
794 // Hack to make delete dialogs smaller
795 if (url.indexOf('/delete') > 0 || url.indexOf('action=delete') > 0) {
796 settings.dialog = {
797 width: 400,
798 height: 300
799 };
800 }
801 // Move options that belong to crmForm. Others will be passed through to crmSnippet
802 options && $.each(options, function(key, value) {
803 if (typeof(settings.crmForm[key]) !== 'undefined') {
804 settings.crmForm[key] = value;
805 }
806 else {
807 settings[key] = value;
808 }
809 });
810
811 var widget = CRM.loadPage(url, settings);
812
813 widget.on('crmFormLoad', function(event, data) {
814 var $el = $(this);
815 var settings = $el.crmSnippet('option', 'crmForm');
816 settings.cancelButton && $(settings.cancelButton, this).click(function(event) {
817 var returnVal = settings.onCancel.call($el, event);
818 if (returnVal !== false) {
819 $el.trigger('crmFormCancel', event);
820 if ($el.data('uiDialog') && settings.autoClose) {
821 $el.dialog('close');
822 }
823 else if (!settings.autoClose) {
824 $el.crmSnippet('resetUrl').crmSnippet('refresh');
825 }
826 }
827 return returnVal === false;
828 });
829 if (settings.validate) {
830 $("form", this).validate(typeof(settings.validate) == 'object' ? settings.validate : CRM.validate.params);
831 }
832 $("form", this).ajaxForm($.extend({
833 url: data.url.replace(/reset=1[&]?/, ''),
834 dataType: 'json',
835 success: function(response) {
836 if (response.status !== 'form_error') {
837 $el.crmSnippet('option', 'block') && $el.unblock();
838 $el.trigger('crmFormSuccess', response);
839 // Reset form for e.g. "save and new"
840 if (response.userContext && settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0) {
841 $el.crmSnippet('option', 'url', response.userContext).crmSnippet('refresh');
842 }
843 else if ($el.data('uiDialog') && settings.autoClose) {
844 $el.dialog('close');
845 }
846 else if (settings.autoClose === false) {
847 $el.crmSnippet('resetUrl').crmSnippet('refresh');
848 }
849 }
850 else {
851 response.url = data.url;
852 settings.onError.call($el, response);
853 }
854 },
855 beforeSerialize: function(form, options) {
856 if (window.CKEDITOR && window.CKEDITOR.instances) {
857 $.each(CKEDITOR.instances, function() {
858 this.updateElement && this.updateElement();
859 });
860 }
861 },
862 beforeSubmit: function(submission) {
863 $el.crmSnippet('option', 'block') && $el.block();
864 $el.trigger('crmFormSubmit', submission);
865 }
866 }, settings.ajaxForm));
867 if (settings.openInline) {
868 settings.autoClose = $el.crmSnippet('isOriginalUrl');
869 $(settings.openInline, this).click(function(event) {
870 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
871 return false;
872 });
873 }
874 });
875 return widget;
876 };
877
878 // Preprocess all cj ajax calls to display messages
879 $(document).ajaxSuccess(function(event, xhr, settings) {
880 try {
881 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
882 var response = $.parseJSON(xhr.responseText);
883 if (typeof(response.crmMessages) == 'object') {
884 $.each(response.crmMessages, function(n, msg) {
885 CRM.alert(msg.text, msg.title, msg.type, msg.options);
886 })
887 }
888 }
889 }
890 // Suppress errors
891 catch (e) {}
892 });
893
894 /**
895 * Temporary stub to get around name conflict with legacy jQuery.autocomplete plugin
896 */
897 $.widget('civi.crmAutocomplete', $.ui.autocomplete, {});
898
899 $(function () {
900 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
901 $('.crm-container').trigger('crmLoad');
902
903 if ($('#crm-notification-container').length) {
904 // Initialize notifications
905 $('#crm-notification-container').notify();
906 messagesFromMarkup.call($('#crm-container'));
907 }
908
909 // bind the event for image popup
910 $('body').on('click', 'a.crm-image-popup', function() {
911 var o = $('<div class="crm-container crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
912
913 CRM.confirm('',
914 {
915 title: ts('Preview'),
916 message: o
917 },
918 ts('Done')
919 );
920 return false;
921 });
922
923 $().crmtooltip();
924 $('body').on('click', function (event) {
925 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
926 if ($(event.target).is('.btn-slide')) {
927 $(event.target).addClass('btn-slide-active').find('.panel').show();
928 }
929 });
930 });
931
932 $.fn.crmAccordions = function (speed) {
933 var container = $(this).length > 0 ? $(this) : $('.crm-container');
934 speed = speed === undefined ? 200 : speed;
935 container
936 .off('click.crmAccordions')
937 // Allow normal clicking of links
938 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
939 e.stopPropagation && e.stopPropagation();
940 })
941 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
942 if ($(this).parent().hasClass('collapsed')) {
943 $(this).next().css('display', 'none').slideDown(speed);
944 }
945 else {
946 $(this).next().css('display', 'block').slideUp(speed);
947 }
948 $(this).parent().toggleClass('collapsed');
949 return false;
950 });
951 };
952 $.fn.crmAccordionToggle = function (speed) {
953 $(this).each(function () {
954 if ($(this).hasClass('collapsed')) {
955 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
956 }
957 else {
958 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
959 }
960 $(this).toggleClass('collapsed');
961 });
962 };
963
964 /**
965 * Clientside currency formatting
966 * @param value
967 * @param format - currency representation of the number 1234.56
968 * @return string
969 * @see CRM_Core_Resources::addCoreResources
970 */
971 var currencyTemplate;
972 CRM.formatMoney = function(value, format) {
973 var decimal, separator, sign, i, j, result;
974 if (value === 'init' && format) {
975 currencyTemplate = format;
976 return;
977 }
978 format = format || currencyTemplate;
979 result = /1(.?)234(.?)56/.exec(format);
980 if (result === null) {
981 return 'Invalid format passed to CRM.formatMoney';
982 }
983 separator = result[1];
984 decimal = result[2];
985 sign = (value < 0) ? '-' : '';
986 //extracting the absolute value of the integer part of the number and converting to string
987 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
988 j = ((j = i.length) > 3) ? j % 3 : 0;
989 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) : '');
990 return format.replace(/1.*234.*56/, result);
991 };
992 })(jQuery);