CRM-10760 - Autocomplte - Create utility to abstract rendering of autocomplete output
[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
6a488035
TO
174/**
175 * reset all the radio buttons with a given name
176 *
177 * @param string fieldName
178 * @param object form
179 * @return null
180 */
181function unselectRadio(fieldName, form) {
0f5816a6
KJ
182 for (i = 0; i < document.forms[form].elements.length; i++) {
183 if (document.forms[form].elements[i].name == fieldName) {
184 document.forms[form].elements[i].checked = false;
6a488035 185 }
0f5816a6
KJ
186 }
187 return;
6a488035
TO
188}
189
190/**
191 * Function to change button text and disable one it is clicked
192 *
193 * @param obj object - the button clicked
194 * @param formID string - the id of the form being submitted
195 * @param string procText - button text after user clicks it
196 * @return null
197 */
0f5816a6 198var submitcount = 0;
c6edd786 199/* Changes button label on submit, and disables button after submit for newer browsers.
200 Puts up alert for older browsers. */
0f5816a6
KJ
201function submitOnce(obj, formId, procText) {
202 // if named button clicked, change text
203 if (obj.value != null) {
204 obj.value = procText + " ...";
205 }
206 if (document.getElementById) { // disable submit button for newer browsers
207 obj.disabled = true;
208 document.getElementById(formId).submit();
209 return true;
210 }
211 else { // for older browsers
212 if (submitcount == 0) {
213 submitcount++;
214 return true;
215 }
216 else {
217 alert("Your request is currently being processed ... Please wait.");
218 return false;
6a488035 219 }
0f5816a6 220 }
6a488035
TO
221}
222
223function popUp(URL) {
224 day = new Date();
0f5816a6 225 id = day.getTime();
6a488035
TO
226 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');");
227}
228
6a488035
TO
229/**
230 * Function to show / hide the row in optionFields
231 *
232 * @param element name index, that whose innerHTML is to hide else will show the hidden row.
233 */
0f5816a6
KJ
234function showHideRow(index) {
235 if (index) {
236 cj('tr#optionField_' + index).hide();
237 if (cj('table#optionField tr:hidden:first').length) {
238 cj('div#optionFieldLink').show();
6a488035 239 }
0f5816a6
KJ
240 }
241 else {
242 cj('table#optionField tr:hidden:first').show();
243 if (!cj('table#optionField tr:hidden:last').length) {
244 cj('div#optionFieldLink').hide();
245 }
246 }
247 return false;
6a488035
TO
248}
249
6a488035
TO
250CRM.strings = CRM.strings || {};
251CRM.validate = CRM.validate || {
252 params: {},
253 functions: []
254};
255
0f5816a6 256(function ($, undefined) {
7553cf23 257 "use strict";
d664f648
CW
258
259 $(document).on('crmLoad', function(e) {
260 $('table.row-highlight', e.target)
261 .off('.rowHighlight')
262 .on('change.rowHighlight', 'input.select-row, input.select-rows', function () {
263 var target, table = $(this).closest('table');
264 if ($(this).hasClass('select-rows')) {
265 target = $('tbody tr', table);
266 $('input.select-row', table).prop('checked', $(this).prop('checked'));
267 }
268 else {
269 target = $(this).closest('tr');
270 $('input.select-rows', table).prop('checked', $(".select-row:not(':checked')", table).length < 1);
271 }
272 target.toggleClass('crm-row-selected', $(this).is(':checked'));
273 })
274 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
6a488035 275 });
148c4e8d
CW
276
277 /**
278 * Function to make multiselect boxes behave as fields in small screens
279 */
280 function advmultiselectResize() {
281 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
282 if (amswidth < 700) {
283 $("form table.advmultiselect td").css('display', 'block');
0f5816a6
KJ
284 }
285 else {
148c4e8d
CW
286 $("form table.advmultiselect td").css('display', 'table-cell');
287 }
288 var contactwidth = $('#crm-container #mainTabContainer').width();
289 if (contactwidth < 600) {
290 $('#crm-container #mainTabContainer').addClass('narrowpage');
0f5816a6 291 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
148c4e8d 292 if (index > 1) {
0f5816a6 293 if (index % 2 == 0) {
148c4e8d
CW
294 $(this).parent().after('<tr class="narrowadded"></tr>');
295 }
296 var item = $(this);
297 $(this).parent().next().append(item);
298 }
299 });
0f5816a6
KJ
300 }
301 else {
148c4e8d 302 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
0f5816a6 303 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
148c4e8d
CW
304 var nitem = $(this);
305 var parent = $(this).parent();
306 $(this).parent().prev().append(nitem);
0f5816a6 307 if (parent.children().size() == 0) {
148c4e8d
CW
308 parent.remove();
309 }
310 });
311 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
312 }
313 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
0f5816a6 314
148c4e8d
CW
315 if (cformwidth < 720) {
316 $('#crm-container .contact_basic_information-section').addClass('narrowform');
317 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
318 if (cformwidth < 480) {
319 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
0f5816a6
KJ
320 }
321 else {
148c4e8d
CW
322 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
323 }
0f5816a6
KJ
324 }
325 else {
148c4e8d
CW
326 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
327 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
328 }
329 }
0f5816a6 330
148c4e8d 331 advmultiselectResize();
0f5816a6 332 $(window).resize(function () {
6a488035
TO
333 advmultiselectResize();
334 });
335
0f5816a6 336 $.fn.crmtooltip = function () {
2c29c2ac
RN
337 $(document)
338 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
339 $(this).addClass('crm-processed');
e24b17b9
CW
340 $(this).addClass('crm-tooltip-active');
341 var topDistance = e.pageY - $(window).scrollTop();
342 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
343 $(this).addClass('crm-tooltip-down');
344 }
345 if (!$(this).children('.crm-tooltip-wrapper').length) {
6a488035
TO
346 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
347 $(this).children().children('.crm-tooltip')
348 .html('<div class="crm-loading-element"></div>')
349 .load(this.href);
350 }
351 })
2c29c2ac
RN
352 .on('mouseout', 'a.crm-summary-link', function () {
353 $(this).removeClass('crm-processed');
e24b17b9
CW
354 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
355 })
2c29c2ac 356 .on('click', 'a.crm-summary-link', false);
6a488035
TO
357 };
358
359 var h;
8e3272a1 360 CRM.help = function (title, params, url) {
6a488035
TO
361 h && h.close && h.close();
362 var options = {
363 expires: 0
364 };
365 h = CRM.alert('...', title, 'crm-help crm-msg-loading', options);
366 params.class_name = 'CRM_Core_Page_Inline_Help';
367 params.type = 'page';
8e3272a1 368 $.ajax(url || CRM.url('civicrm/ajax/inline'),
6a488035
TO
369 {
370 data: params,
371 dataType: 'html',
e24b17b9 372 success: function (data) {
6a488035
TO
373 $('#crm-notification-container .crm-help .notify-content:last').html(data);
374 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
375 },
e24b17b9 376 error: function () {
6a488035
TO
377 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
378 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
379 }
380 }
381 );
382 };
8960d9b9
CW
383 /**
384 * @param startMsg string
385 * @param endMsg string|function
386 * @param deferred optional jQuery deferred object
387 * @return jQuery deferred object - if not supplied a new one will be created
388 */
389 var fadeOut;
390 CRM.status = function(startMsg, endMsg, deferred) {
391 var $bar = $('#civicrm-menu');
392 if (!$bar.length) {
393 console && console.log && console.log('CRM.status called on a page with no menubar');
394 return;
395 }
396 $('.crm-menubar-status-container', $bar).remove();
397 fadeOut && window.clearTimeout(fadeOut);
398 $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>');
399 $('.crm-menubar-status-container', $bar).css('min-width', $('.crm-menubar-status-container', $bar).width());
400 deferred || (deferred = new $.Deferred());
401 deferred.done(function(data) {
402 var msg = typeof(endMsg) === 'function' ? endMsg(data) : endMsg;
4bad157e
CW
403 $('.crm-menubar-status-container', $bar).removeClass('status-busy').addClass('status-done').show().find('.crm-menubar-status-msg').html(msg);
404 if (msg) {
405 fadeOut = window.setTimeout(function() {
406 $('.crm-menubar-status-container', $bar).fadeOut('slow');
407 }, 2000);
408 } else {
409 $('.crm-menubar-status-container', $bar).hide();
410 }
8960d9b9
CW
411 });
412 return deferred;
413 };
6a488035
TO
414
415 /**
416 * @param string text Displayable message
417 * @param string title Displayable title
418 * @param string type 'alert'|'info'|'success'|'error' (default: 'alert')
419 * @param {object} options
420 * @return {*}
421 * @see http://wiki.civicrm.org/confluence/display/CRM/Notifications+in+CiviCRM
422 */
0f5816a6 423 CRM.alert = function (text, title, type, options) {
6a488035
TO
424 type = type || 'alert';
425 title = title || '';
426 options = options || {};
427 if ($('#crm-notification-container').length) {
428 var params = {
429 text: text,
430 title: title,
431 type: type
432 };
433 // By default, don't expire errors and messages containing links
434 var extra = {
435 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
436 unique: true
437 };
438 options = $.extend(extra, options);
e24b17b9 439 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
6a488035 440 if (options.unique && options.unique !== '0') {
0f5816a6 441 $('#crm-notification-container .ui-notify-message').each(function () {
6a488035
TO
442 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
443 $('.icon.ui-notify-close', this).click();
444 }
445 });
446 }
447 return $('#crm-notification-container').notify('create', params, options);
448 }
449 else {
450 if (title.length) {
451 text = title + "\n" + text;
452 }
453 alert(text);
454 return null;
455 }
e24b17b9 456 };
6a488035
TO
457
458 /**
459 * Close whichever alert contains the given node
460 *
461 * @param node
462 */
0f5816a6 463 CRM.closeAlertByChild = function (node) {
6a488035 464 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
e24b17b9 465 };
6a488035
TO
466
467 /**
468 * Prompt the user for confirmation.
469 *
7553cf23
CW
470 * @param buttons {object|function} key|value pairs where key == button label and value == callback function
471 * passing in a function instead of an object is a shortcut for a sinlgle button labeled "Continue"
472 * @param options {object|void} Override defaults, keys include 'title', 'message',
473 * see jQuery.dialog for full list of available params
6a488035 474 */
706cff6d 475 CRM.confirm = function (buttons, options, cancelLabel) {
7553cf23 476 var dialog, callbacks = {};
706cff6d 477 cancelLabel = cancelLabel || ts('Cancel');
7553cf23
CW
478 var settings = {
479 title: ts('Confirm Action'),
480 message: ts('Are you sure you want to continue?'),
6a488035
TO
481 resizable: false,
482 modal: true,
0d5f99d4 483 width: 'auto',
0f5816a6
KJ
484 close: function () {
485 $(dialog).remove();
486 },
7553cf23
CW
487 buttons: {}
488 };
706cff6d
KJ
489
490 settings.buttons[cancelLabel] = function () {
0f5816a6
KJ
491 dialog.dialog('close');
492 };
7553cf23
CW
493 options = options || {};
494 $.extend(settings, options);
495 if (typeof(buttons) === 'function') {
496 callbacks[ts('Continue')] = buttons;
0f5816a6
KJ
497 }
498 else {
7553cf23
CW
499 callbacks = buttons;
500 }
0f5816a6
KJ
501 $.each(callbacks, function (label, callback) {
502 settings.buttons[label] = function () {
7553cf23
CW
503 callback.call(dialog);
504 dialog.dialog('close');
e24b17b9 505 };
6a488035 506 });
7553cf23
CW
507 dialog = $('<div class="crm-container crm-confirm-dialog"></div>')
508 .html(options.message)
509 .appendTo('body')
510 .dialog(settings);
511 return dialog;
e24b17b9 512 };
6a488035
TO
513
514 /**
515 * Sets an error message
516 * If called for a form item, title and removal condition will be handled automatically
517 */
0f5816a6 518 $.fn.crmError = function (text, title, options) {
6a488035
TO
519 title = title || '';
520 text = text || '';
521 options = options || {};
522
523 var extra = {
524 expires: 0
525 };
526 if ($(this).length) {
527 if (title == '') {
528 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
529 if (label.length) {
530 label.addClass('crm-error');
531 var $label = label.clone();
532 if (text == '' && $('.crm-marker', $label).length > 0) {
533 text = $('.crm-marker', $label).attr('title');
534 }
535 $('.crm-marker', $label).remove();
536 title = $label.text();
537 }
538 }
539 $(this).addClass('error');
540 }
541 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
542 if ($(this).length) {
543 var ele = $(this);
0f5816a6
KJ
544 setTimeout(function () {
545 ele.one('change', function () {
546 msg && msg.close && msg.close();
547 ele.removeClass('error');
548 label.removeClass('crm-error');
549 });
550 }, 1000);
6a488035
TO
551 }
552 return msg;
e24b17b9 553 };
6a488035
TO
554
555 // Display system alerts through js notifications
556 function messagesFromMarkup() {
0f5816a6 557 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
e24b17b9 558 var text, title = '';
6a488035
TO
559 $(this).removeClass('status messages');
560 var type = $(this).attr('class').split(' ')[0] || 'alert';
561 type = type.replace('crm-', '');
562 $('.icon', this).remove();
6a488035 563 if ($('.msg-text', this).length > 0) {
e24b17b9 564 text = $('.msg-text', this).html();
6a488035
TO
565 title = $('.msg-title', this).html();
566 }
567 else {
e24b17b9 568 text = $(this).html();
6a488035
TO
569 }
570 var options = $(this).data('options') || {};
571 $(this).remove();
572 // Duplicates were already removed server-side
573 options.unique = false;
574 CRM.alert(text, title, type, options);
575 });
576 // Handle qf form errors
577 $('form :input.error', this).one('blur', function() {
ef04c554 578 // ignore autocomplete fields
23246a80 579 if ($(this).is('.ac_input')) {
580 return;
581 }
ef04c554 582
6a488035
TO
583 $('.ui-notify-message.error a.ui-notify-close').click();
584 $(this).removeClass('error');
585 $(this).next('span.crm-error').remove();
586 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
587 .removeClass('crm-error')
588 .find('.crm-error').removeClass('crm-error');
589 });
590 }
591
23223213 592 $.widget('civi.crmSnippet', {
205bb8ae 593 options: {
a73f25bb 594 url: null,
205bb8ae
CW
595 block: true,
596 crmForm: null
597 },
c02f8fc4 598 _originalContent: null,
fa3a5fe2
CW
599 _originalUrl: null,
600 isOriginalUrl: function() {
0906345e
CW
601 var
602 args = {},
603 same = true,
604 newUrl = this._formatUrl(this.options.url),
605 oldUrl = this._formatUrl(this._originalUrl);
fa3a5fe2 606 // Compare path
0906345e 607 if (newUrl.split('?')[0] !== oldUrl.split('?')[0]) {
fa3a5fe2
CW
608 return false;
609 }
610 // Compare arguments
0906345e 611 $.each(newUrl.split('?')[1].split('&'), function(k, v) {
fa3a5fe2
CW
612 var arg = v.split('=');
613 args[arg[0]] = arg[1];
614 });
0906345e 615 $.each(oldUrl.split('?')[1].split('&'), function(k, v) {
fa3a5fe2
CW
616 var arg = v.split('=');
617 if (args[arg[0]] !== undefined && arg[1] !== args[arg[0]]) {
618 same = false;
619 }
620 });
621 return same;
622 },
623 resetUrl: function() {
624 this.options.url = this._originalUrl;
625 },
205bb8ae 626 _create: function() {
205bb8ae
CW
627 this.element.addClass('crm-ajax-container');
628 if (!this.element.is('.crm-container *')) {
629 this.element.addClass('crm-container');
630 }
4a140040 631 this._handleOrderLinks();
5d92a7e7
CW
632 // Set default if not supplied
633 this.options.url = this.options.url || document.location.href;
fa3a5fe2 634 this._originalUrl = this.options.url;
205bb8ae
CW
635 },
636 _onFailure: function(data) {
637 this.options.block && this.element.unblock();
638 this.element.trigger('crmAjaxFail', data);
639 CRM.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
640 },
641 _formatUrl: function(url) {
0906345e
CW
642 // Strip hash
643 url = url.split('#')[0];
205bb8ae
CW
644 // Add snippet argument to url
645 if (url.search(/[&?]snippet=/) < 0) {
fc05b8da 646 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
8547369d
CW
647 } else {
648 url = url.replace(/snippet=[^&]*/, 'snippet=json');
205bb8ae
CW
649 }
650 return url;
651 },
d6539f93 652 // Hack to deal with civicrm legacy sort functionality
4a140040
CW
653 _handleOrderLinks: function() {
654 var that = this;
655 $('a.crm-weight-arrow', that.element).click(function(e) {
656 that.options.block && that.element.block();
657 $.getJSON(that._formatUrl(this.href)).done(function() {
658 that.refresh();
659 });
660 e.stopImmediatePropagation();
661 return false;
662 });
663 },
205bb8ae
CW
664 refresh: function() {
665 var that = this;
666 var url = this._formatUrl(this.options.url);
4a140040 667 this.options.block && $('.blockOverlay', this.element).length < 1 && this.element.block();
205bb8ae
CW
668 $.getJSON(url, function(data) {
669 if (typeof(data) != 'object' || typeof(data.content) != 'string') {
670 that._onFailure(data);
671 return;
672 }
673 data.url = url;
c02f8fc4
CW
674 that.element.trigger('crmBeforeLoad', data);
675 if (that._originalContent === null) {
676 that._originalContent = that.element.contents().detach();
677 }
678 that.element.html(data.content);
4a140040
CW
679 that._handleOrderLinks();
680 that.element.trigger('crmLoad', data);
205bb8ae
CW
681 that.options.crmForm && that.element.trigger('crmFormLoad', data);
682 }).fail(function() {
683 that._onFailure();
684 });
4b628e67
CW
685 },
686 _destroy: function() {
687 this.element.removeClass('crm-ajax-container');
c02f8fc4
CW
688 if (this._originalContent !== null) {
689 this.element.empty().append(this._originalContent);
690 }
205bb8ae
CW
691 }
692 });
693
0e017a41 694 var dialogCount = 0;
d4e4e9df 695 CRM.loadPage = function(url, options) {
d4e4e9df 696 var settings = {
0e017a41 697 target: '#crm-ajax-dialog-' + (dialogCount++),
8547369d
CW
698 dialog: false
699 };
700 if (!options || !options.target) {
701 settings.dialog = {
d4e4e9df 702 modal: true,
f84151fd
CW
703 width: '65%',
704 height: parseInt($(window).height() * .75),
d4e4e9df 705 close: function() {
c02f8fc4 706 $(this).dialog('destroy').remove();
d4e4e9df 707 }
8547369d
CW
708 };
709 }
205bb8ae 710 options && $.extend(true, settings, options);
0e017a41 711 settings.url = url;
83df6b4a 712 // Create new dialog
8547369d 713 if (settings.dialog) {
205bb8ae 714 $('<div id="'+ settings.target.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings.dialog);
d4e4e9df 715 }
205bb8ae
CW
716 if (settings.dialog && !settings.dialog.title) {
717 $(settings.target).on('crmLoad', function(event, data) {
718 data.title && $(this).dialog('option', 'title', data.title);
719 });
720 }
5d92a7e7
CW
721 $(settings.target).crmSnippet(settings).crmSnippet('refresh');
722 return $(settings.target);
d4e4e9df
CW
723 };
724
725 CRM.loadForm = function(url, options) {
d4e4e9df 726 var settings = {
205bb8ae
CW
727 crmForm: {
728 ajaxForm: {},
205bb8ae
CW
729 autoClose: true,
730 validate: true,
731 refreshAction: ['next_new', 'submit_savenext'],
732 cancelButton: '.cancel.form-submit',
23223213 733 openInline: 'a.button:not("[href=#], .no-popup")',
205bb8ae
CW
734 onCancel: function(event) {},
735 onError: function(data) {
736 var $el = $(this);
5d92a7e7 737 $el.html(data.content).trigger('crmLoad', data).trigger('crmFormLoad', data).trigger('crmFormError', data);
205bb8ae
CW
738 if (typeof(data.errors) == 'object') {
739 $.each(data.errors, function(formElement, msg) {
740 $('[name="'+formElement+'"]', $el).crmError(msg);
741 });
742 }
d4e4e9df 743 }
d4e4e9df
CW
744 }
745 };
a10432db
CW
746 // Hack to make delete dialogs smaller
747 if (url.indexOf('/delete') > 0 || url.indexOf('action=delete') > 0) {
748 settings.dialog = {
749 width: 400,
750 height: 300
751 };
752 }
205bb8ae
CW
753 // Move options that belong to crmForm. Others will be passed through to crmSnippet
754 options && $.each(options, function(key, value) {
755 if (typeof(settings.crmForm[key]) !== 'undefined') {
756 settings.crmForm[key] = value;
757 }
758 else {
759 settings[key] = value;
760 }
761 });
205bb8ae
CW
762
763 var widget = CRM.loadPage(url, settings);
764
765 widget.on('crmFormLoad', function(event, data) {
766 var $el = $(this);
660c46f3 767 var settings = $el.crmSnippet('option', 'crmForm');
205bb8ae
CW
768 settings.cancelButton && $(settings.cancelButton, this).click(function(event) {
769 var returnVal = settings.onCancel.call($el, event);
770 if (returnVal !== false) {
771 $el.trigger('crmFormCancel', event);
660c46f3 772 if ($el.data('uiDialog') && settings.autoClose) {
fa3a5fe2
CW
773 $el.dialog('close');
774 }
775 else if (!settings.autoClose) {
776 $el.crmSnippet('resetUrl').crmSnippet('refresh');
777 }
0e017a41 778 }
205bb8ae
CW
779 return returnVal === false;
780 });
d4e4e9df 781 if (settings.validate) {
0e017a41 782 $("form", this).validate(typeof(settings.validate) == 'object' ? settings.validate : CRM.validate.params);
d4e4e9df 783 }
205bb8ae 784 $("form", this).ajaxForm($.extend({
fa3a5fe2 785 url: data.url.replace(/reset=1[&]?/, ''),
d4e4e9df
CW
786 dataType: 'json',
787 success: function(response) {
34866662 788 if (response.status !== 'form_error') {
36876f55 789 $el.crmSnippet('option', 'block') && $el.unblock();
205bb8ae 790 $el.trigger('crmFormSuccess', response);
0e017a41 791 // Reset form for e.g. "save and new"
d6539f93 792 if (response.userContext && settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0) {
205bb8ae 793 $el.crmSnippet('option', 'url', response.userContext).crmSnippet('refresh');
0e017a41 794 }
660c46f3 795 else if ($el.data('uiDialog') && settings.autoClose) {
205bb8ae 796 $el.dialog('close');
83df6b4a 797 }
d6539f93
CW
798 else if (settings.autoClose === false) {
799 $el.crmSnippet('resetUrl').crmSnippet('refresh');
800 }
d4e4e9df
CW
801 }
802 else {
25bbc4c0 803 response.url = data.url;
205bb8ae 804 settings.onError.call($el, response);
d4e4e9df 805 }
23223213
CW
806 },
807 beforeSerialize: function(form, options) {
808 if (window.CKEDITOR && window.CKEDITOR.instances) {
a10432db
CW
809 $.each(CKEDITOR.instances, function() {
810 this.updateElement && this.updateElement();
811 });
23223213 812 }
83df6b4a 813 },
205bb8ae 814 beforeSubmit: function(submission) {
36876f55 815 $el.crmSnippet('option', 'block') && $el.block();
205bb8ae 816 $el.trigger('crmFormSubmit', submission);
d4e4e9df 817 }
205bb8ae 818 }, settings.ajaxForm));
fa3a5fe2
CW
819 if (settings.openInline) {
820 settings.autoClose = $el.crmSnippet('isOriginalUrl');
821 $(settings.openInline, this).click(function(event) {
822 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
823 return false;
824 });
825 }
205bb8ae
CW
826 });
827 return widget;
d4e4e9df
CW
828 };
829
03a7ec8f
CW
830 // Preprocess all cj ajax calls to display messages
831 $(document).ajaxSuccess(function(event, xhr, settings) {
832 try {
833 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
834 var response = $.parseJSON(xhr.responseText);
835 if (typeof(response.crmMessages) == 'object') {
836 $.each(response.crmMessages, function(n, msg) {
837 CRM.alert(msg.text, msg.title, msg.type, msg.options);
838 })
839 }
840 }
841 }
842 // Suppress errors
843 catch (e) {}
844 });
845
0f5816a6 846 $(function () {
205bb8ae 847 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
8547369d 848 $('.crm-container').trigger('crmLoad');
205bb8ae 849
ef3309b6 850 if ($('#crm-notification-container').length) {
6a488035
TO
851 // Initialize notifications
852 $('#crm-notification-container').notify();
853 messagesFromMarkup.call($('#crm-container'));
6a488035 854 }
ebb9197b
C
855
856 // bind the event for image popup
857 $('body').on('click', 'a.crm-image-popup', function() {
858 var o = $('<div class="crm-container crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
859
860 CRM.confirm('',
861 {
862 title: ts('Preview'),
863 message: o
864 },
865 ts('Done')
866 );
867 return false;
868 });
d664f648
CW
869
870 $().crmtooltip();
871 $('body').on('click', function (event) {
872 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
873 if ($(event.target).is('.btn-slide')) {
874 $(event.target).addClass('btn-slide-active').find('.panel').show();
875 }
876 });
6a488035
TO
877 });
878
0f5816a6 879 $.fn.crmAccordions = function (speed) {
cf021bc5
CW
880 var container = $(this).length > 0 ? $(this) : $('.crm-container');
881 speed = speed === undefined ? 200 : speed;
882 container
883 .off('click.crmAccordions')
6a488035 884 // Allow normal clicking of links
cf021bc5 885 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
6a488035 886 e.stopPropagation && e.stopPropagation();
cf021bc5
CW
887 })
888 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
6a488035
TO
889 if ($(this).parent().hasClass('collapsed')) {
890 $(this).next().css('display', 'none').slideDown(speed);
891 }
892 else {
893 $(this).next().css('display', 'block').slideUp(speed);
894 }
895 $(this).parent().toggleClass('collapsed');
896 return false;
897 });
6a488035 898 };
0f5816a6
KJ
899 $.fn.crmAccordionToggle = function (speed) {
900 $(this).each(function () {
6a488035
TO
901 if ($(this).hasClass('collapsed')) {
902 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
903 }
904 else {
905 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
906 }
907 $(this).toggleClass('collapsed');
908 });
909 };
5ec182d9
CW
910
911 /**
912 * Clientside currency formatting
913 * @param value
3bdb644f 914 * @param format - currency representation of the number 1234.56
5ec182d9 915 * @return string
3bdb644f 916 * @see CRM_Core_Resources::addCoreResources
5ec182d9
CW
917 */
918 var currencyTemplate;
919 CRM.formatMoney = function(value, format) {
920 var decimal, separator, sign, i, j, result;
921 if (value === 'init' && format) {
922 currencyTemplate = format;
923 return;
924 }
925 format = format || currencyTemplate;
926 result = /1(.?)234(.?)56/.exec(format);
927 if (result === null) {
928 return 'Invalid format passed to CRM.formatMoney';
929 }
930 separator = result[1];
931 decimal = result[2];
932 sign = (value < 0) ? '-' : '';
933 //extracting the absolute value of the integer part of the number and converting to string
934 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
5ec182d9
CW
935 j = ((j = i.length) > 3) ? j % 3 : 0;
936 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) : '');
937 return format.replace(/1.*234.*56/, result);
938 };
6a488035 939})(jQuery);