Merge pull request #2311 from yashodha/sms-reminder
[civicrm-core.git] / js / Common.js
1 /*
2 +--------------------------------------------------------------------+
3 | CiviCRM version 4.4 |
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 +--------------------------------------------------------------------+
25 */
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
33 var CRM = CRM || {};
34 var 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 */
44 function ts(text, params) {
45 "use strict";
46 text = CRM.strings[text] || text;
47 if (typeof(params) === 'object') {
48 for (var i in params) {
49 if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') {
50 // sprintf emulation: escape % characters in the replacements to avoid conflicts
51 text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-'));
52 }
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 */
71 function 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;
82 }
83 else {
84 alert('showBlocks array item not in .tpl = ' + showBlocks[i]);
85 }
86 }
87
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]);
97 }
98 }
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
113 */
114 function showHideByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, invert) {
115 if (target_element_type == null) {
116 var target_element_type = 'block';
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 }
144 }
145 }
146 }
147
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 }
160 }
161 else {
162 if (invert) {
163 cj('#' + target[j]).show();
164 }
165 else {
166 cj('#' + target[j]).hide();
167 }
168 }
169 }
170 }
171 }
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 */
186 function toggleCheckboxVals(fldPrefix, object) {
187 var val = (object.id == 'toggleSelect' && cj(object).is(':checked'));
188 cj('Input[id*="' + fldPrefix + '"],Input[id*="toggleSelect"]').prop('checked', val);
189 // change the class of selected rows
190 on_load_init_checkboxes(object.form.name);
191 }
192
193 function countSelectedCheckboxes(fldPrefix, form) {
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++;
199 }
200 }
201 return fieldCount;
202 }
203
204 /**
205 * Function to enable task action select
206 */
207 function 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 }
226 }
227 }
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 */
240 function 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;
255 }
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;
262 }
263 }
264
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 }
270
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;
275 }
276 }
277 else {
278 alert("Please select an action from the drop-down menu.");
279 return false;
280 }
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 */
290 function checkSelectedBox(chkName) {
291 var checkElement = cj('#' + chkName);
292 if (checkElement.prop('checked')) {
293 cj('input[value=ts_sel]:radio').prop('checked', true);
294 checkElement.parents('tr').addClass('crm-row-selected');
295 }
296 else {
297 checkElement.parents('tr').removeClass('crm-row-selected');
298 }
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 */
308 function 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);
315 }
316 }
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 */
328 function 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 }
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 */
357 function on_load_init_check(form) {
358 for (i = 0; i < document.forms[form].elements.length; i++) {
359 if (( document.forms[form].elements[i].type == 'checkbox'
360 && document.forms[form].elements[i].checked == true )
361 || ( document.forms[form].elements[i].type == 'hidden'
362 && document.forms[form].elements[i].value == 1 )) {
363 var ss = document.forms[form].elements[i].id;
364 var row = 'rowid' + ss;
365 changeRowColor(row, form);
366 }
367 }
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 */
377 function unselectRadio(fieldName, form) {
378 for (i = 0; i < document.forms[form].elements.length; i++) {
379 if (document.forms[form].elements[i].name == fieldName) {
380 document.forms[form].elements[i].checked = false;
381 }
382 }
383 return;
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 */
394 var submitcount = 0;
395 /* Changes button label on submit, and disables button after submit for newer browsers.
396 Puts up alert for older browsers. */
397 function submitOnce(obj, formId, procText) {
398 // if named button clicked, change text
399 if (obj.value != null) {
400 obj.value = procText + " ...";
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;
415 }
416 }
417 }
418
419 function popUp(URL) {
420 day = new Date();
421 id = day.getTime();
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
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 */
430 function 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();
435 }
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;
444 }
445
446 CRM.strings = CRM.strings || {};
447 CRM.validate = CRM.validate || {
448 params: {},
449 functions: []
450 };
451
452 (function ($, undefined) {
453 "use strict";
454 $(document).ready(function () {
455 $().crmtooltip();
456 $('.crm-container table.row-highlight').on('change', 'input.select-row, input.select-rows', function () {
457 var target, table = $(this).closest('table');
458 if ($(this).hasClass('select-rows')) {
459 target = $('tbody tr', table);
460 $('input.select-row', table).prop('checked', $(this).prop('checked'));
461 }
462 else {
463 target = $(this).closest('tr');
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 });
468 $('body').on('click', function (event) {
469 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
470 if ($(event.target).is('.btn-slide')) {
471 $(event.target).addClass('btn-slide-active').find('.panel').show();
472 }
473 });
474 });
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');
483 }
484 else {
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');
490 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
491 if (index > 1) {
492 if (index % 2 == 0) {
493 $(this).parent().after('<tr class="narrowadded"></tr>');
494 }
495 var item = $(this);
496 $(this).parent().next().append(item);
497 }
498 });
499 }
500 else {
501 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
502 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
503 var nitem = $(this);
504 var parent = $(this).parent();
505 $(this).parent().prev().append(nitem);
506 if (parent.children().size() == 0) {
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();
513
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');
519 }
520 else {
521 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
522 }
523 }
524 else {
525 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
526 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
527 }
528 }
529
530 advmultiselectResize();
531 $(window).resize(function () {
532 advmultiselectResize();
533 });
534
535 $.fn.crmtooltip = function () {
536 $(document)
537 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
538 $(this).addClass('crm-processed');
539 $(this).addClass('crm-tooltip-active');
540 var topDistance = e.pageY - $(window).scrollTop();
541 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
542 $(this).addClass('crm-tooltip-down');
543 }
544 if (!$(this).children('.crm-tooltip-wrapper').length) {
545 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
546 $(this).children().children('.crm-tooltip')
547 .html('<div class="crm-loading-element"></div>')
548 .load(this.href);
549 }
550 })
551 .on('mouseout', 'a.crm-summary-link', function () {
552 $(this).removeClass('crm-processed');
553 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
554 })
555 .on('click', 'a.crm-summary-link', false);
556 };
557
558 var h;
559 CRM.help = function (title, params, url) {
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';
567 $.ajax(url || CRM.url('civicrm/ajax/inline'),
568 {
569 data: params,
570 dataType: 'html',
571 success: function (data) {
572 $('#crm-notification-container .crm-help .notify-content:last').html(data);
573 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
574 },
575 error: function () {
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 };
582
583 /**
584 * @param string text Displayable message
585 * @param string title Displayable title
586 * @param string type 'alert'|'info'|'success'|'error' (default: 'alert')
587 * @param {object} options
588 * @return {*}
589 * @see http://wiki.civicrm.org/confluence/display/CRM/Notifications+in+CiviCRM
590 */
591 CRM.alert = function (text, title, type, options) {
592 type = type || 'alert';
593 title = title || '';
594 options = options || {};
595 if ($('#crm-notification-container').length) {
596 var params = {
597 text: text,
598 title: title,
599 type: type
600 };
601 // By default, don't expire errors and messages containing links
602 var extra = {
603 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
604 unique: true
605 };
606 options = $.extend(extra, options);
607 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
608 if (options.unique && options.unique !== '0') {
609 $('#crm-notification-container .ui-notify-message').each(function () {
610 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
611 $('.icon.ui-notify-close', this).click();
612 }
613 });
614 }
615 return $('#crm-notification-container').notify('create', params, options);
616 }
617 else {
618 if (title.length) {
619 text = title + "\n" + text;
620 }
621 alert(text);
622 return null;
623 }
624 };
625
626 /**
627 * Close whichever alert contains the given node
628 *
629 * @param node
630 */
631 CRM.closeAlertByChild = function (node) {
632 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
633 };
634
635 /**
636 * Prompt the user for confirmation.
637 *
638 * @param buttons {object|function} key|value pairs where key == button label and value == callback function
639 * passing in a function instead of an object is a shortcut for a sinlgle button labeled "Continue"
640 * @param options {object|void} Override defaults, keys include 'title', 'message',
641 * see jQuery.dialog for full list of available params
642 */
643 CRM.confirm = function (buttons, options, cancelLabel) {
644 var dialog, callbacks = {};
645 cancelLabel = cancelLabel || ts('Cancel');
646 var settings = {
647 title: ts('Confirm Action'),
648 message: ts('Are you sure you want to continue?'),
649 resizable: false,
650 modal: true,
651 width: 'auto',
652 close: function () {
653 $(dialog).remove();
654 },
655 buttons: {}
656 };
657
658 settings.buttons[cancelLabel] = function () {
659 dialog.dialog('close');
660 };
661 options = options || {};
662 $.extend(settings, options);
663 if (typeof(buttons) === 'function') {
664 callbacks[ts('Continue')] = buttons;
665 }
666 else {
667 callbacks = buttons;
668 }
669 $.each(callbacks, function (label, callback) {
670 settings.buttons[label] = function () {
671 callback.call(dialog);
672 dialog.dialog('close');
673 };
674 });
675 dialog = $('<div class="crm-container crm-confirm-dialog"></div>')
676 .html(options.message)
677 .appendTo('body')
678 .dialog(settings);
679 return dialog;
680 };
681
682 /**
683 * Sets an error message
684 * If called for a form item, title and removal condition will be handled automatically
685 */
686 $.fn.crmError = function (text, title, options) {
687 title = title || '';
688 text = text || '';
689 options = options || {};
690
691 var extra = {
692 expires: 0
693 };
694 if ($(this).length) {
695 if (title == '') {
696 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
697 if (label.length) {
698 label.addClass('crm-error');
699 var $label = label.clone();
700 if (text == '' && $('.crm-marker', $label).length > 0) {
701 text = $('.crm-marker', $label).attr('title');
702 }
703 $('.crm-marker', $label).remove();
704 title = $label.text();
705 }
706 }
707 $(this).addClass('error');
708 }
709 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
710 if ($(this).length) {
711 var ele = $(this);
712 setTimeout(function () {
713 ele.one('change', function () {
714 msg && msg.close && msg.close();
715 ele.removeClass('error');
716 label.removeClass('crm-error');
717 });
718 }, 1000);
719 }
720 return msg;
721 };
722
723 // Display system alerts through js notifications
724 function messagesFromMarkup() {
725 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
726 var text, title = '';
727 $(this).removeClass('status messages');
728 var type = $(this).attr('class').split(' ')[0] || 'alert';
729 type = type.replace('crm-', '');
730 $('.icon', this).remove();
731 if ($('.msg-text', this).length > 0) {
732 text = $('.msg-text', this).html();
733 title = $('.msg-title', this).html();
734 }
735 else {
736 text = $(this).html();
737 }
738 var options = $(this).data('options') || {};
739 $(this).remove();
740 // Duplicates were already removed server-side
741 options.unique = false;
742 CRM.alert(text, title, type, options);
743 });
744 // Handle qf form errors
745 $('form :input.error', this).one('blur', function() {
746 // ignore autocomplete fields
747 if ($(this).is('.ac_input')) {
748 return;
749 }
750
751 $('.ui-notify-message.error a.ui-notify-close').click();
752 $(this).removeClass('error');
753 $(this).next('span.crm-error').remove();
754 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
755 .removeClass('crm-error')
756 .find('.crm-error').removeClass('crm-error');
757 });
758 }
759
760 $.widget('civi.crmSnippet', {
761 options: {
762 url: null,
763 block: true,
764 crmForm: null
765 },
766 _originalContent: null,
767 _originalUrl: null,
768 isOriginalUrl: function() {
769 var
770 args = {},
771 same = true,
772 newUrl = this._formatUrl(this.options.url),
773 oldUrl = this._formatUrl(this._originalUrl);
774 // Compare path
775 if (newUrl.split('?')[0] !== oldUrl.split('?')[0]) {
776 return false;
777 }
778 // Compare arguments
779 $.each(newUrl.split('?')[1].split('&'), function(k, v) {
780 var arg = v.split('=');
781 args[arg[0]] = arg[1];
782 });
783 $.each(oldUrl.split('?')[1].split('&'), function(k, v) {
784 var arg = v.split('=');
785 if (args[arg[0]] !== undefined && arg[1] !== args[arg[0]]) {
786 same = false;
787 }
788 });
789 return same;
790 },
791 resetUrl: function() {
792 this.options.url = this._originalUrl;
793 },
794 _create: function() {
795 this.element.addClass('crm-ajax-container');
796 if (!this.element.is('.crm-container *')) {
797 this.element.addClass('crm-container');
798 }
799 this._handleOrderLinks();
800 // Set default if not supplied
801 this.options.url = this.options.url || document.location.href;
802 this._originalUrl = this.options.url;
803 },
804 _onFailure: function(data) {
805 this.options.block && this.element.unblock();
806 this.element.trigger('crmAjaxFail', data);
807 CRM.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
808 },
809 _formatUrl: function(url) {
810 // Strip hash
811 url = url.split('#')[0];
812 // Add snippet argument to url
813 if (url.search(/[&?]snippet=/) < 0) {
814 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
815 } else {
816 url = url.replace(/snippet=[^&]*/, 'snippet=json');
817 }
818 return url;
819 },
820 // Hack to deal with civicrm legacy sort functionality
821 _handleOrderLinks: function() {
822 var that = this;
823 $('a.crm-weight-arrow', that.element).click(function(e) {
824 that.options.block && that.element.block();
825 $.getJSON(that._formatUrl(this.href)).done(function() {
826 that.refresh();
827 });
828 e.stopImmediatePropagation();
829 return false;
830 });
831 },
832 refresh: function() {
833 var that = this;
834 var url = this._formatUrl(this.options.url);
835 this.options.block && $('.blockOverlay', this.element).length < 1 && this.element.block();
836 $.getJSON(url, function(data) {
837 if (typeof(data) != 'object' || typeof(data.content) != 'string') {
838 that._onFailure(data);
839 return;
840 }
841 data.url = url;
842 that.element.trigger('crmBeforeLoad', data);
843 if (that._originalContent === null) {
844 that._originalContent = that.element.contents().detach();
845 }
846 that.element.html(data.content);
847 that._handleOrderLinks();
848 that.element.trigger('crmLoad', data);
849 that.options.crmForm && that.element.trigger('crmFormLoad', data);
850 }).fail(function() {
851 that._onFailure();
852 });
853 },
854 _destroy: function() {
855 this.element.removeClass('crm-ajax-container');
856 if (this._originalContent !== null) {
857 this.element.empty().append(this._originalContent);
858 }
859 }
860 });
861
862 var dialogCount = 0;
863 CRM.loadPage = function(url, options) {
864 var settings = {
865 target: '#crm-ajax-dialog-' + (dialogCount++),
866 dialog: false
867 };
868 if (!options || !options.target) {
869 settings.dialog = {
870 modal: true,
871 width: '65%',
872 height: parseInt($(window).height() * .75),
873 close: function() {
874 $(this).dialog('destroy').remove();
875 }
876 };
877 }
878 options && $.extend(true, settings, options);
879 settings.url = url;
880 // Create new dialog
881 if (settings.dialog) {
882 $('<div id="'+ settings.target.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings.dialog);
883 }
884 if (settings.dialog && !settings.dialog.title) {
885 $(settings.target).on('crmLoad', function(event, data) {
886 data.title && $(this).dialog('option', 'title', data.title);
887 });
888 }
889 $(settings.target).crmSnippet(settings).crmSnippet('refresh');
890 return $(settings.target);
891 };
892
893 CRM.loadForm = function(url, options) {
894 var settings = {
895 crmForm: {
896 ajaxForm: {},
897 autoClose: true,
898 validate: true,
899 refreshAction: ['next_new', 'submit_savenext'],
900 cancelButton: '.cancel.form-submit',
901 openInline: 'a.button:not("[href=#], .no-popup")',
902 onCancel: function(event) {},
903 onError: function(data) {
904 var $el = $(this);
905 $el.html(data.content).trigger('crmLoad', data).trigger('crmFormLoad', data).trigger('crmFormError', data);
906 if (typeof(data.errors) == 'object') {
907 $.each(data.errors, function(formElement, msg) {
908 $('[name="'+formElement+'"]', $el).crmError(msg);
909 });
910 }
911 }
912 }
913 };
914 // Hack to make delete dialogs smaller
915 if (url.indexOf('/delete') > 0 || url.indexOf('action=delete') > 0) {
916 settings.dialog = {
917 width: 400,
918 height: 300
919 };
920 }
921 // Move options that belong to crmForm. Others will be passed through to crmSnippet
922 options && $.each(options, function(key, value) {
923 if (typeof(settings.crmForm[key]) !== 'undefined') {
924 settings.crmForm[key] = value;
925 }
926 else {
927 settings[key] = value;
928 }
929 });
930
931 var widget = CRM.loadPage(url, settings);
932
933 widget.on('crmFormLoad', function(event, data) {
934 var $el = $(this);
935 var settings = $el.crmSnippet('option', 'crmForm');
936 settings.cancelButton && $(settings.cancelButton, this).click(function(event) {
937 var returnVal = settings.onCancel.call($el, event);
938 if (returnVal !== false) {
939 $el.trigger('crmFormCancel', event);
940 if ($el.data('uiDialog') && settings.autoClose) {
941 $el.dialog('close');
942 }
943 else if (!settings.autoClose) {
944 $el.crmSnippet('resetUrl').crmSnippet('refresh');
945 }
946 }
947 return returnVal === false;
948 });
949 if (settings.validate) {
950 $("form", this).validate(typeof(settings.validate) == 'object' ? settings.validate : CRM.validate.params);
951 }
952 $("form", this).ajaxForm($.extend({
953 url: data.url.replace(/reset=1[&]?/, ''),
954 dataType: 'json',
955 success: function(response) {
956 if (response.status !== 'form_error') {
957 $el.crmSnippet('option', 'block') && $el.unblock();
958 $el.trigger('crmFormSuccess', response);
959 // Reset form for e.g. "save and new"
960 if (response.userContext && settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0) {
961 $el.crmSnippet('option', 'url', response.userContext).crmSnippet('refresh');
962 }
963 else if ($el.data('uiDialog') && settings.autoClose) {
964 $el.dialog('close');
965 }
966 else if (settings.autoClose === false) {
967 $el.crmSnippet('resetUrl').crmSnippet('refresh');
968 }
969 }
970 else {
971 response.url = data.url;
972 settings.onError.call($el, response);
973 }
974 },
975 beforeSerialize: function(form, options) {
976 if (window.CKEDITOR && window.CKEDITOR.instances) {
977 $.each(CKEDITOR.instances, function() {
978 this.updateElement && this.updateElement();
979 });
980 }
981 },
982 beforeSubmit: function(submission) {
983 $el.crmSnippet('option', 'block') && $el.block();
984 $el.trigger('crmFormSubmit', submission);
985 }
986 }, settings.ajaxForm));
987 if (settings.openInline) {
988 settings.autoClose = $el.crmSnippet('isOriginalUrl');
989 $(settings.openInline, this).click(function(event) {
990 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
991 return false;
992 });
993 }
994 });
995 return widget;
996 };
997
998 // Preprocess all cj ajax calls to display messages
999 $(document).ajaxSuccess(function(event, xhr, settings) {
1000 try {
1001 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
1002 var response = $.parseJSON(xhr.responseText);
1003 if (typeof(response.crmMessages) == 'object') {
1004 $.each(response.crmMessages, function(n, msg) {
1005 CRM.alert(msg.text, msg.title, msg.type, msg.options);
1006 })
1007 }
1008 }
1009 }
1010 // Suppress errors
1011 catch (e) {}
1012 });
1013
1014 $(function () {
1015 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1016 $('.crm-container').trigger('crmLoad');
1017
1018 if ($('#crm-notification-container').length) {
1019 // Initialize notifications
1020 $('#crm-notification-container').notify();
1021 messagesFromMarkup.call($('#crm-container'));
1022 }
1023
1024 // bind the event for image popup
1025 $('body').on('click', 'a.crm-image-popup', function() {
1026 var o = $('<div class="crm-container crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
1027
1028 CRM.confirm('',
1029 {
1030 title: ts('Preview'),
1031 message: o
1032 },
1033 ts('Done')
1034 );
1035 return false;
1036 });
1037 });
1038
1039 $.fn.crmAccordions = function (speed) {
1040 var container = $(this).length > 0 ? $(this) : $('.crm-container');
1041 speed = speed === undefined ? 200 : speed;
1042 container
1043 .off('click.crmAccordions')
1044 // Allow normal clicking of links
1045 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
1046 e.stopPropagation && e.stopPropagation();
1047 })
1048 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
1049 if ($(this).parent().hasClass('collapsed')) {
1050 $(this).next().css('display', 'none').slideDown(speed);
1051 }
1052 else {
1053 $(this).next().css('display', 'block').slideUp(speed);
1054 }
1055 $(this).parent().toggleClass('collapsed');
1056 return false;
1057 });
1058 };
1059 $.fn.crmAccordionToggle = function (speed) {
1060 $(this).each(function () {
1061 if ($(this).hasClass('collapsed')) {
1062 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
1063 }
1064 else {
1065 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1066 }
1067 $(this).toggleClass('collapsed');
1068 });
1069 };
1070
1071 /**
1072 * Clientside currency formatting
1073 * @param value
1074 * @param format - currency representation of the number 1234.56
1075 * @return string
1076 * @see CRM_Core_Resources::addCoreResources
1077 */
1078 var currencyTemplate;
1079 CRM.formatMoney = function(value, format) {
1080 var decimal, separator, sign, i, j, result;
1081 if (value === 'init' && format) {
1082 currencyTemplate = format;
1083 return;
1084 }
1085 format = format || currencyTemplate;
1086 result = /1(.?)234(.?)56/.exec(format);
1087 if (result === null) {
1088 return 'Invalid format passed to CRM.formatMoney';
1089 }
1090 separator = result[1];
1091 decimal = result[2];
1092 sign = (value < 0) ? '-' : '';
1093 //extracting the absolute value of the integer part of the number and converting to string
1094 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
1095 j = ((j = i.length) > 3) ? j % 3 : 0;
1096 result = sign + (j ? i.substr(0, j) + separator : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + separator) + (2 ? decimal + Math.abs(value - i).toFixed(2).slice(2) : '');
1097 return format.replace(/1.*234.*56/, result);
1098 };
1099 })(jQuery);