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