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