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();
447 * Function to check activity status in relavent to activity date
449 * @param element message JSON object.
451 function activityStatus(message
) {
452 var d
= new Date(), time
= [], i
;
453 var currentDateTime
= d
.getTime()
454 var activityTime
= cj("input#activity_date_time_time").val().replace(":", "");
456 //chunk the time in bunch of 2 (hours,minutes,ampm)
457 for (i
= 0; i
< activityTime
.length
; i
+= 2) {
458 time
.push(activityTime
.slice(i
, i
+ 2));
460 var activityDate
= new Date(cj("input#activity_date_time_hidden").val());
462 d
.setFullYear(activityDate
.getFullYear());
463 d
.setMonth(activityDate
.getMonth());
464 d
.setDate(activityDate
.getDate());
465 var hours
= time
['0'];
466 var ampm
= time
['2'];
468 if (ampm
== "PM" && hours
!= 0 && hours
!= 12) {
469 // force arithmetic instead of string concatenation
470 hours
= hours
* 1 + 12;
473 if (ampm
== "AM" && hours
== 12) {
478 d
.setMinutes(time
['1']);
480 var activity_date_time
= d
.getTime();
482 var activityStatusId
= cj('#status_id').val();
484 if (activityStatusId
== 2 && currentDateTime
< activity_date_time
) {
485 if (!confirm(message
.completed
)) {
490 if (activity_date_time
&& activityStatusId
== 1 && currentDateTime
>= activity_date_time
) {
491 if (!confirm(message
.scheduled
)) {
498 CRM
.strings
= CRM
.strings
|| {};
499 CRM
.validate
= CRM
.validate
|| {
504 (function ($, undefined) {
506 $(document
).ready(function () {
508 $('.crm-container table.row-highlight').on('change', 'input.select-row, input.select-rows', function () {
509 var target
, table
= $(this).closest('table');
510 if ($(this).hasClass('select-rows')) {
511 target
= $('tbody tr', table
);
512 $('input.select-row', table
).prop('checked', $(this).prop('checked'));
515 target
= $(this).closest('tr');
516 $('input.select-rows', table
).prop('checked', $(".select-row:not(':checked')", table
).length
< 1);
518 target
.toggleClass('crm-row-selected', $(this).is(':checked'));
520 $('body').on('click', function (event
) {
521 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
522 if ($(event
.target
).is('.btn-slide')) {
523 $(event
.target
).addClass('btn-slide-active').find('.panel').show();
529 * Function to make multiselect boxes behave as fields in small screens
531 function advmultiselectResize() {
532 var amswidth
= $("#crm-container form:has(table.advmultiselect)").width();
533 if (amswidth
< 700) {
534 $("form table.advmultiselect td").css('display', 'block');
537 $("form table.advmultiselect td").css('display', 'table-cell');
539 var contactwidth
= $('#crm-container #mainTabContainer').width();
540 if (contactwidth
< 600) {
541 $('#crm-container #mainTabContainer').addClass('narrowpage');
542 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index
) {
544 if (index
% 2 == 0) {
545 $(this).parent().after('<tr class="narrowadded"></tr>');
548 $(this).parent().next().append(item
);
553 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
554 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
556 var parent
= $(this).parent();
557 $(this).parent().prev().append(nitem
);
558 if (parent
.children().size() == 0) {
562 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
564 var cformwidth
= $('#crm-container #Contact .contact_basic_information-section').width();
566 if (cformwidth
< 720) {
567 $('#crm-container .contact_basic_information-section').addClass('narrowform');
568 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
569 if (cformwidth
< 480) {
570 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
573 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
577 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
578 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
582 advmultiselectResize();
583 $(window
).resize(function () {
584 advmultiselectResize();
587 $.fn
.crmtooltip = function () {
589 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e
) {
590 $(this).addClass('crm-processed');
591 $(this).addClass('crm-tooltip-active');
592 var topDistance
= e
.pageY
- $(window
).scrollTop();
593 if (topDistance
< 300 | topDistance
< $(this).children('.crm-tooltip-wrapper').height()) {
594 $(this).addClass('crm-tooltip-down');
596 if (!$(this).children('.crm-tooltip-wrapper').length
) {
597 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
598 $(this).children().children('.crm-tooltip')
599 .html('<div class="crm-loading-element"></div>')
603 .on('mouseout', 'a.crm-summary-link', function () {
604 $(this).removeClass('crm-processed');
605 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
607 .on('click', 'a.crm-summary-link', false);
611 CRM
.help = function (title
, params
, url
) {
612 h
&& h
.close
&& h
.close();
616 h
= CRM
.alert('...', title
, 'crm-help crm-msg-loading', options
);
617 params
.class_name
= 'CRM_Core_Page_Inline_Help';
618 params
.type
= 'page';
619 $.ajax(url
|| CRM
.url('civicrm/ajax/inline'),
623 success: function (data
) {
624 $('#crm-notification-container .crm-help .notify-content:last').html(data
);
625 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
628 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
629 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
636 * @param string text Displayable message
637 * @param string title Displayable title
638 * @param string type 'alert'|'info'|'success'|'error' (default: 'alert')
639 * @param {object} options
641 * @see http://wiki.civicrm.org/confluence/display/CRM/Notifications+in+CiviCRM
643 CRM
.alert = function (text
, title
, type
, options
) {
644 type
= type
|| 'alert';
646 options
= options
|| {};
647 if ($('#crm-notification-container').length
) {
653 // By default, don't expire errors and messages containing links
655 expires
: (type
== 'error' || text
.indexOf('<a ') > -1) ? 0 : (text
? 10000 : 5000),
658 options
= $.extend(extra
, options
);
659 options
.expires
= options
.expires
=== false ? 0 : parseInt(options
.expires
, 10);
660 if (options
.unique
&& options
.unique
!== '0') {
661 $('#crm-notification-container .ui-notify-message').each(function () {
662 if (title
=== $('h1', this).html() && text
=== $('.notify-content', this).html()) {
663 $('.icon.ui-notify-close', this).click();
667 return $('#crm-notification-container').notify('create', params
, options
);
671 text
= title
+ "\n" + text
;
679 * Close whichever alert contains the given node
683 CRM
.closeAlertByChild = function (node
) {
684 $(node
).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
688 * Prompt the user for confirmation.
690 * @param buttons {object|function} key|value pairs where key == button label and value == callback function
691 * passing in a function instead of an object is a shortcut for a sinlgle button labeled "Continue"
692 * @param options {object|void} Override defaults, keys include 'title', 'message',
693 * see jQuery.dialog for full list of available params
695 CRM
.confirm = function (buttons
, options
, cancelLabel
) {
696 var dialog
, callbacks
= {};
697 cancelLabel
= cancelLabel
|| ts('Cancel');
699 title
: ts('Confirm Action'),
700 message
: ts('Are you sure you want to continue?'),
710 settings
.buttons
[cancelLabel
] = function () {
711 dialog
.dialog('close');
713 options
= options
|| {};
714 $.extend(settings
, options
);
715 if (typeof(buttons
) === 'function') {
716 callbacks
[ts('Continue')] = buttons
;
721 $.each(callbacks
, function (label
, callback
) {
722 settings
.buttons
[label
] = function () {
723 callback
.call(dialog
);
724 dialog
.dialog('close');
727 dialog
= $('<div class="crm-container crm-confirm-dialog"></div>')
728 .html(options
.message
)
735 * Sets an error message
736 * If called for a form item, title and removal condition will be handled automatically
738 $.fn
.crmError = function (text
, title
, options
) {
741 options
= options
|| {};
746 if ($(this).length
) {
748 var label
= $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
750 label
.addClass('crm-error');
751 var $label
= label
.clone();
752 if (text
== '' && $('.crm-marker', $label
).length
> 0) {
753 text
= $('.crm-marker', $label
).attr('title');
755 $('.crm-marker', $label
).remove();
756 title
= $label
.text();
759 $(this).addClass('error');
761 var msg
= CRM
.alert(text
, title
, 'error', $.extend(extra
, options
));
762 if ($(this).length
) {
764 setTimeout(function () {
765 ele
.one('change', function () {
766 msg
&& msg
.close
&& msg
.close();
767 ele
.removeClass('error');
768 label
.removeClass('crm-error');
775 // Display system alerts through js notifications
776 function messagesFromMarkup() {
777 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
778 var text
, title
= '';
779 $(this).removeClass('status messages');
780 var type
= $(this).attr('class').split(' ')[0] || 'alert';
781 type
= type
.replace('crm-', '');
782 $('.icon', this).remove();
783 if ($('.msg-text', this).length
> 0) {
784 text
= $('.msg-text', this).html();
785 title
= $('.msg-title', this).html();
788 text
= $(this).html();
790 var options
= $(this).data('options') || {};
792 // Duplicates were already removed server-side
793 options
.unique
= false;
794 CRM
.alert(text
, title
, type
, options
);
796 // Handle qf form errors
797 $('form :input.error', this).one('blur', function() {
798 // ignore autocomplete fields
799 if ($(this).is('.ac_input')) {
803 $('.ui-notify-message.error a.ui-notify-close').click();
804 $(this).removeClass('error');
805 $(this).next('span.crm-error').remove();
806 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
807 .removeClass('crm-error')
808 .find('.crm-error').removeClass('crm-error');
812 $.widget('civicrm.crmSnippet', {
819 isOriginalUrl: function() {
823 newUrl
= this._formatUrl(this.options
.url
),
824 oldUrl
= this._formatUrl(this._originalUrl
);
826 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
830 $.each(newUrl
.split('?')[1].split('&'), function(k
, v
) {
831 var arg
= v
.split('=');
832 args
[arg
[0]] = arg
[1];
834 $.each(oldUrl
.split('?')[1].split('&'), function(k
, v
) {
835 var arg
= v
.split('=');
836 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
842 resetUrl: function() {
843 this.options
.url
= this._originalUrl
;
845 _create: function() {
846 this.element
.addClass('crm-ajax-container');
847 if (!this.element
.is('.crm-container *')) {
848 this.element
.addClass('crm-container');
850 this._handleOrderLinks();
851 this.options
.url
? this.refresh() : this.options
.url
= document
.location
.href
;
852 this._originalUrl
= this.options
.url
;
854 _onFailure: function(data
) {
855 this.options
.block
&& this.element
.unblock();
856 this.element
.trigger('crmAjaxFail', data
);
857 CRM
.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
859 _formatUrl: function(url
) {
861 url
= url
.split('#')[0];
862 // Add snippet argument to url
863 if (url
.search(/[&?]snippet=/) < 0) {
864 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
866 url
= url
.replace(/snippet=[^&]*/, 'snippet=json');
870 // Hack to deal with civicrm legacy sort functionality
871 _handleOrderLinks: function() {
873 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
874 that
.options
.block
&& that
.element
.block();
875 $.getJSON(that
._formatUrl(this.href
)).done(function() {
878 e
.stopImmediatePropagation();
882 refresh: function() {
884 var url
= this._formatUrl(this.options
.url
);
885 this.options
.block
&& $('.blockOverlay', this.element
).length
< 1 && this.element
.block();
886 $.getJSON(url
, function(data
) {
887 if (typeof(data
) != 'object' || typeof(data
.content
) != 'string') {
888 that
._onFailure(data
);
892 that
.element
.html(data
.content
);
893 that
._handleOrderLinks();
894 that
.element
.trigger('crmLoad', data
);
895 that
.options
.crmForm
&& that
.element
.trigger('crmFormLoad', data
);
900 _destroy: function() {
901 this.element
.removeClass('crm-ajax-container');
906 CRM
.loadPage = function(url
, options
) {
908 target
: '#crm-ajax-dialog-' + (dialogCount
++),
911 if (!options
|| !options
.target
) {
915 height
: parseInt($(window
).height() * .75),
917 $(this).dialog('destroy');
922 options
&& $.extend(true, settings
, options
);
925 if (settings
.dialog
) {
926 $('<div id="'+ settings
.target
.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings
.dialog
);
928 if (settings
.dialog
&& !settings
.dialog
.title
) {
929 $(settings
.target
).on('crmLoad', function(event
, data
) {
930 data
.title
&& $(this).dialog('option', 'title', data
.title
);
933 return $(settings
.target
).crmSnippet(settings
);
936 CRM
.loadForm = function(url
, options
) {
942 refreshAction
: ['next_new', 'submit_savenext'],
943 cancelButton
: '.cancel.form-submit',
944 openInline
: 'a.button:not([href="#"])',
945 onCancel: function(event
) {},
946 onError: function(data
) {
948 $el
.html(data
.content
).trigger('crmLoad', data
).trigger('crmFormLoad', data
);
949 if (typeof(data
.errors
) == 'object') {
950 $.each(data
.errors
, function(formElement
, msg
) {
951 $('[name="'+formElement
+'"]', $el
).crmError(msg
);
957 // Move options that belong to crmForm. Others will be passed through to crmSnippet
958 options
&& $.each(options
, function(key
, value
) {
959 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
960 settings
.crmForm
[key
] = value
;
963 settings
[key
] = value
;
967 var widget
= CRM
.loadPage(url
, settings
);
969 widget
.on('crmFormLoad', function(event
, data
) {
971 var settings
= $el
.crmSnippet('option', 'crmForm');
972 settings
.cancelButton
&& $(settings
.cancelButton
, this).click(function(event
) {
973 var returnVal
= settings
.onCancel
.call($el
, event
);
974 if (returnVal
!== false) {
975 $el
.trigger('crmFormCancel', event
);
976 if ($el
.data('uiDialog') && settings
.autoClose
) {
979 else if (!settings
.autoClose
) {
980 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
983 return returnVal
=== false;
985 if (settings
.validate
) {
986 $("form", this).validate(typeof(settings
.validate
) == 'object' ? settings
.validate
: CRM
.validate
.params
);
988 $("form", this).ajaxForm($.extend({
989 url
: data
.url
.replace(/reset=1[&]?/, ''),
991 success: function(response
) {
992 if (response
.status
=== 'success') {
993 $el
.crmSnippet('option', 'block') && $el
.unblock();
994 $el
.trigger('crmFormSuccess', response
);
995 // Reset form for e.g. "save and new"
996 if (response
.userContext
&& settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0) {
997 $el
.crmSnippet('option', 'url', response
.userContext
).crmSnippet('refresh');
999 else if ($el
.data('uiDialog') && settings
.autoClose
) {
1000 $el
.dialog('close');
1002 else if (settings
.autoClose
=== false) {
1003 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
1007 response
.url
= data
.url
;
1008 settings
.onError
.call($el
, response
);
1011 beforeSubmit: function(submission
) {
1012 $el
.crmSnippet('option', 'block') && $el
.block();
1013 $el
.trigger('crmFormSubmit', submission
);
1015 }, settings
.ajaxForm
));
1016 if (settings
.openInline
) {
1017 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
1018 $(settings
.openInline
, this).click(function(event
) {
1019 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
1027 // Preprocess all cj ajax calls to display messages
1028 $(document
).ajaxSuccess(function(event
, xhr
, settings
) {
1030 if ((!settings
.dataType
|| settings
.dataType
== 'json') && xhr
.responseText
) {
1031 var response
= $.parseJSON(xhr
.responseText
);
1032 if (typeof(response
.crmMessages
) == 'object') {
1033 $.each(response
.crmMessages
, function(n
, msg
) {
1034 CRM
.alert(msg
.text
, msg
.title
, msg
.type
, msg
.options
);
1044 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1045 $('.crm-container').trigger('crmLoad');
1047 if ($('#crm-notification-container').length
) {
1048 // Initialize notifications
1049 $('#crm-notification-container').notify();
1050 messagesFromMarkup
.call($('#crm-container'));
1053 // bind the event for image popup
1054 $('body').on('click', 'a.crm-image-popup', function() {
1055 var o
= $('<div class="crm-container crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
1059 title
: ts('Preview'),
1068 $.fn
.crmAccordions = function (speed
) {
1069 var container
= $(this).length
> 0 ? $(this) : $('.crm-container');
1070 speed
= speed
=== undefined ? 200 : speed
;
1072 .off('click.crmAccordions')
1073 // Allow normal clicking of links
1074 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e
) {
1075 e
.stopPropagation
&& e
.stopPropagation();
1077 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
1078 if ($(this).parent().hasClass('collapsed')) {
1079 $(this).next().css('display', 'none').slideDown(speed
);
1082 $(this).next().css('display', 'block').slideUp(speed
);
1084 $(this).parent().toggleClass('collapsed');
1088 $.fn
.crmAccordionToggle = function (speed
) {
1089 $(this).each(function () {
1090 if ($(this).hasClass('collapsed')) {
1091 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed
);
1094 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed
);
1096 $(this).toggleClass('collapsed');
1101 * Clientside currency formatting
1103 * @param format - currency representation of the number 1234.56
1105 * @see CRM_Core_Resources::addCoreResources
1107 var currencyTemplate
;
1108 CRM
.formatMoney = function(value
, format
) {
1109 var decimal, separator
, sign
, i
, j
, result
;
1110 if (value
=== 'init' && format
) {
1111 currencyTemplate
= format
;
1114 format
= format
|| currencyTemplate
;
1115 result
= /1(.?)234(.?)56/.exec(format
);
1116 if (result
=== null) {
1117 return 'Invalid format passed to CRM.formatMoney';
1119 separator
= result
[1];
1120 decimal = result
[2];
1121 sign
= (value
< 0) ? '-' : '';
1122 //extracting the absolute value of the integer part of the number and converting to string
1123 i
= parseInt(value
= Math
.abs(value
).toFixed(2)) + '';
1124 j
= ((j
= i
.length
) > 3) ? j
% 3 : 0;
1125 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) : '');
1126 return format
.replace(/1.*234.*56/, result
);