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