CRM-13930 - fix jquery.menu namespace
[civicrm-core.git] / js / Common.js
CommitLineData
6a488035
TO
1/*
2 +--------------------------------------------------------------------+
232624b1 3 | CiviCRM version 4.4 |
6a488035
TO
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 +--------------------------------------------------------------------+
0f5816a6 25 */
6a488035
TO
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
33var CRM = CRM || {};
34var 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 */
44function ts(text, params) {
7553cf23 45 "use strict";
6a488035 46 text = CRM.strings[text] || text;
2788147f 47 if (typeof(params) === 'object') {
6a488035 48 for (var i in params) {
32155ad6 49 if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') {
2788147f 50 // sprintf emulation: escape % characters in the replacements to avoid conflicts
32155ad6 51 text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-'));
2788147f 52 }
6a488035
TO
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 */
0f5816a6
KJ
71function 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;
6a488035 82 }
0f5816a6
KJ
83 else {
84 alert('showBlocks array item not in .tpl = ' + showBlocks[i]);
85 }
86 }
6a488035 87
0f5816a6
KJ
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]);
6a488035 97 }
0f5816a6 98 }
6a488035
TO
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
0f5816a6
KJ
113 */
114function 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 }
6a488035 144 }
0f5816a6
KJ
145 }
146 }
6a488035 147
0f5816a6
KJ
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 }
6a488035 160 }
0f5816a6
KJ
161 else {
162 if (invert) {
163 cj('#' + target[j]).show();
164 }
165 else {
166 cj('#' + target[j]).hide();
167 }
168 }
169 }
6a488035 170 }
0f5816a6 171 }
6a488035
TO
172}
173
174/**
175 *
176 * Function for checking ALL or unchecking ALL check boxes in a resultset page.
177 *
178 * @access public
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) );"
183 *
184 * @return
185 */
186function toggleCheckboxVals(fldPrefix, object) {
0f5816a6
KJ
187 if (object.id == 'toggleSelect' && cj(object).is(':checked')) {
188 cj('Input[id*="' + fldPrefix + '"],Input[id*="toggleSelect"]').attr('checked', true);
189 }
190 else {
191 cj('Input[id*="' + fldPrefix + '"],Input[id*="toggleSelect"]').attr('checked', false);
192 }
193 // change the class of selected rows
194 on_load_init_checkboxes(object.form.name);
6a488035
TO
195}
196
197function countSelectedCheckboxes(fldPrefix, form) {
0f5816a6
KJ
198 fieldCount = 0;
199 for (i = 0; i < form.elements.length; i++) {
200 fpLen = fldPrefix.length;
201 if (form.elements[i].type == 'checkbox' && form.elements[i].name.slice(0, fpLen) == fldPrefix && form.elements[i].checked == true) {
202 fieldCount++;
6a488035 203 }
0f5816a6
KJ
204 }
205 return fieldCount;
6a488035
TO
206}
207
208/**
209 * Function to enable task action select
210 */
0f5816a6
KJ
211function toggleTaskAction(status) {
212 var radio_ts = document.getElementsByName('radio_ts');
213 if (!radio_ts[1]) {
214 radio_ts[0].checked = true;
215 }
216 if (radio_ts[0].checked || radio_ts[1].checked) {
217 status = true;
218 }
219
220 var formElements = ['task', 'Go', 'Print'];
221 for (var i = 0; i < formElements.length; i++) {
222 var element = document.getElementById(formElements[i]);
223 if (element) {
224 if (status) {
225 element.disabled = false;
226 }
227 else {
228 element.disabled = true;
229 }
6a488035 230 }
0f5816a6 231 }
6a488035
TO
232}
233
234/**
235 * This function is used to check if any actio is selected and also to check if any contacts are checked.
236 *
237 * @access public
238 * @param fldPrefix - common string which precedes unique checkbox ID and identifies field as
239 * belonging to the resultset's checkbox collection
240 * @param form - name of form that checkboxes are part of
241 * Sample usage: onClick="javascript:checkPerformAction('chk_', myForm );"
242 *
243 */
0f5816a6
KJ
244function checkPerformAction(fldPrefix, form, taskButton, selection) {
245 var cnt;
246 var gotTask = 0;
247
248 // taskButton TRUE means we don't need to check the 'task' field - it's a button-driven task
249 if (taskButton == 1) {
250 gotTask = 1;
251 }
252 else {
253 if (document.forms[form].task.selectedIndex) {
254 //force user to select all search contacts, CRM-3711
255 if (document.forms[form].task.value == 13 || document.forms[form].task.value == 14) {
256 var toggleSelect = document.getElementsByName('toggleSelect');
257 if (toggleSelect[0].checked || document.forms[form].radio_ts[0].checked) {
258 return true;
6a488035 259 }
0f5816a6
KJ
260 else {
261 alert("Please select all contacts for this action.\n\nTo use the entire set of search results, click the 'all records' radio button.");
262 return false;
263 }
264 }
265 gotTask = 1;
6a488035 266 }
0f5816a6 267 }
6a488035 268
0f5816a6
KJ
269 if (gotTask == 1) {
270 // If user wants to perform action on ALL records and we have a task, return (no need to check further)
271 if (document.forms[form].radio_ts[0].checked) {
272 return true;
273 }
6a488035 274
0f5816a6
KJ
275 cnt = (selection == 1) ? countSelections() : countSelectedCheckboxes(fldPrefix, document.forms[form]);
276 if (!cnt) {
277 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 return false;
6a488035 279 }
0f5816a6
KJ
280 }
281 else {
282 alert("Please select an action from the drop-down menu.");
283 return false;
284 }
6a488035
TO
285}
286
287/**
288 * This function changes the style for a checkbox block when it is selected.
289 *
290 * @access public
291 * @param chkName - it is name of the checkbox
292 * @return null
293 */
0f5816a6
KJ
294function checkSelectedBox(chkName) {
295 var checkElement = cj('#' + chkName);
296 if (checkElement.attr('checked')) {
297 cj('input[value=ts_sel]:radio').attr('checked', true);
298 checkElement.parents('tr').addClass('crm-row-selected');
299 }
300 else {
301 checkElement.parents('tr').removeClass('crm-row-selected');
302 }
6a488035
TO
303}
304
305/**
306 * This function is to show the row with selected checkbox in different color
307 * @param form - name of form that checkboxes are part of
308 *
309 * @access public
310 * @return null
311 */
0f5816a6
KJ
312function on_load_init_checkboxes(form) {
313 var formName = form;
314 var fldPrefix = 'mark_x';
315 for (i = 0; i < document.forms[formName].elements.length; i++) {
316 fpLen = fldPrefix.length;
317 if (document.forms[formName].elements[i].type == 'checkbox' && document.forms[formName].elements[i].name.slice(0, fpLen) == fldPrefix) {
318 checkSelectedBox(document.forms[formName].elements[i].name, formName);
6a488035 319 }
0f5816a6 320 }
6a488035
TO
321}
322
323/**
324 * Function to change the color of the class
325 *
326 * @param form - name of the form
327 * @param rowid - id of the <tr>, <div> you want to change
328 *
329 * @access public
330 * @return null
331 */
0f5816a6
KJ
332function changeRowColor(rowid, form) {
333 switch (document.getElementById(rowid).className) {
334 case 'even-row' :
335 document.getElementById(rowid).className = 'selected even-row';
336 break;
337 case 'odd-row' :
338 document.getElementById(rowid).className = 'selected odd-row';
339 break;
340 case 'selected even-row' :
341 document.getElementById(rowid).className = 'even-row';
342 break;
343 case 'selected odd-row' :
344 document.getElementById(rowid).className = 'odd-row';
345 break;
346 case 'form-item' :
347 document.getElementById(rowid).className = 'selected';
348 break;
349 case 'selected' :
350 document.getElementById(rowid).className = 'form-item';
351 }
6a488035
TO
352}
353
354/**
355 * This function is to show the row with selected checkbox in different color
356 * @param form - name of form that checkboxes are part of
357 *
358 * @access public
359 * @return null
360 */
0f5816a6
KJ
361function on_load_init_check(form) {
362 for (i = 0; i < document.forms[form].elements.length; i++) {
363 if (( document.forms[form].elements[i].type == 'checkbox'
364 && document.forms[form].elements[i].checked == true )
365 || ( document.forms[form].elements[i].type == 'hidden'
366 && document.forms[form].elements[i].value == 1 )) {
367 var ss = document.forms[form].elements[i].id;
368 var row = 'rowid' + ss;
369 changeRowColor(row, form);
6a488035 370 }
0f5816a6 371 }
6a488035
TO
372}
373
374/**
375 * reset all the radio buttons with a given name
376 *
377 * @param string fieldName
378 * @param object form
379 * @return null
380 */
381function unselectRadio(fieldName, form) {
0f5816a6
KJ
382 for (i = 0; i < document.forms[form].elements.length; i++) {
383 if (document.forms[form].elements[i].name == fieldName) {
384 document.forms[form].elements[i].checked = false;
6a488035 385 }
0f5816a6
KJ
386 }
387 return;
6a488035
TO
388}
389
390/**
391 * Function to change button text and disable one it is clicked
392 *
393 * @param obj object - the button clicked
394 * @param formID string - the id of the form being submitted
395 * @param string procText - button text after user clicks it
396 * @return null
397 */
0f5816a6 398var submitcount = 0;
c6edd786 399/* Changes button label on submit, and disables button after submit for newer browsers.
400 Puts up alert for older browsers. */
0f5816a6
KJ
401function submitOnce(obj, formId, procText) {
402 // if named button clicked, change text
403 if (obj.value != null) {
404 obj.value = procText + " ...";
405 }
406 if (document.getElementById) { // disable submit button for newer browsers
407 obj.disabled = true;
408 document.getElementById(formId).submit();
409 return true;
410 }
411 else { // for older browsers
412 if (submitcount == 0) {
413 submitcount++;
414 return true;
415 }
416 else {
417 alert("Your request is currently being processed ... Please wait.");
418 return false;
6a488035 419 }
0f5816a6 420 }
6a488035
TO
421}
422
423function popUp(URL) {
424 day = new Date();
0f5816a6 425 id = day.getTime();
6a488035
TO
426 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');");
427}
428
6a488035
TO
429/**
430 * Function to show / hide the row in optionFields
431 *
432 * @param element name index, that whose innerHTML is to hide else will show the hidden row.
433 */
0f5816a6
KJ
434function showHideRow(index) {
435 if (index) {
436 cj('tr#optionField_' + index).hide();
437 if (cj('table#optionField tr:hidden:first').length) {
438 cj('div#optionFieldLink').show();
6a488035 439 }
0f5816a6
KJ
440 }
441 else {
442 cj('table#optionField tr:hidden:first').show();
443 if (!cj('table#optionField tr:hidden:last').length) {
444 cj('div#optionFieldLink').hide();
445 }
446 }
447 return false;
6a488035
TO
448}
449
450/**
451 * Function to check activity status in relavent to activity date
452 *
453 * @param element message JSON object.
454 */
0f5816a6
KJ
455function activityStatus(message) {
456 var d = new Date(), time = [], i;
457 var currentDateTime = d.getTime()
458 var activityTime = cj("input#activity_date_time_time").val().replace(":", "");
459
460 //chunk the time in bunch of 2 (hours,minutes,ampm)
461 for (i = 0; i < activityTime.length; i += 2) {
462 time.push(activityTime.slice(i, i + 2));
463 }
464 var activityDate = new Date(cj("input#activity_date_time_hidden").val());
6a488035 465
0f5816a6
KJ
466 d.setFullYear(activityDate.getFullYear());
467 d.setMonth(activityDate.getMonth());
468 d.setDate(activityDate.getDate());
469 var hours = time['0'];
470 var ampm = time['2'];
6a488035 471
0f5816a6
KJ
472 if (ampm == "PM" && hours != 0 && hours != 12) {
473 // force arithmetic instead of string concatenation
474 hours = hours * 1 + 12;
475 }
476 else {
477 if (ampm == "AM" && hours == 12) {
478 hours = 0;
6a488035 479 }
0f5816a6
KJ
480 }
481 d.setHours(hours);
482 d.setMinutes(time['1']);
6a488035 483
0f5816a6 484 var activity_date_time = d.getTime();
6a488035 485
0f5816a6 486 var activityStatusId = cj('#status_id').val();
6a488035 487
0f5816a6
KJ
488 if (activityStatusId == 2 && currentDateTime < activity_date_time) {
489 if (!confirm(message.completed)) {
490 return false;
491 }
492 }
493 else {
494 if (activity_date_time && activityStatusId == 1 && currentDateTime >= activity_date_time) {
495 if (!confirm(message.scheduled)) {
496 return false;
497 }
6a488035 498 }
0f5816a6 499 }
6a488035
TO
500}
501
6a488035
TO
502CRM.strings = CRM.strings || {};
503CRM.validate = CRM.validate || {
504 params: {},
505 functions: []
506};
507
0f5816a6 508(function ($, undefined) {
7553cf23 509 "use strict";
0f5816a6 510 $(document).ready(function () {
6a488035 511 $().crmtooltip();
0f5816a6 512 $('.crm-container table.row-highlight').on('change', 'input.select-row, input.select-rows', function () {
e24b17b9 513 var target, table = $(this).closest('table');
6a488035 514 if ($(this).hasClass('select-rows')) {
e24b17b9 515 target = $('tbody tr', table);
6a488035
TO
516 $('input.select-row', table).prop('checked', $(this).prop('checked'));
517 }
518 else {
e24b17b9 519 target = $(this).closest('tr');
6a488035
TO
520 $('input.select-rows', table).prop('checked', $(".select-row:not(':checked')", table).length < 1);
521 }
522 target.toggleClass('crm-row-selected', $(this).is(':checked'));
523 });
8d86fc13
CW
524 $('body').on('click', function (event) {
525 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
e24b17b9 526 if ($(event.target).is('.btn-slide')) {
8d86fc13 527 $(event.target).addClass('btn-slide-active').find('.panel').show();
6a488035
TO
528 }
529 });
530 });
148c4e8d
CW
531
532 /**
533 * Function to make multiselect boxes behave as fields in small screens
534 */
535 function advmultiselectResize() {
536 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
537 if (amswidth < 700) {
538 $("form table.advmultiselect td").css('display', 'block');
0f5816a6
KJ
539 }
540 else {
148c4e8d
CW
541 $("form table.advmultiselect td").css('display', 'table-cell');
542 }
543 var contactwidth = $('#crm-container #mainTabContainer').width();
544 if (contactwidth < 600) {
545 $('#crm-container #mainTabContainer').addClass('narrowpage');
0f5816a6 546 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
148c4e8d 547 if (index > 1) {
0f5816a6 548 if (index % 2 == 0) {
148c4e8d
CW
549 $(this).parent().after('<tr class="narrowadded"></tr>');
550 }
551 var item = $(this);
552 $(this).parent().next().append(item);
553 }
554 });
0f5816a6
KJ
555 }
556 else {
148c4e8d 557 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
0f5816a6 558 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
148c4e8d
CW
559 var nitem = $(this);
560 var parent = $(this).parent();
561 $(this).parent().prev().append(nitem);
0f5816a6 562 if (parent.children().size() == 0) {
148c4e8d
CW
563 parent.remove();
564 }
565 });
566 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
567 }
568 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
0f5816a6 569
148c4e8d
CW
570 if (cformwidth < 720) {
571 $('#crm-container .contact_basic_information-section').addClass('narrowform');
572 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
573 if (cformwidth < 480) {
574 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
0f5816a6
KJ
575 }
576 else {
148c4e8d
CW
577 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
578 }
0f5816a6
KJ
579 }
580 else {
148c4e8d
CW
581 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
582 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
583 }
584 }
0f5816a6 585
148c4e8d 586 advmultiselectResize();
0f5816a6 587 $(window).resize(function () {
6a488035
TO
588 advmultiselectResize();
589 });
590
0f5816a6 591 $.fn.crmtooltip = function () {
2c29c2ac
RN
592 $(document)
593 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
594 $(this).addClass('crm-processed');
e24b17b9
CW
595 $(this).addClass('crm-tooltip-active');
596 var topDistance = e.pageY - $(window).scrollTop();
597 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
598 $(this).addClass('crm-tooltip-down');
599 }
600 if (!$(this).children('.crm-tooltip-wrapper').length) {
6a488035
TO
601 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
602 $(this).children().children('.crm-tooltip')
603 .html('<div class="crm-loading-element"></div>')
604 .load(this.href);
605 }
606 })
2c29c2ac
RN
607 .on('mouseout', 'a.crm-summary-link', function () {
608 $(this).removeClass('crm-processed');
e24b17b9
CW
609 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
610 })
2c29c2ac 611 .on('click', 'a.crm-summary-link', false);
6a488035
TO
612 };
613
614 var h;
8e3272a1 615 CRM.help = function (title, params, url) {
6a488035
TO
616 h && h.close && h.close();
617 var options = {
618 expires: 0
619 };
620 h = CRM.alert('...', title, 'crm-help crm-msg-loading', options);
621 params.class_name = 'CRM_Core_Page_Inline_Help';
622 params.type = 'page';
8e3272a1 623 $.ajax(url || CRM.url('civicrm/ajax/inline'),
6a488035
TO
624 {
625 data: params,
626 dataType: 'html',
e24b17b9 627 success: function (data) {
6a488035
TO
628 $('#crm-notification-container .crm-help .notify-content:last').html(data);
629 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
630 },
e24b17b9 631 error: function () {
6a488035
TO
632 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
633 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
634 }
635 }
636 );
637 };
638
639 /**
640 * @param string text Displayable message
641 * @param string title Displayable title
642 * @param string type 'alert'|'info'|'success'|'error' (default: 'alert')
643 * @param {object} options
644 * @return {*}
645 * @see http://wiki.civicrm.org/confluence/display/CRM/Notifications+in+CiviCRM
646 */
0f5816a6 647 CRM.alert = function (text, title, type, options) {
6a488035
TO
648 type = type || 'alert';
649 title = title || '';
650 options = options || {};
651 if ($('#crm-notification-container').length) {
652 var params = {
653 text: text,
654 title: title,
655 type: type
656 };
657 // By default, don't expire errors and messages containing links
658 var extra = {
659 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
660 unique: true
661 };
662 options = $.extend(extra, options);
e24b17b9 663 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
6a488035 664 if (options.unique && options.unique !== '0') {
0f5816a6 665 $('#crm-notification-container .ui-notify-message').each(function () {
6a488035
TO
666 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
667 $('.icon.ui-notify-close', this).click();
668 }
669 });
670 }
671 return $('#crm-notification-container').notify('create', params, options);
672 }
673 else {
674 if (title.length) {
675 text = title + "\n" + text;
676 }
677 alert(text);
678 return null;
679 }
e24b17b9 680 };
6a488035
TO
681
682 /**
683 * Close whichever alert contains the given node
684 *
685 * @param node
686 */
0f5816a6 687 CRM.closeAlertByChild = function (node) {
6a488035 688 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
e24b17b9 689 };
6a488035
TO
690
691 /**
692 * Prompt the user for confirmation.
693 *
7553cf23
CW
694 * @param buttons {object|function} key|value pairs where key == button label and value == callback function
695 * passing in a function instead of an object is a shortcut for a sinlgle button labeled "Continue"
696 * @param options {object|void} Override defaults, keys include 'title', 'message',
697 * see jQuery.dialog for full list of available params
6a488035 698 */
706cff6d 699 CRM.confirm = function (buttons, options, cancelLabel) {
7553cf23 700 var dialog, callbacks = {};
706cff6d 701 cancelLabel = cancelLabel || ts('Cancel');
7553cf23
CW
702 var settings = {
703 title: ts('Confirm Action'),
704 message: ts('Are you sure you want to continue?'),
6a488035
TO
705 resizable: false,
706 modal: true,
0d5f99d4 707 width: 'auto',
0f5816a6
KJ
708 close: function () {
709 $(dialog).remove();
710 },
7553cf23
CW
711 buttons: {}
712 };
706cff6d
KJ
713
714 settings.buttons[cancelLabel] = function () {
0f5816a6
KJ
715 dialog.dialog('close');
716 };
7553cf23
CW
717 options = options || {};
718 $.extend(settings, options);
719 if (typeof(buttons) === 'function') {
720 callbacks[ts('Continue')] = buttons;
0f5816a6
KJ
721 }
722 else {
7553cf23
CW
723 callbacks = buttons;
724 }
0f5816a6
KJ
725 $.each(callbacks, function (label, callback) {
726 settings.buttons[label] = function () {
7553cf23
CW
727 callback.call(dialog);
728 dialog.dialog('close');
e24b17b9 729 };
6a488035 730 });
7553cf23
CW
731 dialog = $('<div class="crm-container crm-confirm-dialog"></div>')
732 .html(options.message)
733 .appendTo('body')
734 .dialog(settings);
735 return dialog;
e24b17b9 736 };
6a488035
TO
737
738 /**
739 * Sets an error message
740 * If called for a form item, title and removal condition will be handled automatically
741 */
0f5816a6 742 $.fn.crmError = function (text, title, options) {
6a488035
TO
743 title = title || '';
744 text = text || '';
745 options = options || {};
746
747 var extra = {
748 expires: 0
749 };
750 if ($(this).length) {
751 if (title == '') {
752 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
753 if (label.length) {
754 label.addClass('crm-error');
755 var $label = label.clone();
756 if (text == '' && $('.crm-marker', $label).length > 0) {
757 text = $('.crm-marker', $label).attr('title');
758 }
759 $('.crm-marker', $label).remove();
760 title = $label.text();
761 }
762 }
763 $(this).addClass('error');
764 }
765 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
766 if ($(this).length) {
767 var ele = $(this);
0f5816a6
KJ
768 setTimeout(function () {
769 ele.one('change', function () {
770 msg && msg.close && msg.close();
771 ele.removeClass('error');
772 label.removeClass('crm-error');
773 });
774 }, 1000);
6a488035
TO
775 }
776 return msg;
e24b17b9 777 };
6a488035
TO
778
779 // Display system alerts through js notifications
780 function messagesFromMarkup() {
0f5816a6 781 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
e24b17b9 782 var text, title = '';
6a488035
TO
783 $(this).removeClass('status messages');
784 var type = $(this).attr('class').split(' ')[0] || 'alert';
785 type = type.replace('crm-', '');
786 $('.icon', this).remove();
6a488035 787 if ($('.msg-text', this).length > 0) {
e24b17b9 788 text = $('.msg-text', this).html();
6a488035
TO
789 title = $('.msg-title', this).html();
790 }
791 else {
e24b17b9 792 text = $(this).html();
6a488035
TO
793 }
794 var options = $(this).data('options') || {};
795 $(this).remove();
796 // Duplicates were already removed server-side
797 options.unique = false;
798 CRM.alert(text, title, type, options);
799 });
800 // Handle qf form errors
801 $('form :input.error', this).one('blur', function() {
ef04c554 802 // ignore autocomplete fields
23246a80 803 if ($(this).is('.ac_input')) {
804 return;
805 }
ef04c554 806
6a488035
TO
807 $('.ui-notify-message.error a.ui-notify-close').click();
808 $(this).removeClass('error');
809 $(this).next('span.crm-error').remove();
810 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
811 .removeClass('crm-error')
812 .find('.crm-error').removeClass('crm-error');
813 });
814 }
815
205bb8ae
CW
816 $.widget('civicrm.crmSnippet', {
817 options: {
a73f25bb 818 url: null,
205bb8ae
CW
819 block: true,
820 crmForm: null
821 },
fa3a5fe2
CW
822 _originalUrl: null,
823 isOriginalUrl: function() {
824 var args = {}, same = true;
825 // Compare path
826 if (this.options.url.split('?')[0] !== this._originalUrl.split('?')[0]) {
827 return false;
828 }
829 // Compare arguments
830 $.each(this.options.url.split('?')[1].split('&'), function(k, v) {
831 var arg = v.split('=');
832 args[arg[0]] = arg[1];
833 });
834 $.each(this._originalUrl.split('?')[1].split('&'), function(k, v) {
835 var arg = v.split('=');
836 if (args[arg[0]] !== undefined && arg[1] !== args[arg[0]]) {
837 same = false;
838 }
839 });
840 return same;
841 },
842 resetUrl: function() {
843 this.options.url = this._originalUrl;
844 },
205bb8ae 845 _create: function() {
205bb8ae
CW
846 this.element.addClass('crm-ajax-container');
847 if (!this.element.is('.crm-container *')) {
848 this.element.addClass('crm-container');
849 }
4a140040 850 this._handleOrderLinks();
a73f25bb 851 this.options.url ? this.refresh() : this.options.url = document.location.href;
fa3a5fe2 852 this._originalUrl = this.options.url;
205bb8ae
CW
853 },
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');
858 },
859 _formatUrl: function(url) {
860 // Add snippet argument to url
861 if (url.search(/[&?]snippet=/) < 0) {
fc05b8da 862 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
205bb8ae
CW
863 }
864 return url;
865 },
4a140040
CW
866 _handleOrderLinks: function() {
867 var that = this;
868 $('a.crm-weight-arrow', that.element).click(function(e) {
869 that.options.block && that.element.block();
870 $.getJSON(that._formatUrl(this.href)).done(function() {
871 that.refresh();
872 });
873 e.stopImmediatePropagation();
874 return false;
875 });
876 },
205bb8ae
CW
877 refresh: function() {
878 var that = this;
879 var url = this._formatUrl(this.options.url);
4a140040 880 this.options.block && $('.blockOverlay', this.element).length < 1 && this.element.block();
205bb8ae
CW
881 $.getJSON(url, function(data) {
882 if (typeof(data) != 'object' || typeof(data.content) != 'string') {
883 that._onFailure(data);
884 return;
885 }
886 data.url = url;
4a140040
CW
887 that.element.html(data.content);
888 that._handleOrderLinks();
889 that.element.trigger('crmLoad', data);
205bb8ae
CW
890 that.options.crmForm && that.element.trigger('crmFormLoad', data);
891 }).fail(function() {
892 that._onFailure();
893 });
894 }
895 });
896
0e017a41 897 var dialogCount = 0;
d4e4e9df 898 CRM.loadPage = function(url, options) {
d4e4e9df 899 var settings = {
0e017a41 900 target: '#crm-ajax-dialog-' + (dialogCount++),
83df6b4a 901 dialog: {
d4e4e9df 902 modal: true,
f84151fd
CW
903 width: '65%',
904 height: parseInt($(window).height() * .75),
d4e4e9df
CW
905 close: function() {
906 $(this).dialog('destroy');
907 $(this).remove();
908 }
205bb8ae 909 }
d4e4e9df 910 };
205bb8ae 911 options && $.extend(true, settings, options);
0e017a41 912 settings.url = url;
83df6b4a 913 // Create new dialog
0e017a41 914 if (settings.dialog !== false && settings.target[0] == '#') {
205bb8ae 915 $('<div id="'+ settings.target.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings.dialog);
d4e4e9df 916 }
205bb8ae
CW
917 if (settings.dialog && !settings.dialog.title) {
918 $(settings.target).on('crmLoad', function(event, data) {
919 data.title && $(this).dialog('option', 'title', data.title);
920 });
921 }
205bb8ae 922 return $(settings.target).crmSnippet(settings);
d4e4e9df
CW
923 };
924
925 CRM.loadForm = function(url, options) {
d4e4e9df 926 var settings = {
205bb8ae
CW
927 crmForm: {
928 ajaxForm: {},
205bb8ae
CW
929 autoClose: true,
930 validate: true,
931 refreshAction: ['next_new', 'submit_savenext'],
932 cancelButton: '.cancel.form-submit',
933 openInline: 'a.button',
934 onCancel: function(event) {},
935 onError: function(data) {
936 var $el = $(this);
937 $el.html(data.content).trigger('crmLoad', data).trigger('crmFormLoad', data);
938 if (typeof(data.errors) == 'object') {
939 $.each(data.errors, function(formElement, msg) {
940 $('[name="'+formElement+'"]', $el).crmError(msg);
941 });
942 }
d4e4e9df 943 }
d4e4e9df
CW
944 }
945 };
205bb8ae
CW
946 // Move options that belong to crmForm. Others will be passed through to crmSnippet
947 options && $.each(options, function(key, value) {
948 if (typeof(settings.crmForm[key]) !== 'undefined') {
949 settings.crmForm[key] = value;
950 }
951 else {
952 settings[key] = value;
953 }
954 });
205bb8ae
CW
955
956 var widget = CRM.loadPage(url, settings);
957
958 widget.on('crmFormLoad', function(event, data) {
959 var $el = $(this);
960 var settings = $el.data('crmSnippet').options.crmForm;
205bb8ae
CW
961 settings.cancelButton && $(settings.cancelButton, this).click(function(event) {
962 var returnVal = settings.onCancel.call($el, event);
963 if (returnVal !== false) {
964 $el.trigger('crmFormCancel', event);
fa3a5fe2
CW
965 if ($el.data('dialog') && settings.autoClose) {
966 $el.dialog('close');
967 }
968 else if (!settings.autoClose) {
969 $el.crmSnippet('resetUrl').crmSnippet('refresh');
970 }
0e017a41 971 }
205bb8ae
CW
972 return returnVal === false;
973 });
d4e4e9df 974 if (settings.validate) {
0e017a41 975 $("form", this).validate(typeof(settings.validate) == 'object' ? settings.validate : CRM.validate.params);
d4e4e9df 976 }
205bb8ae 977 $("form", this).ajaxForm($.extend({
fa3a5fe2 978 url: data.url.replace(/reset=1[&]?/, ''),
d4e4e9df
CW
979 dataType: 'json',
980 success: function(response) {
981 if (response.status == 'success') {
36876f55 982 $el.crmSnippet('option', 'block') && $el.unblock();
205bb8ae 983 $el.trigger('crmFormSuccess', response);
0e017a41 984 // Reset form for e.g. "save and new"
fa3a5fe2
CW
985 if (response.userContext && (!settings.autoClose ||
986 (settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0)))
987 {
205bb8ae 988 $el.crmSnippet('option', 'url', response.userContext).crmSnippet('refresh');
0e017a41 989 }
36876f55 990 else if ($el.data('dialog') && settings.autoClose) {
205bb8ae 991 $el.dialog('close');
83df6b4a 992 }
d4e4e9df
CW
993 }
994 else {
25bbc4c0 995 response.url = data.url;
205bb8ae 996 settings.onError.call($el, response);
d4e4e9df 997 }
83df6b4a 998 },
205bb8ae 999 beforeSubmit: function(submission) {
36876f55 1000 $el.crmSnippet('option', 'block') && $el.block();
205bb8ae 1001 $el.trigger('crmFormSubmit', submission);
d4e4e9df 1002 }
205bb8ae 1003 }, settings.ajaxForm));
fa3a5fe2
CW
1004 if (settings.openInline) {
1005 settings.autoClose = $el.crmSnippet('isOriginalUrl');
1006 $(settings.openInline, this).click(function(event) {
1007 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
1008 return false;
1009 });
1010 }
205bb8ae
CW
1011 });
1012 return widget;
d4e4e9df
CW
1013 };
1014
03a7ec8f
CW
1015 // Preprocess all cj ajax calls to display messages
1016 $(document).ajaxSuccess(function(event, xhr, settings) {
1017 try {
1018 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
1019 var response = $.parseJSON(xhr.responseText);
1020 if (typeof(response.crmMessages) == 'object') {
1021 $.each(response.crmMessages, function(n, msg) {
1022 CRM.alert(msg.text, msg.title, msg.type, msg.options);
1023 })
1024 }
1025 }
1026 }
1027 // Suppress errors
1028 catch (e) {}
1029 });
1030
0f5816a6 1031 $(function () {
205bb8ae
CW
1032 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1033 $('#crm-container').trigger('crmLoad');
1034
ef3309b6 1035 if ($('#crm-notification-container').length) {
6a488035
TO
1036 // Initialize notifications
1037 $('#crm-notification-container').notify();
1038 messagesFromMarkup.call($('#crm-container'));
1039 $('#crm-container').on('crmFormLoad', '*', messagesFromMarkup);
1040 }
ebb9197b
C
1041
1042 // bind the event for image popup
1043 $('body').on('click', 'a.crm-image-popup', function() {
1044 var o = $('<div class="crm-container crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
1045
1046 CRM.confirm('',
1047 {
1048 title: ts('Preview'),
1049 message: o
1050 },
1051 ts('Done')
1052 );
1053 return false;
1054 });
6a488035
TO
1055 });
1056
0f5816a6 1057 $.fn.crmAccordions = function (speed) {
e24b17b9 1058 var container = $('#crm-container');
6a488035
TO
1059 if (speed === undefined) {
1060 speed = 200;
1061 }
1062 if ($(this).length > 0) {
e24b17b9 1063 container = $(this);
6a488035
TO
1064 }
1065 if (container.length > 0 && !container.hasClass('crm-accordion-processed')) {
1066 // Allow normal clicking of links
1067 container.on('click', 'div.crm-accordion-header a', function (e) {
1068 e.stopPropagation && e.stopPropagation();
1069 });
1070 container.on('click', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
1071 if ($(this).parent().hasClass('collapsed')) {
1072 $(this).next().css('display', 'none').slideDown(speed);
1073 }
1074 else {
1075 $(this).next().css('display', 'block').slideUp(speed);
1076 }
1077 $(this).parent().toggleClass('collapsed');
1078 return false;
1079 });
1080 container.addClass('crm-accordion-processed');
e24b17b9 1081 }
6a488035 1082 };
0f5816a6
KJ
1083 $.fn.crmAccordionToggle = function (speed) {
1084 $(this).each(function () {
6a488035
TO
1085 if ($(this).hasClass('collapsed')) {
1086 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
1087 }
1088 else {
1089 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1090 }
1091 $(this).toggleClass('collapsed');
1092 });
1093 };
5ec182d9
CW
1094
1095 /**
1096 * Clientside currency formatting
1097 * @param value
3bdb644f 1098 * @param format - currency representation of the number 1234.56
5ec182d9 1099 * @return string
3bdb644f 1100 * @see CRM_Core_Resources::addCoreResources
5ec182d9
CW
1101 */
1102 var currencyTemplate;
1103 CRM.formatMoney = function(value, format) {
1104 var decimal, separator, sign, i, j, result;
1105 if (value === 'init' && format) {
1106 currencyTemplate = format;
1107 return;
1108 }
1109 format = format || currencyTemplate;
1110 result = /1(.?)234(.?)56/.exec(format);
1111 if (result === null) {
1112 return 'Invalid format passed to CRM.formatMoney';
1113 }
1114 separator = result[1];
1115 decimal = result[2];
1116 sign = (value < 0) ? '-' : '';
1117 //extracting the absolute value of the integer part of the number and converting to string
1118 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
5ec182d9
CW
1119 j = ((j = i.length) > 3) ? j % 3 : 0;
1120 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) : '');
1121 return format.replace(/1.*234.*56/, result);
1122 };
6a488035 1123})(jQuery);