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