Commit | Line | Data |
---|---|---|
353ea873 | 1 | // https://civicrm.org/licensing |
2b3ddf6e | 2 | /* global CRM:true */ |
b7f93874 | 3 | var CRM = CRM || {}; |
4b513f23 CW |
4 | var cj = CRM.$ = jQuery; |
5 | CRM._ = _; | |
6a488035 TO |
6 | |
7 | /** | |
8 | * Short-named function for string translation, defined in global scope so it's available everywhere. | |
9 | * | |
353ea873 CW |
10 | * @param text string for translating |
11 | * @param params object key:value of additional parameters | |
6a488035 | 12 | * |
353ea873 | 13 | * @return string |
6a488035 TO |
14 | */ |
15 | function ts(text, params) { | |
7553cf23 | 16 | "use strict"; |
3f3bba82 TO |
17 | var d = (params && params.domain) ? ('strings::' + params.domain) : null; |
18 | if (d && CRM[d] && CRM[d][text]) { | |
19 | text = CRM[d][text]; | |
20 | } | |
0d75c29c CW |
21 | else if (CRM.strings[text]) { |
22 | text = CRM.strings[text]; | |
3f3bba82 | 23 | } |
2788147f | 24 | if (typeof(params) === 'object') { |
6a488035 | 25 | for (var i in params) { |
32155ad6 | 26 | if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') { |
2788147f | 27 | // sprintf emulation: escape % characters in the replacements to avoid conflicts |
32155ad6 | 28 | text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-')); |
2788147f | 29 | } |
6a488035 TO |
30 | } |
31 | return text.replace(/%-crmescaped-/g, '%'); | |
32 | } | |
33 | return text; | |
34 | } | |
35 | ||
2b3ddf6e CW |
36 | // Legacy code - ignore warnings |
37 | /* jshint ignore:start */ | |
38 | ||
6a488035 TO |
39 | /** |
40 | * This function is called by default at the bottom of template files which have forms that have | |
41 | * conditionally displayed/hidden sections and elements. The PHP is responsible for generating | |
42 | * a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to | |
43 | * this function. | |
44 | * | |
353ea873 | 45 | * @deprecated |
6a488035 TO |
46 | * @param showBlocks Array of element Id's to be displayed |
47 | * @param hideBlocks Array of element Id's to be hidden | |
48 | * @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...) | |
6a488035 | 49 | */ |
0f5816a6 | 50 | function on_load_init_blocks(showBlocks, hideBlocks, elementType) { |
2b3ddf6e | 51 | if (elementType == null) { |
f54254d8 | 52 | elementType = 'block'; |
0f5816a6 KJ |
53 | } |
54 | ||
f54254d8 TO |
55 | var myElement, i; |
56 | ||
0f5816a6 | 57 | /* This loop is used to display the blocks whose IDs are present within the showBlocks array */ |
f54254d8 TO |
58 | for (i = 0; i < showBlocks.length; i++) { |
59 | myElement = document.getElementById(showBlocks[i]); | |
0f5816a6 | 60 | /* getElementById returns null if element id doesn't exist in the document */ |
2b3ddf6e | 61 | if (myElement != null) { |
0f5816a6 | 62 | myElement.style.display = elementType; |
6a488035 | 63 | } |
0f5816a6 KJ |
64 | else { |
65 | alert('showBlocks array item not in .tpl = ' + showBlocks[i]); | |
66 | } | |
67 | } | |
6a488035 | 68 | |
0f5816a6 | 69 | /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */ |
f54254d8 TO |
70 | for (i = 0; i < hideBlocks.length; i++) { |
71 | myElement = document.getElementById(hideBlocks[i]); | |
0f5816a6 | 72 | /* getElementById returns null if element id doesn't exist in the document */ |
2b3ddf6e | 73 | if (myElement != null) { |
0f5816a6 KJ |
74 | myElement.style.display = 'none'; |
75 | } | |
76 | else { | |
77 | alert('showBlocks array item not in .tpl = ' + hideBlocks[i]); | |
6a488035 | 78 | } |
0f5816a6 | 79 | } |
6a488035 TO |
80 | } |
81 | ||
82 | /** | |
83 | * This function is called when we need to show or hide a related form element (target_element) | |
84 | * based on the value (trigger_value) of another form field (trigger_field). | |
85 | * | |
353ea873 | 86 | * @deprecated |
6a488035 TO |
87 | * @param trigger_field_id HTML id of field whose onchange is the trigger |
88 | * @param trigger_value List of integers - option value(s) which trigger show-element action for target_field | |
89 | * @param target_element_id HTML id of element to be shown or hidden | |
90 | * @param target_element_type Type of element to be shown or hidden ('block' or 'table-row') | |
91 | * @param field_type Type of element radio/select | |
92 | * @param invert Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match | |
0f5816a6 KJ |
93 | */ |
94 | function showHideByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, invert) { | |
f54254d8 | 95 | var target, j; |
0f5816a6 KJ |
96 | |
97 | if (field_type == 'select') { | |
98 | var trigger = trigger_value.split("|"); | |
24cc4545 | 99 | var selectedOptionValue = cj('#' + trigger_field_id).val(); |
0f5816a6 | 100 | |
f54254d8 TO |
101 | target = target_element_id.split("|"); |
102 | for (j = 0; j < target.length; j++) { | |
0f5816a6 KJ |
103 | if (invert) { |
104 | cj('#' + target[j]).show(); | |
105 | } | |
106 | else { | |
107 | cj('#' + target[j]).hide(); | |
108 | } | |
109 | for (var i = 0; i < trigger.length; i++) { | |
110 | if (selectedOptionValue == trigger[i]) { | |
111 | if (invert) { | |
112 | cj('#' + target[j]).hide(); | |
113 | } | |
114 | else { | |
115 | cj('#' + target[j]).show(); | |
116 | } | |
6a488035 | 117 | } |
0f5816a6 KJ |
118 | } |
119 | } | |
6a488035 | 120 | |
0f5816a6 KJ |
121 | } |
122 | else { | |
123 | if (field_type == 'radio') { | |
f54254d8 TO |
124 | target = target_element_id.split("|"); |
125 | for (j = 0; j < target.length; j++) { | |
5fb3af09 | 126 | if (cj('[name="' + trigger_field_id + '"]:first').is(':checked')) { |
0f5816a6 KJ |
127 | if (invert) { |
128 | cj('#' + target[j]).hide(); | |
129 | } | |
130 | else { | |
131 | cj('#' + target[j]).show(); | |
132 | } | |
6a488035 | 133 | } |
0f5816a6 KJ |
134 | else { |
135 | if (invert) { | |
136 | cj('#' + target[j]).show(); | |
137 | } | |
138 | else { | |
139 | cj('#' + target[j]).hide(); | |
140 | } | |
141 | } | |
142 | } | |
6a488035 | 143 | } |
0f5816a6 | 144 | } |
6a488035 TO |
145 | } |
146 | ||
6a488035 TO |
147 | /** |
148 | * Function to change button text and disable one it is clicked | |
353ea873 | 149 | * @deprecated |
6a488035 TO |
150 | * @param obj object - the button clicked |
151 | * @param formID string - the id of the form being submitted | |
152 | * @param string procText - button text after user clicks it | |
353ea873 | 153 | * @return bool |
6a488035 | 154 | */ |
0f5816a6 | 155 | var submitcount = 0; |
c6edd786 | 156 | /* Changes button label on submit, and disables button after submit for newer browsers. |
157 | Puts up alert for older browsers. */ | |
0f5816a6 KJ |
158 | function submitOnce(obj, formId, procText) { |
159 | // if named button clicked, change text | |
160 | if (obj.value != null) { | |
161 | obj.value = procText + " ..."; | |
162 | } | |
47ea29e3 | 163 | cj(obj).closest('form').attr('data-warn-changes', 'false'); |
0f5816a6 KJ |
164 | if (document.getElementById) { // disable submit button for newer browsers |
165 | obj.disabled = true; | |
166 | document.getElementById(formId).submit(); | |
167 | return true; | |
168 | } | |
169 | else { // for older browsers | |
170 | if (submitcount == 0) { | |
171 | submitcount++; | |
172 | return true; | |
173 | } | |
174 | else { | |
175 | alert("Your request is currently being processed ... Please wait."); | |
176 | return false; | |
6a488035 | 177 | } |
0f5816a6 | 178 | } |
6a488035 | 179 | } |
6a488035 | 180 | |
6a488035 TO |
181 | /** |
182 | * Function to show / hide the row in optionFields | |
353ea873 CW |
183 | * @deprecated |
184 | * @param index string, element whose innerHTML is to hide else will show the hidden row. | |
6a488035 | 185 | */ |
0f5816a6 KJ |
186 | function showHideRow(index) { |
187 | if (index) { | |
188 | cj('tr#optionField_' + index).hide(); | |
189 | if (cj('table#optionField tr:hidden:first').length) { | |
190 | cj('div#optionFieldLink').show(); | |
6a488035 | 191 | } |
0f5816a6 KJ |
192 | } |
193 | else { | |
194 | cj('table#optionField tr:hidden:first').show(); | |
195 | if (!cj('table#optionField tr:hidden:last').length) { | |
196 | cj('div#optionFieldLink').hide(); | |
197 | } | |
198 | } | |
199 | return false; | |
6a488035 TO |
200 | } |
201 | ||
2b3ddf6e CW |
202 | /* jshint ignore:end */ |
203 | ||
475e9f44 | 204 | CRM.utils = CRM.utils || {}; |
6a488035 | 205 | CRM.strings = CRM.strings || {}; |
6a488035 | 206 | |
4b513f23 | 207 | (function ($, _, undefined) { |
7553cf23 | 208 | "use strict"; |
0d75c29c | 209 | /* jshint validthis: true */ |
d664f648 | 210 | |
3f586963 CW |
211 | // Theme classes for unattached elements |
212 | $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container'; | |
213 | ||
47f21f3a CW |
214 | // https://github.com/ivaynberg/select2/pull/2090 |
215 | $.fn.select2.defaults.width = 'resolve'; | |
216 | ||
e20523a8 CW |
217 | // Workaround for https://github.com/ivaynberg/select2/issues/1246 |
218 | $.ui.dialog.prototype._allowInteraction = function(e) { | |
e5b38290 | 219 | return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop, .cke_dialog, #civicrm-menu').length; |
e20523a8 CW |
220 | }; |
221 | ||
9f8862e1 CW |
222 | // Implements jQuery hook.prop |
223 | $.propHooks.disabled = { | |
224 | set: function (el, value, name) { | |
225 | // Sync button enabled status with wrapper css | |
226 | if ($(el).is('span.crm-button > input.crm-form-submit')) { | |
227 | $(el).parent().toggleClass('crm-button-disabled', !!value); | |
228 | } | |
229 | // Sync button enabled status with dialog button | |
230 | if ($(el).is('.ui-dialog input.crm-form-submit')) { | |
9bce560a CW |
231 | $(el).closest('.ui-dialog').find('.ui-dialog-buttonset button[data-identifier='+ $(el).attr('name') +']').prop('disabled', value); |
232 | } | |
233 | if ($(el).is('.crm-form-date-wrapper .crm-hidden-date')) { | |
234 | $(el).siblings().prop('disabled', value); | |
9f8862e1 CW |
235 | } |
236 | } | |
237 | }; | |
238 | ||
475e9f44 CW |
239 | /** |
240 | * Populate a select list, overwriting the existing options except for the placeholder. | |
581c7be2 | 241 | * @param select jquery selector - 1 or more select elements |
475e9f44 | 242 | * @param options array in format returned by api.getoptions |
b7ceb253 CW |
243 | * @param placeholder string|bool - new placeholder or false (default) to keep the old one |
244 | * @param value string|array - will silently update the element with new value without triggering change | |
475e9f44 | 245 | */ |
b7ceb253 | 246 | CRM.utils.setOptions = function(select, options, placeholder, value) { |
581c7be2 | 247 | $(select).each(function() { |
475e9f44 CW |
248 | var |
249 | $elect = $(this), | |
b7ceb253 CW |
250 | val = value || $elect.val() || [], |
251 | opts = placeholder || placeholder === '' ? '' : '[value!=""]'; | |
23e8a31b | 252 | $elect.find('option' + opts).remove(); |
b7ceb253 | 253 | var newOptions = CRM.utils.renderOptions(options, val); |
1d07e7ab | 254 | if (typeof placeholder === 'string') { |
581c7be2 CW |
255 | if ($elect.is('[multiple]')) { |
256 | select.attr('placeholder', placeholder); | |
1d07e7ab CW |
257 | } else { |
258 | newOptions = '<option value="">' + placeholder + '</option>' + newOptions; | |
259 | } | |
260 | } | |
261 | $elect.append(newOptions); | |
b7ceb253 CW |
262 | if (!value) { |
263 | $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change'); | |
264 | } | |
475e9f44 CW |
265 | }); |
266 | }; | |
267 | ||
b7ceb253 CW |
268 | /** |
269 | * Render an option list | |
8decea37 CW |
270 | * @param options {array} |
271 | * @param val {string} default value | |
272 | * @param escapeHtml {bool} | |
b7ceb253 CW |
273 | * @return string |
274 | */ | |
8decea37 CW |
275 | CRM.utils.renderOptions = function(options, val, escapeHtml) { |
276 | var rendered = '', | |
277 | esc = escapeHtml === false ? _.identity : _.escape; | |
b7ceb253 CW |
278 | if (!$.isArray(val)) { |
279 | val = [val]; | |
280 | } | |
281 | _.each(options, function(option) { | |
282 | if (option.children) { | |
8decea37 | 283 | rendered += '<optgroup label="' + esc(option.value) + '">' + |
52e6588d CW |
284 | CRM.utils.renderOptions(option.children, val) + |
285 | '</optgroup>'; | |
b7ceb253 CW |
286 | } else { |
287 | var selected = ($.inArray('' + option.key, val) > -1) ? 'selected="selected"' : ''; | |
8decea37 | 288 | rendered += '<option value="' + esc(option.key) + '"' + selected + '>' + esc(option.value) + '</option>'; |
b7ceb253 | 289 | } |
475e9f44 | 290 | }); |
b7ceb253 | 291 | return rendered; |
475e9f44 CW |
292 | }; |
293 | ||
1d07e7ab CW |
294 | function chainSelect() { |
295 | var $form = $(this).closest('form'), | |
296 | $target = $('select[data-name="' + $(this).data('target') + '"]', $form), | |
297 | data = $target.data(), | |
298 | val = $(this).val(); | |
299 | $target.prop('disabled', true); | |
300 | if ($target.is('select.crm-chain-select-control')) { | |
301 | $('select[data-name="' + $target.data('target') + '"]', $form).prop('disabled', true).blur(); | |
302 | } | |
303 | if (!(val && val.length)) { | |
304 | CRM.utils.setOptions($target.blur(), [], data.emptyPrompt); | |
305 | } else { | |
306 | $target.addClass('loading'); | |
307 | $.getJSON(CRM.url(data.callback), {_value: val}, function(vals) { | |
308 | $target.prop('disabled', false).removeClass('loading'); | |
309 | CRM.utils.setOptions($target, vals || [], (vals && vals.length ? data.selectPrompt : data.nonePrompt)); | |
310 | }); | |
311 | } | |
312 | } | |
313 | ||
52e6588d CW |
314 | /** |
315 | * Compare Form Input values against cached initial value. | |
316 | * | |
317 | * @return {Boolean} true if changes have been made. | |
318 | */ | |
3e201321 | 319 | CRM.utils.initialValueChanged = function(el) { |
88e9380e | 320 | var isDirty = false; |
d4fa3633 | 321 | $(':input:visible, .select2-container:visible+:input:hidden', el).not('[type=submit], [type=button], .crm-action-menu, :disabled').each(function () { |
603f899a CW |
322 | var |
323 | initialValue = $(this).data('crm-initial-value'), | |
324 | currentValue = $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val(); | |
3c0624e2 | 325 | // skip change of value for submit buttons |
603f899a | 326 | if (initialValue !== undefined && !_.isEqual(initialValue, currentValue)) { |
88e9380e CW |
327 | isDirty = true; |
328 | } | |
3e201321 | 329 | }); |
330 | return isDirty; | |
8d36b801 | 331 | }; |
52e6588d | 332 | |
b1fc510d CW |
333 | /** |
334 | * This provides defaults for ui.dialog which either need to be calculated or are different from global defaults | |
335 | * | |
336 | * @param settings | |
337 | * @returns {*} | |
338 | */ | |
339 | CRM.utils.adjustDialogDefaults = function(settings) { | |
340 | settings = $.extend({width: '65%', height: '65%', modal: true}, settings || {}); | |
341 | // Support relative height | |
342 | if (typeof settings.height === 'string' && settings.height.indexOf('%') > 0) { | |
343 | settings.height = parseInt($(window).height() * (parseFloat(settings.height)/100), 10); | |
344 | } | |
345 | // Responsive adjustment - increase percent width on small screens | |
346 | if (typeof settings.width === 'string' && settings.width.indexOf('%') > 0) { | |
347 | var screenWidth = $(window).width(), | |
348 | percentage = parseInt(settings.width.replace('%', ''), 10), | |
349 | gap = 100-percentage; | |
350 | if (screenWidth < 701) { | |
351 | settings.width = '100%'; | |
352 | } | |
353 | else if (screenWidth < 1400) { | |
354 | settings.width = '' + parseInt(percentage+gap-((screenWidth - 700)/7*(gap)/100), 10) + '%'; | |
355 | } | |
356 | } | |
357 | return settings; | |
358 | }; | |
52e6588d | 359 | |
ba4fb2b2 | 360 | /** |
353ea873 | 361 | * Wrapper for select2 initialization function; supplies defaults |
a88cf11a | 362 | * @param options object |
ba4fb2b2 | 363 | */ |
a88cf11a CW |
364 | $.fn.crmSelect2 = function(options) { |
365 | return $(this).each(function () { | |
366 | var | |
367 | $el = $(this), | |
a243158e | 368 | settings = {allowClear: !$el.hasClass('required')}; |
a88cf11a CW |
369 | // quickform doesn't support optgroups so here's a hack :( |
370 | $('option[value^=crm_optgroup]', this).each(function () { | |
371 | $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />'); | |
372 | $(this).remove(); | |
373 | }); | |
47358d92 | 374 | |
375 | // quickform does not support disabled option, so yet another hack to | |
376 | // add disabled property for option values | |
711da13f | 377 | $('option[value^=crm_disabled_opt]', this).attr('disabled', 'disabled'); |
27a6b676 | 378 | |
a88cf11a CW |
379 | // Defaults for single-selects |
380 | if ($el.is('select:not([multiple])')) { | |
a243158e | 381 | settings.minimumResultsForSearch = 10; |
a88cf11a | 382 | if ($('option:first', this).val() === '') { |
a243158e | 383 | settings.placeholderOption = 'first'; |
a88cf11a | 384 | } |
ba4fb2b2 | 385 | } |
a243158e CW |
386 | $.extend(settings, $el.data('select-params') || {}, options || {}); |
387 | if (settings.ajax) { | |
388 | $el.addClass('crm-ajax-select'); | |
389 | } | |
390 | $el.select2(settings); | |
a88cf11a CW |
391 | }); |
392 | }; | |
393 | ||
394 | /** | |
353ea873 | 395 | * @see CRM_Core_Form::addEntityRef for docs |
a88cf11a CW |
396 | * @param options object |
397 | */ | |
398 | $.fn.crmEntityRef = function(options) { | |
399 | options = options || {}; | |
400 | options.select = options.select || {}; | |
401 | return $(this).each(function() { | |
402 | var | |
4c993609 | 403 | $el = $(this).off('.crmEntity'), |
a88cf11a CW |
404 | entity = options.entity || $el.data('api-entity') || 'contact', |
405 | selectParams = {}; | |
406 | $el.data('api-entity', entity); | |
407 | $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select)); | |
408 | $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api)); | |
a4799f04 | 409 | $el.data('create-links', options.create || $el.data('create-links')); |
b7ceb253 | 410 | $el.addClass('crm-form-entityref crm-' + entity.toLowerCase() + '-ref'); |
ba4fb2b2 | 411 | var settings = { |
b7ceb253 | 412 | // Use select2 ajax helper instead of CRM.api3 because it provides more value |
ba4fb2b2 CW |
413 | ajax: { |
414 | url: CRM.url('civicrm/ajax/rest'), | |
415 | data: function (input, page_num) { | |
b7ceb253 | 416 | var params = getEntityRefApiParams($el); |
ba4fb2b2 CW |
417 | params.input = input; |
418 | params.page_num = page_num; | |
419 | return { | |
420 | entity: $el.data('api-entity'), | |
421 | action: 'getlist', | |
422 | json: JSON.stringify(params) | |
423 | }; | |
424 | }, | |
425 | results: function(data) { | |
426 | return {more: data.more_results, results: data.values || []}; | |
427 | } | |
428 | }, | |
a88cf11a | 429 | minimumInputLength: 1, |
3c0b6a40 | 430 | formatResult: CRM.utils.formatSelect2Result, |
ba4fb2b2 CW |
431 | formatSelection: function(row) { |
432 | return row.label; | |
433 | }, | |
434 | escapeMarkup: function (m) {return m;}, | |
a88cf11a CW |
435 | initSelection: function($el, callback) { |
436 | var | |
437 | multiple = !!$el.data('select-params').multiple, | |
438 | val = $el.val(), | |
439 | stored = $el.data('entity-value') || []; | |
440 | if (val === '') { | |
441 | return; | |
442 | } | |
443 | // If we already have this data, just return it | |
444 | if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) { | |
445 | callback(multiple ? stored : stored[0]); | |
446 | } else { | |
78b203e5 | 447 | var params = $.extend({}, $el.data('api-params') || {}, {id: val}); |
a88cf11a | 448 | CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) { |
d2b4810b CW |
449 | callback(multiple ? result.values : result.values[0]); |
450 | // Trigger change (store data to avoid an infinite loop of lookups) | |
451 | $el.data('entity-value', result.values).trigger('change'); | |
a88cf11a CW |
452 | }); |
453 | } | |
ba4fb2b2 CW |
454 | } |
455 | }; | |
4c993609 | 456 | // Create new items inline - works for tags |
b7ceb253 | 457 | if ($el.data('create-links') && entity.toLowerCase() === 'tag') { |
4c993609 CW |
458 | selectParams.createSearchChoice = function(term, data) { |
459 | if (!_.findKey(data, {label: term})) { | |
460 | return {id: "0", term: term, label: term + ' (' + ts('new tag') + ')'}; | |
461 | } | |
462 | }; | |
e4f4dc22 | 463 | selectParams.tokenSeparators = [',']; |
4c993609 | 464 | selectParams.createSearchChoicePosition = 'bottom'; |
05b21c58 | 465 | $el.on('select2-selecting.crmEntity', function(e) { |
4c993609 | 466 | if (e.val === "0") { |
a2c28a94 | 467 | // Create a new term |
4c993609 CW |
468 | e.object.label = e.object.term; |
469 | CRM.api3(entity, 'create', $.extend({name: e.object.term}, $el.data('api-params').params || {})) | |
470 | .done(function(created) { | |
471 | var | |
4c993609 CW |
472 | val = $el.select2('val'), |
473 | data = $el.select2('data'), | |
474 | item = {id: created.id, label: e.object.term}; | |
475 | if (val === "0") { | |
e4f4dc22 | 476 | $el.select2('data', item, true); |
4c993609 CW |
477 | } |
478 | else if ($.isArray(val) && $.inArray("0", val) > -1) { | |
479 | _.remove(data, {id: "0"}); | |
480 | data.push(item); | |
e4f4dc22 | 481 | $el.select2('data', data, true); |
4c993609 CW |
482 | } |
483 | }); | |
484 | } | |
485 | }); | |
b7ceb253 CW |
486 | } |
487 | else { | |
a88cf11a CW |
488 | selectParams.formatInputTooShort = function() { |
489 | var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this); | |
cdc8d05f | 490 | txt += renderEntityRefFilters($el) + renderEntityRefCreateLinks($el); |
ba4fb2b2 CW |
491 | return txt; |
492 | }; | |
a88cf11a | 493 | selectParams.formatNoMatches = function() { |
ba4fb2b2 | 494 | var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches; |
cdc8d05f | 495 | txt += renderEntityRefFilters($el) + renderEntityRefCreateLinks($el); |
b7ceb253 | 496 | return txt; |
ba4fb2b2 | 497 | }; |
4c993609 | 498 | $el.on('select2-open.crmEntity', function() { |
ba4fb2b2 | 499 | var $el = $(this); |
b7ceb253 CW |
500 | loadEntityRefFilterOptions($el); |
501 | $('#select2-drop') | |
502 | .off('.crmEntity') | |
503 | .on('click.crmEntity', 'a.crm-add-entity', function(e) { | |
504 | $el.select2('close'); | |
505 | CRM.loadForm($(this).attr('href'), { | |
776ff7a0 | 506 | dialog: {width: 500, height: 220} |
b7ceb253 CW |
507 | }).on('crmFormSuccess', function(e, data) { |
508 | if (data.status === 'success' && data.id) { | |
509 | CRM.status(ts('%1 Created', {1: data.label})); | |
510 | if ($el.select2('container').hasClass('select2-container-multi')) { | |
511 | var selection = $el.select2('data'); | |
512 | selection.push(data); | |
513 | $el.select2('data', selection, true); | |
514 | } else { | |
515 | $el.select2('data', data, true); | |
516 | } | |
c92f6436 | 517 | } |
b7ceb253 CW |
518 | }); |
519 | return false; | |
520 | }) | |
521 | .on('change.crmEntity', 'select.crm-entityref-filter-value', function() { | |
522 | var filter = $el.data('user-filter') || {}; | |
523 | filter.value = $(this).val(); | |
524 | $(this).toggleClass('active', !!filter.value); | |
525 | $el.data('user-filter', filter); | |
526 | if (filter.value) { | |
527 | // Once a filter has been chosen, rerender create links and refocus the search box | |
528 | $el.select2('close'); | |
529 | $el.select2('open'); | |
ba4fb2b2 | 530 | } |
b7ceb253 CW |
531 | }) |
532 | .on('change.crmEntity', 'select.crm-entityref-filter-key', function() { | |
533 | var filter = $el.data('user-filter') || {}; | |
534 | filter.key = $(this).val(); | |
535 | $(this).toggleClass('active', !!filter.key); | |
536 | $el.data('user-filter', filter); | |
537 | loadEntityRefFilterOptions($el); | |
ba4fb2b2 | 538 | }); |
ba4fb2b2 CW |
539 | }); |
540 | } | |
05b21c58 | 541 | $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams)); |
a88cf11a | 542 | }); |
ba4fb2b2 CW |
543 | }; |
544 | ||
b7ceb253 CW |
545 | /** |
546 | * Combine api-params with user-filter | |
547 | * @param $el | |
548 | * @returns {*} | |
549 | */ | |
550 | function getEntityRefApiParams($el) { | |
551 | var | |
552 | params = $.extend({params: {}}, $el.data('api-params') || {}), | |
553 | // Prevent original data from being modified - $.extend and _.clone don't cut it, they pass nested objects by reference! | |
554 | combined = _.cloneDeep(params), | |
555 | filter = $.extend({}, $el.data('user-filter') || {}); | |
556 | if (filter.key && filter.value) { | |
557 | // Special case for contact type/sub-type combo | |
bee6039a CW |
558 | if (filter.key === 'contact_type' && (filter.value.indexOf('__') > 0)) { |
559 | combined.params.contact_type = filter.value.split('__')[0]; | |
560 | combined.params.contact_sub_type = filter.value.split('__')[1]; | |
b7ceb253 | 561 | } else { |
cdc8d05f CW |
562 | // Allow json-encoded api filters e.g. {"BETWEEN":[123,456]} |
563 | combined.params[filter.key] = filter.value.charAt(0) === '{' ? $.parseJSON(filter.value) : filter.value; | |
b7ceb253 CW |
564 | } |
565 | } | |
566 | return combined; | |
567 | } | |
568 | ||
9bce560a CW |
569 | function copyAttributes($source, $target, attributes) { |
570 | _.each(attributes, function(name) { | |
571 | if ($source.attr(name)) { | |
572 | $target.attr(name, $source.attr(name)); | |
573 | } | |
574 | }); | |
575 | } | |
576 | ||
577 | $.fn.crmDatepicker = function(options) { | |
578 | return $(this).each(function() { | |
579 | if ($(this).is('.crm-form-date-wrapper .crm-hidden-date')) { | |
580 | // Already initialized | |
581 | return; | |
582 | } | |
583 | var | |
584 | $dataField = $(this).wrap('<span class="crm-form-date-wrapper" />'), | |
585 | settings = $.extend({}, $dataField.data('datepicker') || {}, options || {}), | |
586 | $dateField = $(), | |
587 | $timeField = $(), | |
588 | $clearLink = $(); | |
589 | ||
590 | if (settings.allowClear !== undefined ? settings.allowClear : !$dataField.hasClass('required')) { | |
591 | $clearLink = $('<a class="crm-hover-button crm-clear-link" title="'+ ts('Clear') +'"><span class="icon ui-icon-close"></span></a>') | |
592 | .insertAfter($dataField); | |
593 | } | |
594 | if (settings.time !== false) { | |
595 | $timeField = $('<input>').insertAfter($dataField); | |
596 | copyAttributes($dataField, $timeField, ['class', 'disabled']); | |
597 | $timeField | |
598 | .addClass('crm-form-text crm-form-time') | |
599 | .attr('placeholder', $dataField.attr('time-placeholder') === undefined ? ts('Time') : $dataField.attr('time-placeholder')) | |
600 | .change(updateDataField) | |
601 | .timeEntry({ | |
602 | spinnerImage: '', | |
0d05e8a1 | 603 | show24Hours: settings.time === true || settings.time === undefined ? CRM.config.timeIs24Hr : settings.time == '24' |
9bce560a CW |
604 | }); |
605 | } | |
606 | if (settings.date !== false) { | |
607 | $dateField = $('<input>').insertAfter($dataField); | |
608 | copyAttributes($dataField, $dateField, ['placeholder', 'style', 'class', 'disabled']); | |
609 | $dateField.addClass('crm-form-text crm-form-date'); | |
610 | settings.dateFormat = settings.dateFormat || CRM.config.dateInputFormat; | |
611 | settings.changeMonth = _.includes('m', settings.dateFormat); | |
612 | settings.changeYear = _.includes('y', settings.dateFormat); | |
613 | $dateField.datepicker(settings).change(updateDataField); | |
614 | } | |
8e2e2658 CW |
615 | // Rudimentary validation. TODO: Roll into use of jQUery validate and ui.datepicker.validation |
616 | function isValidDate() { | |
617 | try { | |
618 | $.datepicker.parseDate(settings.dateFormat, $dateField.val()); | |
619 | return true; | |
620 | } catch (e) { | |
621 | return false; | |
622 | } | |
623 | } | |
9bce560a | 624 | function updateInputFields(e, context) { |
ac5009c1 CW |
625 | var val = $dataField.val(), |
626 | time = null; | |
9bce560a | 627 | if (context !== 'userInput' && context !== 'crmClear') { |
ac5009c1 CW |
628 | if ($dateField.length) { |
629 | $dateField.datepicker('setDate', _.includes(val, '-') ? $.datepicker.parseDate('yy-mm-dd', val) : null); | |
630 | } | |
631 | if ($timeField.length) { | |
632 | if (val.length === 8) { | |
633 | time = val; | |
634 | } else if (val.length === 19) { | |
635 | time = val.split(' ')[1]; | |
9bce560a | 636 | } |
ac5009c1 | 637 | $timeField.timeEntry('setTime', time); |
9bce560a CW |
638 | } |
639 | } | |
ac5009c1 | 640 | $clearLink.css('visibility', val ? 'visible' : 'hidden'); |
9bce560a CW |
641 | } |
642 | function updateDataField(e, context) { | |
8e2e2658 | 643 | // The crmClear event wipes all the field values anyway, so no need to respond |
9bce560a CW |
644 | if (context !== 'crmClear') { |
645 | var val = ''; | |
646 | if ($dateField.val()) { | |
8e2e2658 CW |
647 | if (isValidDate()) { |
648 | val = $.datepicker.formatDate('yy-mm-dd', $dateField.datepicker('getDate')); | |
649 | $dateField.removeClass('crm-error'); | |
650 | } else { | |
651 | $dateField.addClass('crm-error'); | |
652 | } | |
9bce560a CW |
653 | } |
654 | if ($timeField.val()) { | |
ac5009c1 | 655 | val += (val ? ' ' : '') + $timeField.timeEntry('getTime').toTimeString().substr(0, 8); |
9bce560a CW |
656 | } |
657 | $dataField.val(val).trigger('change', ['userInput']); | |
658 | } | |
659 | } | |
660 | $dataField.hide().addClass('crm-hidden-date').on('change', updateInputFields); | |
661 | updateInputFields(); | |
662 | }); | |
663 | }; | |
664 | ||
3c0b6a40 | 665 | CRM.utils.formatSelect2Result = function (row) { |
88881f79 | 666 | var markup = '<div class="crm-select2-row">'; |
ff88d165 | 667 | if (row.image !== undefined) { |
88881f79 | 668 | markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>'; |
ff88d165 | 669 | } |
54bee7df | 670 | else if (row.icon_class) { |
88881f79 | 671 | markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>'; |
54bee7df | 672 | } |
3c0b6a40 | 673 | markup += '<div><div class="crm-select2-row-label '+(row.label_class || '')+'">' + row.label + '</div>'; |
88881f79 CW |
674 | markup += '<div class="crm-select2-row-description">'; |
675 | $.each(row.description || [], function(k, text) { | |
676 | markup += '<p>' + text + '</p>'; | |
677 | }); | |
678 | markup += '</div></div></div>'; | |
ff88d165 | 679 | return markup; |
3c0b6a40 | 680 | }; |
a4799f04 | 681 | |
b7ceb253 | 682 | function renderEntityRefCreateLinks($el) { |
a4799f04 CW |
683 | var |
684 | createLinks = $el.data('create-links'), | |
b7ceb253 CW |
685 | params = getEntityRefApiParams($el).params, |
686 | markup = '<div class="crm-entityref-links">'; | |
687 | if (!createLinks || $el.data('api-entity').toLowerCase() !== 'contact') { | |
688 | return ''; | |
689 | } | |
a4799f04 | 690 | if (createLinks === true) { |
b7ceb253 | 691 | createLinks = params.contact_type ? _.where(CRM.config.entityRef.contactCreate, {type: params.contact_type}) : CRM.config.entityRef.contactCreate; |
a4799f04 | 692 | } |
a4799f04 | 693 | _.each(createLinks, function(link) { |
79ae07d9 | 694 | markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">'; |
a4799f04 CW |
695 | if (link.type) { |
696 | markup += '<span class="icon ' + link.type + '-profile-icon"></span> '; | |
79ae07d9 CW |
697 | } |
698 | markup += link.label + '</a>'; | |
699 | }); | |
b7ceb253 CW |
700 | markup += '</div>'; |
701 | return markup; | |
702 | } | |
703 | ||
704 | function getEntityRefFilters($el) { | |
705 | var | |
706 | entity = $el.data('api-entity').toLowerCase(), | |
707 | filters = $.extend([], CRM.config.entityRef.filters[entity] || []), | |
708 | filter = $el.data('user-filter') || {}, | |
709 | params = $.extend({params: {}}, $el.data('api-params') || {}).params, | |
710 | result = []; | |
711 | $.each(filters, function() { | |
712 | if (typeof params[this.key] === 'undefined') { | |
713 | result.push(this); | |
714 | } | |
715 | else if (this.key == 'contact_type' && typeof params.contact_sub_type === 'undefined') { | |
716 | this.options = _.remove(this.options, function(option) { | |
bee6039a | 717 | return option.key.indexOf(params.contact_type + '__') === 0; |
b7ceb253 CW |
718 | }); |
719 | result.push(this); | |
720 | } | |
721 | }); | |
722 | return result; | |
723 | } | |
724 | ||
725 | function renderEntityRefFilters($el) { | |
726 | var | |
727 | filters = getEntityRefFilters($el), | |
728 | filter = $el.data('user-filter') || {}, | |
729 | filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null; | |
730 | if (!filters.length) { | |
731 | return ''; | |
732 | } | |
733 | var markup = '<div class="crm-entityref-filters">' + | |
734 | '<select class="crm-entityref-filter-key' + (filter.key ? ' active' : '') + '">' + | |
52e6588d CW |
735 | '<option value="">' + ts('Refine search...') + '</option>' + |
736 | CRM.utils.renderOptions(filters, filter.key) + | |
b7ceb253 CW |
737 | '</select> ' + |
738 | '<select class="crm-entityref-filter-value' + (filter.key ? ' active"' : '"') + (filter.key ? '' : ' style="display:none;"') + '>' + | |
52e6588d | 739 | '<option value="">' + ts('- select -') + '</option>'; |
b7ceb253 CW |
740 | if (filterSpec && filterSpec.options) { |
741 | markup += CRM.utils.renderOptions(filterSpec.options, filter.value); | |
742 | } | |
743 | markup += '</select></div>'; | |
79ae07d9 | 744 | return markup; |
a4799f04 | 745 | } |
ff88d165 | 746 | |
b7ceb253 CW |
747 | /** |
748 | * Fetch options for a filter (via ajax if necessary) and populate the appropriate select list | |
749 | * @param $el | |
750 | */ | |
751 | function loadEntityRefFilterOptions($el) { | |
752 | var | |
753 | filters = getEntityRefFilters($el), | |
754 | filter = $el.data('user-filter') || {}, | |
755 | filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null, | |
756 | $valField = $('.crm-entityref-filter-value', '#select2-drop'); | |
757 | if (filterSpec) { | |
758 | $valField.show().val(''); | |
759 | if (filterSpec.options) { | |
760 | CRM.utils.setOptions($valField, filterSpec.options, false, filter.value); | |
761 | } else { | |
762 | $valField.prop('disabled', true); | |
bee6039a | 763 | CRM.api3(filterSpec.entity || $el.data('api-entity'), 'getoptions', {field: filter.key, context: 'search', sequential: 1}) |
b7ceb253 CW |
764 | .done(function(result) { |
765 | var entity = $el.data('api-entity').toLowerCase(), | |
766 | globalFilterSpec = _.find(CRM.config.entityRef.filters[entity], {key: filter.key}) || {}; | |
767 | // Store options globally so we don't have to look them up again | |
768 | globalFilterSpec.options = result.values; | |
769 | $valField.prop('disabled', false); | |
770 | CRM.utils.setOptions($valField, result.values); | |
771 | $valField.val(filter.value || ''); | |
772 | }); | |
773 | } | |
774 | } else { | |
775 | $valField.hide(); | |
776 | } | |
777 | } | |
778 | ||
1136a401 | 779 | //CRM-15598 - Override url validator method to allow relative url's (e.g. /index.htm) |
780 | $.validator.addMethod("url", function(value, element) { | |
781 | if (/^\//.test(value)) { | |
782 | // Relative url: prepend dummy path for validation. | |
783 | value = 'http://domain.tld' + value; | |
784 | } | |
785 | // From jQuery Validation Plugin v1.12.0 | |
786 | return this.optional(element) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value); | |
787 | }); | |
788 | ||
3d527838 CW |
789 | /** |
790 | * Wrapper for jQuery validate initialization function; supplies defaults | |
3d527838 CW |
791 | */ |
792 | $.fn.crmValidate = function(params) { | |
793 | return $(this).each(function () { | |
794 | var that = this, | |
795 | settings = $.extend({}, CRM.validate._defaults, CRM.validate.params); | |
796 | $(this).validate(settings); | |
797 | // Call any post-initialization callbacks | |
798 | if (CRM.validate.functions && CRM.validate.functions.length) { | |
799 | $.each(CRM.validate.functions, function(i, func) { | |
800 | func.call(that); | |
801 | }); | |
802 | } | |
803 | }); | |
b7ceb253 | 804 | }; |
3d527838 | 805 | |
f7b92fcd | 806 | // Initialize widgets |
eb90857a CW |
807 | $(document) |
808 | .on('crmLoad', function(e) { | |
809 | $('table.row-highlight', e.target) | |
810 | .off('.rowHighlight') | |
7e13d44e CW |
811 | .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) { |
812 | var filter, $table = $(this).closest('table'); | |
eb90857a | 813 | if ($(this).hasClass('select-rows')) { |
7e13d44e CW |
814 | filter = $(this).prop('checked') ? ':not(:checked)' : ':checked'; |
815 | $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected'); | |
eb90857a CW |
816 | } |
817 | else { | |
7e13d44e CW |
818 | $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked')); |
819 | if (data !== 'master-selected') { | |
820 | $('input.select-rows', $table).prop('checked', $(".select-row:not(':checked')", $table).length < 1); | |
821 | } | |
eb90857a | 822 | } |
eb90857a CW |
823 | }) |
824 | .find('input.select-row:checked').parents('tr').addClass('crm-row-selected'); | |
82661158 JP |
825 | if ($("input:radio[name=radio_ts]").size() == 1) { |
826 | $("input:radio[name=radio_ts]").prop("checked", true); | |
827 | } | |
5f34e50b CW |
828 | $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2(); |
829 | $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef(); | |
1d07e7ab | 830 | $('select.crm-chain-select-control', e.target).off('.chainSelect').on('change.chainSelect', chainSelect); |
3e201321 | 831 | // Cache Form Input initial values |
88e9380e | 832 | $('form[data-warn-changes] :input', e.target).each(function() { |
603f899a | 833 | $(this).data('crm-initial-value', $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val()); |
3e201321 | 834 | }); |
4d49c3a2 | 835 | $('textarea.crm-wysiwyg', e.target) |
f91b1c0c CW |
836 | .not('.crm-wysiwyg-enabled') |
837 | .addClass('crm-wysiwyg-enabled') | |
4d49c3a2 TC |
838 | .each(function() { |
839 | if ($(this).hasClass("collapsed")) { | |
f91b1c0c | 840 | CRM.wysiwyg.createCollapsed(this); |
4d49c3a2 TC |
841 | } else { |
842 | CRM.wysiwyg.create(this); | |
843 | } | |
844 | }); | |
a5a0ed13 | 845 | }) |
eb90857a | 846 | .on('dialogopen', function(e) { |
f292709b CW |
847 | var $el = $(e.target); |
848 | // Modal dialogs should disable scrollbars | |
849 | if ($el.dialog('option', 'modal')) { | |
850 | $el.addClass('modal-dialog'); | |
eb90857a CW |
851 | $('body').css({overflow: 'hidden'}); |
852 | } | |
f292709b | 853 | // Add resize button |
a243158e | 854 | if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) { |
77a8d7f9 | 855 | $el.parent().find('.ui-dialog-titlebar').append($('<button class="crm-dialog-titlebar-resize ui-dialog-titlebar-close" title="'+ts('Toggle fullscreen')+'" style="right:2em;"/>').button({icons: {primary: 'ui-icon-newwin'}, text: false})); |
f292709b CW |
856 | $('.crm-dialog-titlebar-resize', $el.parent()).click(function(e) { |
857 | if ($el.data('origSize')) { | |
858 | $el.dialog('option', $el.data('origSize')); | |
859 | $el.data('origSize', null); | |
860 | } else { | |
28d510ab | 861 | var menuHeight = $('#civicrm-menu').outerHeight(); |
f292709b | 862 | $el.data('origSize', { |
28d510ab | 863 | position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window}, |
f292709b CW |
864 | width: $el.dialog('option', 'width'), |
865 | height: $el.dialog('option', 'height') | |
866 | }); | |
f2f191fe | 867 | $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: {my: "top", at: "top+"+menuHeight, of: window}}); |
f292709b | 868 | } |
02cd9764 | 869 | $el.trigger('dialogresize'); |
f292709b CW |
870 | e.preventDefault(); |
871 | }); | |
872 | } | |
eb90857a CW |
873 | }) |
874 | .on('dialogclose', function(e) { | |
f292709b | 875 | // Restore scrollbars when closing modal |
5a6148a0 | 876 | if ($('.ui-dialog .modal-dialog:visible').not(e.target).length < 1) { |
eb90857a CW |
877 | $('body').css({overflow: ''}); |
878 | } | |
afc021d8 | 879 | }) |
880 | .on('submit', function(e) { | |
f582fc8f | 881 | // CRM-14353 - disable changes warn when submitting a form |
abb6e044 | 882 | $('[data-warn-changes]').attr('data-warn-changes', 'false'); |
52e6588d | 883 | }); |
f582fc8f CW |
884 | |
885 | // CRM-14353 - Warn of unsaved changes for forms which have opted in | |
886 | window.onbeforeunload = function() { | |
18469bf2 | 887 | if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]:visible'))) { |
f582fc8f | 888 | return ts('You have unsaved changes.'); |
0f5816a6 | 889 | } |
f582fc8f | 890 | }; |
6a488035 | 891 | |
0f5816a6 | 892 | $.fn.crmtooltip = function () { |
2c29c2ac RN |
893 | $(document) |
894 | .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) { | |
895 | $(this).addClass('crm-processed'); | |
e24b17b9 CW |
896 | $(this).addClass('crm-tooltip-active'); |
897 | var topDistance = e.pageY - $(window).scrollTop(); | |
2b3ddf6e | 898 | if (topDistance < 300 || topDistance < $(this).children('.crm-tooltip-wrapper').height()) { |
e24b17b9 CW |
899 | $(this).addClass('crm-tooltip-down'); |
900 | } | |
901 | if (!$(this).children('.crm-tooltip-wrapper').length) { | |
6a488035 TO |
902 | $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>'); |
903 | $(this).children().children('.crm-tooltip') | |
904 | .html('<div class="crm-loading-element"></div>') | |
905 | .load(this.href); | |
906 | } | |
907 | }) | |
2c29c2ac RN |
908 | .on('mouseout', 'a.crm-summary-link', function () { |
909 | $(this).removeClass('crm-processed'); | |
e24b17b9 CW |
910 | $(this).removeClass('crm-tooltip-active crm-tooltip-down'); |
911 | }) | |
2c29c2ac | 912 | .on('click', 'a.crm-summary-link', false); |
6a488035 TO |
913 | }; |
914 | ||
b0ca6188 | 915 | var helpDisplay, helpPrevious; |
8e3272a1 | 916 | CRM.help = function (title, params, url) { |
55a93b02 | 917 | if (helpDisplay && helpDisplay.close) { |
b0ca6188 | 918 | // If the same link is clicked twice, just close the display - todo use underscore method for this comparison |
55a93b02 CW |
919 | if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) { |
920 | helpDisplay.close(); | |
b0ca6188 CW |
921 | return; |
922 | } | |
55a93b02 | 923 | helpDisplay.close(); |
b0ca6188 CW |
924 | } |
925 | helpPrevious = JSON.stringify(params); | |
6a488035 TO |
926 | params.class_name = 'CRM_Core_Page_Inline_Help'; |
927 | params.type = 'page'; | |
b0ca6188 | 928 | helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0}); |
8e3272a1 | 929 | $.ajax(url || CRM.url('civicrm/ajax/inline'), |
6a488035 TO |
930 | { |
931 | data: params, | |
932 | dataType: 'html', | |
e24b17b9 | 933 | success: function (data) { |
6a488035 TO |
934 | $('#crm-notification-container .crm-help .notify-content:last').html(data); |
935 | $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info'); | |
936 | }, | |
e24b17b9 | 937 | error: function () { |
6a488035 TO |
938 | $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.'); |
939 | $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error'); | |
940 | } | |
941 | } | |
942 | ); | |
943 | }; | |
8960d9b9 | 944 | /** |
7442e8f6 | 945 | * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference |
8960d9b9 | 946 | */ |
1b2475e1 | 947 | CRM.status = function(options, deferred) { |
9a7ef94f | 948 | // For simple usage without async operations you can pass in a string. 2nd param is optional string 'error' if this is not a success msg. |
1b2475e1 CW |
949 | if (typeof options === 'string') { |
950 | return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve'](); | |
8960d9b9 | 951 | } |
1b2475e1 CW |
952 | var opts = $.extend({ |
953 | start: ts('Saving...'), | |
9a7ef94f | 954 | success: ts('Saved'), |
47737104 CW |
955 | error: function(data) { |
956 | var msg = $.isPlainObject(data) && data.error_message; | |
957 | CRM.alert(msg || ts('Sorry an error occurred and your information was not saved'), ts('Error'), 'error'); | |
1b2475e1 CW |
958 | } |
959 | }, options || {}); | |
960 | var $msg = $('<div class="crm-status-box-outer status-start"><div class="crm-status-box-inner"><div class="crm-status-box-msg">' + opts.start + '</div></div></div>') | |
961 | .appendTo('body'); | |
962 | $msg.css('min-width', $msg.width()); | |
963 | function handle(status, data) { | |
964 | var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status]; | |
965 | if (endMsg) { | |
966 | $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg); | |
967 | window.setTimeout(function() { | |
f54254d8 TO |
968 | $msg.fadeOut('slow', function() { |
969 | $msg.remove(); | |
970 | }); | |
4bad157e CW |
971 | }, 2000); |
972 | } else { | |
1b2475e1 | 973 | $msg.remove(); |
4bad157e | 974 | } |
1b2475e1 CW |
975 | } |
976 | return (deferred || new $.Deferred()) | |
977 | .done(function(data) { | |
978 | // If the server returns an error msg call the error handler | |
979 | var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success'; | |
980 | handle(status, data); | |
981 | }) | |
982 | .fail(function(data) { | |
983 | handle('error', data); | |
984 | }); | |
8960d9b9 | 985 | }; |
6a488035 | 986 | |
beab9d1b TO |
987 | // Convert an Angular promise to a jQuery promise |
988 | CRM.toJqPromise = function(aPromise) { | |
989 | var jqDeferred = $.Deferred(); | |
990 | aPromise.then( | |
991 | function(data) { jqDeferred.resolve(data); }, | |
992 | function(data) { jqDeferred.reject(data); } | |
993 | // should we also handle progress events? | |
994 | ); | |
995 | return jqDeferred.promise(); | |
996 | }; | |
997 | ||
705c61e9 TO |
998 | CRM.toAPromise = function($q, jqPromise) { |
999 | var aDeferred = $q.defer(); | |
1000 | jqPromise.then( | |
1001 | function(data) { aDeferred.resolve(data); }, | |
1002 | function(data) { aDeferred.reject(data); } | |
1003 | // should we also handle progress events? | |
1004 | ); | |
1005 | return aDeferred.promise; | |
1006 | }; | |
1007 | ||
6a488035 | 1008 | /** |
7442e8f6 | 1009 | * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference |
6a488035 | 1010 | */ |
0f5816a6 | 1011 | CRM.alert = function (text, title, type, options) { |
6a488035 TO |
1012 | type = type || 'alert'; |
1013 | title = title || ''; | |
1014 | options = options || {}; | |
1015 | if ($('#crm-notification-container').length) { | |
1016 | var params = { | |
1017 | text: text, | |
1018 | title: title, | |
1019 | type: type | |
1020 | }; | |
1021 | // By default, don't expire errors and messages containing links | |
1022 | var extra = { | |
1023 | expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000), | |
1024 | unique: true | |
1025 | }; | |
1026 | options = $.extend(extra, options); | |
e24b17b9 | 1027 | options.expires = options.expires === false ? 0 : parseInt(options.expires, 10); |
6a488035 | 1028 | if (options.unique && options.unique !== '0') { |
0f5816a6 | 1029 | $('#crm-notification-container .ui-notify-message').each(function () { |
6a488035 TO |
1030 | if (title === $('h1', this).html() && text === $('.notify-content', this).html()) { |
1031 | $('.icon.ui-notify-close', this).click(); | |
1032 | } | |
1033 | }); | |
1034 | } | |
1035 | return $('#crm-notification-container').notify('create', params, options); | |
1036 | } | |
1037 | else { | |
1038 | if (title.length) { | |
1039 | text = title + "\n" + text; | |
1040 | } | |
1041 | alert(text); | |
1042 | return null; | |
1043 | } | |
e24b17b9 | 1044 | }; |
6a488035 TO |
1045 | |
1046 | /** | |
1047 | * Close whichever alert contains the given node | |
1048 | * | |
1049 | * @param node | |
1050 | */ | |
0f5816a6 | 1051 | CRM.closeAlertByChild = function (node) { |
6a488035 | 1052 | $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click(); |
e24b17b9 | 1053 | }; |
6a488035 TO |
1054 | |
1055 | /** | |
7442e8f6 | 1056 | * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference |
6a488035 | 1057 | */ |
5fb83680 | 1058 | CRM.confirm = function (options) { |
27f190b4 | 1059 | var dialog, url, msg, buttons = [], settings = { |
a65e5f52 | 1060 | title: ts('Confirm'), |
7553cf23 | 1061 | message: ts('Are you sure you want to continue?'), |
3f4328da | 1062 | url: null, |
0d5f99d4 | 1063 | width: 'auto', |
a8a8ddac | 1064 | height: 'auto', |
a243158e | 1065 | resizable: false, |
5fb83680 | 1066 | dialogClass: 'crm-container crm-confirm', |
0f5816a6 | 1067 | close: function () { |
5fb83680 | 1068 | $(this).dialog('destroy').remove(); |
0f5816a6 | 1069 | }, |
5fb83680 CW |
1070 | options: { |
1071 | no: ts('Cancel'), | |
1072 | yes: ts('Continue') | |
1073 | } | |
0f5816a6 | 1074 | }; |
a8a8ddac CW |
1075 | if (options && options.url) { |
1076 | settings.resizable = true; | |
1077 | settings.height = '50%'; | |
1078 | } | |
5fb83680 | 1079 | $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {}); |
a8a8ddac | 1080 | settings = CRM.utils.adjustDialogDefaults(settings); |
5fb83680 | 1081 | if (!settings.buttons && $.isPlainObject(settings.options)) { |
27f190b4 CW |
1082 | $.each(settings.options, function(op, label) { |
1083 | buttons.push({ | |
5fb83680 | 1084 | text: label, |
27f190b4 CW |
1085 | 'data-op': op, |
1086 | icons: {primary: op === 'no' ? 'ui-icon-close' : 'ui-icon-check'}, | |
5fb83680 | 1087 | click: function() { |
27f190b4 | 1088 | var event = $.Event('crmConfirm:' + op); |
5fb83680 CW |
1089 | $(this).trigger(event); |
1090 | if (!event.isDefaultPrevented()) { | |
1091 | dialog.dialog('close'); | |
1092 | } | |
1093 | } | |
1094 | }); | |
1095 | }); | |
27f190b4 CW |
1096 | // Order buttons so that "no" goes on the right-hand side |
1097 | settings.buttons = _.sortBy(buttons, 'data-op').reverse(); | |
2a06342c | 1098 | } |
3f4328da | 1099 | url = settings.url; |
c0b7c815 | 1100 | msg = url ? '' : settings.message; |
5fb83680 CW |
1101 | delete settings.options; |
1102 | delete settings.message; | |
3f4328da | 1103 | delete settings.url; |
c0b7c815 | 1104 | dialog = $('<div class="crm-confirm-dialog"></div>').html(msg || '').dialog(settings); |
5fb83680 CW |
1105 | if ($.isFunction(options)) { |
1106 | dialog.on('crmConfirm:yes', options); | |
7553cf23 | 1107 | } |
3f4328da CW |
1108 | if (url) { |
1109 | CRM.loadPage(url, {target: dialog}); | |
1110 | } | |
c0b7c815 CW |
1111 | else { |
1112 | dialog.trigger('crmLoad'); | |
3f4328da CW |
1113 | } |
1114 | return dialog; | |
e24b17b9 | 1115 | }; |
6a488035 | 1116 | |
ed7225e6 CW |
1117 | /** provides a local copy of ts for a domain */ |
1118 | CRM.ts = function(domain) { | |
1119 | return function(message, options) { | |
1120 | if (domain) { | |
1121 | options = $.extend(options || {}, {domain: domain}); | |
1122 | } | |
f97524d9 TO |
1123 | return ts(message, options); |
1124 | }; | |
f97524d9 TO |
1125 | }; |
1126 | ||
e3d90d6c TO |
1127 | CRM.addStrings = function(domain, strings) { |
1128 | var bucket = (domain == 'civicrm' ? 'strings' : 'strings::' + domain); | |
1129 | CRM[bucket] = CRM[bucket] || {}; | |
1130 | _.extend(CRM[bucket], strings); | |
1131 | }; | |
1132 | ||
6a488035 | 1133 | /** |
7442e8f6 | 1134 | * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference |
6a488035 | 1135 | */ |
0f5816a6 | 1136 | $.fn.crmError = function (text, title, options) { |
6a488035 TO |
1137 | title = title || ''; |
1138 | text = text || ''; | |
1139 | options = options || {}; | |
1140 | ||
1141 | var extra = { | |
1142 | expires: 0 | |
1143 | }; | |
1144 | if ($(this).length) { | |
0d75c29c | 1145 | if (title === '') { |
6a488035 TO |
1146 | var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]'); |
1147 | if (label.length) { | |
1148 | label.addClass('crm-error'); | |
1149 | var $label = label.clone(); | |
0d75c29c | 1150 | if (text === '' && $('.crm-marker', $label).length > 0) { |
6a488035 TO |
1151 | text = $('.crm-marker', $label).attr('title'); |
1152 | } | |
1153 | $('.crm-marker', $label).remove(); | |
1154 | title = $label.text(); | |
1155 | } | |
1156 | } | |
47737104 | 1157 | $(this).addClass('crm-error'); |
6a488035 TO |
1158 | } |
1159 | var msg = CRM.alert(text, title, 'error', $.extend(extra, options)); | |
1160 | if ($(this).length) { | |
1161 | var ele = $(this); | |
0f5816a6 KJ |
1162 | setTimeout(function () { |
1163 | ele.one('change', function () { | |
f54254d8 | 1164 | if (msg && msg.close) msg.close(); |
0f5816a6 KJ |
1165 | ele.removeClass('error'); |
1166 | label.removeClass('crm-error'); | |
1167 | }); | |
1168 | }, 1000); | |
6a488035 TO |
1169 | } |
1170 | return msg; | |
e24b17b9 | 1171 | }; |
6a488035 TO |
1172 | |
1173 | // Display system alerts through js notifications | |
1174 | function messagesFromMarkup() { | |
0f5816a6 | 1175 | $('div.messages:visible', this).not('.help').not('.no-popup').each(function () { |
e24b17b9 | 1176 | var text, title = ''; |
6a488035 TO |
1177 | $(this).removeClass('status messages'); |
1178 | var type = $(this).attr('class').split(' ')[0] || 'alert'; | |
1179 | type = type.replace('crm-', ''); | |
1180 | $('.icon', this).remove(); | |
6a488035 | 1181 | if ($('.msg-text', this).length > 0) { |
e24b17b9 | 1182 | text = $('.msg-text', this).html(); |
6a488035 TO |
1183 | title = $('.msg-title', this).html(); |
1184 | } | |
1185 | else { | |
e24b17b9 | 1186 | text = $(this).html(); |
6a488035 TO |
1187 | } |
1188 | var options = $(this).data('options') || {}; | |
1189 | $(this).remove(); | |
1190 | // Duplicates were already removed server-side | |
1191 | options.unique = false; | |
1192 | CRM.alert(text, title, type, options); | |
1193 | }); | |
1194 | // Handle qf form errors | |
1195 | $('form :input.error', this).one('blur', function() { | |
1196 | $('.ui-notify-message.error a.ui-notify-close').click(); | |
1197 | $(this).removeClass('error'); | |
1198 | $(this).next('span.crm-error').remove(); | |
1199 | $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]') | |
1200 | .removeClass('crm-error') | |
1201 | .find('.crm-error').removeClass('crm-error'); | |
1202 | }); | |
1203 | } | |
1204 | ||
e4762285 CW |
1205 | /** |
1206 | * Improve blockUI when used with jQuery dialog | |
1207 | */ | |
1adbbe2d CW |
1208 | var originalBlock = $.fn.block, |
1209 | originalUnblock = $.fn.unblock; | |
1210 | ||
1211 | $.fn.block = function(opts) { | |
1212 | if ($(this).is('.ui-dialog-content')) { | |
1213 | originalBlock.call($(this).parents('.ui-dialog'), opts); | |
1214 | return $(this); | |
1215 | } | |
1216 | return originalBlock.call(this, opts); | |
e4762285 | 1217 | }; |
1adbbe2d CW |
1218 | $.fn.unblock = function(opts) { |
1219 | if ($(this).is('.ui-dialog-content')) { | |
1220 | originalUnblock.call($(this).parents('.ui-dialog'), opts); | |
1221 | return $(this); | |
1222 | } | |
1223 | return originalUnblock.call(this, opts); | |
e4762285 | 1224 | }; |
1adbbe2d | 1225 | |
e4762285 | 1226 | // Preprocess all CRM ajax calls to display messages |
03a7ec8f CW |
1227 | $(document).ajaxSuccess(function(event, xhr, settings) { |
1228 | try { | |
1229 | if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) { | |
1230 | var response = $.parseJSON(xhr.responseText); | |
1231 | if (typeof(response.crmMessages) == 'object') { | |
1232 | $.each(response.crmMessages, function(n, msg) { | |
1233 | CRM.alert(msg.text, msg.title, msg.type, msg.options); | |
f54254d8 | 1234 | }); |
03a7ec8f | 1235 | } |
bba9b4f0 CW |
1236 | if (response.backtrace) { |
1237 | CRM.console('log', response.backtrace); | |
1238 | } | |
82983331 CW |
1239 | if (typeof response.deprecated === 'string') { |
1240 | CRM.console('warn', response.deprecated); | |
1241 | } | |
03a7ec8f CW |
1242 | } |
1243 | } | |
82983331 | 1244 | // Ignore errors thrown by parseJSON |
03a7ec8f CW |
1245 | catch (e) {} |
1246 | }); | |
1247 | ||
0f5816a6 | 1248 | $(function () { |
fdeb4de2 | 1249 | $.blockUI.defaults.message = null; |
1adbbe2d | 1250 | $.blockUI.defaults.ignoreIfBlocked = true; |
fdeb4de2 | 1251 | |
65b86482 CW |
1252 | if ($('#crm-container').hasClass('crm-public')) { |
1253 | $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container crm-public'; | |
1254 | } | |
1255 | ||
205bb8ae | 1256 | // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content. |
8547369d | 1257 | $('.crm-container').trigger('crmLoad'); |
205bb8ae | 1258 | |
ef3309b6 | 1259 | if ($('#crm-notification-container').length) { |
6a488035 TO |
1260 | // Initialize notifications |
1261 | $('#crm-notification-container').notify(); | |
1262 | messagesFromMarkup.call($('#crm-container')); | |
6a488035 | 1263 | } |
ebb9197b | 1264 | |
ad9d3592 CW |
1265 | // Hide CiviCRM menubar when editor is fullscreen |
1266 | if (window.CKEDITOR) { | |
1267 | CKEDITOR.on('instanceCreated', function (e) { | |
1268 | e.editor.on('maximize', function (e) { | |
1269 | $('#civicrm-menu').toggle(e.data === 2); | |
1270 | }); | |
1271 | }); | |
1272 | } | |
1273 | ||
475e9f44 | 1274 | $('body') |
5fb83680 CW |
1275 | // bind the event for image popup |
1276 | .on('click', 'a.crm-image-popup', function(e) { | |
1277 | CRM.confirm({ | |
1278 | title: ts('Preview'), | |
a243158e | 1279 | resizable: true, |
e4762285 | 1280 | message: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>', |
5fb83680 CW |
1281 | options: null |
1282 | }); | |
1283 | e.preventDefault(); | |
475e9f44 | 1284 | }) |
ebb9197b | 1285 | |
475e9f44 CW |
1286 | .on('click', function (event) { |
1287 | $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide(); | |
1288 | if ($(event.target).is('.btn-slide')) { | |
1289 | $(event.target).addClass('btn-slide-active').find('.panel').show(); | |
1290 | } | |
1291 | }) | |
d664f648 | 1292 | |
4a143c04 CW |
1293 | // Handle clear button for form elements |
1294 | .on('click', 'a.crm-clear-link', function() { | |
9bce560a CW |
1295 | $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).trigger('change', ['crmClear']); |
1296 | $(this).siblings('input:text').val('').trigger('change', ['crmClear']); | |
4a143c04 CW |
1297 | return false; |
1298 | }) | |
1299 | .on('change', 'input.crm-form-radio:checked', function() { | |
1300 | $(this).siblings('.crm-clear-link').css({visibility: ''}); | |
843bfb07 | 1301 | }) |
6a488035 | 1302 | |
843bfb07 | 1303 | // Allow normal clicking of links within accordions |
cf021bc5 | 1304 | .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) { |
843bfb07 | 1305 | e.stopPropagation(); |
cf021bc5 | 1306 | }) |
843bfb07 CW |
1307 | // Handle accordions |
1308 | .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) { | |
6a488035 | 1309 | if ($(this).parent().hasClass('collapsed')) { |
843bfb07 | 1310 | $(this).next().css('display', 'none').slideDown(200); |
6a488035 TO |
1311 | } |
1312 | else { | |
843bfb07 | 1313 | $(this).next().css('display', 'block').slideUp(200); |
6a488035 TO |
1314 | } |
1315 | $(this).parent().toggleClass('collapsed'); | |
843bfb07 | 1316 | e.preventDefault(); |
6a488035 | 1317 | }); |
843bfb07 CW |
1318 | |
1319 | $().crmtooltip(); | |
1320 | }); | |
d5768733 | 1321 | |
843bfb07 CW |
1322 | /** |
1323 | * Collapse or expand an accordion | |
1324 | * @param speed | |
1325 | */ | |
0f5816a6 KJ |
1326 | $.fn.crmAccordionToggle = function (speed) { |
1327 | $(this).each(function () { | |
6a488035 TO |
1328 | if ($(this).hasClass('collapsed')) { |
1329 | $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed); | |
1330 | } | |
1331 | else { | |
1332 | $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed); | |
1333 | } | |
1334 | $(this).toggleClass('collapsed'); | |
1335 | }); | |
1336 | }; | |
5ec182d9 CW |
1337 | |
1338 | /** | |
1339 | * Clientside currency formatting | |
e4762285 | 1340 | * @param number value |
7f92cfa9 | 1341 | * @param [optional] boolean onlyNumber - if true, we return formated amount without currency sign |
e4762285 | 1342 | * @param [optional] string format - currency representation of the number 1234.56 |
5ec182d9 CW |
1343 | * @return string |
1344 | */ | |
1345 | var currencyTemplate; | |
7f92cfa9 | 1346 | CRM.formatMoney = function(value, onlyNumber, format) { |
5ec182d9 CW |
1347 | var decimal, separator, sign, i, j, result; |
1348 | if (value === 'init' && format) { | |
1349 | currencyTemplate = format; | |
1350 | return; | |
1351 | } | |
1352 | format = format || currencyTemplate; | |
1353 | result = /1(.?)234(.?)56/.exec(format); | |
1354 | if (result === null) { | |
1355 | return 'Invalid format passed to CRM.formatMoney'; | |
1356 | } | |
1357 | separator = result[1]; | |
1358 | decimal = result[2]; | |
1359 | sign = (value < 0) ? '-' : ''; | |
1360 | //extracting the absolute value of the integer part of the number and converting to string | |
1361 | i = parseInt(value = Math.abs(value).toFixed(2)) + ''; | |
5ec182d9 CW |
1362 | j = ((j = i.length) > 3) ? j % 3 : 0; |
1363 | 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) : ''); | |
567e9eea | 1364 | if ( onlyNumber ) { |
1365 | return result; | |
1366 | } | |
5ec182d9 CW |
1367 | return format.replace(/1.*234.*56/, result); |
1368 | }; | |
bba9b4f0 CW |
1369 | |
1370 | CRM.console = function(method, title, msg) { | |
1371 | if (window.console) { | |
1372 | method = $.isFunction(console[method]) ? method : 'log'; | |
1373 | if (msg === undefined) { | |
1374 | return console[method](title); | |
1375 | } else { | |
1376 | return console[method](title, msg); | |
1377 | } | |
1378 | } | |
e4762285 | 1379 | }; |
90efc417 TO |
1380 | |
1381 | // Determine if a user has a given permission. | |
1382 | // @see CRM_Core_Resources::addPermissions | |
1383 | CRM.checkPerm = function(perm) { | |
1384 | return CRM.permissions[perm]; | |
1385 | }; | |
2cfa1092 TO |
1386 | |
1387 | // Round while preserving sigfigs | |
1388 | CRM.sigfig = function(n, digits) { | |
1389 | var len = ("" + n).length; | |
1390 | var scale = Math.pow(10.0, len-digits); | |
1391 | return Math.round(n / scale) * scale; | |
1392 | }; | |
4b513f23 | 1393 | })(jQuery, _); |