2 +--------------------------------------------------------------------+
3 | CiviCRM version 4.4 |
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC (c) 2004-2013 |
6 +--------------------------------------------------------------------+
7 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
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
37 * Short-named function for string translation, defined in global scope so it's available everywhere.
39 * @param $text string string for translating
40 * @param $params object key:value of additional parameters
42 * @return string the translated string
44 function ts(text
, params
) {
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-'));
54 return text
.replace(/%-crmescaped-/g, '%');
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
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 ...)
71 function on_load_init_blocks(showBlocks
, hideBlocks
, elementType
) {
72 if (elementType
== null) {
73 var elementType
= 'block';
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
;
84 alert('showBlocks array item not in .tpl = ' + showBlocks
[i
]);
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';
96 alert('showBlocks array item not in .tpl = ' + hideBlocks
[i
]);
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).
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
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';
119 if (target_element_type
== 'table-row') {
120 var target_element_type
= '';
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
;
128 var target
= target_element_id
.split("|");
129 for (var j
= 0; j
< target
.length
; j
++) {
131 cj('#' + target
[j
]).show();
134 cj('#' + target
[j
]).hide();
136 for (var i
= 0; i
< trigger
.length
; i
++) {
137 if (selectedOptionValue
== trigger
[i
]) {
139 cj('#' + target
[j
]).hide();
142 cj('#' + target
[j
]).show();
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
) {
155 cj('#' + target
[j
]).hide();
158 cj('#' + target
[j
]).show();
163 cj('#' + target
[j
]).show();
166 cj('#' + target
[j
]).hide();
176 * Function for checking ALL or unchecking ALL check boxes in a resultset page.
179 * @param fldPrefix - common string which precedes unique checkbox ID and identifies field as
180 * belonging to the resultset's checkbox collection
181 * @param object - checkbox
182 * Sample usage: onClick="javascript:changeCheckboxValues('chk_', cj(this) );"
186 function toggleCheckboxVals(fldPrefix
, object
) {
187 var val
= (object
.id
== 'toggleSelect' && cj(object
).is(':checked'));
188 cj('Input[id*="' + fldPrefix
+ '"],Input[id*="toggleSelect"]').prop('checked', val
);
189 // change the class of selected rows
190 on_load_init_checkboxes(object
.form
.name
);
193 function countSelectedCheckboxes(fldPrefix
, form
) {
195 for (i
= 0; i
< form
.elements
.length
; i
++) {
196 fpLen
= fldPrefix
.length
;
197 if (form
.elements
[i
].type
== 'checkbox' && form
.elements
[i
].name
.slice(0, fpLen
) == fldPrefix
&& form
.elements
[i
].checked
== true) {
205 * Function to enable task action select
207 function toggleTaskAction(status
) {
208 var radio_ts
= document
.getElementsByName('radio_ts');
210 radio_ts
[0].checked
= true;
212 if (radio_ts
[0].checked
|| radio_ts
[1].checked
) {
216 var formElements
= ['task', 'Go', 'Print'];
217 for (var i
= 0; i
< formElements
.length
; i
++) {
218 var element
= document
.getElementById(formElements
[i
]);
221 element
.disabled
= false;
224 element
.disabled
= true;
231 * This function is used to check if any actio is selected and also to check if any contacts are checked.
234 * @param fldPrefix - common string which precedes unique checkbox ID and identifies field as
235 * belonging to the resultset's checkbox collection
236 * @param form - name of form that checkboxes are part of
237 * Sample usage: onClick="javascript:checkPerformAction('chk_', myForm );"
240 function checkPerformAction(fldPrefix
, form
, taskButton
, selection
) {
244 // taskButton TRUE means we don't need to check the 'task' field - it's a button-driven task
245 if (taskButton
== 1) {
249 if (document
.forms
[form
].task
.selectedIndex
) {
250 //force user to select all search contacts, CRM-3711
251 if (document
.forms
[form
].task
.value
== 13 || document
.forms
[form
].task
.value
== 14) {
252 var toggleSelect
= document
.getElementsByName('toggleSelect');
253 if (toggleSelect
[0].checked
|| document
.forms
[form
].radio_ts
[0].checked
) {
257 alert("Please select all contacts for this action.\n\nTo use the entire set of search results, click the 'all records' radio button.");
266 // If user wants to perform action on ALL records and we have a task, return (no need to check further)
267 if (document
.forms
[form
].radio_ts
[0].checked
) {
271 cnt
= (selection
== 1) ? countSelections() : countSelectedCheckboxes(fldPrefix
, document
.forms
[form
]);
273 alert("Please select one or more contacts for this action.\n\nTo use the entire set of search results, click the 'all records' radio button.");
278 alert("Please select an action from the drop-down menu.");
284 * This function changes the style for a checkbox block when it is selected.
287 * @param chkName - it is name of the checkbox
290 function checkSelectedBox(chkName
) {
291 var checkElement
= cj('#' + chkName
);
292 if (checkElement
.prop('checked')) {
293 cj('input[value=ts_sel]:radio').prop('checked', true);
294 checkElement
.parents('tr').addClass('crm-row-selected');
297 checkElement
.parents('tr').removeClass('crm-row-selected');
302 * This function is to show the row with selected checkbox in different color
303 * @param form - name of form that checkboxes are part of
308 function on_load_init_checkboxes(form
) {
310 var fldPrefix
= 'mark_x';
311 for (i
= 0; i
< document
.forms
[formName
].elements
.length
; i
++) {
312 fpLen
= fldPrefix
.length
;
313 if (document
.forms
[formName
].elements
[i
].type
== 'checkbox' && document
.forms
[formName
].elements
[i
].name
.slice(0, fpLen
) == fldPrefix
) {
314 checkSelectedBox(document
.forms
[formName
].elements
[i
].name
, formName
);
320 * Function to change the color of the class
322 * @param form - name of the form
323 * @param rowid - id of the <tr>, <div> you want to change
328 function changeRowColor(rowid
, form
) {
329 switch (document
.getElementById(rowid
).className
) {
331 document
.getElementById(rowid
).className
= 'selected even-row';
334 document
.getElementById(rowid
).className
= 'selected odd-row';
336 case 'selected even-row' :
337 document
.getElementById(rowid
).className
= 'even-row';
339 case 'selected odd-row' :
340 document
.getElementById(rowid
).className
= 'odd-row';
343 document
.getElementById(rowid
).className
= 'selected';
346 document
.getElementById(rowid
).className
= 'form-item';
351 * This function is to show the row with selected checkbox in different color
352 * @param form - name of form that checkboxes are part of
357 function on_load_init_check(form
) {
358 for (i
= 0; i
< document
.forms
[form
].elements
.length
; i
++) {
359 if (( document
.forms
[form
].elements
[i
].type
== 'checkbox'
360 && document
.forms
[form
].elements
[i
].checked
== true )
361 || ( document
.forms
[form
].elements
[i
].type
== 'hidden'
362 && document
.forms
[form
].elements
[i
].value
== 1 )) {
363 var ss
= document
.forms
[form
].elements
[i
].id
;
364 var row
= 'rowid' + ss
;
365 changeRowColor(row
, form
);
371 * reset all the radio buttons with a given name
373 * @param string fieldName
377 function unselectRadio(fieldName
, form
) {
378 for (i
= 0; i
< document
.forms
[form
].elements
.length
; i
++) {
379 if (document
.forms
[form
].elements
[i
].name
== fieldName
) {
380 document
.forms
[form
].elements
[i
].checked
= false;
387 * Function to change button text and disable one it is clicked
389 * @param obj object - the button clicked
390 * @param formID string - the id of the form being submitted
391 * @param string procText - button text after user clicks it
395 /* Changes button label on submit, and disables button after submit for newer browsers.
396 Puts up alert for older browsers. */
397 function submitOnce(obj
, formId
, procText
) {
398 // if named button clicked, change text
399 if (obj
.value
!= null) {
400 obj
.value
= procText
+ " ...";
402 if (document
.getElementById
) { // disable submit button for newer browsers
404 document
.getElementById(formId
).submit();
407 else { // for older browsers
408 if (submitcount
== 0) {
413 alert("Your request is currently being processed ... Please wait.");
419 function popUp(URL
) {
422 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');");
426 * Function to show / hide the row in optionFields
428 * @param element name index, that whose innerHTML is to hide else will show the hidden row.
430 function showHideRow(index
) {
432 cj('tr#optionField_' + index
).hide();
433 if (cj('table#optionField tr:hidden:first').length
) {
434 cj('div#optionFieldLink').show();
438 cj('table#optionField tr:hidden:first').show();
439 if (!cj('table#optionField tr:hidden:last').length
) {
440 cj('div#optionFieldLink').hide();
446 CRM
.strings
= CRM
.strings
|| {};
447 CRM
.validate
= CRM
.validate
|| {
452 (function ($, undefined) {
454 $(document
).ready(function () {
456 $('.crm-container table.row-highlight').on('change', 'input.select-row, input.select-rows', function () {
457 var target
, table
= $(this).closest('table');
458 if ($(this).hasClass('select-rows')) {
459 target
= $('tbody tr', table
);
460 $('input.select-row', table
).prop('checked', $(this).prop('checked'));
463 target
= $(this).closest('tr');
464 $('input.select-rows', table
).prop('checked', $(".select-row:not(':checked')", table
).length
< 1);
466 target
.toggleClass('crm-row-selected', $(this).is(':checked'));
468 $('body').on('click', function (event
) {
469 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
470 if ($(event
.target
).is('.btn-slide')) {
471 $(event
.target
).addClass('btn-slide-active').find('.panel').show();
477 * Function to make multiselect boxes behave as fields in small screens
479 function advmultiselectResize() {
480 var amswidth
= $("#crm-container form:has(table.advmultiselect)").width();
481 if (amswidth
< 700) {
482 $("form table.advmultiselect td").css('display', 'block');
485 $("form table.advmultiselect td").css('display', 'table-cell');
487 var contactwidth
= $('#crm-container #mainTabContainer').width();
488 if (contactwidth
< 600) {
489 $('#crm-container #mainTabContainer').addClass('narrowpage');
490 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index
) {
492 if (index
% 2 == 0) {
493 $(this).parent().after('<tr class="narrowadded"></tr>');
496 $(this).parent().next().append(item
);
501 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
502 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
504 var parent
= $(this).parent();
505 $(this).parent().prev().append(nitem
);
506 if (parent
.children().size() == 0) {
510 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
512 var cformwidth
= $('#crm-container #Contact .contact_basic_information-section').width();
514 if (cformwidth
< 720) {
515 $('#crm-container .contact_basic_information-section').addClass('narrowform');
516 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
517 if (cformwidth
< 480) {
518 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
521 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
525 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
526 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
530 advmultiselectResize();
531 $(window
).resize(function () {
532 advmultiselectResize();
535 $.fn
.crmtooltip = function () {
537 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e
) {
538 $(this).addClass('crm-processed');
539 $(this).addClass('crm-tooltip-active');
540 var topDistance
= e
.pageY
- $(window
).scrollTop();
541 if (topDistance
< 300 | topDistance
< $(this).children('.crm-tooltip-wrapper').height()) {
542 $(this).addClass('crm-tooltip-down');
544 if (!$(this).children('.crm-tooltip-wrapper').length
) {
545 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
546 $(this).children().children('.crm-tooltip')
547 .html('<div class="crm-loading-element"></div>')
551 .on('mouseout', 'a.crm-summary-link', function () {
552 $(this).removeClass('crm-processed');
553 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
555 .on('click', 'a.crm-summary-link', false);
559 CRM
.help = function (title
, params
, url
) {
560 h
&& h
.close
&& h
.close();
564 h
= CRM
.alert('...', title
, 'crm-help crm-msg-loading', options
);
565 params
.class_name
= 'CRM_Core_Page_Inline_Help';
566 params
.type
= 'page';
567 $.ajax(url
|| CRM
.url('civicrm/ajax/inline'),
571 success: function (data
) {
572 $('#crm-notification-container .crm-help .notify-content:last').html(data
);
573 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
576 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
577 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
584 * @param string text Displayable message
585 * @param string title Displayable title
586 * @param string type 'alert'|'info'|'success'|'error' (default: 'alert')
587 * @param {object} options
589 * @see http://wiki.civicrm.org/confluence/display/CRM/Notifications+in+CiviCRM
591 CRM
.alert = function (text
, title
, type
, options
) {
592 type
= type
|| 'alert';
594 options
= options
|| {};
595 if ($('#crm-notification-container').length
) {
601 // By default, don't expire errors and messages containing links
603 expires
: (type
== 'error' || text
.indexOf('<a ') > -1) ? 0 : (text
? 10000 : 5000),
606 options
= $.extend(extra
, options
);
607 options
.expires
= options
.expires
=== false ? 0 : parseInt(options
.expires
, 10);
608 if (options
.unique
&& options
.unique
!== '0') {
609 $('#crm-notification-container .ui-notify-message').each(function () {
610 if (title
=== $('h1', this).html() && text
=== $('.notify-content', this).html()) {
611 $('.icon.ui-notify-close', this).click();
615 return $('#crm-notification-container').notify('create', params
, options
);
619 text
= title
+ "\n" + text
;
627 * Close whichever alert contains the given node
631 CRM
.closeAlertByChild = function (node
) {
632 $(node
).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
636 * Prompt the user for confirmation.
638 * @param buttons {object|function} key|value pairs where key == button label and value == callback function
639 * passing in a function instead of an object is a shortcut for a sinlgle button labeled "Continue"
640 * @param options {object|void} Override defaults, keys include 'title', 'message',
641 * see jQuery.dialog for full list of available params
643 CRM
.confirm = function (buttons
, options
, cancelLabel
) {
644 var dialog
, callbacks
= {};
645 cancelLabel
= cancelLabel
|| ts('Cancel');
647 title
: ts('Confirm Action'),
648 message
: ts('Are you sure you want to continue?'),
658 settings
.buttons
[cancelLabel
] = function () {
659 dialog
.dialog('close');
661 options
= options
|| {};
662 $.extend(settings
, options
);
663 if (typeof(buttons
) === 'function') {
664 callbacks
[ts('Continue')] = buttons
;
669 $.each(callbacks
, function (label
, callback
) {
670 settings
.buttons
[label
] = function () {
671 callback
.call(dialog
);
672 dialog
.dialog('close');
675 dialog
= $('<div class="crm-container crm-confirm-dialog"></div>')
676 .html(options
.message
)
683 * Sets an error message
684 * If called for a form item, title and removal condition will be handled automatically
686 $.fn
.crmError = function (text
, title
, options
) {
689 options
= options
|| {};
694 if ($(this).length
) {
696 var label
= $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
698 label
.addClass('crm-error');
699 var $label
= label
.clone();
700 if (text
== '' && $('.crm-marker', $label
).length
> 0) {
701 text
= $('.crm-marker', $label
).attr('title');
703 $('.crm-marker', $label
).remove();
704 title
= $label
.text();
707 $(this).addClass('error');
709 var msg
= CRM
.alert(text
, title
, 'error', $.extend(extra
, options
));
710 if ($(this).length
) {
712 setTimeout(function () {
713 ele
.one('change', function () {
714 msg
&& msg
.close
&& msg
.close();
715 ele
.removeClass('error');
716 label
.removeClass('crm-error');
723 // Display system alerts through js notifications
724 function messagesFromMarkup() {
725 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
726 var text
, title
= '';
727 $(this).removeClass('status messages');
728 var type
= $(this).attr('class').split(' ')[0] || 'alert';
729 type
= type
.replace('crm-', '');
730 $('.icon', this).remove();
731 if ($('.msg-text', this).length
> 0) {
732 text
= $('.msg-text', this).html();
733 title
= $('.msg-title', this).html();
736 text
= $(this).html();
738 var options
= $(this).data('options') || {};
740 // Duplicates were already removed server-side
741 options
.unique
= false;
742 CRM
.alert(text
, title
, type
, options
);
744 // Handle qf form errors
745 $('form :input.error', this).one('blur', function() {
746 // ignore autocomplete fields
747 if ($(this).is('.ac_input')) {
751 $('.ui-notify-message.error a.ui-notify-close').click();
752 $(this).removeClass('error');
753 $(this).next('span.crm-error').remove();
754 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
755 .removeClass('crm-error')
756 .find('.crm-error').removeClass('crm-error');
760 $.widget('civi.crmSnippet', {
766 _originalContent
: null,
768 isOriginalUrl: function() {
772 newUrl
= this._formatUrl(this.options
.url
),
773 oldUrl
= this._formatUrl(this._originalUrl
);
775 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
779 $.each(newUrl
.split('?')[1].split('&'), function(k
, v
) {
780 var arg
= v
.split('=');
781 args
[arg
[0]] = arg
[1];
783 $.each(oldUrl
.split('?')[1].split('&'), function(k
, v
) {
784 var arg
= v
.split('=');
785 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
791 resetUrl: function() {
792 this.options
.url
= this._originalUrl
;
794 _create: function() {
795 this.element
.addClass('crm-ajax-container');
796 if (!this.element
.is('.crm-container *')) {
797 this.element
.addClass('crm-container');
799 this._handleOrderLinks();
800 // Set default if not supplied
801 this.options
.url
= this.options
.url
|| document
.location
.href
;
802 this._originalUrl
= this.options
.url
;
804 _onFailure: function(data
) {
805 this.options
.block
&& this.element
.unblock();
806 this.element
.trigger('crmAjaxFail', data
);
807 CRM
.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
809 _formatUrl: function(url
) {
811 url
= url
.split('#')[0];
812 // Add snippet argument to url
813 if (url
.search(/[&?]snippet=/) < 0) {
814 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
816 url
= url
.replace(/snippet=[^&]*/, 'snippet=json');
820 // Hack to deal with civicrm legacy sort functionality
821 _handleOrderLinks: function() {
823 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
824 that
.options
.block
&& that
.element
.block();
825 $.getJSON(that
._formatUrl(this.href
)).done(function() {
828 e
.stopImmediatePropagation();
832 refresh: function() {
834 var url
= this._formatUrl(this.options
.url
);
835 this.options
.block
&& $('.blockOverlay', this.element
).length
< 1 && this.element
.block();
836 $.getJSON(url
, function(data
) {
837 if (typeof(data
) != 'object' || typeof(data
.content
) != 'string') {
838 that
._onFailure(data
);
842 that
.element
.trigger('crmBeforeLoad', data
);
843 if (that
._originalContent
=== null) {
844 that
._originalContent
= that
.element
.contents().detach();
846 that
.element
.html(data
.content
);
847 that
._handleOrderLinks();
848 that
.element
.trigger('crmLoad', data
);
849 that
.options
.crmForm
&& that
.element
.trigger('crmFormLoad', data
);
854 _destroy: function() {
855 this.element
.removeClass('crm-ajax-container');
856 if (this._originalContent
!== null) {
857 this.element
.empty().append(this._originalContent
);
863 CRM
.loadPage = function(url
, options
) {
865 target
: '#crm-ajax-dialog-' + (dialogCount
++),
868 if (!options
|| !options
.target
) {
872 height
: parseInt($(window
).height() * .75),
874 $(this).dialog('destroy').remove();
878 options
&& $.extend(true, settings
, options
);
881 if (settings
.dialog
) {
882 $('<div id="'+ settings
.target
.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings
.dialog
);
884 if (settings
.dialog
&& !settings
.dialog
.title
) {
885 $(settings
.target
).on('crmLoad', function(event
, data
) {
886 data
.title
&& $(this).dialog('option', 'title', data
.title
);
889 $(settings
.target
).crmSnippet(settings
).crmSnippet('refresh');
890 return $(settings
.target
);
893 CRM
.loadForm = function(url
, options
) {
899 refreshAction
: ['next_new', 'submit_savenext'],
900 cancelButton
: '.cancel.form-submit',
901 openInline
: 'a.button:not("[href=#], .no-popup")',
902 onCancel: function(event
) {},
903 onError: function(data
) {
905 $el
.html(data
.content
).trigger('crmLoad', data
).trigger('crmFormLoad', data
).trigger('crmFormError', data
);
906 if (typeof(data
.errors
) == 'object') {
907 $.each(data
.errors
, function(formElement
, msg
) {
908 $('[name="'+formElement
+'"]', $el
).crmError(msg
);
914 // Hack to make delete dialogs smaller
915 if (url
.indexOf('/delete') > 0 || url
.indexOf('action=delete') > 0) {
921 // Move options that belong to crmForm. Others will be passed through to crmSnippet
922 options
&& $.each(options
, function(key
, value
) {
923 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
924 settings
.crmForm
[key
] = value
;
927 settings
[key
] = value
;
931 var widget
= CRM
.loadPage(url
, settings
);
933 widget
.on('crmFormLoad', function(event
, data
) {
935 var settings
= $el
.crmSnippet('option', 'crmForm');
936 settings
.cancelButton
&& $(settings
.cancelButton
, this).click(function(event
) {
937 var returnVal
= settings
.onCancel
.call($el
, event
);
938 if (returnVal
!== false) {
939 $el
.trigger('crmFormCancel', event
);
940 if ($el
.data('uiDialog') && settings
.autoClose
) {
943 else if (!settings
.autoClose
) {
944 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
947 return returnVal
=== false;
949 if (settings
.validate
) {
950 $("form", this).validate(typeof(settings
.validate
) == 'object' ? settings
.validate
: CRM
.validate
.params
);
952 $("form", this).ajaxForm($.extend({
953 url
: data
.url
.replace(/reset=1[&]?/, ''),
955 success: function(response
) {
956 if (response
.status
!== 'form_error') {
957 $el
.crmSnippet('option', 'block') && $el
.unblock();
958 $el
.trigger('crmFormSuccess', response
);
959 // Reset form for e.g. "save and new"
960 if (response
.userContext
&& settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0) {
961 $el
.crmSnippet('option', 'url', response
.userContext
).crmSnippet('refresh');
963 else if ($el
.data('uiDialog') && settings
.autoClose
) {
966 else if (settings
.autoClose
=== false) {
967 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
971 response
.url
= data
.url
;
972 settings
.onError
.call($el
, response
);
975 beforeSerialize: function(form
, options
) {
976 if (window
.CKEDITOR
&& window
.CKEDITOR
.instances
) {
977 $.each(CKEDITOR
.instances
, function() {
978 this.updateElement
&& this.updateElement();
982 beforeSubmit: function(submission
) {
983 $el
.crmSnippet('option', 'block') && $el
.block();
984 $el
.trigger('crmFormSubmit', submission
);
986 }, settings
.ajaxForm
));
987 if (settings
.openInline
) {
988 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
989 $(settings
.openInline
, this).click(function(event
) {
990 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
998 // Preprocess all cj ajax calls to display messages
999 $(document
).ajaxSuccess(function(event
, xhr
, settings
) {
1001 if ((!settings
.dataType
|| settings
.dataType
== 'json') && xhr
.responseText
) {
1002 var response
= $.parseJSON(xhr
.responseText
);
1003 if (typeof(response
.crmMessages
) == 'object') {
1004 $.each(response
.crmMessages
, function(n
, msg
) {
1005 CRM
.alert(msg
.text
, msg
.title
, msg
.type
, msg
.options
);
1015 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1016 $('.crm-container').trigger('crmLoad');
1018 if ($('#crm-notification-container').length
) {
1019 // Initialize notifications
1020 $('#crm-notification-container').notify();
1021 messagesFromMarkup
.call($('#crm-container'));
1024 // bind the event for image popup
1025 $('body').on('click', 'a.crm-image-popup', function() {
1026 var o
= $('<div class="crm-container crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
1030 title
: ts('Preview'),
1039 $.fn
.crmAccordions = function (speed
) {
1040 var container
= $(this).length
> 0 ? $(this) : $('.crm-container');
1041 speed
= speed
=== undefined ? 200 : speed
;
1043 .off('click.crmAccordions')
1044 // Allow normal clicking of links
1045 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e
) {
1046 e
.stopPropagation
&& e
.stopPropagation();
1048 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
1049 if ($(this).parent().hasClass('collapsed')) {
1050 $(this).next().css('display', 'none').slideDown(speed
);
1053 $(this).next().css('display', 'block').slideUp(speed
);
1055 $(this).parent().toggleClass('collapsed');
1059 $.fn
.crmAccordionToggle = function (speed
) {
1060 $(this).each(function () {
1061 if ($(this).hasClass('collapsed')) {
1062 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed
);
1065 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed
);
1067 $(this).toggleClass('collapsed');
1072 * Clientside currency formatting
1074 * @param format - currency representation of the number 1234.56
1076 * @see CRM_Core_Resources::addCoreResources
1078 var currencyTemplate
;
1079 CRM
.formatMoney = function(value
, format
) {
1080 var decimal, separator
, sign
, i
, j
, result
;
1081 if (value
=== 'init' && format
) {
1082 currencyTemplate
= format
;
1085 format
= format
|| currencyTemplate
;
1086 result
= /1(.?)234(.?)56/.exec(format
);
1087 if (result
=== null) {
1088 return 'Invalid format passed to CRM.formatMoney';
1090 separator
= result
[1];
1091 decimal = result
[2];
1092 sign
= (value
< 0) ? '-' : '';
1093 //extracting the absolute value of the integer part of the number and converting to string
1094 i
= parseInt(value
= Math
.abs(value
).toFixed(2)) + '';
1095 j
= ((j
= i
.length
) > 3) ? j
% 3 : 0;
1096 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) : '');
1097 return format
.replace(/1.*234.*56/, result
);