Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2015-02-09-11-44-07
[civicrm-core.git] / js / Common.js
1 // https://civicrm.org/licensing
2 var CRM = CRM || {};
3 var cj = CRM.$ = jQuery;
4 CRM._ = _;
5
6 /**
7 * Short-named function for string translation, defined in global scope so it's available everywhere.
8 *
9 * @param text string for translating
10 * @param params object key:value of additional parameters
11 *
12 * @return string
13 */
14 function ts(text, params) {
15 "use strict";
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 }
23 if (typeof(params) === 'object') {
24 for (var i in params) {
25 if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') {
26 // sprintf emulation: escape % characters in the replacements to avoid conflicts
27 text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-'));
28 }
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 *
41 * @deprecated
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 ...)
45 */
46 function on_load_init_blocks(showBlocks, hideBlocks, elementType) {
47 if (elementType == null) {
48 elementType = 'block';
49 }
50
51 var myElement, i;
52
53 /* This loop is used to display the blocks whose IDs are present within the showBlocks array */
54 for (i = 0; i < showBlocks.length; i++) {
55 myElement = document.getElementById(showBlocks[i]);
56 /* getElementById returns null if element id doesn't exist in the document */
57 if (myElement != null) {
58 myElement.style.display = elementType;
59 }
60 else {
61 alert('showBlocks array item not in .tpl = ' + showBlocks[i]);
62 }
63 }
64
65 /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
66 for (i = 0; i < hideBlocks.length; i++) {
67 myElement = document.getElementById(hideBlocks[i]);
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]);
74 }
75 }
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 *
82 * @deprecated
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
89 */
90 function showHideByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, invert) {
91 var target, j;
92
93 if (field_type == 'select') {
94 var trigger = trigger_value.split("|");
95 var selectedOptionValue = cj('#' + trigger_field_id).val();
96
97 target = target_element_id.split("|");
98 for (j = 0; j < target.length; j++) {
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 }
113 }
114 }
115 }
116
117 }
118 else {
119 if (field_type == 'radio') {
120 target = target_element_id.split("|");
121 for (j = 0; j < target.length; j++) {
122 if (cj('[name="' + trigger_field_id + '"]:first').is(':checked')) {
123 if (invert) {
124 cj('#' + target[j]).hide();
125 }
126 else {
127 cj('#' + target[j]).show();
128 }
129 }
130 else {
131 if (invert) {
132 cj('#' + target[j]).show();
133 }
134 else {
135 cj('#' + target[j]).hide();
136 }
137 }
138 }
139 }
140 }
141 }
142
143 /**
144 * Function to change button text and disable one it is clicked
145 * @deprecated
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
149 * @return bool
150 */
151 var submitcount = 0;
152 /* Changes button label on submit, and disables button after submit for newer browsers.
153 Puts up alert for older browsers. */
154 function submitOnce(obj, formId, procText) {
155 // if named button clicked, change text
156 if (obj.value != null) {
157 obj.value = procText + " ...";
158 }
159 cj(obj).closest('form').attr('data-warn-changes', 'false');
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;
173 }
174 }
175 }
176
177 /**
178 * Function to show / hide the row in optionFields
179 * @deprecated
180 * @param index string, element whose innerHTML is to hide else will show the hidden row.
181 */
182 function 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();
187 }
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;
196 }
197
198 CRM.utils = CRM.utils || {};
199 CRM.strings = CRM.strings || {};
200
201 (function ($, _, undefined) {
202 "use strict";
203
204 // Theme classes for unattached elements
205 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container';
206
207 // https://github.com/ivaynberg/select2/pull/2090
208 $.fn.select2.defaults.width = 'resolve';
209
210 // Workaround for https://github.com/ivaynberg/select2/issues/1246
211 $.ui.dialog.prototype._allowInteraction = function(e) {
212 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop, .cke_dialog').length;
213 };
214
215 /**
216 * Populate a select list, overwriting the existing options except for the placeholder.
217 * @param select jquery selector - 1 or more select elements
218 * @param options array in format returned by api.getoptions
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
221 */
222 CRM.utils.setOptions = function(select, options, placeholder, value) {
223 $(select).each(function() {
224 var
225 $elect = $(this),
226 val = value || $elect.val() || [],
227 opts = placeholder || placeholder === '' ? '' : '[value!=""]';
228 $elect.find('option' + opts).remove();
229 var newOptions = CRM.utils.renderOptions(options, val);
230 if (typeof placeholder === 'string') {
231 if ($elect.is('[multiple]')) {
232 select.attr('placeholder', placeholder);
233 } else {
234 newOptions = '<option value="">' + placeholder + '</option>' + newOptions;
235 }
236 }
237 $elect.append(newOptions);
238 if (!value) {
239 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
240 }
241 });
242 };
243
244 /**
245 * Render an option list
246 * @param options {array}
247 * @param val {string} default value
248 * @param escapeHtml {bool}
249 * @return string
250 */
251 CRM.utils.renderOptions = function(options, val, escapeHtml) {
252 var rendered = '',
253 esc = escapeHtml === false ? _.identity : _.escape;
254 if (!$.isArray(val)) {
255 val = [val];
256 }
257 _.each(options, function(option) {
258 if (option.children) {
259 rendered += '<optgroup label="' + esc(option.value) + '">' +
260 CRM.utils.renderOptions(option.children, val) +
261 '</optgroup>';
262 } else {
263 var selected = ($.inArray('' + option.key, val) > -1) ? 'selected="selected"' : '';
264 rendered += '<option value="' + esc(option.key) + '"' + selected + '>' + esc(option.value) + '</option>';
265 }
266 });
267 return rendered;
268 };
269
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
290 /**
291 * Compare Form Input values against cached initial value.
292 *
293 * @return {Boolean} true if changes have been made.
294 */
295 CRM.utils.initialValueChanged = function(el) {
296 var isDirty = false;
297 $(':input:visible, .select2-container:visible+:input.select2-offscreen', el).not('[type=submit], [type=button], .crm-action-menu').each(function () {
298 var initialValue = $(this).data('crm-initial-value');
299 // skip change of value for submit buttons
300 if (initialValue !== undefined && !_.isEqual(initialValue, $(this).val())) {
301 isDirty = true;
302 }
303 });
304 return isDirty;
305 };
306
307 /**
308 * Wrapper for select2 initialization function; supplies defaults
309 * @param options object
310 */
311 $.fn.crmSelect2 = function(options) {
312 return $(this).each(function () {
313 var
314 $el = $(this),
315 settings = {allowClear: !$el.hasClass('required')};
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 });
321
322 // quickform does not support disabled option, so yet another hack to
323 // add disabled property for option values
324 $('option[value^=crm_disabled_opt]', this).attr('disabled', 'disabled');
325
326 // Defaults for single-selects
327 if ($el.is('select:not([multiple])')) {
328 settings.minimumResultsForSearch = 10;
329 if ($('option:first', this).val() === '') {
330 settings.placeholderOption = 'first';
331 }
332 }
333 $.extend(settings, $el.data('select-params') || {}, options || {});
334 if (settings.ajax) {
335 $el.addClass('crm-ajax-select');
336 }
337 $el.select2(settings);
338 });
339 };
340
341 /**
342 * @see CRM_Core_Form::addEntityRef for docs
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
350 $el = $(this).off('.crmEntity'),
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));
356 $el.data('create-links', options.create || $el.data('create-links'));
357 $el.addClass('crm-form-entityref crm-' + entity.toLowerCase() + '-ref');
358 var settings = {
359 // Use select2 ajax helper instead of CRM.api3 because it provides more value
360 ajax: {
361 url: CRM.url('civicrm/ajax/rest'),
362 data: function (input, page_num) {
363 var params = getEntityRefApiParams($el);
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 },
376 minimumInputLength: 1,
377 formatResult: CRM.utils.formatSelect2Result,
378 formatSelection: function(row) {
379 return row.label;
380 },
381 escapeMarkup: function (m) {return m;},
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 {
394 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
395 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
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');
399 });
400 }
401 }
402 };
403 // Create new items inline - works for tags
404 if ($el.data('create-links') && entity.toLowerCase() === 'tag') {
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 };
410 selectParams.tokenSeparators = [','];
411 selectParams.createSearchChoicePosition = 'bottom';
412 $el.on('select2-selecting.crmEntity', function(e) {
413 if (e.val === "0") {
414 // Create a new term
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
419 val = $el.select2('val'),
420 data = $el.select2('data'),
421 item = {id: created.id, label: e.object.term};
422 if (val === "0") {
423 $el.select2('data', item, true);
424 }
425 else if ($.isArray(val) && $.inArray("0", val) > -1) {
426 _.remove(data, {id: "0"});
427 data.push(item);
428 $el.select2('data', data, true);
429 }
430 });
431 }
432 });
433 }
434 else {
435 selectParams.formatInputTooShort = function() {
436 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
437 txt += renderEntityRefFilters($el) + renderEntityRefCreateLinks($el);
438 return txt;
439 };
440 selectParams.formatNoMatches = function() {
441 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
442 txt += renderEntityRefFilters($el) + renderEntityRefCreateLinks($el);
443 return txt;
444 };
445 $el.on('select2-open.crmEntity', function() {
446 var $el = $(this);
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 }
464 }
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');
477 }
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);
485 });
486 });
487 }
488 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams));
489 });
490 };
491
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
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];
508 } else {
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;
511 }
512 }
513 return combined;
514 }
515
516 CRM.utils.formatSelect2Result = function (row) {
517 var markup = '<div class="crm-select2-row">';
518 if (row.image !== undefined) {
519 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
520 }
521 else if (row.icon_class) {
522 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
523 }
524 markup += '<div><div class="crm-select2-row-label '+(row.label_class || '')+'">' + row.label + '</div>';
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>';
530 return markup;
531 };
532
533 function renderEntityRefCreateLinks($el) {
534 var
535 createLinks = $el.data('create-links'),
536 params = getEntityRefApiParams($el).params,
537 markup = '<div class="crm-entityref-links">';
538 if (!createLinks || $el.data('api-entity').toLowerCase() !== 'contact') {
539 return '';
540 }
541 if (createLinks === true) {
542 createLinks = params.contact_type ? _.where(CRM.config.entityRef.contactCreate, {type: params.contact_type}) : CRM.config.entityRef.contactCreate;
543 }
544 _.each(createLinks, function(link) {
545 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
546 if (link.type) {
547 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
548 }
549 markup += link.label + '</a>';
550 });
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) {
568 return option.key.indexOf(params.contact_type + '__') === 0;
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>';
595 return markup;
596 }
597
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);
614 CRM.api3(filterSpec.entity || $el.data('api-entity'), 'getoptions', {field: filter.key, context: 'search', sequential: 1})
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
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
640 /**
641 * Wrapper for jQuery validate initialization function; supplies defaults
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 });
655 };
656
657 // Initialize widgets
658 $(document)
659 .on('crmLoad', function(e) {
660 $('table.row-highlight', e.target)
661 .off('.rowHighlight')
662 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) {
663 var filter, $table = $(this).closest('table');
664 if ($(this).hasClass('select-rows')) {
665 filter = $(this).prop('checked') ? ':not(:checked)' : ':checked';
666 $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
667 }
668 else {
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 }
673 }
674 })
675 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
676 if ($("input:radio[name=radio_ts]").size() == 1) {
677 $("input:radio[name=radio_ts]").prop("checked", true);
678 }
679 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
680 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
681 $('select.crm-chain-select-control', e.target).off('.chainSelect').on('change.chainSelect', chainSelect);
682 // Cache Form Input initial values
683 $('form[data-warn-changes] :input', e.target).each(function() {
684 $(this).data('crm-initial-value', $(this).val());
685 });
686 })
687 .on('dialogopen', function(e) {
688 var $el = $(e.target);
689 // Modal dialogs should disable scrollbars
690 if ($el.dialog('option', 'modal')) {
691 $el.addClass('modal-dialog');
692 $('body').css({overflow: 'hidden'});
693 }
694 // Add resize button
695 if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) {
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}));
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 {
702 var menuHeight = $('#civicrm-menu').outerHeight();
703 $el.data('origSize', {
704 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
705 width: $el.dialog('option', 'width'),
706 height: $el.dialog('option', 'height')
707 });
708 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: {my: "top", at: "top+"+menuHeight, of: window}});
709 }
710 e.preventDefault();
711 });
712 }
713 })
714 .on('dialogclose', function(e) {
715 // Restore scrollbars when closing modal
716 if ($('.ui-dialog .modal-dialog:visible').not(e.target).length < 1) {
717 $('body').css({overflow: ''});
718 }
719 })
720 .on('submit', function(e) {
721 // CRM-14353 - disable changes warn when submitting a form
722 $('[data-warn-changes]').attr('data-warn-changes', 'false');
723 })
724 ;
725
726 // CRM-14353 - Warn of unsaved changes for forms which have opted in
727 window.onbeforeunload = function() {
728 if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
729 return ts('You have unsaved changes.');
730 }
731 };
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');
740 }
741 else {
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');
747 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
748 if (index > 1) {
749 if (index % 2 == 0) {
750 $(this).parent().after('<tr class="narrowadded"></tr>');
751 }
752 var item = $(this);
753 $(this).parent().next().append(item);
754 }
755 });
756 }
757 else {
758 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
759 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
760 var nitem = $(this);
761 var parent = $(this).parent();
762 $(this).parent().prev().append(nitem);
763 if (parent.children().size() == 0) {
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();
770
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');
776 }
777 else {
778 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
779 }
780 }
781 else {
782 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
783 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
784 }
785 }
786
787 advmultiselectResize();
788 $(window).resize(advmultiselectResize);
789
790 $.fn.crmtooltip = function () {
791 $(document)
792 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
793 $(this).addClass('crm-processed');
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) {
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 })
806 .on('mouseout', 'a.crm-summary-link', function () {
807 $(this).removeClass('crm-processed');
808 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
809 })
810 .on('click', 'a.crm-summary-link', false);
811 };
812
813 var helpDisplay, helpPrevious;
814 CRM.help = function (title, params, url) {
815 if (helpDisplay && helpDisplay.close) {
816 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
817 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
818 helpDisplay.close();
819 return;
820 }
821 helpDisplay.close();
822 }
823 helpPrevious = JSON.stringify(params);
824 params.class_name = 'CRM_Core_Page_Inline_Help';
825 params.type = 'page';
826 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
827 $.ajax(url || CRM.url('civicrm/ajax/inline'),
828 {
829 data: params,
830 dataType: 'html',
831 success: function (data) {
832 $('#crm-notification-container .crm-help .notify-content:last').html(data);
833 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
834 },
835 error: function () {
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 };
842 /**
843 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
844 */
845 CRM.status = function(options, deferred) {
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.
847 if (typeof options === 'string') {
848 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
849 }
850 var opts = $.extend({
851 start: ts('Saving...'),
852 success: ts('Saved'),
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');
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() {
866 $msg.fadeOut('slow', function() {
867 $msg.remove();
868 });
869 }, 2000);
870 } else {
871 $msg.remove();
872 }
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 });
883 };
884
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
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
906 /**
907 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
908 */
909 CRM.alert = function (text, title, type, options) {
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);
925 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
926 if (options.unique && options.unique !== '0') {
927 $('#crm-notification-container .ui-notify-message').each(function () {
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 }
942 };
943
944 /**
945 * Close whichever alert contains the given node
946 *
947 * @param node
948 */
949 CRM.closeAlertByChild = function (node) {
950 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
951 };
952
953 /**
954 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
955 */
956 CRM.confirm = function (options) {
957 var dialog, url, msg, buttons = [], settings = {
958 title: ts('Confirm'),
959 message: ts('Are you sure you want to continue?'),
960 url: null,
961 width: 'auto',
962 modal: true,
963 resizable: false,
964 dialogClass: 'crm-container crm-confirm',
965 close: function () {
966 $(this).dialog('destroy').remove();
967 },
968 options: {
969 no: ts('Cancel'),
970 yes: ts('Continue')
971 }
972 };
973 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
974 if (!settings.buttons && $.isPlainObject(settings.options)) {
975 $.each(settings.options, function(op, label) {
976 buttons.push({
977 text: label,
978 'data-op': op,
979 icons: {primary: op === 'no' ? 'ui-icon-close' : 'ui-icon-check'},
980 click: function() {
981 var event = $.Event('crmConfirm:' + op);
982 $(this).trigger(event);
983 if (!event.isDefaultPrevented()) {
984 dialog.dialog('close');
985 }
986 }
987 });
988 });
989 // Order buttons so that "no" goes on the right-hand side
990 settings.buttons = _.sortBy(buttons, 'data-op').reverse();
991 }
992 url = settings.url;
993 msg = url ? '' : settings.message;
994 delete settings.options;
995 delete settings.message;
996 delete settings.url;
997 dialog = $('<div class="crm-confirm-dialog"></div>').html(msg || '').dialog(settings);
998 if ($.isFunction(options)) {
999 dialog.on('crmConfirm:yes', options);
1000 }
1001 if (url) {
1002 CRM.loadPage(url, {target: dialog});
1003 }
1004 else {
1005 dialog.trigger('crmLoad');
1006 }
1007 return dialog;
1008 };
1009
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 }
1016 return ts(message, options);
1017 };
1018 };
1019
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
1026 /**
1027 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1028 */
1029 $.fn.crmError = function (text, title, options) {
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 }
1050 $(this).addClass('crm-error');
1051 }
1052 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
1053 if ($(this).length) {
1054 var ele = $(this);
1055 setTimeout(function () {
1056 ele.one('change', function () {
1057 if (msg && msg.close) msg.close();
1058 ele.removeClass('error');
1059 label.removeClass('crm-error');
1060 });
1061 }, 1000);
1062 }
1063 return msg;
1064 };
1065
1066 // Display system alerts through js notifications
1067 function messagesFromMarkup() {
1068 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
1069 var text, title = '';
1070 $(this).removeClass('status messages');
1071 var type = $(this).attr('class').split(' ')[0] || 'alert';
1072 type = type.replace('crm-', '');
1073 $('.icon', this).remove();
1074 if ($('.msg-text', this).length > 0) {
1075 text = $('.msg-text', this).html();
1076 title = $('.msg-title', this).html();
1077 }
1078 else {
1079 text = $(this).html();
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
1098 /**
1099 * Improve blockUI when used with jQuery dialog
1100 */
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);
1110 };
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);
1117 };
1118
1119 // Preprocess all CRM ajax calls to display messages
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);
1127 });
1128 }
1129 if (response.backtrace) {
1130 CRM.console('log', response.backtrace);
1131 }
1132 if (typeof response.deprecated === 'string') {
1133 CRM.console('warn', response.deprecated);
1134 }
1135 }
1136 }
1137 // Ignore errors thrown by parseJSON
1138 catch (e) {}
1139 });
1140
1141 $(function () {
1142 $.blockUI.defaults.message = null;
1143 $.blockUI.defaults.ignoreIfBlocked = true;
1144
1145 if ($('#crm-container').hasClass('crm-public')) {
1146 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container crm-public';
1147 }
1148
1149 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1150 $('.crm-container').trigger('crmLoad');
1151
1152 if ($('#crm-notification-container').length) {
1153 // Initialize notifications
1154 $('#crm-notification-container').notify();
1155 messagesFromMarkup.call($('#crm-container'));
1156 }
1157
1158 $('body')
1159 // bind the event for image popup
1160 .on('click', 'a.crm-image-popup', function(e) {
1161 CRM.confirm({
1162 title: ts('Preview'),
1163 resizable: true,
1164 message: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
1165 options: null
1166 });
1167 e.preventDefault();
1168 })
1169
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 })
1176
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();
1180 $(this).siblings('input:text').val('').change();
1181 return false;
1182 })
1183 .on('change', 'input.crm-form-radio:checked', function() {
1184 $(this).siblings('.crm-clear-link').css({visibility: ''});
1185 })
1186
1187 // Allow normal clicking of links within accordions
1188 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
1189 e.stopPropagation();
1190 })
1191 // Handle accordions
1192 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
1193 if ($(this).parent().hasClass('collapsed')) {
1194 $(this).next().css('display', 'none').slideDown(200);
1195 }
1196 else {
1197 $(this).next().css('display', 'block').slideUp(200);
1198 }
1199 $(this).parent().toggleClass('collapsed');
1200 e.preventDefault();
1201 });
1202
1203 $().crmtooltip();
1204 });
1205 /**
1206 * @deprecated
1207 */
1208 $.fn.crmAccordions = function () {
1209 CRM.console('warn', 'Warning: $.crmAccordions was called. This function is deprecated and should not be used.');
1210 };
1211 /**
1212 * Collapse or expand an accordion
1213 * @param speed
1214 */
1215 $.fn.crmAccordionToggle = function (speed) {
1216 $(this).each(function () {
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 };
1226
1227 /**
1228 * Clientside currency formatting
1229 * @param number value
1230 * @param [optional] string format - currency representation of the number 1234.56
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)) + '';
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 };
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 }
1264 };
1265 })(jQuery, _);