rename contact_1 to individual_1 for individual model
[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
6a488035
TO
446CRM.strings = CRM.strings || {};
447CRM.validate = CRM.validate || {
448 params: {},
449 functions: []
450};
451
0f5816a6 452(function ($, undefined) {
7553cf23 453 "use strict";
0f5816a6 454 $(document).ready(function () {
6a488035 455 $().crmtooltip();
0f5816a6 456 $('.crm-container table.row-highlight').on('change', 'input.select-row, input.select-rows', function () {
e24b17b9 457 var target, table = $(this).closest('table');
6a488035 458 if ($(this).hasClass('select-rows')) {
e24b17b9 459 target = $('tbody tr', table);
6a488035
TO
460 $('input.select-row', table).prop('checked', $(this).prop('checked'));
461 }
462 else {
e24b17b9 463 target = $(this).closest('tr');
6a488035
TO
464 $('input.select-rows', table).prop('checked', $(".select-row:not(':checked')", table).length < 1);
465 }
466 target.toggleClass('crm-row-selected', $(this).is(':checked'));
467 });
8d86fc13
CW
468 $('body').on('click', function (event) {
469 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
e24b17b9 470 if ($(event.target).is('.btn-slide')) {
8d86fc13 471 $(event.target).addClass('btn-slide-active').find('.panel').show();
6a488035
TO
472 }
473 });
474 });
148c4e8d
CW
475
476 /**
477 * Function to make multiselect boxes behave as fields in small screens
478 */
479 function advmultiselectResize() {
480 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
481 if (amswidth < 700) {
482 $("form table.advmultiselect td").css('display', 'block');
0f5816a6
KJ
483 }
484 else {
148c4e8d
CW
485 $("form table.advmultiselect td").css('display', 'table-cell');
486 }
487 var contactwidth = $('#crm-container #mainTabContainer').width();
488 if (contactwidth < 600) {
489 $('#crm-container #mainTabContainer').addClass('narrowpage');
0f5816a6 490 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
148c4e8d 491 if (index > 1) {
0f5816a6 492 if (index % 2 == 0) {
148c4e8d
CW
493 $(this).parent().after('<tr class="narrowadded"></tr>');
494 }
495 var item = $(this);
496 $(this).parent().next().append(item);
497 }
498 });
0f5816a6
KJ
499 }
500 else {
148c4e8d 501 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
0f5816a6 502 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
148c4e8d
CW
503 var nitem = $(this);
504 var parent = $(this).parent();
505 $(this).parent().prev().append(nitem);
0f5816a6 506 if (parent.children().size() == 0) {
148c4e8d
CW
507 parent.remove();
508 }
509 });
510 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
511 }
512 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
0f5816a6 513
148c4e8d
CW
514 if (cformwidth < 720) {
515 $('#crm-container .contact_basic_information-section').addClass('narrowform');
516 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
517 if (cformwidth < 480) {
518 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
0f5816a6
KJ
519 }
520 else {
148c4e8d
CW
521 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
522 }
0f5816a6
KJ
523 }
524 else {
148c4e8d
CW
525 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
526 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
527 }
528 }
0f5816a6 529
148c4e8d 530 advmultiselectResize();
0f5816a6 531 $(window).resize(function () {
6a488035
TO
532 advmultiselectResize();
533 });
534
0f5816a6 535 $.fn.crmtooltip = function () {
2c29c2ac
RN
536 $(document)
537 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
538 $(this).addClass('crm-processed');
e24b17b9
CW
539 $(this).addClass('crm-tooltip-active');
540 var topDistance = e.pageY - $(window).scrollTop();
541 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
542 $(this).addClass('crm-tooltip-down');
543 }
544 if (!$(this).children('.crm-tooltip-wrapper').length) {
6a488035
TO
545 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
546 $(this).children().children('.crm-tooltip')
547 .html('<div class="crm-loading-element"></div>')
548 .load(this.href);
549 }
550 })
2c29c2ac
RN
551 .on('mouseout', 'a.crm-summary-link', function () {
552 $(this).removeClass('crm-processed');
e24b17b9
CW
553 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
554 })
2c29c2ac 555 .on('click', 'a.crm-summary-link', false);
6a488035
TO
556 };
557
558 var h;
8e3272a1 559 CRM.help = function (title, params, url) {
6a488035
TO
560 h && h.close && h.close();
561 var options = {
562 expires: 0
563 };
564 h = CRM.alert('...', title, 'crm-help crm-msg-loading', options);
565 params.class_name = 'CRM_Core_Page_Inline_Help';
566 params.type = 'page';
8e3272a1 567 $.ajax(url || CRM.url('civicrm/ajax/inline'),
6a488035
TO
568 {
569 data: params,
570 dataType: 'html',
e24b17b9 571 success: function (data) {
6a488035
TO
572 $('#crm-notification-container .crm-help .notify-content:last').html(data);
573 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
574 },
e24b17b9 575 error: function () {
6a488035
TO
576 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
577 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
578 }
579 }
580 );
581 };
8960d9b9
CW
582 /**
583 * @param startMsg string
584 * @param endMsg string|function
585 * @param deferred optional jQuery deferred object
586 * @return jQuery deferred object - if not supplied a new one will be created
587 */
588 var fadeOut;
589 CRM.status = function(startMsg, endMsg, deferred) {
590 var $bar = $('#civicrm-menu');
591 if (!$bar.length) {
592 console && console.log && console.log('CRM.status called on a page with no menubar');
593 return;
594 }
595 $('.crm-menubar-status-container', $bar).remove();
596 fadeOut && window.clearTimeout(fadeOut);
597 $bar.append('<li class="crm-menubar-status-container status-busy"><div class="crm-menubar-status-progressbar"><div class="crm-menubar-status-msg">' + startMsg + '</div></div></li>');
598 $('.crm-menubar-status-container', $bar).css('min-width', $('.crm-menubar-status-container', $bar).width());
599 deferred || (deferred = new $.Deferred());
600 deferred.done(function(data) {
601 var msg = typeof(endMsg) === 'function' ? endMsg(data) : endMsg;
4bad157e
CW
602 $('.crm-menubar-status-container', $bar).removeClass('status-busy').addClass('status-done').show().find('.crm-menubar-status-msg').html(msg);
603 if (msg) {
604 fadeOut = window.setTimeout(function() {
605 $('.crm-menubar-status-container', $bar).fadeOut('slow');
606 }, 2000);
607 } else {
608 $('.crm-menubar-status-container', $bar).hide();
609 }
8960d9b9
CW
610 });
611 return deferred;
612 };
6a488035
TO
613
614 /**
615 * @param string text Displayable message
616 * @param string title Displayable title
617 * @param string type 'alert'|'info'|'success'|'error' (default: 'alert')
618 * @param {object} options
619 * @return {*}
620 * @see http://wiki.civicrm.org/confluence/display/CRM/Notifications+in+CiviCRM
621 */
0f5816a6 622 CRM.alert = function (text, title, type, options) {
6a488035
TO
623 type = type || 'alert';
624 title = title || '';
625 options = options || {};
626 if ($('#crm-notification-container').length) {
627 var params = {
628 text: text,
629 title: title,
630 type: type
631 };
632 // By default, don't expire errors and messages containing links
633 var extra = {
634 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
635 unique: true
636 };
637 options = $.extend(extra, options);
e24b17b9 638 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
6a488035 639 if (options.unique && options.unique !== '0') {
0f5816a6 640 $('#crm-notification-container .ui-notify-message').each(function () {
6a488035
TO
641 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
642 $('.icon.ui-notify-close', this).click();
643 }
644 });
645 }
646 return $('#crm-notification-container').notify('create', params, options);
647 }
648 else {
649 if (title.length) {
650 text = title + "\n" + text;
651 }
652 alert(text);
653 return null;
654 }
e24b17b9 655 };
6a488035
TO
656
657 /**
658 * Close whichever alert contains the given node
659 *
660 * @param node
661 */
0f5816a6 662 CRM.closeAlertByChild = function (node) {
6a488035 663 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
e24b17b9 664 };
6a488035
TO
665
666 /**
667 * Prompt the user for confirmation.
668 *
7553cf23
CW
669 * @param buttons {object|function} key|value pairs where key == button label and value == callback function
670 * passing in a function instead of an object is a shortcut for a sinlgle button labeled "Continue"
671 * @param options {object|void} Override defaults, keys include 'title', 'message',
672 * see jQuery.dialog for full list of available params
6a488035 673 */
706cff6d 674 CRM.confirm = function (buttons, options, cancelLabel) {
7553cf23 675 var dialog, callbacks = {};
706cff6d 676 cancelLabel = cancelLabel || ts('Cancel');
7553cf23
CW
677 var settings = {
678 title: ts('Confirm Action'),
679 message: ts('Are you sure you want to continue?'),
6a488035
TO
680 resizable: false,
681 modal: true,
0d5f99d4 682 width: 'auto',
0f5816a6
KJ
683 close: function () {
684 $(dialog).remove();
685 },
7553cf23
CW
686 buttons: {}
687 };
706cff6d
KJ
688
689 settings.buttons[cancelLabel] = function () {
0f5816a6
KJ
690 dialog.dialog('close');
691 };
7553cf23
CW
692 options = options || {};
693 $.extend(settings, options);
694 if (typeof(buttons) === 'function') {
695 callbacks[ts('Continue')] = buttons;
0f5816a6
KJ
696 }
697 else {
7553cf23
CW
698 callbacks = buttons;
699 }
0f5816a6
KJ
700 $.each(callbacks, function (label, callback) {
701 settings.buttons[label] = function () {
7553cf23
CW
702 callback.call(dialog);
703 dialog.dialog('close');
e24b17b9 704 };
6a488035 705 });
7553cf23
CW
706 dialog = $('<div class="crm-container crm-confirm-dialog"></div>')
707 .html(options.message)
708 .appendTo('body')
709 .dialog(settings);
710 return dialog;
e24b17b9 711 };
6a488035
TO
712
713 /**
714 * Sets an error message
715 * If called for a form item, title and removal condition will be handled automatically
716 */
0f5816a6 717 $.fn.crmError = function (text, title, options) {
6a488035
TO
718 title = title || '';
719 text = text || '';
720 options = options || {};
721
722 var extra = {
723 expires: 0
724 };
725 if ($(this).length) {
726 if (title == '') {
727 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
728 if (label.length) {
729 label.addClass('crm-error');
730 var $label = label.clone();
731 if (text == '' && $('.crm-marker', $label).length > 0) {
732 text = $('.crm-marker', $label).attr('title');
733 }
734 $('.crm-marker', $label).remove();
735 title = $label.text();
736 }
737 }
738 $(this).addClass('error');
739 }
740 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
741 if ($(this).length) {
742 var ele = $(this);
0f5816a6
KJ
743 setTimeout(function () {
744 ele.one('change', function () {
745 msg && msg.close && msg.close();
746 ele.removeClass('error');
747 label.removeClass('crm-error');
748 });
749 }, 1000);
6a488035
TO
750 }
751 return msg;
e24b17b9 752 };
6a488035
TO
753
754 // Display system alerts through js notifications
755 function messagesFromMarkup() {
0f5816a6 756 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
e24b17b9 757 var text, title = '';
6a488035
TO
758 $(this).removeClass('status messages');
759 var type = $(this).attr('class').split(' ')[0] || 'alert';
760 type = type.replace('crm-', '');
761 $('.icon', this).remove();
6a488035 762 if ($('.msg-text', this).length > 0) {
e24b17b9 763 text = $('.msg-text', this).html();
6a488035
TO
764 title = $('.msg-title', this).html();
765 }
766 else {
e24b17b9 767 text = $(this).html();
6a488035
TO
768 }
769 var options = $(this).data('options') || {};
770 $(this).remove();
771 // Duplicates were already removed server-side
772 options.unique = false;
773 CRM.alert(text, title, type, options);
774 });
775 // Handle qf form errors
776 $('form :input.error', this).one('blur', function() {
ef04c554 777 // ignore autocomplete fields
23246a80 778 if ($(this).is('.ac_input')) {
779 return;
780 }
ef04c554 781
6a488035
TO
782 $('.ui-notify-message.error a.ui-notify-close').click();
783 $(this).removeClass('error');
784 $(this).next('span.crm-error').remove();
785 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
786 .removeClass('crm-error')
787 .find('.crm-error').removeClass('crm-error');
788 });
789 }
790
23223213 791 $.widget('civi.crmSnippet', {
205bb8ae 792 options: {
a73f25bb 793 url: null,
205bb8ae
CW
794 block: true,
795 crmForm: null
796 },
c02f8fc4 797 _originalContent: null,
fa3a5fe2
CW
798 _originalUrl: null,
799 isOriginalUrl: function() {
0906345e
CW
800 var
801 args = {},
802 same = true,
803 newUrl = this._formatUrl(this.options.url),
804 oldUrl = this._formatUrl(this._originalUrl);
fa3a5fe2 805 // Compare path
0906345e 806 if (newUrl.split('?')[0] !== oldUrl.split('?')[0]) {
fa3a5fe2
CW
807 return false;
808 }
809 // Compare arguments
0906345e 810 $.each(newUrl.split('?')[1].split('&'), function(k, v) {
fa3a5fe2
CW
811 var arg = v.split('=');
812 args[arg[0]] = arg[1];
813 });
0906345e 814 $.each(oldUrl.split('?')[1].split('&'), function(k, v) {
fa3a5fe2
CW
815 var arg = v.split('=');
816 if (args[arg[0]] !== undefined && arg[1] !== args[arg[0]]) {
817 same = false;
818 }
819 });
820 return same;
821 },
822 resetUrl: function() {
823 this.options.url = this._originalUrl;
824 },
205bb8ae 825 _create: function() {
205bb8ae
CW
826 this.element.addClass('crm-ajax-container');
827 if (!this.element.is('.crm-container *')) {
828 this.element.addClass('crm-container');
829 }
4a140040 830 this._handleOrderLinks();
5d92a7e7
CW
831 // Set default if not supplied
832 this.options.url = this.options.url || document.location.href;
fa3a5fe2 833 this._originalUrl = this.options.url;
205bb8ae
CW
834 },
835 _onFailure: function(data) {
836 this.options.block && this.element.unblock();
837 this.element.trigger('crmAjaxFail', data);
838 CRM.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
839 },
840 _formatUrl: function(url) {
0906345e
CW
841 // Strip hash
842 url = url.split('#')[0];
205bb8ae
CW
843 // Add snippet argument to url
844 if (url.search(/[&?]snippet=/) < 0) {
fc05b8da 845 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
8547369d
CW
846 } else {
847 url = url.replace(/snippet=[^&]*/, 'snippet=json');
205bb8ae
CW
848 }
849 return url;
850 },
d6539f93 851 // Hack to deal with civicrm legacy sort functionality
4a140040
CW
852 _handleOrderLinks: function() {
853 var that = this;
854 $('a.crm-weight-arrow', that.element).click(function(e) {
855 that.options.block && that.element.block();
856 $.getJSON(that._formatUrl(this.href)).done(function() {
857 that.refresh();
858 });
859 e.stopImmediatePropagation();
860 return false;
861 });
862 },
205bb8ae
CW
863 refresh: function() {
864 var that = this;
865 var url = this._formatUrl(this.options.url);
4a140040 866 this.options.block && $('.blockOverlay', this.element).length < 1 && this.element.block();
205bb8ae
CW
867 $.getJSON(url, function(data) {
868 if (typeof(data) != 'object' || typeof(data.content) != 'string') {
869 that._onFailure(data);
870 return;
871 }
872 data.url = url;
c02f8fc4
CW
873 that.element.trigger('crmBeforeLoad', data);
874 if (that._originalContent === null) {
875 that._originalContent = that.element.contents().detach();
876 }
877 that.element.html(data.content);
4a140040
CW
878 that._handleOrderLinks();
879 that.element.trigger('crmLoad', data);
205bb8ae
CW
880 that.options.crmForm && that.element.trigger('crmFormLoad', data);
881 }).fail(function() {
882 that._onFailure();
883 });
4b628e67
CW
884 },
885 _destroy: function() {
886 this.element.removeClass('crm-ajax-container');
c02f8fc4
CW
887 if (this._originalContent !== null) {
888 this.element.empty().append(this._originalContent);
889 }
205bb8ae
CW
890 }
891 });
892
0e017a41 893 var dialogCount = 0;
d4e4e9df 894 CRM.loadPage = function(url, options) {
d4e4e9df 895 var settings = {
0e017a41 896 target: '#crm-ajax-dialog-' + (dialogCount++),
8547369d
CW
897 dialog: false
898 };
899 if (!options || !options.target) {
900 settings.dialog = {
d4e4e9df 901 modal: true,
f84151fd
CW
902 width: '65%',
903 height: parseInt($(window).height() * .75),
d4e4e9df 904 close: function() {
c02f8fc4 905 $(this).dialog('destroy').remove();
d4e4e9df 906 }
8547369d
CW
907 };
908 }
205bb8ae 909 options && $.extend(true, settings, options);
0e017a41 910 settings.url = url;
83df6b4a 911 // Create new dialog
8547369d 912 if (settings.dialog) {
205bb8ae 913 $('<div id="'+ settings.target.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings.dialog);
d4e4e9df 914 }
205bb8ae
CW
915 if (settings.dialog && !settings.dialog.title) {
916 $(settings.target).on('crmLoad', function(event, data) {
917 data.title && $(this).dialog('option', 'title', data.title);
918 });
919 }
5d92a7e7
CW
920 $(settings.target).crmSnippet(settings).crmSnippet('refresh');
921 return $(settings.target);
d4e4e9df
CW
922 };
923
924 CRM.loadForm = function(url, options) {
d4e4e9df 925 var settings = {
205bb8ae
CW
926 crmForm: {
927 ajaxForm: {},
205bb8ae
CW
928 autoClose: true,
929 validate: true,
930 refreshAction: ['next_new', 'submit_savenext'],
931 cancelButton: '.cancel.form-submit',
23223213 932 openInline: 'a.button:not("[href=#], .no-popup")',
205bb8ae
CW
933 onCancel: function(event) {},
934 onError: function(data) {
935 var $el = $(this);
5d92a7e7 936 $el.html(data.content).trigger('crmLoad', data).trigger('crmFormLoad', data).trigger('crmFormError', data);
205bb8ae
CW
937 if (typeof(data.errors) == 'object') {
938 $.each(data.errors, function(formElement, msg) {
939 $('[name="'+formElement+'"]', $el).crmError(msg);
940 });
941 }
d4e4e9df 942 }
d4e4e9df
CW
943 }
944 };
a10432db
CW
945 // Hack to make delete dialogs smaller
946 if (url.indexOf('/delete') > 0 || url.indexOf('action=delete') > 0) {
947 settings.dialog = {
948 width: 400,
949 height: 300
950 };
951 }
205bb8ae
CW
952 // Move options that belong to crmForm. Others will be passed through to crmSnippet
953 options && $.each(options, function(key, value) {
954 if (typeof(settings.crmForm[key]) !== 'undefined') {
955 settings.crmForm[key] = value;
956 }
957 else {
958 settings[key] = value;
959 }
960 });
205bb8ae
CW
961
962 var widget = CRM.loadPage(url, settings);
963
964 widget.on('crmFormLoad', function(event, data) {
965 var $el = $(this);
660c46f3 966 var settings = $el.crmSnippet('option', 'crmForm');
205bb8ae
CW
967 settings.cancelButton && $(settings.cancelButton, this).click(function(event) {
968 var returnVal = settings.onCancel.call($el, event);
969 if (returnVal !== false) {
970 $el.trigger('crmFormCancel', event);
660c46f3 971 if ($el.data('uiDialog') && settings.autoClose) {
fa3a5fe2
CW
972 $el.dialog('close');
973 }
974 else if (!settings.autoClose) {
975 $el.crmSnippet('resetUrl').crmSnippet('refresh');
976 }
0e017a41 977 }
205bb8ae
CW
978 return returnVal === false;
979 });
d4e4e9df 980 if (settings.validate) {
0e017a41 981 $("form", this).validate(typeof(settings.validate) == 'object' ? settings.validate : CRM.validate.params);
d4e4e9df 982 }
205bb8ae 983 $("form", this).ajaxForm($.extend({
fa3a5fe2 984 url: data.url.replace(/reset=1[&]?/, ''),
d4e4e9df
CW
985 dataType: 'json',
986 success: function(response) {
34866662 987 if (response.status !== 'form_error') {
36876f55 988 $el.crmSnippet('option', 'block') && $el.unblock();
205bb8ae 989 $el.trigger('crmFormSuccess', response);
0e017a41 990 // Reset form for e.g. "save and new"
d6539f93 991 if (response.userContext && settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0) {
205bb8ae 992 $el.crmSnippet('option', 'url', response.userContext).crmSnippet('refresh');
0e017a41 993 }
660c46f3 994 else if ($el.data('uiDialog') && settings.autoClose) {
205bb8ae 995 $el.dialog('close');
83df6b4a 996 }
d6539f93
CW
997 else if (settings.autoClose === false) {
998 $el.crmSnippet('resetUrl').crmSnippet('refresh');
999 }
d4e4e9df
CW
1000 }
1001 else {
25bbc4c0 1002 response.url = data.url;
205bb8ae 1003 settings.onError.call($el, response);
d4e4e9df 1004 }
23223213
CW
1005 },
1006 beforeSerialize: function(form, options) {
1007 if (window.CKEDITOR && window.CKEDITOR.instances) {
a10432db
CW
1008 $.each(CKEDITOR.instances, function() {
1009 this.updateElement && this.updateElement();
1010 });
23223213 1011 }
83df6b4a 1012 },
205bb8ae 1013 beforeSubmit: function(submission) {
36876f55 1014 $el.crmSnippet('option', 'block') && $el.block();
205bb8ae 1015 $el.trigger('crmFormSubmit', submission);
d4e4e9df 1016 }
205bb8ae 1017 }, settings.ajaxForm));
fa3a5fe2
CW
1018 if (settings.openInline) {
1019 settings.autoClose = $el.crmSnippet('isOriginalUrl');
1020 $(settings.openInline, this).click(function(event) {
1021 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
1022 return false;
1023 });
1024 }
205bb8ae
CW
1025 });
1026 return widget;
d4e4e9df
CW
1027 };
1028
03a7ec8f
CW
1029 // Preprocess all cj ajax calls to display messages
1030 $(document).ajaxSuccess(function(event, xhr, settings) {
1031 try {
1032 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
1033 var response = $.parseJSON(xhr.responseText);
1034 if (typeof(response.crmMessages) == 'object') {
1035 $.each(response.crmMessages, function(n, msg) {
1036 CRM.alert(msg.text, msg.title, msg.type, msg.options);
1037 })
1038 }
1039 }
1040 }
1041 // Suppress errors
1042 catch (e) {}
1043 });
1044
0f5816a6 1045 $(function () {
205bb8ae 1046 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
8547369d 1047 $('.crm-container').trigger('crmLoad');
205bb8ae 1048
ef3309b6 1049 if ($('#crm-notification-container').length) {
6a488035
TO
1050 // Initialize notifications
1051 $('#crm-notification-container').notify();
1052 messagesFromMarkup.call($('#crm-container'));
6a488035 1053 }
ebb9197b
C
1054
1055 // bind the event for image popup
1056 $('body').on('click', 'a.crm-image-popup', function() {
1057 var o = $('<div class="crm-container crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
1058
1059 CRM.confirm('',
1060 {
1061 title: ts('Preview'),
1062 message: o
1063 },
1064 ts('Done')
1065 );
1066 return false;
1067 });
6a488035
TO
1068 });
1069
0f5816a6 1070 $.fn.crmAccordions = function (speed) {
cf021bc5
CW
1071 var container = $(this).length > 0 ? $(this) : $('.crm-container');
1072 speed = speed === undefined ? 200 : speed;
1073 container
1074 .off('click.crmAccordions')
6a488035 1075 // Allow normal clicking of links
cf021bc5 1076 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
6a488035 1077 e.stopPropagation && e.stopPropagation();
cf021bc5
CW
1078 })
1079 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
6a488035
TO
1080 if ($(this).parent().hasClass('collapsed')) {
1081 $(this).next().css('display', 'none').slideDown(speed);
1082 }
1083 else {
1084 $(this).next().css('display', 'block').slideUp(speed);
1085 }
1086 $(this).parent().toggleClass('collapsed');
1087 return false;
1088 });
6a488035 1089 };
0f5816a6
KJ
1090 $.fn.crmAccordionToggle = function (speed) {
1091 $(this).each(function () {
6a488035
TO
1092 if ($(this).hasClass('collapsed')) {
1093 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
1094 }
1095 else {
1096 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1097 }
1098 $(this).toggleClass('collapsed');
1099 });
1100 };
5ec182d9
CW
1101
1102 /**
1103 * Clientside currency formatting
1104 * @param value
3bdb644f 1105 * @param format - currency representation of the number 1234.56
5ec182d9 1106 * @return string
3bdb644f 1107 * @see CRM_Core_Resources::addCoreResources
5ec182d9
CW
1108 */
1109 var currencyTemplate;
1110 CRM.formatMoney = function(value, format) {
1111 var decimal, separator, sign, i, j, result;
1112 if (value === 'init' && format) {
1113 currencyTemplate = format;
1114 return;
1115 }
1116 format = format || currencyTemplate;
1117 result = /1(.?)234(.?)56/.exec(format);
1118 if (result === null) {
1119 return 'Invalid format passed to CRM.formatMoney';
1120 }
1121 separator = result[1];
1122 decimal = result[2];
1123 sign = (value < 0) ? '-' : '';
1124 //extracting the absolute value of the integer part of the number and converting to string
1125 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
5ec182d9
CW
1126 j = ((j = i.length) > 3) ? j % 3 : 0;
1127 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) : '');
1128 return format.replace(/1.*234.*56/, result);
1129 };
6a488035 1130})(jQuery);