CRM-13970 - Fix admin option links
[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
475e9f44 250CRM.utils = CRM.utils || {};
6a488035
TO
251CRM.strings = CRM.strings || {};
252CRM.validate = CRM.validate || {
253 params: {},
254 functions: []
255};
256
0f5816a6 257(function ($, undefined) {
7553cf23 258 "use strict";
d664f648 259
47f21f3a
CW
260 // Set select2 defaults
261 $.fn.select2.defaults.minimumResultsForSearch = 10;
262 // https://github.com/ivaynberg/select2/pull/2090
263 $.fn.select2.defaults.width = 'resolve';
264
e20523a8
CW
265 // Workaround for https://github.com/ivaynberg/select2/issues/1246
266 $.ui.dialog.prototype._allowInteraction = function(e) {
267 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop').length;
268 };
269
475e9f44
CW
270 /**
271 * Populate a select list, overwriting the existing options except for the placeholder.
272 * @param $el jquery collection - 1 or more select elements
273 * @param options array in format returned by api.getoptions
274 */
275 CRM.utils.setOptions = function($el, options) {
276 $el.each(function() {
277 var
278 $elect = $(this),
279 val = $elect.val() || [];
280 if (typeof(val) !== 'array') {
281 val = [val];
282 }
283 $elect.find('option[value!=""]').remove();
284 $.each(options, function(key, option) {
285 var selected = ($.inArray(''+option.key, val) > -1) ? 'selected="selected"' : '';
286 $elect.append('<option value="' + option.key + '"' + selected + '>' + option.value + '</option>');
287 });
288 $elect.trigger('change');
289 });
290 };
291
f7b92fcd 292 // Initialize widgets
d664f648
CW
293 $(document).on('crmLoad', function(e) {
294 $('table.row-highlight', e.target)
295 .off('.rowHighlight')
296 .on('change.rowHighlight', 'input.select-row, input.select-rows', function () {
297 var target, table = $(this).closest('table');
298 if ($(this).hasClass('select-rows')) {
299 target = $('tbody tr', table);
300 $('input.select-row', table).prop('checked', $(this).prop('checked'));
301 }
302 else {
303 target = $(this).closest('tr');
304 $('input.select-rows', table).prop('checked', $(".select-row:not(':checked')", table).length < 1);
305 }
306 target.toggleClass('crm-row-selected', $(this).is(':checked'));
307 })
308 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
f7b92fcd 309 $('.crm-select2', e.target).each(function() {
f411b7d5
CW
310 // quickform doesn't support optgroups so here's a hack :(
311 $('option[value^=crm_optgroup]', this).each(function() {
312 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
313 $(this).remove();
314 });
47f21f3a 315 var options = $(this).data('select-params') || {};
a3162197
CW
316 // Set placeholder from markup if not specified
317 if ($(this).is('select:not([multiple])')) {
318 options.allowClear = options.allowClear !== undefined ? options.allowClear : !($(this).hasClass('required'));
319 if (options.placeHolder === undefined && $('option:first', this).val() === '') {
320 options.placeholderOption = 'first';
321 }
322 }
47f21f3a
CW
323 // Api-based searching
324 if ($(this).data('api-params')) {
325 $(this).addClass('crm-ajax-select')
326 options.query = function(info) {
327 var api = $(info.element).data('api-params');
328 var params = api.params || {};
329 params[api.search] = info.term;
330 CRM.api3(api.entity, api.action, params).done(function(data) {
331 var results = {context: info.context, results: []};
332 if (typeof(data.values) === 'object') {
333 $.each(data.values, function(k, v) {
334 results.results.push({id: v[api.key], text: v[api.label]});
335 });
336 }
337 info.callback(results);
338 });
339 };
340 options.initSelection = function(el, callback) {
341 callback(el.data('entity-value'));
342 };
343 }
ab345ca5 344 $(this).select2(options).removeClass('crm-select2');
f7b92fcd 345 });
6a488035 346 });
148c4e8d
CW
347
348 /**
349 * Function to make multiselect boxes behave as fields in small screens
350 */
351 function advmultiselectResize() {
352 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
353 if (amswidth < 700) {
354 $("form table.advmultiselect td").css('display', 'block');
0f5816a6
KJ
355 }
356 else {
148c4e8d
CW
357 $("form table.advmultiselect td").css('display', 'table-cell');
358 }
359 var contactwidth = $('#crm-container #mainTabContainer').width();
360 if (contactwidth < 600) {
361 $('#crm-container #mainTabContainer').addClass('narrowpage');
0f5816a6 362 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
148c4e8d 363 if (index > 1) {
0f5816a6 364 if (index % 2 == 0) {
148c4e8d
CW
365 $(this).parent().after('<tr class="narrowadded"></tr>');
366 }
367 var item = $(this);
368 $(this).parent().next().append(item);
369 }
370 });
0f5816a6
KJ
371 }
372 else {
148c4e8d 373 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
0f5816a6 374 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
148c4e8d
CW
375 var nitem = $(this);
376 var parent = $(this).parent();
377 $(this).parent().prev().append(nitem);
0f5816a6 378 if (parent.children().size() == 0) {
148c4e8d
CW
379 parent.remove();
380 }
381 });
382 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
383 }
384 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
0f5816a6 385
148c4e8d
CW
386 if (cformwidth < 720) {
387 $('#crm-container .contact_basic_information-section').addClass('narrowform');
388 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
389 if (cformwidth < 480) {
390 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
0f5816a6
KJ
391 }
392 else {
148c4e8d
CW
393 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
394 }
0f5816a6
KJ
395 }
396 else {
148c4e8d
CW
397 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
398 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
399 }
400 }
0f5816a6 401
148c4e8d 402 advmultiselectResize();
0f5816a6 403 $(window).resize(function () {
6a488035
TO
404 advmultiselectResize();
405 });
406
0f5816a6 407 $.fn.crmtooltip = function () {
2c29c2ac
RN
408 $(document)
409 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
410 $(this).addClass('crm-processed');
e24b17b9
CW
411 $(this).addClass('crm-tooltip-active');
412 var topDistance = e.pageY - $(window).scrollTop();
413 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
414 $(this).addClass('crm-tooltip-down');
415 }
416 if (!$(this).children('.crm-tooltip-wrapper').length) {
6a488035
TO
417 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
418 $(this).children().children('.crm-tooltip')
419 .html('<div class="crm-loading-element"></div>')
420 .load(this.href);
421 }
422 })
2c29c2ac
RN
423 .on('mouseout', 'a.crm-summary-link', function () {
424 $(this).removeClass('crm-processed');
e24b17b9
CW
425 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
426 })
2c29c2ac 427 .on('click', 'a.crm-summary-link', false);
6a488035
TO
428 };
429
b0ca6188 430 var helpDisplay, helpPrevious;
8e3272a1 431 CRM.help = function (title, params, url) {
55a93b02 432 if (helpDisplay && helpDisplay.close) {
b0ca6188 433 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
55a93b02
CW
434 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
435 helpDisplay.close();
b0ca6188
CW
436 return;
437 }
55a93b02 438 helpDisplay.close();
b0ca6188
CW
439 }
440 helpPrevious = JSON.stringify(params);
6a488035
TO
441 params.class_name = 'CRM_Core_Page_Inline_Help';
442 params.type = 'page';
b0ca6188 443 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
8e3272a1 444 $.ajax(url || CRM.url('civicrm/ajax/inline'),
6a488035
TO
445 {
446 data: params,
447 dataType: 'html',
e24b17b9 448 success: function (data) {
6a488035
TO
449 $('#crm-notification-container .crm-help .notify-content:last').html(data);
450 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
451 },
e24b17b9 452 error: function () {
6a488035
TO
453 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
454 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
455 }
456 }
457 );
458 };
8960d9b9
CW
459 /**
460 * @param startMsg string
461 * @param endMsg string|function
462 * @param deferred optional jQuery deferred object
463 * @return jQuery deferred object - if not supplied a new one will be created
464 */
465 var fadeOut;
466 CRM.status = function(startMsg, endMsg, deferred) {
467 var $bar = $('#civicrm-menu');
468 if (!$bar.length) {
469 console && console.log && console.log('CRM.status called on a page with no menubar');
470 return;
471 }
472 $('.crm-menubar-status-container', $bar).remove();
473 fadeOut && window.clearTimeout(fadeOut);
474 $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>');
475 $('.crm-menubar-status-container', $bar).css('min-width', $('.crm-menubar-status-container', $bar).width());
476 deferred || (deferred = new $.Deferred());
477 deferred.done(function(data) {
478 var msg = typeof(endMsg) === 'function' ? endMsg(data) : endMsg;
4bad157e
CW
479 $('.crm-menubar-status-container', $bar).removeClass('status-busy').addClass('status-done').show().find('.crm-menubar-status-msg').html(msg);
480 if (msg) {
481 fadeOut = window.setTimeout(function() {
482 $('.crm-menubar-status-container', $bar).fadeOut('slow');
483 }, 2000);
484 } else {
485 $('.crm-menubar-status-container', $bar).hide();
486 }
8960d9b9
CW
487 });
488 return deferred;
489 };
6a488035
TO
490
491 /**
492 * @param string text Displayable message
493 * @param string title Displayable title
494 * @param string type 'alert'|'info'|'success'|'error' (default: 'alert')
495 * @param {object} options
496 * @return {*}
497 * @see http://wiki.civicrm.org/confluence/display/CRM/Notifications+in+CiviCRM
498 */
0f5816a6 499 CRM.alert = function (text, title, type, options) {
6a488035
TO
500 type = type || 'alert';
501 title = title || '';
502 options = options || {};
503 if ($('#crm-notification-container').length) {
504 var params = {
505 text: text,
506 title: title,
507 type: type
508 };
509 // By default, don't expire errors and messages containing links
510 var extra = {
511 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
512 unique: true
513 };
514 options = $.extend(extra, options);
e24b17b9 515 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
6a488035 516 if (options.unique && options.unique !== '0') {
0f5816a6 517 $('#crm-notification-container .ui-notify-message').each(function () {
6a488035
TO
518 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
519 $('.icon.ui-notify-close', this).click();
520 }
521 });
522 }
523 return $('#crm-notification-container').notify('create', params, options);
524 }
525 else {
526 if (title.length) {
527 text = title + "\n" + text;
528 }
529 alert(text);
530 return null;
531 }
e24b17b9 532 };
6a488035
TO
533
534 /**
535 * Close whichever alert contains the given node
536 *
537 * @param node
538 */
0f5816a6 539 CRM.closeAlertByChild = function (node) {
6a488035 540 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
e24b17b9 541 };
6a488035
TO
542
543 /**
544 * Prompt the user for confirmation.
545 *
7553cf23
CW
546 * @param buttons {object|function} key|value pairs where key == button label and value == callback function
547 * passing in a function instead of an object is a shortcut for a sinlgle button labeled "Continue"
548 * @param options {object|void} Override defaults, keys include 'title', 'message',
549 * see jQuery.dialog for full list of available params
6a488035 550 */
706cff6d 551 CRM.confirm = function (buttons, options, cancelLabel) {
7553cf23 552 var dialog, callbacks = {};
706cff6d 553 cancelLabel = cancelLabel || ts('Cancel');
7553cf23
CW
554 var settings = {
555 title: ts('Confirm Action'),
556 message: ts('Are you sure you want to continue?'),
6a488035
TO
557 resizable: false,
558 modal: true,
0d5f99d4 559 width: 'auto',
0f5816a6
KJ
560 close: function () {
561 $(dialog).remove();
562 },
7553cf23
CW
563 buttons: {}
564 };
706cff6d
KJ
565
566 settings.buttons[cancelLabel] = function () {
0f5816a6
KJ
567 dialog.dialog('close');
568 };
7553cf23
CW
569 options = options || {};
570 $.extend(settings, options);
571 if (typeof(buttons) === 'function') {
572 callbacks[ts('Continue')] = buttons;
0f5816a6
KJ
573 }
574 else {
7553cf23
CW
575 callbacks = buttons;
576 }
0f5816a6
KJ
577 $.each(callbacks, function (label, callback) {
578 settings.buttons[label] = function () {
7553cf23
CW
579 callback.call(dialog);
580 dialog.dialog('close');
e24b17b9 581 };
6a488035 582 });
7553cf23
CW
583 dialog = $('<div class="crm-container crm-confirm-dialog"></div>')
584 .html(options.message)
585 .appendTo('body')
586 .dialog(settings);
587 return dialog;
e24b17b9 588 };
6a488035
TO
589
590 /**
591 * Sets an error message
592 * If called for a form item, title and removal condition will be handled automatically
593 */
0f5816a6 594 $.fn.crmError = function (text, title, options) {
6a488035
TO
595 title = title || '';
596 text = text || '';
597 options = options || {};
598
599 var extra = {
600 expires: 0
601 };
602 if ($(this).length) {
603 if (title == '') {
604 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
605 if (label.length) {
606 label.addClass('crm-error');
607 var $label = label.clone();
608 if (text == '' && $('.crm-marker', $label).length > 0) {
609 text = $('.crm-marker', $label).attr('title');
610 }
611 $('.crm-marker', $label).remove();
612 title = $label.text();
613 }
614 }
615 $(this).addClass('error');
616 }
617 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
618 if ($(this).length) {
619 var ele = $(this);
0f5816a6
KJ
620 setTimeout(function () {
621 ele.one('change', function () {
622 msg && msg.close && msg.close();
623 ele.removeClass('error');
624 label.removeClass('crm-error');
625 });
626 }, 1000);
6a488035
TO
627 }
628 return msg;
e24b17b9 629 };
6a488035
TO
630
631 // Display system alerts through js notifications
632 function messagesFromMarkup() {
0f5816a6 633 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
e24b17b9 634 var text, title = '';
6a488035
TO
635 $(this).removeClass('status messages');
636 var type = $(this).attr('class').split(' ')[0] || 'alert';
637 type = type.replace('crm-', '');
638 $('.icon', this).remove();
6a488035 639 if ($('.msg-text', this).length > 0) {
e24b17b9 640 text = $('.msg-text', this).html();
6a488035
TO
641 title = $('.msg-title', this).html();
642 }
643 else {
e24b17b9 644 text = $(this).html();
6a488035
TO
645 }
646 var options = $(this).data('options') || {};
647 $(this).remove();
648 // Duplicates were already removed server-side
649 options.unique = false;
650 CRM.alert(text, title, type, options);
651 });
652 // Handle qf form errors
653 $('form :input.error', this).one('blur', function() {
ef04c554 654 // ignore autocomplete fields
23246a80 655 if ($(this).is('.ac_input')) {
656 return;
657 }
ef04c554 658
6a488035
TO
659 $('.ui-notify-message.error a.ui-notify-close').click();
660 $(this).removeClass('error');
661 $(this).next('span.crm-error').remove();
662 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
663 .removeClass('crm-error')
664 .find('.crm-error').removeClass('crm-error');
665 });
666 }
667
23223213 668 $.widget('civi.crmSnippet', {
205bb8ae 669 options: {
a73f25bb 670 url: null,
205bb8ae
CW
671 block: true,
672 crmForm: null
673 },
c02f8fc4 674 _originalContent: null,
fa3a5fe2
CW
675 _originalUrl: null,
676 isOriginalUrl: function() {
0906345e
CW
677 var
678 args = {},
679 same = true,
680 newUrl = this._formatUrl(this.options.url),
681 oldUrl = this._formatUrl(this._originalUrl);
fa3a5fe2 682 // Compare path
0906345e 683 if (newUrl.split('?')[0] !== oldUrl.split('?')[0]) {
fa3a5fe2
CW
684 return false;
685 }
686 // Compare arguments
0906345e 687 $.each(newUrl.split('?')[1].split('&'), function(k, v) {
fa3a5fe2
CW
688 var arg = v.split('=');
689 args[arg[0]] = arg[1];
690 });
0906345e 691 $.each(oldUrl.split('?')[1].split('&'), function(k, v) {
fa3a5fe2
CW
692 var arg = v.split('=');
693 if (args[arg[0]] !== undefined && arg[1] !== args[arg[0]]) {
694 same = false;
695 }
696 });
697 return same;
698 },
699 resetUrl: function() {
700 this.options.url = this._originalUrl;
701 },
205bb8ae 702 _create: function() {
205bb8ae
CW
703 this.element.addClass('crm-ajax-container');
704 if (!this.element.is('.crm-container *')) {
705 this.element.addClass('crm-container');
706 }
4a140040 707 this._handleOrderLinks();
5d92a7e7
CW
708 // Set default if not supplied
709 this.options.url = this.options.url || document.location.href;
fa3a5fe2 710 this._originalUrl = this.options.url;
205bb8ae
CW
711 },
712 _onFailure: function(data) {
713 this.options.block && this.element.unblock();
714 this.element.trigger('crmAjaxFail', data);
715 CRM.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
716 },
717 _formatUrl: function(url) {
0906345e
CW
718 // Strip hash
719 url = url.split('#')[0];
205bb8ae
CW
720 // Add snippet argument to url
721 if (url.search(/[&?]snippet=/) < 0) {
fc05b8da 722 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
8547369d
CW
723 } else {
724 url = url.replace(/snippet=[^&]*/, 'snippet=json');
205bb8ae
CW
725 }
726 return url;
727 },
d6539f93 728 // Hack to deal with civicrm legacy sort functionality
4a140040
CW
729 _handleOrderLinks: function() {
730 var that = this;
731 $('a.crm-weight-arrow', that.element).click(function(e) {
732 that.options.block && that.element.block();
733 $.getJSON(that._formatUrl(this.href)).done(function() {
734 that.refresh();
735 });
736 e.stopImmediatePropagation();
737 return false;
738 });
739 },
205bb8ae
CW
740 refresh: function() {
741 var that = this;
742 var url = this._formatUrl(this.options.url);
4a140040 743 this.options.block && $('.blockOverlay', this.element).length < 1 && this.element.block();
205bb8ae
CW
744 $.getJSON(url, function(data) {
745 if (typeof(data) != 'object' || typeof(data.content) != 'string') {
746 that._onFailure(data);
747 return;
748 }
749 data.url = url;
c02f8fc4
CW
750 that.element.trigger('crmBeforeLoad', data);
751 if (that._originalContent === null) {
752 that._originalContent = that.element.contents().detach();
753 }
754 that.element.html(data.content);
4a140040
CW
755 that._handleOrderLinks();
756 that.element.trigger('crmLoad', data);
205bb8ae
CW
757 that.options.crmForm && that.element.trigger('crmFormLoad', data);
758 }).fail(function() {
759 that._onFailure();
760 });
4b628e67
CW
761 },
762 _destroy: function() {
763 this.element.removeClass('crm-ajax-container');
c02f8fc4
CW
764 if (this._originalContent !== null) {
765 this.element.empty().append(this._originalContent);
766 }
205bb8ae
CW
767 }
768 });
769
0e017a41 770 var dialogCount = 0;
d4e4e9df 771 CRM.loadPage = function(url, options) {
d4e4e9df 772 var settings = {
0e017a41 773 target: '#crm-ajax-dialog-' + (dialogCount++),
8547369d
CW
774 dialog: false
775 };
776 if (!options || !options.target) {
777 settings.dialog = {
d4e4e9df 778 modal: true,
f84151fd
CW
779 width: '65%',
780 height: parseInt($(window).height() * .75),
d4e4e9df 781 close: function() {
c02f8fc4 782 $(this).dialog('destroy').remove();
d4e4e9df 783 }
8547369d
CW
784 };
785 }
205bb8ae 786 options && $.extend(true, settings, options);
0e017a41 787 settings.url = url;
83df6b4a 788 // Create new dialog
8547369d 789 if (settings.dialog) {
205bb8ae 790 $('<div id="'+ settings.target.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings.dialog);
d4e4e9df 791 }
205bb8ae
CW
792 if (settings.dialog && !settings.dialog.title) {
793 $(settings.target).on('crmLoad', function(event, data) {
794 data.title && $(this).dialog('option', 'title', data.title);
795 });
796 }
5d92a7e7
CW
797 $(settings.target).crmSnippet(settings).crmSnippet('refresh');
798 return $(settings.target);
d4e4e9df
CW
799 };
800
801 CRM.loadForm = function(url, options) {
d4e4e9df 802 var settings = {
205bb8ae
CW
803 crmForm: {
804 ajaxForm: {},
205bb8ae
CW
805 autoClose: true,
806 validate: true,
807 refreshAction: ['next_new', 'submit_savenext'],
808 cancelButton: '.cancel.form-submit',
23223213 809 openInline: 'a.button:not("[href=#], .no-popup")',
205bb8ae
CW
810 onCancel: function(event) {},
811 onError: function(data) {
812 var $el = $(this);
5d92a7e7 813 $el.html(data.content).trigger('crmLoad', data).trigger('crmFormLoad', data).trigger('crmFormError', data);
205bb8ae
CW
814 if (typeof(data.errors) == 'object') {
815 $.each(data.errors, function(formElement, msg) {
816 $('[name="'+formElement+'"]', $el).crmError(msg);
817 });
818 }
d4e4e9df 819 }
d4e4e9df
CW
820 }
821 };
a10432db
CW
822 // Hack to make delete dialogs smaller
823 if (url.indexOf('/delete') > 0 || url.indexOf('action=delete') > 0) {
824 settings.dialog = {
825 width: 400,
826 height: 300
827 };
828 }
205bb8ae
CW
829 // Move options that belong to crmForm. Others will be passed through to crmSnippet
830 options && $.each(options, function(key, value) {
831 if (typeof(settings.crmForm[key]) !== 'undefined') {
832 settings.crmForm[key] = value;
833 }
834 else {
835 settings[key] = value;
836 }
837 });
205bb8ae
CW
838
839 var widget = CRM.loadPage(url, settings);
840
841 widget.on('crmFormLoad', function(event, data) {
842 var $el = $(this);
660c46f3 843 var settings = $el.crmSnippet('option', 'crmForm');
205bb8ae
CW
844 settings.cancelButton && $(settings.cancelButton, this).click(function(event) {
845 var returnVal = settings.onCancel.call($el, event);
846 if (returnVal !== false) {
847 $el.trigger('crmFormCancel', event);
660c46f3 848 if ($el.data('uiDialog') && settings.autoClose) {
fa3a5fe2
CW
849 $el.dialog('close');
850 }
851 else if (!settings.autoClose) {
852 $el.crmSnippet('resetUrl').crmSnippet('refresh');
853 }
0e017a41 854 }
205bb8ae
CW
855 return returnVal === false;
856 });
d4e4e9df 857 if (settings.validate) {
0e017a41 858 $("form", this).validate(typeof(settings.validate) == 'object' ? settings.validate : CRM.validate.params);
d4e4e9df 859 }
205bb8ae 860 $("form", this).ajaxForm($.extend({
fa3a5fe2 861 url: data.url.replace(/reset=1[&]?/, ''),
d4e4e9df
CW
862 dataType: 'json',
863 success: function(response) {
34866662 864 if (response.status !== 'form_error') {
36876f55 865 $el.crmSnippet('option', 'block') && $el.unblock();
205bb8ae 866 $el.trigger('crmFormSuccess', response);
0e017a41 867 // Reset form for e.g. "save and new"
d6539f93 868 if (response.userContext && settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0) {
205bb8ae 869 $el.crmSnippet('option', 'url', response.userContext).crmSnippet('refresh');
0e017a41 870 }
660c46f3 871 else if ($el.data('uiDialog') && settings.autoClose) {
205bb8ae 872 $el.dialog('close');
83df6b4a 873 }
d6539f93
CW
874 else if (settings.autoClose === false) {
875 $el.crmSnippet('resetUrl').crmSnippet('refresh');
876 }
d4e4e9df
CW
877 }
878 else {
25bbc4c0 879 response.url = data.url;
205bb8ae 880 settings.onError.call($el, response);
d4e4e9df 881 }
23223213
CW
882 },
883 beforeSerialize: function(form, options) {
884 if (window.CKEDITOR && window.CKEDITOR.instances) {
a10432db
CW
885 $.each(CKEDITOR.instances, function() {
886 this.updateElement && this.updateElement();
887 });
23223213 888 }
83df6b4a 889 },
205bb8ae 890 beforeSubmit: function(submission) {
36876f55 891 $el.crmSnippet('option', 'block') && $el.block();
205bb8ae 892 $el.trigger('crmFormSubmit', submission);
d4e4e9df 893 }
205bb8ae 894 }, settings.ajaxForm));
fa3a5fe2
CW
895 if (settings.openInline) {
896 settings.autoClose = $el.crmSnippet('isOriginalUrl');
897 $(settings.openInline, this).click(function(event) {
898 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
899 return false;
900 });
901 }
205bb8ae
CW
902 });
903 return widget;
d4e4e9df
CW
904 };
905
03a7ec8f
CW
906 // Preprocess all cj ajax calls to display messages
907 $(document).ajaxSuccess(function(event, xhr, settings) {
908 try {
909 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
910 var response = $.parseJSON(xhr.responseText);
911 if (typeof(response.crmMessages) == 'object') {
912 $.each(response.crmMessages, function(n, msg) {
913 CRM.alert(msg.text, msg.title, msg.type, msg.options);
914 })
915 }
916 }
917 }
918 // Suppress errors
919 catch (e) {}
920 });
921
7cb72342
CW
922 /**
923 * Temporary stub to get around name conflict with legacy jQuery.autocomplete plugin
924 */
925 $.widget('civi.crmAutocomplete', $.ui.autocomplete, {});
926
0f5816a6 927 $(function () {
205bb8ae 928 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
8547369d 929 $('.crm-container').trigger('crmLoad');
205bb8ae 930
ef3309b6 931 if ($('#crm-notification-container').length) {
6a488035
TO
932 // Initialize notifications
933 $('#crm-notification-container').notify();
934 messagesFromMarkup.call($('#crm-container'));
6a488035 935 }
ebb9197b
C
936
937 // bind the event for image popup
475e9f44
CW
938 $('body')
939 .on('click', 'a.crm-image-popup', function() {
940 var o = $('<div class="crm-container crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
941
942 CRM.confirm('',
943 {
944 title: ts('Preview'),
945 message: o
946 },
947 ts('Done')
948 );
949 return false;
950 })
ebb9197b 951
475e9f44
CW
952 .on('click', function (event) {
953 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
954 if ($(event.target).is('.btn-slide')) {
955 $(event.target).addClass('btn-slide-active').find('.panel').show();
956 }
957 })
d664f648 958
475e9f44
CW
959 .on('click', 'a.crm-edit-optionvalue-link', function() {
960 var url = $(this).data('option-group-url');
961 CRM.loadForm(CRM.url(url, {reset: 1}))
962 .on('dialogclose', function() {
963 var $elects = $('select[data-option-group-url="' + url + '"]');
e869b07d 964 CRM.api3($elects.data('api-entity'), 'getoptions', {sequential: 1, field: $elects.data('api-field')})
475e9f44
CW
965 .done(function(data) {
966 CRM.utils.setOptions($elects, data.values);
967 });
968 });
969 return false;
970 });
d664f648 971 $().crmtooltip();
6a488035
TO
972 });
973
0f5816a6 974 $.fn.crmAccordions = function (speed) {
cf021bc5
CW
975 var container = $(this).length > 0 ? $(this) : $('.crm-container');
976 speed = speed === undefined ? 200 : speed;
977 container
978 .off('click.crmAccordions')
6a488035 979 // Allow normal clicking of links
cf021bc5 980 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
6a488035 981 e.stopPropagation && e.stopPropagation();
cf021bc5
CW
982 })
983 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
6a488035
TO
984 if ($(this).parent().hasClass('collapsed')) {
985 $(this).next().css('display', 'none').slideDown(speed);
986 }
987 else {
988 $(this).next().css('display', 'block').slideUp(speed);
989 }
990 $(this).parent().toggleClass('collapsed');
991 return false;
992 });
6a488035 993 };
0f5816a6
KJ
994 $.fn.crmAccordionToggle = function (speed) {
995 $(this).each(function () {
6a488035
TO
996 if ($(this).hasClass('collapsed')) {
997 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
998 }
999 else {
1000 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1001 }
1002 $(this).toggleClass('collapsed');
1003 });
1004 };
5ec182d9
CW
1005
1006 /**
1007 * Clientside currency formatting
1008 * @param value
3bdb644f 1009 * @param format - currency representation of the number 1234.56
5ec182d9 1010 * @return string
3bdb644f 1011 * @see CRM_Core_Resources::addCoreResources
5ec182d9
CW
1012 */
1013 var currencyTemplate;
1014 CRM.formatMoney = function(value, format) {
1015 var decimal, separator, sign, i, j, result;
1016 if (value === 'init' && format) {
1017 currencyTemplate = format;
1018 return;
1019 }
1020 format = format || currencyTemplate;
1021 result = /1(.?)234(.?)56/.exec(format);
1022 if (result === null) {
1023 return 'Invalid format passed to CRM.formatMoney';
1024 }
1025 separator = result[1];
1026 decimal = result[2];
1027 sign = (value < 0) ? '-' : '';
1028 //extracting the absolute value of the integer part of the number and converting to string
1029 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
5ec182d9
CW
1030 j = ((j = i.length) > 3) ? j % 3 : 0;
1031 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) : '');
1032 return format.replace(/1.*234.*56/, result);
1033 };
6a488035 1034})(jQuery);