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