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