Merge remote-tracking branch 'upstream/4.4' into 4.4-master-2014-03-03-17-36-50
[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 = cj('#' + trigger_field_id).val();
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 (cj('[name="' + trigger_field_id + '"]').is(':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 * Function to change button text and disable one it is clicked
176 *
177 * @param obj object - the button clicked
178 * @param formID string - the id of the form being submitted
179 * @param string procText - button text after user clicks it
180 * @return null
181 */
182 var submitcount = 0;
183 /* Changes button label on submit, and disables button after submit for newer browsers.
184 Puts up alert for older browsers. */
185 function submitOnce(obj, formId, procText) {
186 // if named button clicked, change text
187 if (obj.value != null) {
188 obj.value = procText + " ...";
189 }
190 if (document.getElementById) { // disable submit button for newer browsers
191 obj.disabled = true;
192 document.getElementById(formId).submit();
193 return true;
194 }
195 else { // for older browsers
196 if (submitcount == 0) {
197 submitcount++;
198 return true;
199 }
200 else {
201 alert("Your request is currently being processed ... Please wait.");
202 return false;
203 }
204 }
205 }
206
207 function popUp(URL) {
208 day = new Date();
209 id = day.getTime();
210 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');");
211 }
212
213 /**
214 * Function to show / hide the row in optionFields
215 *
216 * @param element name index, that whose innerHTML is to hide else will show the hidden row.
217 */
218 function showHideRow(index) {
219 if (index) {
220 cj('tr#optionField_' + index).hide();
221 if (cj('table#optionField tr:hidden:first').length) {
222 cj('div#optionFieldLink').show();
223 }
224 }
225 else {
226 cj('table#optionField tr:hidden:first').show();
227 if (!cj('table#optionField tr:hidden:last').length) {
228 cj('div#optionFieldLink').hide();
229 }
230 }
231 return false;
232 }
233
234 CRM.utils = CRM.utils || {};
235 CRM.strings = CRM.strings || {};
236 CRM.validate = CRM.validate || {
237 params: {},
238 functions: []
239 };
240
241 (function ($, undefined) {
242 "use strict";
243
244 // https://github.com/ivaynberg/select2/pull/2090
245 $.fn.select2.defaults.width = 'resolve';
246
247 // Workaround for https://github.com/ivaynberg/select2/issues/1246
248 $.ui.dialog.prototype._allowInteraction = function(e) {
249 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop').length;
250 };
251
252 /**
253 * Populate a select list, overwriting the existing options except for the placeholder.
254 * @param $el jquery collection - 1 or more select elements
255 * @param options array in format returned by api.getoptions
256 */
257 CRM.utils.setOptions = function($el, options) {
258 $el.each(function() {
259 var
260 $elect = $(this),
261 val = $elect.val() || [];
262 if (typeof(val) !== 'array') {
263 val = [val];
264 }
265 $elect.find('option[value!=""]').remove();
266 $.each(options, function(key, option) {
267 var selected = ($.inArray(''+option.key, val) > -1) ? 'selected="selected"' : '';
268 $elect.append('<option value="' + option.key + '"' + selected + '>' + option.value + '</option>');
269 });
270 $elect.trigger('crmOptionsUpdated').trigger('change');
271 });
272 };
273
274 /**
275 * Select2 api leaves something to be desired. To alter options on-the-fly often requires re-rendering the whole thing.
276 * So making this function public in case anyone needs it.
277 */
278 CRM.utils.buildSelect2Element = function() {
279 var $el = $(this);
280 var options = {};
281 // quickform doesn't support optgroups so here's a hack :(
282 $('option[value^=crm_optgroup]', this).each(function() {
283 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
284 $(this).remove();
285 });
286 // Defaults for single-selects
287 if ($el.is('select:not([multiple])')) {
288 options.minimumResultsForSearch = 10;
289 options.allowClear = !($el.hasClass('required'));
290 if ($('option:first', this).val() === '') {
291 options.placeholderOption = 'first';
292 }
293 }
294 $.extend(options, $el.data('select-params') || {});
295 // Autocomplete using the getlist api
296 if ($el.data('api-entity') && $el.hasClass('crm-form-entityref')) {
297 $el.addClass('crm-ajax-select');
298 var settings = {
299 // Use select2 ajax helper instead of CRM.api because it provides more value
300 ajax: {
301 url: CRM.url('civicrm/ajax/rest'),
302 data: function (input, page_num) {
303 var params = $el.data('api-params') || {};
304 params.input = input;
305 params.page_num = page_num;
306 return {
307 entity: $el.data('api-entity'),
308 action: 'getlist',
309 json: JSON.stringify(params)
310 };
311 },
312 results: function(data) {
313 return {more: data.more_results, results: data.values || []};
314 }
315 },
316 formatResult: CRM.utils.formatSelect2Result,
317 formatSelection: function(row) {
318 return row.label;
319 },
320 escapeMarkup: function (m) {return m;},
321 initSelection: function(el, callback) {
322 callback(el.data('entity-value'));
323 }
324 };
325 if ($el.data('create-links')) {
326 options.formatInputTooShort = function() {
327 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort;
328 if ($el.data('create-links').length) {
329 txt += ' ' + ts('or') + '<br />' + CRM.utils.formatSelect2CreateLinks($el);
330 }
331 return txt;
332 };
333 options.formatNoMatches = function() {
334 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
335 return txt + '<br />' + CRM.utils.formatSelect2CreateLinks($el);
336 };
337 $el.on('select2-open', function() {
338 var $el = $(this);
339 $('#select2-drop').off('.crmEntity').on('click.crmEntity', 'a.crm-add-entity', function(e) {
340 $el.select2('close');
341 CRM.loadForm($(this).attr('href'), {
342 dialog: {width: 500, height: 'auto'}
343 }).on('crmFormSuccess', function(e, data) {
344 if (data.status === 'success' && data.id) {
345 if ($el.select2('container').hasClass('select2-container-multi')) {
346 var selection = $el.select2('data');
347 selection.push(data);
348 $el.select2('data', selection, true);
349 } else {
350 $el.select2('data', data, true);
351 }
352 }
353 });
354 return false;
355 });
356 });
357 }
358 options = $.extend(settings, options);
359 }
360 options.dropdownCssClass = 'crm-container';
361 $(this).select2(options).removeClass('crm-select2');
362 };
363
364 CRM.utils.formatSelect2Result = function(row) {
365 var markup = '<div class="crm-select2-row">';
366 if (row.image !== undefined) {
367 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
368 }
369 else if (row.icon_class) {
370 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
371 }
372 markup += '<div><div class="crm-select2-row-label">' + row.label + '</div>';
373 markup += '<div class="crm-select2-row-description">';
374 $.each(row.description || [], function(k, text) {
375 markup += '<p>' + text + '</p>';
376 });
377 markup += '</div></div></div>';
378 return markup;
379 };
380
381 CRM.utils.formatSelect2CreateLinks = function($el) {
382 var markup = '';
383 $.each($el.data('create-links'), function(k, link) {
384 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
385 if (link.name) {
386 markup += '<span class="icon ' + link.name + '-icon"></span> ';
387 }
388 markup += link.label + '</a>';
389 });
390 return markup;
391 };
392
393 // Initialize widgets
394 $(document).on('crmLoad', function(e) {
395 $('table.row-highlight', e.target)
396 .off('.rowHighlight')
397 .on('change.rowHighlight', 'input.select-row, input.select-rows', function () {
398 var target, table = $(this).closest('table');
399 if ($(this).hasClass('select-rows')) {
400 target = $('tbody tr', table);
401 $('input.select-row', table).prop('checked', $(this).prop('checked'));
402 }
403 else {
404 target = $(this).closest('tr');
405 $('input.select-rows', table).prop('checked', $(".select-row:not(':checked')", table).length < 1);
406 }
407 target.toggleClass('crm-row-selected', $(this).is(':checked'));
408 })
409 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
410 $('.crm-select2', e.target).each(CRM.utils.buildSelect2Element);
411 });
412
413 /**
414 * Function to make multiselect boxes behave as fields in small screens
415 */
416 function advmultiselectResize() {
417 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
418 if (amswidth < 700) {
419 $("form table.advmultiselect td").css('display', 'block');
420 }
421 else {
422 $("form table.advmultiselect td").css('display', 'table-cell');
423 }
424 var contactwidth = $('#crm-container #mainTabContainer').width();
425 if (contactwidth < 600) {
426 $('#crm-container #mainTabContainer').addClass('narrowpage');
427 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
428 if (index > 1) {
429 if (index % 2 == 0) {
430 $(this).parent().after('<tr class="narrowadded"></tr>');
431 }
432 var item = $(this);
433 $(this).parent().next().append(item);
434 }
435 });
436 }
437 else {
438 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
439 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
440 var nitem = $(this);
441 var parent = $(this).parent();
442 $(this).parent().prev().append(nitem);
443 if (parent.children().size() == 0) {
444 parent.remove();
445 }
446 });
447 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
448 }
449 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
450
451 if (cformwidth < 720) {
452 $('#crm-container .contact_basic_information-section').addClass('narrowform');
453 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
454 if (cformwidth < 480) {
455 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
456 }
457 else {
458 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
459 }
460 }
461 else {
462 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
463 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
464 }
465 }
466
467 advmultiselectResize();
468 $(window).resize(function () {
469 advmultiselectResize();
470 });
471
472 $.fn.crmtooltip = function () {
473 $(document)
474 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
475 $(this).addClass('crm-processed');
476 $(this).addClass('crm-tooltip-active');
477 var topDistance = e.pageY - $(window).scrollTop();
478 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
479 $(this).addClass('crm-tooltip-down');
480 }
481 if (!$(this).children('.crm-tooltip-wrapper').length) {
482 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
483 $(this).children().children('.crm-tooltip')
484 .html('<div class="crm-loading-element"></div>')
485 .load(this.href);
486 }
487 })
488 .on('mouseout', 'a.crm-summary-link', function () {
489 $(this).removeClass('crm-processed');
490 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
491 })
492 .on('click', 'a.crm-summary-link', false);
493 };
494
495 var helpDisplay, helpPrevious;
496 CRM.help = function (title, params, url) {
497 if (helpDisplay && helpDisplay.close) {
498 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
499 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
500 helpDisplay.close();
501 return;
502 }
503 helpDisplay.close();
504 }
505 helpPrevious = JSON.stringify(params);
506 params.class_name = 'CRM_Core_Page_Inline_Help';
507 params.type = 'page';
508 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
509 $.ajax(url || CRM.url('civicrm/ajax/inline'),
510 {
511 data: params,
512 dataType: 'html',
513 success: function (data) {
514 $('#crm-notification-container .crm-help .notify-content:last').html(data);
515 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
516 },
517 error: function () {
518 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
519 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
520 }
521 }
522 );
523 };
524 /**
525 * @param startMsg string
526 * @param endMsg string|function
527 * @param deferred optional jQuery deferred object
528 * @return jQuery deferred object - if not supplied a new one will be created
529 */
530 var fadeOut;
531 CRM.status = function(startMsg, endMsg, deferred) {
532 var $bar = $('#civicrm-menu');
533 if (!$bar.length) {
534 console && console.log && console.log('CRM.status called on a page with no menubar');
535 return;
536 }
537 $('.crm-menubar-status-container', $bar).remove();
538 fadeOut && window.clearTimeout(fadeOut);
539 $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>');
540 $('.crm-menubar-status-container', $bar).css('min-width', $('.crm-menubar-status-container', $bar).width());
541 deferred || (deferred = new $.Deferred());
542 deferred.done(function(data) {
543 var msg = typeof(endMsg) === 'function' ? endMsg(data) : endMsg;
544 $('.crm-menubar-status-container', $bar).removeClass('status-busy').addClass('status-done').show().find('.crm-menubar-status-msg').html(msg);
545 if (msg) {
546 fadeOut = window.setTimeout(function() {
547 $('.crm-menubar-status-container', $bar).fadeOut('slow');
548 }, 2000);
549 } else {
550 $('.crm-menubar-status-container', $bar).hide();
551 }
552 });
553 return deferred;
554 };
555
556 /**
557 * @param string text Displayable message
558 * @param string title Displayable title
559 * @param string type 'alert'|'info'|'success'|'error' (default: 'alert')
560 * @param {object} options
561 * @return {*}
562 * @see http://wiki.civicrm.org/confluence/display/CRM/Notifications+in+CiviCRM
563 */
564 CRM.alert = function (text, title, type, options) {
565 type = type || 'alert';
566 title = title || '';
567 options = options || {};
568 if ($('#crm-notification-container').length) {
569 var params = {
570 text: text,
571 title: title,
572 type: type
573 };
574 // By default, don't expire errors and messages containing links
575 var extra = {
576 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
577 unique: true
578 };
579 options = $.extend(extra, options);
580 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
581 if (options.unique && options.unique !== '0') {
582 $('#crm-notification-container .ui-notify-message').each(function () {
583 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
584 $('.icon.ui-notify-close', this).click();
585 }
586 });
587 }
588 return $('#crm-notification-container').notify('create', params, options);
589 }
590 else {
591 if (title.length) {
592 text = title + "\n" + text;
593 }
594 alert(text);
595 return null;
596 }
597 };
598
599 /**
600 * Close whichever alert contains the given node
601 *
602 * @param node
603 */
604 CRM.closeAlertByChild = function (node) {
605 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
606 };
607
608 /**
609 * Prompt the user for confirmation.
610 *
611 * @param buttons {object|function} key|value pairs where key == button label and value == callback function
612 * passing in a function instead of an object is a shortcut for a sinlgle button labeled "Continue"
613 * @param options {object|void} Override defaults, keys include 'title', 'message',
614 * see jQuery.dialog for full list of available params
615 * @param cancelLabel {string}
616 */
617 CRM.confirm = function (buttons, options, cancelLabel) {
618 var dialog, callbacks = {};
619 cancelLabel = cancelLabel || ts('Cancel');
620 var settings = {
621 title: ts('Confirm Action'),
622 message: ts('Are you sure you want to continue?'),
623 resizable: false,
624 modal: true,
625 width: 'auto',
626 close: function () {
627 $(dialog).remove();
628 },
629 buttons: {}
630 };
631
632 settings.buttons[cancelLabel] = function () {
633 dialog.dialog('close');
634 };
635 options = options || {};
636 $.extend(settings, options);
637 if (typeof(buttons) === 'function') {
638 callbacks[ts('Continue')] = buttons;
639 }
640 else {
641 callbacks = buttons;
642 }
643 $.each(callbacks, function (label, callback) {
644 settings.buttons[label] = function () {
645 if (callback.call(dialog) !== false) {
646 dialog.dialog('close');
647 }
648 };
649 });
650 dialog = $('<div class="crm-container crm-confirm-dialog"></div>')
651 .html(options.message)
652 .appendTo('body')
653 .dialog(settings);
654 return dialog;
655 };
656
657 /**
658 * Sets an error message
659 * If called for a form item, title and removal condition will be handled automatically
660 */
661 $.fn.crmError = function (text, title, options) {
662 title = title || '';
663 text = text || '';
664 options = options || {};
665
666 var extra = {
667 expires: 0
668 };
669 if ($(this).length) {
670 if (title == '') {
671 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
672 if (label.length) {
673 label.addClass('crm-error');
674 var $label = label.clone();
675 if (text == '' && $('.crm-marker', $label).length > 0) {
676 text = $('.crm-marker', $label).attr('title');
677 }
678 $('.crm-marker', $label).remove();
679 title = $label.text();
680 }
681 }
682 $(this).addClass('error');
683 }
684 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
685 if ($(this).length) {
686 var ele = $(this);
687 setTimeout(function () {
688 ele.one('change', function () {
689 msg && msg.close && msg.close();
690 ele.removeClass('error');
691 label.removeClass('crm-error');
692 });
693 }, 1000);
694 }
695 return msg;
696 };
697
698 // Display system alerts through js notifications
699 function messagesFromMarkup() {
700 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
701 var text, title = '';
702 $(this).removeClass('status messages');
703 var type = $(this).attr('class').split(' ')[0] || 'alert';
704 type = type.replace('crm-', '');
705 $('.icon', this).remove();
706 if ($('.msg-text', this).length > 0) {
707 text = $('.msg-text', this).html();
708 title = $('.msg-title', this).html();
709 }
710 else {
711 text = $(this).html();
712 }
713 var options = $(this).data('options') || {};
714 $(this).remove();
715 // Duplicates were already removed server-side
716 options.unique = false;
717 CRM.alert(text, title, type, options);
718 });
719 // Handle qf form errors
720 $('form :input.error', this).one('blur', function() {
721 // ignore autocomplete fields
722 if ($(this).is('.ac_input')) {
723 return;
724 }
725
726 $('.ui-notify-message.error a.ui-notify-close').click();
727 $(this).removeClass('error');
728 $(this).next('span.crm-error').remove();
729 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
730 .removeClass('crm-error')
731 .find('.crm-error').removeClass('crm-error');
732 });
733 }
734
735 $.widget('civi.crmSnippet', {
736 options: {
737 url: null,
738 block: true,
739 crmForm: null
740 },
741 _originalContent: null,
742 _originalUrl: null,
743 isOriginalUrl: function() {
744 var
745 args = {},
746 same = true,
747 newUrl = this._formatUrl(this.options.url),
748 oldUrl = this._formatUrl(this._originalUrl);
749 // Compare path
750 if (newUrl.split('?')[0] !== oldUrl.split('?')[0]) {
751 return false;
752 }
753 // Compare arguments
754 $.each(newUrl.split('?')[1].split('&'), function(k, v) {
755 var arg = v.split('=');
756 args[arg[0]] = arg[1];
757 });
758 $.each(oldUrl.split('?')[1].split('&'), function(k, v) {
759 var arg = v.split('=');
760 if (args[arg[0]] !== undefined && arg[1] !== args[arg[0]]) {
761 same = false;
762 }
763 });
764 return same;
765 },
766 resetUrl: function() {
767 this.options.url = this._originalUrl;
768 },
769 _create: function() {
770 this.element.addClass('crm-ajax-container');
771 if (!this.element.is('.crm-container *')) {
772 this.element.addClass('crm-container');
773 }
774 this._handleOrderLinks();
775 // Set default if not supplied
776 this.options.url = this.options.url || document.location.href;
777 this._originalUrl = this.options.url;
778 },
779 _onFailure: function(data) {
780 this.options.block && this.element.unblock();
781 this.element.trigger('crmAjaxFail', data);
782 CRM.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
783 },
784 _formatUrl: function(url) {
785 // Strip hash
786 url = url.split('#')[0];
787 // Add snippet argument to url
788 if (url.search(/[&?]snippet=/) < 0) {
789 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
790 } else {
791 url = url.replace(/snippet=[^&]*/, 'snippet=json');
792 }
793 return url;
794 },
795 // Hack to deal with civicrm legacy sort functionality
796 _handleOrderLinks: function() {
797 var that = this;
798 $('a.crm-weight-arrow', that.element).click(function(e) {
799 that.options.block && that.element.block();
800 $.getJSON(that._formatUrl(this.href)).done(function() {
801 that.refresh();
802 });
803 e.stopImmediatePropagation();
804 return false;
805 });
806 },
807 refresh: function() {
808 var that = this;
809 var url = this._formatUrl(this.options.url);
810 this.options.block && $('.blockOverlay', this.element).length < 1 && this.element.block();
811 $.getJSON(url, function(data) {
812 if (typeof(data) != 'object' || typeof(data.content) != 'string') {
813 that._onFailure(data);
814 return;
815 }
816 data.url = url;
817 that.element.trigger('crmBeforeLoad', data);
818 if (that._originalContent === null) {
819 that._originalContent = that.element.contents().detach();
820 }
821 that.element.html(data.content);
822 that._handleOrderLinks();
823 that.element.trigger('crmLoad', data);
824 that.options.crmForm && that.element.trigger('crmFormLoad', data);
825 }).fail(function() {
826 that._onFailure();
827 });
828 },
829 _destroy: function() {
830 this.element.removeClass('crm-ajax-container');
831 if (this._originalContent !== null) {
832 this.element.empty().append(this._originalContent);
833 }
834 }
835 });
836
837 var dialogCount = 0;
838 CRM.loadPage = function(url, options) {
839 var settings = {
840 target: '#crm-ajax-dialog-' + (dialogCount++),
841 dialog: false
842 };
843 if (!options || !options.target) {
844 settings.dialog = {
845 modal: true,
846 width: '65%',
847 height: parseInt($(window).height() * .75),
848 close: function() {
849 $(this).dialog('destroy').remove();
850 }
851 };
852 }
853 options && $.extend(true, settings, options);
854 settings.url = url;
855 // Create new dialog
856 if (settings.dialog) {
857 $('<div id="'+ settings.target.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings.dialog);
858 }
859 if (settings.dialog && !settings.dialog.title) {
860 $(settings.target).on('crmLoad', function(event, data) {
861 data.title && $(this).dialog('option', 'title', data.title);
862 });
863 }
864 $(settings.target).crmSnippet(settings).crmSnippet('refresh');
865 return $(settings.target);
866 };
867
868 CRM.loadForm = function(url, options) {
869 var settings = {
870 crmForm: {
871 ajaxForm: {},
872 autoClose: true,
873 validate: true,
874 refreshAction: ['next_new', 'submit_savenext'],
875 cancelButton: '.cancel.form-submit',
876 openInline: 'a.button:not("[href=#], .no-popup")',
877 onCancel: function(event) {},
878 onError: function(data) {
879 var $el = $(this);
880 $el.html(data.content).trigger('crmLoad', data).trigger('crmFormLoad', data).trigger('crmFormError', data);
881 if (typeof(data.errors) == 'object') {
882 $.each(data.errors, function(formElement, msg) {
883 $('[name="'+formElement+'"]', $el).crmError(msg);
884 });
885 }
886 }
887 }
888 };
889 // Hack to make delete dialogs smaller
890 if (url.indexOf('/delete') > 0 || url.indexOf('action=delete') > 0) {
891 settings.dialog = {
892 width: 400,
893 height: 300
894 };
895 }
896 // Move options that belong to crmForm. Others will be passed through to crmSnippet
897 options && $.each(options, function(key, value) {
898 if (typeof(settings.crmForm[key]) !== 'undefined') {
899 settings.crmForm[key] = value;
900 }
901 else {
902 settings[key] = value;
903 }
904 });
905
906 var widget = CRM.loadPage(url, settings);
907
908 widget.on('crmFormLoad', function(event, data) {
909 var $el = $(this);
910 var settings = $el.crmSnippet('option', 'crmForm');
911 settings.cancelButton && $(settings.cancelButton, this).click(function(event) {
912 var returnVal = settings.onCancel.call($el, event);
913 if (returnVal !== false) {
914 $el.trigger('crmFormCancel', event);
915 if ($el.data('uiDialog') && settings.autoClose) {
916 $el.dialog('close');
917 }
918 else if (!settings.autoClose) {
919 $el.crmSnippet('resetUrl').crmSnippet('refresh');
920 }
921 }
922 return returnVal === false;
923 });
924 if (settings.validate) {
925 $("form", this).validate(typeof(settings.validate) == 'object' ? settings.validate : CRM.validate.params);
926 }
927 $("form", this).ajaxForm($.extend({
928 url: data.url.replace(/reset=1[&]?/, ''),
929 dataType: 'json',
930 success: function(response) {
931 if (response.status !== 'form_error') {
932 $el.crmSnippet('option', 'block') && $el.unblock();
933 $el.trigger('crmFormSuccess', response);
934 // Reset form for e.g. "save and new"
935 if (response.userContext && settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0) {
936 $el.crmSnippet('option', 'url', response.userContext).crmSnippet('refresh');
937 }
938 else if ($el.data('uiDialog') && settings.autoClose) {
939 $el.dialog('close');
940 }
941 else if (settings.autoClose === false) {
942 $el.crmSnippet('resetUrl').crmSnippet('refresh');
943 }
944 }
945 else {
946 response.url = data.url;
947 settings.onError.call($el, response);
948 }
949 },
950 beforeSerialize: function(form, options) {
951 if (window.CKEDITOR && window.CKEDITOR.instances) {
952 $.each(CKEDITOR.instances, function() {
953 this.updateElement && this.updateElement();
954 });
955 }
956 },
957 beforeSubmit: function(submission) {
958 $el.crmSnippet('option', 'block') && $el.block();
959 $el.trigger('crmFormSubmit', submission);
960 }
961 }, settings.ajaxForm));
962 if (settings.openInline) {
963 settings.autoClose = $el.crmSnippet('isOriginalUrl');
964 $(settings.openInline, this).click(function(event) {
965 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
966 return false;
967 });
968 }
969 // For convenience, focus the first field
970 $('input[type=text], textarea, select', this).filter(':visible').first().focus();
971 });
972 return widget;
973 };
974
975 // Preprocess all cj ajax calls to display messages
976 $(document).ajaxSuccess(function(event, xhr, settings) {
977 try {
978 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
979 var response = $.parseJSON(xhr.responseText);
980 if (typeof(response.crmMessages) == 'object') {
981 $.each(response.crmMessages, function(n, msg) {
982 CRM.alert(msg.text, msg.title, msg.type, msg.options);
983 })
984 }
985 }
986 }
987 // Suppress errors
988 catch (e) {}
989 });
990
991 /**
992 * Temporary stub to get around name conflict with legacy jQuery.autocomplete plugin
993 */
994 $.widget('civi.crmAutocomplete', $.ui.autocomplete, {});
995
996 $(function () {
997 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
998 $('.crm-container').trigger('crmLoad');
999
1000 if ($('#crm-notification-container').length) {
1001 // Initialize notifications
1002 $('#crm-notification-container').notify();
1003 messagesFromMarkup.call($('#crm-container'));
1004 }
1005
1006 // bind the event for image popup
1007 $('body')
1008 .on('click', 'a.crm-image-popup', function() {
1009 var o = $('<div class="crm-container crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
1010
1011 CRM.confirm('',
1012 {
1013 title: ts('Preview'),
1014 message: o
1015 },
1016 ts('Done')
1017 );
1018 return false;
1019 })
1020
1021 .on('click', function (event) {
1022 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1023 if ($(event.target).is('.btn-slide')) {
1024 $(event.target).addClass('btn-slide-active').find('.panel').show();
1025 }
1026 })
1027
1028 .on('click', 'a.crm-option-edit-link', function() {
1029 var link = $(this);
1030 CRM.loadForm(this.href, {openInline: 'a:not("[href=#], .no-popup")'})
1031 // Lots of things can happen once the form opens, this is the only event we can really rely on
1032 .on('dialogclose', function() {
1033 link.trigger('crmOptionsEdited');
1034 var $elects = $('select[data-option-edit-path="' + link.data('option-edit-path') + '"]');
1035 if ($elects.data('api-entity') && $elects.data('api-field')) {
1036 CRM.api3($elects.data('api-entity'), 'getoptions', {sequential: 1, field: $elects.data('api-field')})
1037 .done(function(data) {
1038 CRM.utils.setOptions($elects, data.values);
1039 });
1040 }
1041 });
1042 return false;
1043 })
1044 // Handle clear button for form elements
1045 .on('click', 'a.crm-clear-link', function() {
1046 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
1047 $(this).siblings('input:text').val('').change();
1048 return false;
1049 })
1050 .on('change', 'input.crm-form-radio:checked', function() {
1051 $(this).siblings('.crm-clear-link').css({visibility: ''});
1052 });
1053 $().crmtooltip();
1054 });
1055
1056 $.fn.crmAccordions = function (speed) {
1057 var container = $(this).length > 0 ? $(this) : $('.crm-container');
1058 speed = speed === undefined ? 200 : speed;
1059 container
1060 .off('click.crmAccordions')
1061 // Allow normal clicking of links
1062 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
1063 e.stopPropagation && e.stopPropagation();
1064 })
1065 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
1066 if ($(this).parent().hasClass('collapsed')) {
1067 $(this).next().css('display', 'none').slideDown(speed);
1068 }
1069 else {
1070 $(this).next().css('display', 'block').slideUp(speed);
1071 }
1072 $(this).parent().toggleClass('collapsed');
1073 return false;
1074 });
1075 };
1076 $.fn.crmAccordionToggle = function (speed) {
1077 $(this).each(function () {
1078 if ($(this).hasClass('collapsed')) {
1079 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
1080 }
1081 else {
1082 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1083 }
1084 $(this).toggleClass('collapsed');
1085 });
1086 };
1087
1088 /**
1089 * Clientside currency formatting
1090 * @param value
1091 * @param format - currency representation of the number 1234.56
1092 * @return string
1093 * @see CRM_Core_Resources::addCoreResources
1094 */
1095 var currencyTemplate;
1096 CRM.formatMoney = function(value, format) {
1097 var decimal, separator, sign, i, j, result;
1098 if (value === 'init' && format) {
1099 currencyTemplate = format;
1100 return;
1101 }
1102 format = format || currencyTemplate;
1103 result = /1(.?)234(.?)56/.exec(format);
1104 if (result === null) {
1105 return 'Invalid format passed to CRM.formatMoney';
1106 }
1107 separator = result[1];
1108 decimal = result[2];
1109 sign = (value < 0) ? '-' : '';
1110 //extracting the absolute value of the integer part of the number and converting to string
1111 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
1112 j = ((j = i.length) > 3) ? j % 3 : 0;
1113 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) : '');
1114 return format.replace(/1.*234.*56/, result);
1115 };
1116 })(jQuery);