').append(opciones._header.obj.clone()).html().replace(/header/g, 'footer');\n $('#' + selfId).after(footerHTML);\n }\n\n populateHeaderFooterOpts(true);\n /**\r\n * MULTISORT DIALOG\r\n */\n\n opciones._idMultiSortDialog = selfId + '-mord-dialog';\n /**\r\n * ROWNUM\r\n */\n\n self._rownumInit.apply(self);\n /**\r\n * SORT - MULTISORT\r\n */\n\n\n if (!opciones.isMultiSort) {\n // Sidx select to rup-combo\n self._sidxComboInit.apply(self); // Inicialización sord\n\n\n self._sordButtonInit(self);\n } else {\n // Inicialización del multisort\n self._multisortInit.apply(self);\n } // Asociación de eventos\n\n\n $('#' + self.element[0].id).on('load', opciones.load);\n $('#' + self.element[0].id).on('modElement', function (e, item, json) {\n opciones.modElement(e, item, json);\n self.element.append(item);\n });\n /**\r\n * PAGENAV\r\n */\n\n self._pagenavInit.apply(self);\n /**\r\n * SELECT/MULTISELECT\r\n */\n\n\n if (opciones.selectable) {\n opciones._header.selectables.show();\n\n if (opciones.createFooter) {\n opciones._footer.selectables.show();\n }\n\n self._selectablesInit.apply(self);\n } else {\n opciones._header.selectables.hide();\n\n if (opciones.createFooter) {\n opciones._footer.selectables.hide();\n }\n }\n /**\r\n * SCROLL LIST\r\n */\n\n\n if (opciones.isScrollList) {\n self._scrollListInit.apply(self);\n }\n /**\r\n * PRINT\r\n */\n\n\n if (opciones.print) {\n self._print.apply(self);\n }\n /**\r\n * MULTIFILTER\r\n */\n\n\n if (opciones.isMultiFilter) {\n self._multiFilter.apply(self);\n }\n\n self.isFiltering.resolve();\n /** \r\n * INIT COMPLETE EVENT\r\n */\n\n if (opciones.isMultisort) {\n $('#' + self.element[0].id).on('rup_list-mord-inited', function () {\n $('#' + self.element[0].id).trigger('initComplete');\n });\n } else {\n $('#' + self.element[0].id).trigger('initComplete');\n } //Se audita el componente\n\n\n $.rup.auditComponent('rup_list', 'init');\n })[\"catch\"](function (error) {\n console.error('Error al inicializar el componente:\\n', error);\n });\n },\n\n /**\r\n * Método interno que inicializa el listado con seleccionables\r\n * @name _selectablesInit\r\n * @private\r\n * @function\r\n */\n _selectablesInit: function _selectablesInit() {\n var self = this;\n var opciones = self.options;\n $('#' + self.element[0].id + '-content').find(opciones.selectable.selector).attr('rup-list-selector', 'enabled');\n opciones.multiselection = {\n selectedIds: null,\n selectedAll: false,\n selectedRowsPerPage: null\n };\n\n if (opciones.selectable.multi) {\n self._generateSelectablesBtnGroup();\n }\n\n var isControl = false,\n isShift = false,\n modeAll;\n\n if (opciones.isSuperSelect) {\n $(document).on('keydown', function (e) {\n if (e.keyCode == '17') {\n isControl = true;\n } else if (e.keyCode == '16') {\n isShift = true;\n }\n });\n $(document).on('keyup', function (e) {\n if (e.keyCode == '17') {\n isControl = false;\n } else if (e.keyCode == '16') {\n isShift = false;\n }\n });\n }\n\n opciones._content.find(opciones.selectable.selector).on('click keyup', function (e) {\n var $clickedEl = $(e.currentTarget);\n\n if (e.type === 'click' || e.type === 'keyup' && (e.keyCode == '13' || e.keyCode == '32')) {\n var clickedPK = $clickedEl.data('pk');\n\n if (opciones.multiselection.selectedIds == null) {\n opciones.multiselection.selectedIds = [];\n }\n\n if (opciones.multiselection.selectedRowsPerPage == null) {\n opciones.multiselection.selectedRowsPerPage = [];\n }\n\n if (opciones.multiselection.selectedAll) {\n modeAll = true;\n } else {\n modeAll = false;\n }\n\n if (opciones.isSuperSelect) {\n if (isShift && isControl) {\n if (opciones.multiselection.selectedIds[opciones.multiselection.selectedIds.length - 1]) {\n var posicionClicked = getPosicion(opciones.multiselection.selectedIds[opciones.multiselection.selectedIds.length - 1], clickedPK);\n var newRangeLastClickedPK = opciones.multiselection.selectedIds[opciones.multiselection.selectedIds.length - 1];\n\n if (posicionClicked[0] > posicionClicked[1]) {\n deselect($clickedEl, newRangeLastClickedPK, modeAll);\n selectRange(newRangeLastClickedPK, clickedPK, modeAll);\n } else {\n selectRange(newRangeLastClickedPK, clickedPK, modeAll);\n }\n } else {\n select($clickedEl, modeAll);\n }\n } else if (!isShift && isControl) {\n if (opciones.multiselection.selectedIds.includes(clickedPK)) {\n deselect($clickedEl, modeAll);\n } else {\n select($clickedEl, modeAll);\n }\n } else if (isShift && !isControl) {\n if (opciones.multiselection.selectedIds[opciones.multiselection.selectedIds.length - 1]) {\n var _newRangeLastClickedPK = opciones.multiselection.selectedIds[0];\n deselectRest(modeAll);\n selectRange(_newRangeLastClickedPK, clickedPK, modeAll);\n } else {\n select($clickedEl, modeAll);\n }\n } else if (!isShift && !isControl) {\n if (opciones.multiselection.selectedIds.includes(clickedPK)) {\n deselect($clickedEl, modeAll);\n } else {\n deselectRest(modeAll);\n select($clickedEl, modeAll);\n }\n }\n } else {\n if (opciones.multiselection.selectedIds.includes(clickedPK)) {\n deselect($clickedEl, modeAll);\n } else {\n select($clickedEl, modeAll);\n }\n }\n }\n });\n\n var select = function select($clickedEl, modeAll) {\n var clickedPK = $clickedEl.data('pk');\n\n if (!opciones.selectable.multi) {\n opciones.multiselection.selectedAll = false;\n opciones.multiselection.selectedIds = [];\n opciones.multiselection.selectedRowsPerPage = [];\n self.element.find('.rup_list-item-selected').each(function (i, e) {\n $(e).removeClass('rup_list-item-selected');\n $(e).attr('aria-selected', 'false');\n });\n }\n\n opciones.multiselection.selectedRowsPerPage.push({\n id: clickedPK,\n line: function () {\n var cont = 0;\n var _final = 0;\n self.element.children().toArray().forEach(function (element) {\n if (element.id == $clickedEl.attr('id')) {\n _final = cont;\n }\n\n cont++;\n });\n return _final;\n }(),\n page: function () {\n if (opciones.isScrollList) {\n return 1;\n } else {\n return opciones.page;\n }\n }()\n });\n opciones.multiselection.selectedIds.push(clickedPK);\n\n if (!modeAll) {\n $clickedEl.addClass('rup_list-item-selected');\n $clickedEl.attr('aria-selected', 'true');\n } else {\n $clickedEl.removeClass('rup_list-item-selected');\n $clickedEl.removeClass('aria-selected', 'false');\n }\n };\n\n var deselect = function deselect($clickedEl, modeAll) {\n var clickedPK = $clickedEl.data('pk');\n var index = opciones.multiselection.selectedIds.indexOf(clickedPK);\n opciones.multiselection.selectedIds.splice(index, 1);\n opciones.multiselection.selectedRowsPerPage = opciones.multiselection.selectedRowsPerPage.filter(function (elem) {\n return elem.id != clickedPK;\n });\n\n if (!modeAll) {\n $clickedEl.removeClass('rup_list-item-selected');\n $clickedEl.attr('aria-selected', 'false');\n } else {\n $clickedEl.addClass('rup_list-item-selected');\n $clickedEl.attr('aria-selected', 'true');\n }\n };\n\n var deselectRest = function deselectRest(modeAll) {\n var deselectRestItem = function deselectRestItem(index) {\n var item2SelectPk = String(opciones.content[index][opciones.key]);\n var deselectRestItem = self.element.find('.rup_list-item').filter(function (i, e) {\n return $(e).data('pk') == item2SelectPk;\n });\n\n if (!modeAll) {\n deselectRestItem.removeClass('rup_list-item-selected');\n deselectRestItem.attr('aria-selected', 'false');\n } else {\n deselectRestItem.addClass('rup_list-item-selected');\n deselectRestItem.attr('aria-selected', 'true');\n }\n };\n\n if (!modeAll) {\n opciones.multiselection.selectedAll = false;\n } else {\n opciones.multiselection.selectedAll = true;\n }\n\n opciones.multiselection.selectedIds = [];\n opciones.multiselection.selectedRowsPerPage = [];\n\n for (var i = 0; i < opciones.content.length; i++) {\n deselectRestItem(i);\n }\n };\n\n var selectRange = function selectRange(lastClickedPK, clickedPK, modeAll) {\n var selectRangeItem = function selectRangeItem(index) {\n var item2SelectPk = String(opciones.content[index][opciones.key]);\n\n if (!opciones.multiselection.selectedIds.includes(item2SelectPk)) {\n var $item2Select = $('.rup_list-item').filter(function (i, e) {\n return $(e).data('pk') == item2SelectPk;\n });\n select($item2Select, modeAll);\n }\n };\n\n var posicionClicked = getPosicion(lastClickedPK, clickedPK);\n\n if (posicionClicked[0] > posicionClicked[1]) {\n for (var i = posicionClicked[1]; i <= posicionClicked[0]; i++) {\n selectRangeItem(i);\n }\n } else {\n for (var _i = posicionClicked[1]; _i >= posicionClicked[0]; _i--) {\n selectRangeItem(_i);\n }\n }\n };\n\n var getPosicion = function getPosicion(lastClickedPK, clickedPK) {\n var posicionClicked = {};\n\n for (var i = 0; i < opciones.content.length; i++) {\n if (opciones.content[i][opciones.key] == clickedPK) {\n posicionClicked[0] = i;\n } else if (opciones.content[i][opciones.key] == lastClickedPK) {\n posicionClicked[1] = i;\n }\n }\n\n return posicionClicked;\n };\n },\n\n /**\r\n * Método interno que crea el scrollList\r\n * @name _scrollListInit\r\n * @private\r\n * @function\r\n */\n _scrollListInit: function _scrollListInit() {\n var self = this;\n self.options.stepLoad = self.element.children().length / self.options.rowNum.value;\n self.options.stepOnLoad = false;\n self.options.stepCounter = 0;\n $(self.element).on('scrollListPageNext', function () {\n return self.options.page++;\n });\n $(self.element).on('scrollListPagePrev', function () {\n return self.options.page--;\n });\n $(window).on('scroll', function () {\n var windowHeight = document.documentElement.clientHeight,\n targetOpciones = self.element[0].getBoundingClientRect(),\n targetHeight = targetOpciones.height,\n targetTopPoint = targetOpciones.top,\n targetButtomPoint = targetHeight + targetTopPoint + 150;\n self.options.stepLoad = self.element.children().length / self.options.rowNum.value;\n\n if (self.options.stepLoad == self.options.page) {\n if (targetButtomPoint < windowHeight) {\n self.options.stepCounter++;\n\n if (self.options.stepCounter == 1) {\n if (self.element.children().length <= self.options.rowNum.value * self.options.page) {\n if (!self.options.stepOnLoad) {\n self.options.stepOnLoad = true;\n\n self._lock();\n\n $(self.element).trigger('scrollListPageNext');\n $.when(self.isFiltering).done(function () {\n // Reiniciar la promesa de filtrado\n delete self.isFiltering;\n self.isFiltering = $.Deferred();\n\n self._doFilter();\n });\n }\n }\n }\n }\n }\n });\n },\n\n /**\r\n * Método que aplica el modo 'sticky' al header\r\n * @name _headerSticky\r\n * @private\r\n * @function\r\n */\n _headerSticky: function _headerSticky() {\n var self = this;\n var opciones = self.options;\n $(window).on('resize', function () {\n opciones._header.obj.css('width', self.element.css('width'));\n });\n $(window).on('scroll', function () {\n if ($('.rup-navbar.navbar').hasClass('rup-navbar-sticky')) {\n window.scrollHeight = $('.rup-navbar').height();\n } else {\n window.scrollHeight = 0;\n }\n\n var targetOpciones = opciones._header.obj[0].getBoundingClientRect(),\n targetTopPoint = targetOpciones.top;\n\n if (opciones._header.obj.hasClass('rup_list-sticky')) {\n targetOpciones = self.element[0].getBoundingClientRect();\n targetTopPoint = targetOpciones.top;\n }\n\n opciones._header.obj.css('width', self.element.css('width'));\n\n if (targetTopPoint < window.scrollHeight) {\n opciones._header.obj.addClass('rup_list-sticky');\n\n self.element.css({\n 'padding-top': opciones._header.obj[0].offsetHeight\n });\n\n opciones._header.obj.css({\n 'top': window.scrollHeight\n });\n } else if (targetTopPoint >= window.scrollHeight) {\n if (opciones._header.obj.hasClass('rup_list-sticky')) {\n opciones._header.obj.removeClass('rup_list-sticky');\n\n self.element.css({\n 'padding-top': 0\n });\n\n opciones._header.obj.css({\n 'top': 0\n });\n }\n }\n });\n },\n\n /**\r\n * Método que crea el loader\r\n * @name _loader\r\n * @private\r\n * @function\r\n */\n _loader: function _loader() {\n var self = this;\n var opciones = self.options;\n var selfId = self.element.attr('id');\n\n if (!opciones._overlay) {\n opciones._idOverlay = selfId + '-overlay';\n opciones._overlay = jQuery('
');\n }\n\n opciones.loader(opciones._overlay);\n },\n\n /**\r\n * Método que lanza la impresión HTML\r\n * @name _print\r\n * @private\r\n * @function\r\n */\n _print: function _print() {\n var self = this;\n var opciones = self.options;\n\n if ($('#' + opciones.filterForm).find('#listPrint').length == 0) {\n opciones.btnPrint = $('
');\n opciones.btnPrint.appendTo($('#' + opciones.filterForm));\n opciones.btnPrint[0].disabled = true;\n opciones.btnPrint.on('click', btnPrintMain);\n }\n\n function btnPrintMain(e) {\n e.preventDefault();\n var doc = new printd__WEBPACK_IMPORTED_MODULE_0___default.a(),\n printDoc = $('
', {\n 'id': 'rup-list-link-print',\n 'rel': 'stylesheet',\n // 'media': 'print',\n 'href': opciones.print\n }),\n sidx = '',\n sord = '';\n\n if (opciones.isMultiSort) {\n sidx = opciones.multiorder.sidx;\n sord = opciones.multiorder.sord;\n } else {\n sidx = opciones.sidx.value;\n sord = opciones.sord;\n } // Si el formulario de filtrado indicado es correcto se parsea\n\n\n var filterForm = {};\n\n if ($(\"form[id=\\\"\".concat(opciones.filterForm, \"\\\"]\")).length == 1) {\n filterForm = $('#' + opciones.filterForm).rup_form('formToJson');\n }\n\n var filter = {\n filter: filterForm,\n page: 1,\n rows: opciones.records,\n sidx: sidx,\n sord: sord,\n multiselection: opciones.multiselection,\n core: {\n pkNames: [opciones.key],\n pkToken: '~'\n }\n };\n printDoc.append(printTagStyle);\n jQuery.rup_ajax({\n url: opciones.action,\n type: 'POST',\n dataType: 'json',\n data: JSON.stringify(filter),\n contentType: 'application/json',\n success: function success(xhr) {\n if (!opciones.multiselection.selectedIds || opciones.multiselection.selectedIds.length == 0) {\n for (var i = 0; i < xhr.rows.length; i++) {\n printDoc.append($('
'));\n }\n } else {\n for (var x = 0; x < xhr.rows.length; x++) {\n for (var y = 0; y < xhr.reorderedSelection.length; y++) {\n if (xhr.rows[x][opciones.key] == xhr.reorderedSelection[y].pk[opciones.key]) {\n printDoc.append($('
'));\n }\n }\n }\n }\n\n doc.print(printDoc[0]);\n }\n });\n }\n },\n\n /**\r\n * Método interno que configura MultiFilter\r\n * @name _multiFilter\r\n * @private\r\n * @function\r\n */\n _multiFilter: function _multiFilter() {\n var self = this;\n var opciones = self.options;\n opciones.multiFilter = {};\n opciones.multiFilter._filterSelector = 'generated';\n opciones.multiFilter._filterUser = 'udaPruebas';\n opciones.multiFilter._dialogId = self.element[0].id + '_dropdownDialog';\n opciones.multiFilter.$btn = $('#' + opciones.filterForm).find('button').eq(0);\n opciones.multiFilter.$dialog = $('
');\n opciones.multiFilter.$btn.after(opciones.multiFilter.$dialog);\n opciones.multiFilter.$combo = $('#' + opciones.multiFilter._dialogId + '_combo');\n opciones.multiFilter.$feedback = $('#' + opciones.multiFilter._dialogId + '_feedback');\n opciones.multiFilter.$feedback.rup_feedback({\n block: false,\n delay: 2000\n }); // Dropdown dialog\n\n opciones.multiFilter.$btn.rup_button({\n dropdown: {\n dropdownDialog: opciones.multiFilter._dialogId,\n dropdownDialogConfig: {\n autoOpen: false,\n modal: true,\n resizable: true,\n title: '
Administración de filtros',\n width: '380px',\n buttons: [{\n id: opciones.multiFilter._dialogId + '_btn_save',\n text: 'Guardar',\n click: function click() {\n if ($('#' + opciones.filterForm).rup_form('formToJson').length != 0) {\n var elem = {\n filtro: {\n filterSelector: opciones.multiFilter._filterSelector,\n filterName: opciones.multiFilter.$label.val(),\n filterValue: JSON.stringify($('#' + opciones.filterForm).rup_form('formToJson')),\n filterDefault: opciones.multiFilter.$dialog.find('#' + opciones.multiFilter._dialogId + '-defaultFilter')[0].checked,\n filterUser: opciones.multiFilter._filterUser\n }\n };\n $.rup_ajax({\n url: opciones.action + '/./multiFilter/add',\n type: 'POST',\n dataType: 'json',\n data: JSON.stringify(elem),\n contentType: 'application/json',\n success: function success() {\n opciones.multiFilter.$feedback.rup_feedback('set', $.rup.i18n.base.rup_table.plugins.multifilter.ok, 'ok');\n },\n error: function error() {\n opciones.multiFilter.$feedback.rup_feedback('set', $.rup.i18n.base.rup_table.plugins.multifilter.error, 'error');\n }\n });\n }\n }\n }, {\n id: opciones.multiFilter._dialogId + '_btn_apply',\n text: 'Aplicar',\n click: function click() {\n if (opciones.multiFilter.selected) {\n opciones.multiFilter.$dialog.dialog('close');\n self.element.rup_list('filter');\n }\n }\n }, {\n id: opciones.multiFilter._dialogId + '_btn_delete',\n text: 'Eliminar',\n click: function click() {\n if (opciones.multiFilter.selected) {\n var elem = {\n filtro: {\n filterSelector: opciones.multiFilter.selected.filterSelector,\n filterName: opciones.multiFilter.selected.filterName,\n filterValue: JSON.stringify(opciones.multiFilter.selected.filterValue),\n filterDefault: opciones.multiFilter.selected.filterDefault,\n filterUser: opciones.multiFilter.selected.filterUser\n }\n };\n $.rup_ajax({\n url: opciones.action + '/./multiFilter/delete',\n type: 'POST',\n dataType: 'json',\n data: JSON.stringify(elem),\n contentType: 'application/json',\n success: function success() {\n opciones.multiFilter.$feedback.rup_feedback('set', $.rup.i18n.base.rup_table.plugins.multifilter.ok, 'ok');\n opciones.multiFilter.$combo.rup_autocomplete('set', '', '');\n opciones.multiFilter.$label.data('tmp.loadObjects.term', null);\n opciones.multiFilter.$label.data('loadObjects', {});\n opciones.multiFilter.$label.data('tmp.data', {});\n },\n error: function error() {\n opciones.multiFilter.$feedback.rup_feedback('set', $.rup.i18n.base.rup_table.plugins.multifilter.error, 'error');\n }\n });\n }\n }\n }, {\n id: opciones.multiFilter._dialogId + '_btn_cancel',\n text: 'Cancelar',\n click: function click() {\n opciones.multiFilter.$dialog.dialog('close');\n },\n btnType: $.rup.dialog.LINK\n }]\n }\n }\n });\n opciones.multiFilter.$combo.rup_autocomplete({\n source: opciones.action + '/./multiFilter/getAll?filterSelector=' + opciones.multiFilter._filterSelector + '&user=' + opciones.multiFilter._filterUser,\n sourceParam: {\n label: 'filterName',\n value: 'filterDefault',\n data: 'filterValue',\n category: 'filter'\n },\n method: 'GET',\n menuMaxHeight: 325,\n minLength: 3,\n combobox: true,\n contains: true,\n select: function select() {\n if (opciones.multiFilter.$combo.rup_autocomplete('getRupValue')) {\n opciones.multiFilter.selected = {\n filterSelector: opciones.multiFilter._filterSelector,\n filterName: opciones.multiFilter.$combo.rup_autocomplete('getRupValue'),\n filterDefault: opciones.multiFilter.$dialog.find('#' + opciones.multiFilter._dialogId + '-defaultFilter')[0].checked,\n filterUser: opciones.multiFilter._filterUser\n };\n $.rup_ajax({\n url: opciones.action + '/./multiFilter/getAll?filterSelector=' + opciones.multiFilter._filterSelector + '&user=' + opciones.multiFilter._filterUser,\n type: 'GET',\n dataType: 'json',\n contentType: 'application/json',\n success: function success(data) {\n if (opciones.multiFilter.selected.filterName) {\n for (var i = 0; i < data.length; i++) {\n if (opciones.multiFilter.selected.filterName == data[i].filterName) {\n opciones.multiFilter.selected.filterValue = JSON.parse(data[i].filterValue);\n opciones.multiFilter.selected.filterDefault = data[i].filterDefault;\n }\n }\n\n if (opciones.multiFilter.selected.filterDefault) {\n opciones.multiFilter.$dialog.find('#' + opciones.multiFilter._dialogId + '-defaultFilter')[0].checked = true;\n } else {\n opciones.multiFilter.$dialog.find('#' + opciones.multiFilter._dialogId + '-defaultFilter')[0].checked = false;\n }\n\n $('#' + opciones.filterForm).find('input').val('');\n\n for (var _i2 = 0; _i2 < $('#' + opciones.filterForm).find('input').length; _i2++) {\n if (opciones.multiFilter.selected.filterValue[$('#' + opciones.filterForm).find('input').eq(_i2).attr('name')] != undefined) {\n $('#' + opciones.filterForm).find('input').eq(_i2).val(opciones.multiFilter.selected.filterValue[$('#' + opciones.filterForm).find('input').eq(_i2).attr('name')]);\n }\n }\n }\n },\n error: function error() {\n opciones.multiFilter.$feedback.rup_feedback('set', $.rup.i18n.base.rup_table.plugins.multifilter.error, 'error');\n }\n });\n }\n }\n });\n opciones.multiFilter.$label = $('#' + opciones.multiFilter._dialogId + '_combo_label'); //filtro por derecho\n\n $.rup_ajax({\n url: opciones.action + '/./multiFilter/getDefault?filterSelector=' + opciones.multiFilter._filterSelector + '&user=' + opciones.multiFilter._filterUser,\n type: 'GET',\n dataType: 'json',\n contentType: 'application/json',\n success: function success(data) {\n opciones.multiFilter.$label.val(data.filterName);\n data.filterValue = JSON.parse(data.filterValue);\n\n if (data.filterDefault) {\n opciones.multiFilter.$dialog.find('#' + opciones.multiFilter._dialogId + '-defaultFilter')[0].checked = true;\n } else {\n opciones.multiFilter.$dialog.find('#' + opciones.multiFilter._dialogId + '-defaultFilter')[0].checked = false;\n }\n\n for (var i = 0; i < $('#' + opciones.filterForm).find('input').length; i++) {\n if (data.filterValue[$('#' + opciones.filterForm).find('input').eq(i).attr('name')] != undefined) {\n $('#' + opciones.filterForm).find('input').eq(i).val(data.filterValue[$('#' + opciones.filterForm).find('input').eq(i).attr('name')]);\n }\n }\n }\n });\n\n opciones.multiFilter.$label.data('uiAutocomplete')._renderItem = function (ul, item) {\n return $('
').appendTo(ul);\n };\n\n opciones.multiFilter.$label.off('blur click');\n },\n\n /**\r\n * Método interno que configura el boton de alternar el sord en la ordenación simple\r\n * @name _sordButtonInit\r\n * @private\r\n * @function\r\n */\n _sordButtonInit: function _sordButtonInit() {\n var self = this;\n var opciones = self.options;\n var sordH = opciones._header.sord;\n var sordF = opciones._footer.sord;\n sordH.attr('aria-controls', self.element.attr('id'));\n\n if (opciones.createFooter) {\n sordF.attr('aria-controls', self.element.attr('id'));\n }\n\n if (opciones.sord === 'asc') {\n sordH.addClass('asc');\n sordH.removeClass('desc');\n sordH.attr('aria-label', $.rup.i18n.base.rup_list.sort.asc);\n\n if (opciones.createFooter) {\n sordF.addClass('asc');\n sordF.removeClass('desc');\n sordF.attr('aria-label', $.rup.i18n.base.rup_list.sort.asc);\n }\n } else {\n sordH.addClass('desc');\n sordH.removeClass('asc');\n sordH.attr('aria-label', $.rup.i18n.base.rup_list.sort.desc);\n\n if (opciones.createFooter) {\n sordF.addClass('desc');\n sordF.removeClass('asc');\n sordF.attr('aria-label', $.rup.i18n.base.rup_list.sort.desc);\n }\n } // Funcionamiento botón sord\n\n\n $('#' + opciones._idListHeader.sord + ', #' + opciones._idListFooter.sord).on('click', function () {\n sordH.toggleClass('asc');\n sordH.toggleClass('desc');\n\n if (opciones.createFooter) {\n sordF.toggleClass('asc');\n sordF.toggleClass('desc');\n }\n\n var label = sordH.hasClass('asc') ? $.rup.i18n.base.rup_list.sort.asc : $.rup.i18n.base.rup_list.sort.desc;\n sordH.attr('aria-label', label);\n\n if (opciones.createFooter) {\n sordF.attr('aria-label', label);\n }\n\n self._changeOption('sord', sordH.hasClass('asc') ? 'asc' : 'desc');\n });\n },\n\n /**\r\n * Método interno que configura el combo de seleccion de sidx en la ordenación simple\r\n * @name _sidxComboInit\r\n * @private\r\n * @function\r\n */\n _sidxComboInit: function _sidxComboInit() {\n var self = this;\n var opciones = self.options;\n\n var doChange = function doChange(obj, change) {\n if (!$('#' + obj.id).rup_combo('isDisabled')) {\n var iden = opciones._header.sidx[0].id;\n $('#' + iden).rup_combo('setRupValue', $('#' + obj.id).rup_combo('getRupValue'));\n\n if (opciones.createFooter) {\n iden = opciones._footer.sidx[0].id;\n $('#' + iden).rup_combo('setRupValue', $('#' + obj.id).rup_combo('getRupValue'));\n }\n\n if (change) {\n self._changeOption('sidx', $('#' + obj.id).rup_combo('getRupValue'));\n }\n }\n };\n\n var changeH = function changeH() {\n doChange(this, true);\n };\n\n var changeF = function changeF() {\n doChange(this, false);\n };\n\n var sidxRupConf = {\n source: opciones.sidx.source,\n width: 'initial',\n selected: opciones.sidx.value,\n rowStriping: true,\n ordered: false,\n change: changeH\n };\n\n opciones._header.sidx.rup_combo(sidxRupConf);\n\n opciones._header.sidx = $('#' + opciones._idListHeader.sidx);\n\n if (opciones.createFooter) {\n var sidxRupConfFoot = {\n source: opciones.sidx.source,\n width: 'initial',\n selected: opciones.sidx.value,\n rowStriping: true,\n ordered: false,\n change: changeF\n };\n\n opciones._footer.sidx.rup_combo(sidxRupConfFoot);\n\n opciones._footer.sidx = $('#' + opciones._idListFooter.sidx);\n }\n },\n\n /**\r\n * Método interno que configura los elementos de la multiordenación.\r\n * @name _multisortInit\r\n * @private\r\n * @function\r\n */\n _multisortInit: function _multisortInit() {\n var self = this;\n var opciones = self.options;\n var selfId = self.element.attr('id'); // Creamos un apartado en opciones\n\n opciones.multiorder = {\n sidx: opciones.sidx.value,\n sord: function () {\n if (opciones.sord) {\n var sordArr = opciones.sord.split(',');\n var sidxArr = opciones.sidx.value.split(',');\n\n if (sordArr.length == sidxArr.length) {\n return opciones.sord;\n }\n\n if (sordArr.length > sidxArr.length) {\n return sordArr.splice(0, sidxArr.length).join(',');\n }\n\n if (sordArr.length < sidxArr.length) {\n var diff = sidxArr.length - sordArr.length;\n\n for (var i = 0; i < diff; i++) {\n sordArr.push('asc');\n }\n\n return sordArr.join(',');\n }\n } else {\n var _sordArr = [];\n\n for (var _i3 = 0; _i3 < opciones.sidx.value.split(',').length; _i3++) {\n _sordArr.push('asc');\n }\n\n return _sordArr.join(',');\n }\n }()\n };\n\n var doInit = function doInit(isFooter) {\n var idObj = isFooter ? '_idListFooter' : '_idListHeader';\n var obj = isFooter ? '_footer' : '_header';\n var label = isFooter ? '-footer-' : '-header-';\n opciones[idObj].multiSort.dialog = selfId + label + 'mord-dialog';\n opciones[idObj].multiSort.summary = selfId + label + 'mord-summary';\n opciones[idObj].multiSort.edit = selfId + label + 'mord-edit'; // Generamos un span para el resumen\n\n var $spanResumen = $('
');\n opciones[obj].sidx.wrap($tmpWrapSummary);\n $tmpWrapSummary = opciones[obj].sidx.parent();\n $tmpWrapSummary.children().remove();\n $tmpWrapSummary.append($spanResumen);\n $spanResumen.unwrap();\n opciones[obj].multiSort.summary = $('#' + opciones[idObj].multiSort.summary); // Se rellena el resumen con el order por defecto\n\n opciones.multiorder.sidx.split(',').map(function (e) {\n return e.trim();\n }).forEach(function (e, i) {\n if (e !== '') {\n var $tmpSum = $('
');\n\n var geti18n = function geti18n(val) {\n var srcVal = opciones.sidx.source.filter(function (x) {\n return x.value == val;\n });\n return srcVal[0].i18nCaption;\n };\n\n var sordBadge = $('
');\n sordBadge.text(' ');\n\n var _arrSord = opciones.multiorder.sord.split(',').map(function (e) {\n return e.trim();\n });\n\n if (_arrSord[i] == 'asc') {\n sordBadge.addClass('asc mdi mdi-chevron-up');\n sordBadge.attr('aria-label', $.rup.i18n.base.rup_list.sort.asc);\n } else {\n sordBadge.addClass('desc mdi mdi-chevron-down');\n sordBadge.attr('aria-label', $.rup.i18n.base.rup_list.sort.desc);\n }\n\n $tmpSum.append(geti18n(e)).append(sordBadge.clone());\n $spanResumen.append($tmpSum.clone());\n }\n }); // Creamos el botón para el dialogo\n\n var $btnOrderDialog = $(\"
\"));\n $btnOrderDialog.attr('aria-haspopup', 'true');\n $btnOrderDialog.attr('aria-expanded', 'false');\n $btnOrderDialog.attr('aria-label', $.rup.i18n.base.rup_list.openMordDialog);\n var $tmpWrapEditMord = $('
');\n opciones[obj].sord.wrap($tmpWrapEditMord);\n $tmpWrapEditMord = opciones[obj].sord.parent();\n $tmpWrapEditMord.children().remove();\n $tmpWrapEditMord.append($btnOrderDialog);\n $btnOrderDialog.unwrap();\n opciones[obj].multiSort.edit = $('#' + opciones[idObj].multiSort.edit); // Establecemos el boton para el dialogo\n\n opciones[obj].multiSort.edit.on('click keyup', function (e) {\n if (e.type === 'click' || e.type === 'keyup' && e.keyCode == '13') {\n opciones._multiSortDialog.rup_dialog('open');\n }\n });\n var arrSidx = opciones.multiorder.sidx.split(',').map(function (a) {\n return a.trim();\n });\n var arrSord = opciones.multiorder.sord.split(',').map(function (a) {\n return a.trim();\n });\n\n if (arrSidx.length > 0) {\n var cont = 0;\n $(self.element).on('rup_list-mord-changed', function () {\n cont++;\n\n if (cont == arrSidx.length) {\n $(self.element).trigger('rup_list-mord-inited');\n }\n });\n arrSidx.forEach(function (elem, i) {\n $('button[data-ordValue=\"' + elem + '\"]').trigger('click', [arrSord[i], true]);\n });\n } else {\n $(self.element).trigger('rup_list-mord-inited');\n }\n }; //Creamos el dialogo\n\n\n $('
').append(\"\\n
\\n
\\n
\".concat($.rup.i18n.base.rup_list.multiSortDialog.msg1, \"\\n \").concat($.rup.i18n.base.rup_list.multiSortDialog.msg2, \"
\\n
\\n \\n
\\n
\\n
\\n
\").concat($.rup.i18n.base.rup_list.multiSortDialog.msg3, \"
\\n
\").concat($.rup.i18n.base.rup_list.multiSortDialog.msg4, \"
\\n
\\n
\\n
\\n \")).appendTo('body');\n opciones._multiSortDialog = $('#' + opciones._idMultiSortDialog); //Creamos el contenido del diálogo\n\n opciones.sidx.source.forEach(function (el) {\n var $btn = $(\"\\n
\\n \"));\n $btn.attr('aria-controls', \"\".concat(opciones._idMultiSortDialog, \"-orderfields \").concat(opciones._idMultiSortDialog, \"-ordersort\"));\n $('.rup_list-mord-orderfields').append($btn.clone());\n });\n $('.rup_list-mord-orderfields').children().on('click', function (e, param, isInit) {\n self._actualizarOrdenMulti.apply(self, [e, param, isInit]);\n }); //Creamos el componente para el dialogo\n\n opciones._multiSortDialog.rup_dialog({\n type: $.rup.dialog.DIV,\n autoOpen: false,\n modal: true,\n resizable: false,\n width: 'auto',\n title: $.rup.i18n.base.rup_list.multiSortDialog.title,\n buttons: [{\n text: 'cerrar',\n click: function click() {\n opciones._multiSortDialog.rup_dialog('close');\n }\n }],\n open: function open() {\n $(self.element).trigger('rup_list-mord-dialogOpen');\n\n opciones._header.multiSort.edit.attr('aria-expanded', true);\n\n if (opciones.createFooter) {\n opciones._footer.multiSort.edit.attr('aria-expanded', true);\n }\n },\n onBeforeClose: function onBeforeClose() {\n $(self.element).trigger('rup_list-mord-dialogClose');\n\n opciones._header.multiSort.edit.attr('aria-expanded', false);\n\n if (opciones.createFooter) {\n opciones._footer.multiSort.edit.attr('aria-expanded', false);\n }\n }\n });\n\n doInit();\n\n if (opciones.createFooter) {\n doInit(true);\n }\n },\n\n /**\r\n * Método interno que configura el combo de elementos de lista por página\r\n * @name _rownumInit\r\n * @private\r\n * @function\r\n */\n _rownumInit: function _rownumInit() {\n var self = this;\n var opciones = self.options;\n\n var doChange = function doChange(obj, change) {\n if (!$('#' + obj.id).rup_combo('isDisabled')) {\n var _iden = opciones._header.rowNum[0].id;\n $('#' + _iden).rup_combo('setRupValue', $('#' + obj.id).rup_combo('getRupValue'));\n\n if (opciones.createFooter) {\n _iden = opciones._footer.rowNum[0].id;\n $('#' + _iden).rup_combo('setRupValue', $('#' + obj.id).rup_combo('getRupValue'));\n }\n\n if (change) {\n self._changeOption('rowNum', $('#' + obj.id).rup_combo('getRupValue'));\n }\n }\n };\n\n var changeH = function changeH() {\n doChange(this, true);\n };\n\n var changeF = function changeF() {\n doChange(this, false);\n };\n\n var rowNumRupConf = {\n source: opciones.rowNum.source,\n width: 'initial',\n selected: opciones.rowNum.value,\n rowStriping: true,\n ordered: false,\n change: changeH\n };\n var iden = opciones._header.rowNum[0].id;\n $('#' + iden).rup_combo(rowNumRupConf);\n opciones._header.rowNum = $('#' + opciones._idListHeader.rowNum);\n\n if (opciones.createFooter) {\n var rowNumRupConfFoot = {\n source: opciones.rowNum.source,\n width: 'initial',\n selected: opciones.rowNum.value,\n rowStriping: true,\n ordered: false,\n change: changeF\n };\n var idenFoot = opciones._footer.rowNum[0].id;\n $('#' + idenFoot).rup_combo(rowNumRupConfFoot);\n opciones._footer.rowNum = $('#' + opciones._idListFooter.rowNum);\n }\n },\n\n /**\r\n * Método interno para deshabilitar botones de paginación\r\n * @private\r\n * @function\r\n * @param $navItem Objeto JQuery con el ítem de la navegación sobre el que actuar\r\n */\n _disableNavItem: function _disableNavItem($navItem) {\n $navItem.addClass('disabled');\n $navItem.attr('aria-disabled', 'true');\n $navItem.attr('tabindex', '-1');\n },\n\n /**\r\n * Método interno para habilitar botones de paginación\r\n * @private\r\n * @function\r\n * @param $navItem Objeto JQuery con el ítem de la navegación sobre el que actuar\r\n */\n _enableNavItem: function _enableNavItem($navItem) {\n $navItem.removeClass('disabled');\n $navItem.attr('aria-disabled', 'false');\n $navItem.attr('tabindex', '0');\n },\n\n /**\r\n * Método interno que configura el nav de la paginación\r\n * @name _pagenavInit\r\n * @private\r\n * @function\r\n */\n _pagenavInit: function _pagenavInit() {\n var self = this;\n var opciones = self.options;\n $('.page-separator').hide().attr('aria-hidden', 'true'); // A11Y\n\n opciones._header.pagenav.attr('aria-label', $.rup.i18n.base.rup_list.paginacion);\n\n opciones._header.pagenav.attr('aria-controls', self.element.attr('id'));\n\n opciones._header.pagePrev.attr('role', 'button').attr('aria-controls', self.element.attr('id')).attr('aria-label', $.rup.i18n.base.rup_list.paginaAnterior);\n\n opciones._header.pageNext.attr('role', 'button').attr('aria-controls', self.element.attr('id')).attr('aria-label', $.rup.i18n.base.rup_list.paginaSiguiente);\n\n if (opciones.createFooter) {\n opciones._footer.pagenav.attr('aria-label', $.rup.i18n.base.rup_list.paginacion);\n\n opciones._footer.pagenav.attr('aria-controls', self.element.attr('id'));\n\n opciones._footer.pagePrev.attr('role', 'button').attr('aria-controls', self.element.attr('id')).attr('aria-label', $.rup.i18n.base.rup_list.paginaAnterior);\n\n opciones._footer.pageNext.attr('role', 'button').attr('aria-controls', self.element.attr('id')).attr('aria-label', $.rup.i18n.base.rup_list.paginaSiguiente);\n }\n\n var onPageChange = function onPageChange(elem) {\n if ($(elem).is('.disabled')) {\n return false;\n }\n\n var maxpage = $('.page').eq(-1).attr('data-page');\n\n var actualPage = opciones._header.pagenav.find('.rup_list-page-item.page.active').attr('data-page');\n\n if (actualPage == 1) {\n self._disableNavItem(opciones._header.pagePrev);\n\n self._enableNavItem(opciones._header.pageNext);\n\n if (opciones.createFooter) {\n self._disableNavItem(opciones._footer.pagePrev);\n\n self._enableNavItem(opciones._footer.pageNext);\n }\n\n return true;\n }\n\n if (actualPage == maxpage) {\n self._enableNavItem(opciones._header.pagePrev);\n\n self._disableNavItem(opciones._header.pageNext);\n\n if (opciones.createFooter) {\n self._enableNavItem(opciones._footer.pagePrev);\n\n self._disableNavItem(opciones._footer.pageNext);\n }\n\n return true;\n }\n\n self._enableNavItem(opciones._header.pagePrev);\n\n self._enableNavItem(opciones._header.pageNext);\n\n if (opciones.createFooter) {\n self._enableNavItem(opciones._footer.pagePrev);\n\n self._enableNavItem(opciones._footer.pageNext);\n }\n\n return true;\n };\n\n opciones._header.pagePrev.on('click', function () {\n if (!onPageChange(this)) {\n return;\n }\n\n self._changeOption('page', opciones._header.pagenav.find('.rup_list-page-item.page.active').prev('[data-page]').data('page'));\n });\n\n opciones._header.pageNext.on('click', function () {\n if (!onPageChange(this)) {\n return;\n }\n\n self._changeOption('page', opciones._header.pagenav.find('.rup_list-page-item.page.active').next('[data-page]').data('page'));\n });\n\n if (opciones.createFooter) {\n opciones._footer.pagePrev.on('click', function () {\n if (!onPageChange(this)) {\n return;\n }\n\n self._changeOption('page', opciones._header.pagenav.find('.rup_list-page-item.page.active').prev('[data-page]').data('page'));\n });\n\n opciones._footer.pageNext.on('click', function () {\n if (!onPageChange(this)) {\n return;\n }\n\n self._changeOption('page', opciones._header.pagenav.find('.rup_list-page-item.page.active').next('[data-page]').data('page'));\n });\n }\n },\n\n /**\r\n * Método interno que crea la estructura de las líneas en la multiordenación\r\n *\r\n * @name _actualizarOrdenMulti\r\n * @private\r\n * @function\r\n * @param {Event} e\r\n * @param {JQueryObj} self Objeto JQuery del botón\r\n * @param {String} ord Direccion de la ordenación con la que se va a generar la línea\r\n */\n _actualizarOrdenMulti: function _actualizarOrdenMulti(e) {\n var ord = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'asc';\n var isInit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'false';\n var self = this;\n var opciones = self.options;\n var sortDiv = $('.rup_list-mord-ordersort'); // Añadimos las opciones al componente\n\n if (opciones.multiorder.sidx.length) {\n var tmpSidxArr = opciones.multiorder.sidx.split(',').map(function (e) {\n return e.trim();\n });\n var tmpSordArr = opciones.multiorder.sord.split(',').map(function (e) {\n return e.trim();\n });\n\n if (tmpSidxArr.indexOf($(e.target).attr('data-ordValue')) == -1) {\n tmpSidxArr.push($(e.target).attr('data-ordValue'));\n tmpSordArr.push(ord);\n }\n\n opciones.multiorder.sidx = tmpSidxArr.join(',');\n opciones.multiorder.sord = tmpSordArr.join(',');\n } //Creamos la linea\n\n\n var $operateLine = $(\"\\n
\\n
\\n
\\n
\\n
\").concat($(e.target).text(), \"
\\n
\\n
\\n
\\n \"));\n $operateLine.find('button').rup_button();\n $(e.target).remove();\n sortDiv.append($operateLine);\n\n self._fnOrderOfOrderFields.apply(self, [$('[data-ordValue=\"' + $(e.target).attr('data-ordValue') + '\"]', sortDiv), isInit]);\n },\n\n /**\r\n * Método interno que da funcionalidad a cada línea en la multiordenación\r\n *\r\n * @name _fnOrderOfOrderFields\r\n * @private\r\n * @function\r\n * @param {JQuery} ctx La instancia de rup_list\r\n * @param {JQuery} line Objeto JQuery de la línea a la que se va a dar funcionalidad\r\n */\n _fnOrderOfOrderFields: function _fnOrderOfOrderFields(line, isInit) {\n var _this2 = this;\n\n var self = this;\n var opciones = self.options; //Función de guardado de la multiordenación\n\n var save = function save() {\n opciones.multiorder.sidx = '';\n opciones.multiorder.sord = '';\n var $sortDiv = $('.rup_list-mord-ordersort');\n var sidxArr = [];\n var sordArr = [];\n $sortDiv.children().toArray().forEach(function (elem) {\n if (sidxArr.indexOf($(elem).attr('data-ordValue')) == -1) {\n sidxArr.push($(elem).attr('data-ordValue'));\n sordArr.push($('.rup_list-mord', $(elem)).attr('data-direction'));\n }\n });\n\n if (sidxArr.length > 0) {\n opciones.multiorder.sidx = sidxArr.join(',');\n opciones.multiorder.sord = sordArr.join(',');\n } //Crear el label de resumen\n\n\n opciones._content.find('.rup_list-mord-summary').empty();\n\n if (opciones.multiorder.sidx != null && opciones.multiorder.sidx.length > 0) {\n opciones.multiorder.sidx.split(',').map(function (e) {\n return e.trim();\n }).forEach(function (e, i) {\n var geti18n = function geti18n(val) {\n var srcVal = opciones.sidx.source.filter(function (x) {\n return x.value == val;\n });\n return srcVal[0].i18nCaption;\n };\n\n var sordBadge = $('
').text(' ');\n var arrSord = opciones.multiorder.sord.split(',').map(function (e) {\n return e.trim();\n });\n\n if (arrSord[i] == 'asc') {\n sordBadge.addClass('mdi mdi-chevron-up');\n } else {\n sordBadge.addClass('mdi mdi-chevron-down');\n }\n\n $('
').append(geti18n(e)).append(sordBadge.clone()).appendTo(opciones._content.find('.rup_list-mord-summary'));\n });\n } // Función para dehabilitar los botones de reordenación correspondientes\n\n\n opciones._multiSortDialog.find('.rup_list-mord-up, .rup_list-mord-down').button('enable');\n\n opciones._multiSortDialog.find('.rup_list-mord-up, .rup_list-mord-down').attr('aria-disabled', 'false');\n\n opciones._multiSortDialog.find('.rup_list-mord-up, .rup_list-mord-down').attr('tabindex', '0');\n\n opciones._multiSortDialog.find('.rup_list-mord-up').first().button('disable');\n\n opciones._multiSortDialog.find('.rup_list-mord-down').last().button('disable');\n\n opciones._multiSortDialog.find('.rup_list-mord-up').first().attr('aria-disabled', 'true');\n\n opciones._multiSortDialog.find('.rup_list-mord-down').last().attr('aria-disabled', 'true');\n\n opciones._multiSortDialog.find('.rup_list-mord-up').first().attr('tabindex', '-1');\n\n opciones._multiSortDialog.find('.rup_list-mord-down').last().attr('tabindex', '-1');\n\n var ariaSummary = $('.rup_list-ord-line').toArray().map(function (e) {\n return $(e).attr('aria-label') + '; ';\n }).reduce(function (rest, el) {\n return rest + el;\n }, '');\n $sortDiv.attr('aria-label', ariaSummary ? $.rup.i18n.base.rup_list.ariaSummary + ariaSummary : $.rup.i18n.base.rup_list.ariaSummaryEmpty);\n $(self.element).trigger('rup_list-mord-changed');\n\n if (isInit != true) {\n isInit = false;\n\n _this2.reload();\n } else {\n isInit = false;\n }\n }; // Funcionalidad de los botones de reordenación\n\n\n $('.rup_list-mord-up', line).click(function () {\n if ($(line).is(':first-child')) {\n return;\n }\n\n $(line).prev().before(line);\n $(this).focus();\n save();\n });\n $('.rup_list-mord-down', line).click(function () {\n if ($(line).is(':last-child')) {\n return;\n }\n\n $(line).next().after(line);\n $(this).focus();\n save();\n }); //ponemos icono al sord\n\n if ($('.rup_list-mord', line).attr('data-direction') == 'asc') {\n $('.rup_list-mord', line).addClass('mdi-chevron-up');\n } else {\n $('.rup_list-mord', line).addClass('mdi-chevron-down');\n }\n\n $('.rup_list-mord').text(' '); //funcionalidad del sord\n\n $('.rup_list-mord', line).off('click');\n $('.rup_list-mord', line).click(function () {\n if ($('.rup_list-mord', line).attr('data-direction') == 'asc') {\n $('.rup_list-mord', line).attr('data-direction', 'desc');\n $('.rup_list-mord', line).attr('aria-label', $.rup.i18n.base.rup_list.sort.desc);\n $('.rup_list-mord', line).addClass('mdi-chevron-down');\n $('.rup_list-mord', line).removeClass('mdi-chevron-up'); // Se cambia el aria-label de la línea entera para que sea entendible\n\n $('.rup_list-mord', line).parent().attr('aria-label', \"\".concat($('.rup_list-mord', line).parent().text().trim(), \", \").concat($.rup.i18n.base.rup_list.sort.desc));\n } else {\n $('.rup_list-mord', line).attr('data-direction', 'asc');\n $('.rup_list-mord', line).attr('aria-label', $.rup.i18n.base.rup_list.sort.asc);\n $('.rup_list-mord', line).addClass('mdi-chevron-up');\n $('.rup_list-mord', line).removeClass('mdi-chevron-down'); // Se cambia el aria-label de la línea entera para que sea entendible\n\n $('.rup_list-mord', line).parent().attr('aria-label', \"\".concat($('.rup_list-mord', line).parent().text().trim(), \", \").concat($.rup.i18n.base.rup_list.sort.asc));\n }\n\n save();\n }); //funcionalidad de retirar la ordenación\n\n $('.rup_list-mord-remove', line).click(function () {\n //recreamos el botón\n var $btn = $(\"\\n
\\n \"));\n $('.rup_list-mord-orderfields').append($btn.clone());\n $('.rup_list-mord-orderfields').children().off('click');\n $('.rup_list-mord-orderfields').children().on('click', function (e) {\n self._actualizarOrdenMulti.apply(self, [e]);\n }); // Eliminamos la linea\n\n $(line).remove();\n save();\n });\n save();\n },\n\n /**\r\n * Método interno para seleccionar todos los elementos de la lista.\r\n *\r\n * @name _selectAll\r\n * @private\r\n * @function\r\n */\n _selectAll: function _selectAll() {\n var self = this;\n var opciones = self.options;\n opciones.multiselection.selectedAll = true;\n opciones.multiselection.selectedIds = [];\n opciones.multiselection.selectedRowsPerPage = [];\n\n self._getPageElementsIds().forEach(function (elem) {\n $('#' + elem).addClass('rup_list-item-selected');\n $('#' + elem).attr('aria-selected', 'true');\n });\n\n $('#' + self.element[0].id).trigger('listAfterMultiselection');\n },\n\n /**\r\n * Método interno para deseleccionar todos los elementos de la lista\r\n *\r\n * @name _deselectAll\r\n * @private\r\n * @function\r\n */\n _deselectAll: function _deselectAll() {\n var self = this;\n var opciones = self.options;\n opciones.multiselection.selectedAll = false;\n opciones.multiselection.selectedIds = null;\n opciones.multiselection.selectedRowsPerPage = null;\n\n self._getPageElementsIds().forEach(function (elem) {\n $('#' + elem).removeClass('rup_list-item-selected');\n $('#' + elem).attr('aria-selected', 'false');\n });\n\n $('#' + self.element[0].id).trigger('listAfterMultiselection');\n },\n\n /**\r\n * Método interno para seleccionar todos los elementos en la página actual\r\n *\r\n * @name _selectPage\r\n * @private\r\n * @function\r\n */\n _selectPage: function _selectPage() {\n var self = this;\n var opciones = self.options;\n\n if (opciones.multiselection.selectedIds == null) {\n opciones.multiselection.selectedIds = [];\n }\n\n if (opciones.multiselection.selectedRowsPerPage == null) {\n opciones.multiselection.selectedRowsPerPage = [];\n }\n\n if (opciones.multiselection.selectedAll == false) {\n self._getPageIds().forEach(function (arrElem) {\n var tmp = opciones.multiselection.selectedRowsPerPage.filter(function (x) {\n return x.id == arrElem;\n });\n\n if (tmp.length == 0) {\n var id = arrElem.split('_').pop();\n opciones.multiselection.selectedIds.push(id);\n opciones.multiselection.selectedRowsPerPage.push({\n id: arrElem,\n line: function () {\n var cont = 0;\n var _final2 = 0;\n self.element.children().toArray().forEach(function (element) {\n if (element.id == arrElem) {\n _final2 = cont;\n }\n\n cont++;\n });\n return _final2;\n }(),\n page: opciones.page\n });\n $('#' + self.options._idItemTemplate + '_' + arrElem).addClass('rup_list-item-selected');\n $('#' + self.options._idItemTemplate + '_' + arrElem).attr('aria-selected', 'true');\n }\n });\n } else {\n self._getPageIds().forEach(function (arrElem) {\n var tmp = opciones.multiselection.selectedRowsPerPage.filter(function (x) {\n return x.id == arrElem;\n });\n\n if (tmp.length > 0) {\n var id = arrElem.split('_').pop();\n opciones.multiselection.selectedIds = opciones.multiselection.selectedIds.filter(function (z) {\n return z != id;\n });\n opciones.multiselection.selectedRowsPerPage = opciones.multiselection.selectedRowsPerPage.filter(function (z) {\n return z.id != arrElem;\n });\n $('#' + self.options._idItemTemplate + '_' + arrElem).addClass('rup_list-item-selected');\n $('#' + self.options._idItemTemplate + '_' + arrElem).attr('aria-selected', 'true');\n }\n });\n }\n\n if (opciones.multiselection.selectedIds.length == 0) {\n opciones.multiselection.selectedIds = null;\n }\n\n if (opciones.multiselection.selectedRowsPerPage.length == 0) {\n opciones.multiselection.selectedRowsPerPage = null;\n }\n\n $('#' + self.element[0].id).trigger('listAfterMultiselection');\n },\n\n /**\r\n * Método interno para deseleccionar todos los elementos en la página actual\r\n *\r\n * @name _deselectPage\r\n * @private\r\n * @function\r\n */\n _deselectPage: function _deselectPage() {\n var self = this;\n var opciones = self.options;\n\n if (opciones.multiselection.selectedIds == null) {\n opciones.multiselection.selectedIds = [];\n }\n\n if (opciones.multiselection.selectedRowsPerPage == null) {\n opciones.multiselection.selectedRowsPerPage = [];\n }\n\n if (opciones.multiselection.selectedAll == false) {\n self._getPageIds().forEach(function (arrElem) {\n var tmp = opciones.multiselection.selectedRowsPerPage.filter(function (x) {\n return x.id == arrElem;\n });\n\n if (tmp.length > 0) {\n var id = arrElem.split('_').pop();\n opciones.multiselection.selectedIds = opciones.multiselection.selectedIds.filter(function (z) {\n return z != id;\n });\n opciones.multiselection.selectedRowsPerPage = opciones.multiselection.selectedRowsPerPage.filter(function (z) {\n return z.id != arrElem;\n });\n $('#' + self.options._idItemTemplate + '_' + arrElem).removeClass('rup_list-item-selected');\n $('#' + self.options._idItemTemplate + '_' + arrElem).attr('aria-selected', 'false');\n }\n });\n } else {\n self._getPageIds().forEach(function (arrElem) {\n var tmp = opciones.multiselection.selectedRowsPerPage.filter(function (x) {\n return x.id == arrElem;\n });\n\n if (tmp.length == 0) {\n var id = arrElem.split('_').pop();\n opciones.multiselection.selectedIds.push(id);\n opciones.multiselection.selectedRowsPerPage.push({\n id: arrElem,\n line: function () {\n var cont = 0;\n var _final3 = 0;\n self.element.children().toArray().forEach(function (element) {\n if (element.id == arrElem) {\n _final3 = cont;\n }\n\n cont++;\n });\n return _final3;\n }(),\n page: opciones.page\n });\n }\n\n $('#' + self.options._idItemTemplate + '_' + arrElem).removeClass('rup_list-item-selected');\n $('#' + self.options._idItemTemplate + '_' + arrElem).attr('aria-selected', 'false');\n });\n }\n\n if (opciones.multiselection.selectedIds.length == 0) {\n opciones.multiselection.selectedIds = null;\n }\n\n if (opciones.multiselection.selectedRowsPerPage.length == 0) {\n opciones.multiselection.selectedRowsPerPage = null;\n }\n\n $('#' + self.element[0].id).trigger('listAfterMultiselection');\n },\n\n /**\r\n * Método interno que genera el desplegable de multiseleccion\r\n *\r\n * @name _generateSelectablesBtnGroup\r\n * @private\r\n * @function\r\n */\n _generateSelectablesBtnGroup: function _generateSelectablesBtnGroup() {\n var self = this;\n var selfId = self.element.attr('id');\n var opciones = self.options;\n var $btnGroup = $(\"\\n
\\n \\n \\n
\\n \"));\n\n opciones._header.selectables.text('');\n\n opciones._header.selectables.append($btnGroup.clone());\n\n if (opciones.createFooter) {\n opciones._footer.selectables.text('');\n\n opciones._footer.selectables.append($btnGroup.clone());\n } //Creamos funcionalidad\n\n\n $('.selectable-selectAll').on('click', function () {\n self._selectAll.apply(self);\n });\n $('.selectable-deselectAll').on('click', function () {\n self._deselectAll.apply(self);\n });\n $('.selectable-selectPage').on('click', function () {\n self._selectPage.apply(self);\n });\n $('.selectable-deselectPage').on('click', function () {\n self._deselectPage.apply(self);\n });\n },\n\n /**\r\n * Método interno para obtener los Ids de los elementos de la página actual\r\n *\r\n * @name _getPageElementsIds\r\n * @private\r\n * @function\r\n */\n _getPageElementsIds: function _getPageElementsIds() {\n var self = this;\n var keys = [];\n $('#' + self.element[0].id).children().toArray().forEach(function (elem) {\n keys.push(String($(elem)[0].id));\n });\n return keys;\n },\n\n /**\r\n * Método interno para obtener los Ids de la página actual\r\n *\r\n * @name _getPageIds\r\n * @private\r\n * @function\r\n */\n _getPageIds: function _getPageIds() {\n var self = this;\n var keys = [];\n $('#' + self.element[0].id).children().toArray().forEach(function (elem) {\n keys.push(String($(elem).data('pk')));\n });\n return keys;\n },\n\n /**\r\n * Método interno que otorga funcionalidad a la paginación\r\n *\r\n * @name _pagenavManagement\r\n * @private\r\n * @function\r\n * @param {Number} numPages Número total de páginas\r\n */\n _pagenavManagement: function _pagenavManagement(numPages) {\n var self = this;\n var opciones = this.options;\n var $pagenavH = opciones._header.pagenav;\n var $pagenavH_prev = opciones._header.pagePrev;\n var $pagenavH_next = opciones._header.pageNext;\n var $pagenavF = opciones._footer.pagenav;\n var $pagenavF_prev = opciones._footer.pagePrev;\n var $pagenavF_next = opciones._footer.pageNext; // Si el número de páginas a mostrar es superior a las configuradas como visibles hay que mostrar el separador\n\n if (numPages > opciones.visiblePages + 1) {\n // Mostrar las páginas visibles antes del separador\n var initPage = 1;\n var endPage = 1;\n\n if (opciones.page >= opciones.visiblePages) {\n if (opciones.page + opciones.visiblePages - 1 > numPages) {\n initPage = numPages - opciones.visiblePages + 1;\n } else {\n initPage = opciones.page - 1;\n } // Se añade la página inicial\n\n\n var $page = $('
' + 1 + '
');\n $page.addClass('rup_list-page-item page-item page');\n $page.attr('tabindex', '0');\n $page.attr('role', 'button');\n $page.attr('aria-controls', self.element.attr('id'));\n $page.attr('aria-label', $.rup.i18nTemplate($.rup.i18n.base.rup_list, 'paginaLabel', 1, numPages));\n $pagenavH.find('.page-separator').first().before($page);\n $pagenavF.find('.page-separator').first().before($page.clone());\n\n if (opciones.page - opciones.visiblePages > 0) {\n // Mostrar el separador de inicio\n $pagenavH.find('.page-separator').first().show();\n $pagenavH.find('.page-separator').first().attr('aria-hidden', 'false');\n $pagenavF.find('.page-separator').first().show();\n $pagenavF.find('.page-separator').first().attr('aria-hidden', 'false');\n }\n }\n\n endPage = initPage + opciones.visiblePages < numPages ? initPage + opciones.visiblePages : numPages + 1;\n\n for (var i = initPage; i < endPage; i++) {\n var _$page = $('
' + i + '
');\n\n _$page.addClass('rup_list-page-item page-item page');\n\n _$page.attr('tabindex', '0');\n\n _$page.attr('role', 'button');\n\n _$page.attr('aria-controls', self.element.attr('id'));\n\n _$page.attr('aria-label', $.rup.i18nTemplate($.rup.i18n.base.rup_list, 'paginaLabel', i, numPages));\n\n $pagenavH.find('.page-separator').last().before(_$page);\n $pagenavF.find('.page-separator').last().before(_$page.clone());\n }\n\n if (opciones.page + opciones.visiblePages - 1 < numPages) {\n // Mostrar el separador de fin\n $pagenavH.find('.page-separator').last().show();\n $pagenavH.find('.page-separator').last().attr('aria-hidden', 'false');\n $pagenavF.find('.page-separator').last().show();\n $pagenavF.find('.page-separator').last().attr('aria-hidden', 'false');\n }\n\n if (endPage < numPages) {\n // Añadir el número de la página final\n var _$page2 = $('
' + numPages + '
');\n\n _$page2.addClass('rup_list-page-item page-item page');\n\n _$page2.attr('tabindex', '0');\n\n _$page2.attr('role', 'button');\n\n _$page2.attr('aria-controls', self.element.attr('id'));\n\n _$page2.attr('aria-label', $.rup.i18nTemplate($.rup.i18n.base.rup_list, 'paginaLabel', numPages, numPages));\n\n $pagenavH.find('.page-separator').last().after(_$page2);\n $pagenavF.find('.page-separator').last().after(_$page2.clone());\n }\n } else {\n // Añadir todas las páginas al nav\n for (var _i4 = numPages; _i4 > 0; _i4--) {\n var _$page3 = $('
' + _i4 + '
');\n\n _$page3.addClass('rup_list-page-item page-item page');\n\n _$page3.attr('tabindex', '0');\n\n _$page3.attr('role', 'button');\n\n _$page3.attr('aria-controls', self.element.attr('id'));\n\n _$page3.attr('aria-label', $.rup.i18nTemplate($.rup.i18n.base.rup_list, 'paginaLabel', _i4, numPages));\n\n $pagenavH_prev.after(_$page3);\n $pagenavF_prev.after(_$page3.clone());\n }\n } // Ocultar el pagenav si sólo se muestra una única página\n\n\n if (numPages > 1) {\n opciones._header.pagenav.show();\n\n if (opciones.createFooter) {\n opciones._footer.pagenav.show();\n }\n } else {\n opciones._header.pagenav.hide();\n\n if (opciones.createFooter) {\n opciones._footer.pagenav.hide();\n }\n }\n\n var $activePageHeader = $('#' + opciones._idListHeader.pagenav + ' ' + '.page[data-page=\"' + opciones.page + '\"]');\n var $activePageFooter = $('#' + opciones._idListFooter.pagenav + ' ' + '.page[data-page=\"' + opciones.page + '\"]'); // Marcar la página actual como activa\n\n $activePageHeader.toggleClass('active');\n $activePageHeader.attr('aria-current', 'true');\n $activePageFooter.toggleClass('active');\n $activePageFooter.attr('aria-current', 'true'); // Funcionamiento del pagenav\n\n $('#' + opciones._idListHeader.pagenav + ' .rup_list-page-item.page, #' + opciones._idListFooter.pagenav + ' .rup_list-page-item.page').on('click', function () {\n var $pageActiveHeader = $('#' + opciones._idListHeader.pagenav + ' .rup_list-page-item.page.active');\n var $pageActiveFooter = $('#' + opciones._idListFooter.pagenav + ' .rup_list-page-item.page.active'); // La página activa se desactiva\n\n $pageActiveHeader.toggleClass('active');\n $pageActiveHeader.attr('aria-current', 'false');\n $pageActiveFooter.toggleClass('active');\n $pageActiveFooter.attr('aria-current', 'false'); // La página seleccionada se activa\n\n $(this).toggleClass('active');\n $(this).attr('aria-current', 'true');\n\n self._changeOption('page', $(this).data('page'));\n });\n\n if (opciones.page > 1) {\n self._enableNavItem($pagenavH_prev);\n\n self._enableNavItem($pagenavF_prev);\n } else {\n self._disableNavItem($pagenavH_prev);\n\n self._disableNavItem($pagenavF_prev);\n }\n\n if (opciones.page < numPages) {\n self._enableNavItem($pagenavH_next);\n\n self._enableNavItem($pagenavF_next);\n } else {\n self._disableNavItem($pagenavH_next);\n\n self._disableNavItem($pagenavF_next);\n }\n },\n\n /**\r\n * Método interno que se encarga de reordenar del servidor\r\n *\r\n * @name _reorderDataFromServer\r\n * @private\r\n * @function\r\n */\n _reorderDataFromServer: function _reorderDataFromServer(self, opciones, xhr) {\n var reorderSelection = xhr.reorderedSelection;\n\n if (reorderSelection !== null && reorderSelection.length > 0 && xhr.records != reorderSelection.length) {\n //Se mira la nueva reordenacion y se ordena.\n opciones.multiselection.selectedIds = [];\n opciones.multiselection.selectedRowsPerPage = []; //Viene del servidor por eso la linea de la pagina es 1 menos.\n\n $.each(reorderSelection, function (index, p) {\n var arra = {\n id: p.pk[opciones.key],\n page: p.page,\n line: p.pageLine - 1\n };\n opciones.multiselection.selectedIds.splice(index, 0, arra.id);\n opciones.multiselection.selectedRowsPerPage.splice(index, 0, arra);\n });\n $('#' + self.element[0].id).triggerHandler('listAfterReorderData', opciones);\n }\n },\n\n /**\r\n * Método interno que se encarga del bloqueo del componente\r\n *\r\n * @name _lock\r\n * @private\r\n * @function\r\n */\n _lock: function _lock() {\n var self = this;\n var opciones = self.options;\n\n if (opciones.isScrollList && opciones.stepOnLoad) {\n $('#' + opciones._idOverlay).remove();\n\n opciones._overlay.css({\n 'position': 'relative',\n 'height': 'auto'\n });\n\n self.element.after(opciones._overlay);\n } else {\n opciones._header.obj.css('opacity', '0.3');\n\n self.element.css('opacity', '0.3');\n\n if (opciones.createFooter) {\n opciones._footer.obj.css('opacity', '0.3');\n }\n\n $('#' + opciones._idOverlay).remove();\n\n opciones._overlay.css({\n 'position': 'absolute'\n });\n\n opciones._content.prepend(opciones._overlay);\n\n opciones._overlay.height(opciones._content.height());\n }\n },\n\n /**\r\n * Método interno que se encarga del desbloqueo del componente\r\n *\r\n * @name _unlock\r\n * @private\r\n * @function\r\n */\n _unlock: function _unlock() {\n var self = this;\n var opciones = self.options;\n\n opciones._header.obj.css('opacity', '1');\n\n self.element.css('opacity', '1');\n\n if (opciones.createFooter) {\n opciones._footer.obj.css('opacity', '1');\n }\n\n $('#' + opciones._idOverlay).remove();\n },\n\n /**\r\n * Método para destruir el componente\r\n *\r\n * @name destroy\r\n * @public\r\n * @function\r\n * @example\r\n * $('#rup-list').rup_list('destroy');\r\n */\n destroy: function destroy() {\n var self = this;\n var opciones = this.options;\n $(self.element).empty();\n\n if (opciones.createFooter) {\n opciones._footer.obj.remove();\n }\n\n opciones.feedback.rup_feedback('destroy');\n $.Widget.prototype.destroy.apply(this, arguments);\n },\n\n /**\r\n * Método interno que se encarga de realizar el filtrado y construir la lista desde los datos recibidos\r\n *\r\n * @name _doFilter\r\n * @private\r\n * @function\r\n */\n _doFilter: function _doFilter() {\n var self = this;\n var opciones = this.options;\n var $itemTemplate = opciones._itemTemplate;\n var $pagenavH = opciones._header.pagenav;\n var $pagenavF = opciones._footer.pagenav; // Validar si la ordenacion es simple o múltiple\n\n var sidx = '';\n var sord = '';\n\n if (opciones.isMultiSort) {\n sidx = opciones.multiorder.sidx;\n sord = opciones.multiorder.sord;\n } else {\n sidx = opciones.sidx.value;\n sord = opciones.sord;\n } // Componer el filtro\n\n\n var filter = {\n filter: $('#' + opciones.filterForm).rup_form('formToJson'),\n page: opciones.page,\n rows: opciones.rowNum.value,\n sidx: sidx,\n sord: sord,\n multiselection: opciones.multiselection,\n core: {\n pkNames: [opciones.key],\n pkToken: '~'\n }\n };\n /**\r\n * SHOW, HIDE\r\n */\n\n if (opciones.show) {\n if (opciones.show.constructor == Object) {\n opciones.show = opciones.show;\n }\n } else if (opciones.show == false) {\n opciones.show = {};\n opciones.animation = false;\n } else {\n opciones.show = {};\n opciones.show.animation = 'drop';\n opciones.show.delay = 200;\n }\n\n if (opciones.hide) {\n if (opciones.hide.constructor == Object) {\n opciones.hide = opciones.hide;\n }\n } else if (opciones.hide == false) {\n opciones.hide = {};\n opciones.animation = false;\n } else {\n opciones.hide = {};\n opciones.hide.animation = 'drop';\n opciones.hide.delay = 200;\n }\n\n if (opciones.btnPrint) {\n if (opciones.btnPrint[0].disabled) {\n opciones.btnPrint[0].disabled = false;\n }\n } // Si hay formulario de filtrado se valida antes de filtrar\n\n\n var canFilter = true;\n\n if ($(\"form[id=\\\"\".concat(opciones.filterForm, \"\\\"]\")).length == 1) {\n canFilter = $('#' + opciones.filterForm).rup_form('valid');\n }\n\n if (canFilter) {\n jQuery.rup_ajax({\n url: opciones.action,\n type: 'POST',\n dataType: 'json',\n data: JSON.stringify(filter),\n contentType: 'application/json',\n success: function success(xhr) {\n $pagenavH.find('.page').remove();\n $pagenavH.find('.page-separator').hide();\n $pagenavH.find('.page-separator').attr('aria-hidden', 'true');\n $pagenavF.find('.page').remove();\n $pagenavF.find('.page-separator').hide();\n $pagenavF.find('.page-separator').attr('aria-hidden', 'true');\n\n if (xhr === null || xhr.length === 0) {\n opciones._header.obj.hide();\n\n self.element.hide();\n\n if (opciones.createFooter) {\n opciones._footer.obj.hide();\n }\n\n opciones.feedback.rup_feedback('set', $.rup.i18n.base.rup_table.errors.errorOnGet, 'error');\n\n opciones._content.slideDown();\n\n self.element.trigger('load');\n $(self.element).attr('aria-live', 'polite');\n self.isFiltering.resolve();\n\n self._unlock();\n } else {\n if (xhr.rows && xhr.rows.length > 0) {\n self._reorderDataFromServer(self, opciones, xhr);\n\n var initRecord = (opciones.page - 1) * parseInt(opciones.rowNum.value) + 1;\n var endRecord = initRecord + xhr.rows.length - 1;\n var records = parseInt(xhr.records) == 0 ? xhr.rows.length : xhr.records;\n opciones.records = records;\n var msgRecords = $.rup.i18nTemplate($.rup.i18n.base.rup_table.defaults, 'recordtext', initRecord, endRecord, records);\n opciones.feedback.rup_feedback({});\n opciones.feedback.rup_feedback('set', msgRecords, 'ok');\n\n self._pagenavManagement(Math.ceil(xhr.records / opciones.rowNum.value));\n\n $.each(xhr.rows, function (index, elem) {\n var $item = $itemTemplate.clone(true, true);\n $item.removeClass('rup_list-itemTemplate');\n $item.addClass('rup_list-item');\n $item.attr('id', $item.attr('id') + '_' + elem[opciones.key]);\n $item.data('all', elem);\n $item.data('pk', elem[opciones.key]);\n var elemArr = $.rup_utils.jsontoarray(elem);\n var elemArrKeys = Object.keys($.rup_utils.jsontoarray(elem));\n\n if (opciones.selectable) {\n var selectorElement = $(opciones.selectable.selector, $item);\n selectorElement.attr('id', selectorElement.attr('id') + '_' + elem[opciones.key]);\n }\n\n if (xhr.reorderedSelection) {\n var tmp = xhr.reorderedSelection.filter(function (arrItem) {\n return arrItem.pk[opciones.key] == elem[opciones.key];\n });\n\n if (tmp.length > 0 && !xhr.selectedAll || tmp.length == 0 && xhr.selectedAll || xhr.records == xhr.reorderedSelection.length) {\n $item.addClass('rup_list-item-selected');\n $item.attr('aria-selected', 'true');\n }\n }\n\n for (var i = 0; i < elemArrKeys.length; ++i) {\n $item.find('[id=\"' + elemArrKeys[i] + '_label\"]').text(opciones.colNames[elemArrKeys[i]] ? opciones.colNames[elemArrKeys[i]] : elemArrKeys[i]).attr('id', elemArrKeys[i] + '_label_' + elem[opciones.key]);\n $item.find('[id=\"' + elemArrKeys[i] + '_value\"]').text(elemArr[elemArrKeys[i]]).attr('id', elemArrKeys[i] + '_value_' + elem[opciones.key]);\n }\n\n $('#' + self.element[0].id).trigger('modElement', [$item, elem]);\n }); // si ha resultados se muestran cabecera/pie y listado\n\n opciones._header.obj.show();\n\n self.element.show();\n\n if (opciones.createFooter) {\n opciones._footer.obj.show();\n } // Si no se está mostrando el content se despliega\n\n\n opciones._content.slideDown();\n\n if (!opciones.content) {\n opciones.content = {};\n }\n\n if (opciones.content.length == 0 || opciones.content.length == undefined) {\n opciones.content = xhr.rows;\n } else {\n if (!opciones.isScrollList) {\n opciones.content = xhr.rows;\n } else {\n var x = opciones.content.length;\n\n for (var i = 0; i < xhr.rows.length; i++) {\n opciones.content[x + i] = xhr.rows[i];\n }\n }\n } // A11Y\n\n\n $('.rup_list-item').attr('role', 'listitem');\n\n if (opciones.selectable) {\n $(opciones.selectable.selector + '.rup_list-item').attr('tabindex', '0');\n $(opciones.selectable.selector + '.rup_list-item').attr('role', 'option');\n }\n } else {\n // Si no se devuelven resultados\n opciones._header.obj.hide();\n\n self.element.hide();\n\n if (opciones.createFooter) {\n opciones._footer.obj.hide();\n }\n\n opciones.feedback.rup_feedback('set', $.rup.i18n.base.rup_table.defaults.emptyrecords, 'alert');\n\n opciones._content.slideDown();\n\n self.element.trigger('load');\n self.isFiltering.resolve();\n\n self._unlock();\n }\n }\n\n if (opciones.isScrollList) {\n $pagenavH.hide();\n $pagenavF.hide();\n }\n\n if (opciones.isHeaderSticky) {\n self._headerSticky.apply(self);\n }\n\n self.element.children().each(function (i, e) {\n setTimeout(function () {\n $(e).show(opciones.show.animation, {}, opciones.show.delay, function () {\n if ($(e).next().length == 0) {\n self.element.css('height', 'auto');\n self.element.trigger('load');\n\n if (opciones.isScrollList && opciones.stepOnLoad) {\n self.isFiltering.resolve();\n\n self._unlock();\n }\n\n if (opciones.isScrollList) {\n self.options.stepLoad = self.element.children().length / self.options.rowNum.value;\n self.options.stepOnLoad = false;\n self.options.stepCounter = 0;\n }\n }\n\n if (i === self.element.children().length - 1 && !opciones.stepOnLoad) {\n $('.rup_list-item').removeAttr('aria-hidden');\n self.isFiltering.resolve();\n\n self._unlock();\n }\n });\n\n if (!opciones.show.animation) {\n if ($(e).next().length == 0) {\n self.element.css('height', 'auto');\n self.element.trigger('load');\n\n if (opciones.isScrollList && opciones.stepOnLoad) {\n self.isFiltering.resolve();\n\n self._unlock();\n }\n\n if (opciones.isScrollList) {\n self.options.stepLoad = self.element.children().length / self.options.rowNum.value;\n self.options.stepOnLoad = false;\n self.options.stepCounter = 0;\n }\n }\n }\n }, 50 + i * 50);\n });\n },\n error: function error(XMLHttpResponse) {\n opciones.feedback.rup_feedback('set', XMLHttpResponse.responseText, 'error');\n\n opciones._header.obj.hide();\n\n self.element.hide();\n\n if (opciones.createFooter) {\n opciones._footer.obj.hide();\n }\n\n opciones._content.slideDown();\n\n self.element.trigger('load');\n self.isFiltering.resolve();\n\n self._unlock();\n }\n });\n } else {\n self.element.trigger('load');\n self.isFiltering.resolve();\n\n self._unlock();\n }\n },\n\n /**\r\n * Método que se encarga de realizar una recarga de la lista\r\n *\r\n * @name reload\r\n * @public\r\n * @function\r\n * @example\r\n * $('#rup-list').rup_list('reload');\r\n */\n reload: function reload() {\n var self = this,\n opciones = self.options;\n $.when(self.isFiltering).done(function () {\n // Reiniciar la promesa de filtrado\n delete self.isFiltering;\n self.isFiltering = $.Deferred();\n\n self._lock();\n\n if (self.element.children().length > 0) {\n // Eliminar el listado actual y buscar el nuevo\n self.element.css('height', self.element.outerHeight() + 16).children().each(function (i, e) {\n setTimeout(function () {\n $(e).hide(opciones.hide.animation, {}, opciones.hide.delay, function () {\n $(this).attr('aria-hidden', 'true');\n $(this).remove(); // Si hemos llegado al último elemento procedemos a buscar el nuevo listado\n\n if (self.element.children().length == 0) {\n self._doFilter();\n }\n });\n }, 50 + i * 50);\n });\n } else {\n self._doFilter();\n }\n });\n },\n\n /**\r\n * Método que se encarga de realizar el filtrado de la lista\r\n *\r\n * @name filter\r\n * @public\r\n * @function\r\n * @example\r\n * $('#rup-list').rup_list('filter');\r\n */\n filter: function filter() {\n var self = this;\n var opciones = this.options;\n opciones.page = 1;\n $.when(self.isFiltering).done(function () {\n // Reiniciar la promesa de filtrado\n delete self.isFiltering;\n self.isFiltering = $.Deferred();\n\n self._lock();\n\n if (self.element.children().length > 0) {\n // Eliminar el listado actual y buscar el nuevo\n self.element.css('height', self.element.outerHeight() + 16).children().each(function (i, e) {\n setTimeout(function () {\n $(e).hide(opciones.hide.animation, {}, opciones.hide.delay, function () {\n $(this).remove();\n $(this).attr('aria-hidden', 'true');\n\n if (opciones.isScrollList) {\n self._deselectAll();\n } // Si hemos llegado al último elemento procedemos a buscar el nuevo listado\n\n\n if (self.element.children().length == 0) {\n self._doFilter();\n }\n });\n }, 50 + i * 50);\n });\n } else {\n self._doFilter();\n }\n });\n },\n\n /**\r\n * Método para cambiar la página actual.\r\n *\r\n * @name page\r\n * @public\r\n * @function\r\n * @param {Number} page La página a la que navegar\r\n * @example\r\n * $('#rup-list').rup_list('page', 3);\r\n */\n page: function page(_page) {\n var self = this;\n\n self._changeOption('page', _page);\n },\n\n /**\r\n * Método que obtiene la información de la selección actual\r\n *\r\n * @name getSelectedIds\r\n * @public\r\n * @function\r\n * @example\r\n * $('#rup-list').rup_list('getSelectedIds');\r\n */\n getSelectedIds: function getSelectedIds() {\n var self = this;\n var options = self.options.multiselection;\n return {\n selectedIds: options.selectedIds,\n selectedAll: options.selectedAll\n };\n }\n });\n});\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../node_modules/webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\"), __webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\")))\n\n//# sourceURL=webpack://rup/./src/rup.list.js?");
/***/ }),
@@ -8546,7 +8546,7 @@ eval("var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPAC
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
-eval("/* WEBPACK VAR INJECTION */(function(jQuery, global, $) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\n/* eslint-disable no-useless-escape */\n\n/*!\r\n * Copyright 2021 E.J.I.E., S.A.\r\n *\r\n * Licencia con arreglo a la EUPL, Versión 1.1 exclusivamente (la «Licencia»);\r\n * Solo podrá usarse esta obra si se respeta la Licencia.\r\n * Puede obtenerse una copia de la Licencia en\r\n *\r\n * http://ec.europa.eu/idabc/eupl.html\r\n *\r\n * Salvo cuando lo exija la legislación aplicable o se acuerde por escrito,\r\n * el programa distribuido con arreglo a la Licencia se distribuye «TAL CUAL»,\r\n * SIN GARANTÍAS NI CONDICIONES DE NINGÚN TIPO, ni expresas ni implícitas.\r\n * Véase la Licencia en el idioma concreto que rige los permisos y limitaciones\r\n * que establece la Licencia.\r\n */\n\n/**\r\n * Permite al usuario recuperar un elemento de una gran lista de elementos o de\r\n * varias listas dependientes de forma sencilla y ocupando poco espacio en la\r\n * interfaz.\r\n * \r\n * @summary Componente RUP Select.\r\n * @module rup_select\r\n * @see El componente está basado en el plugin\r\n * {@link https://select2.org//|Select2}. Para mas información acerca de\r\n * las funcionalidades y opciones de configuración pinche\r\n * {@link https://select2.org//|aquí}.\r\n * @example $(\"#idSelect\").rup_select({ source : \"selectSimple/remote\",\r\n * sourceParam : {label:\"desc\"+$.rup_utils.capitalizedLang(),\r\n * value:\"code\", style:\"css\"} });\r\n */\n\n/* global define */\n\n/* global jQuery */\n(function (factory) {\n if (true) {\n // AMD. Register as an anonymous module.\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\"), __webpack_require__(/*! ./rup.base */ \"./src/rup.base.js\"), __webpack_require__(/*! select2 */ \"./node_modules/select2/dist/js/select2.js\"), __webpack_require__(/*! ./external/select2MultiCheckboxes */ \"./src/external/select2MultiCheckboxes.js\")], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?\n\t\t\t\t(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n } else {}\n})(function ($) {\n // ****************************************************************************************************************\n // DEFINICIÓN BASE DEL PATRÁN (definición de la variable privada que\n // contendrá los métodos y la función de jQuery)\n // ****************************************************************************************************************\n var rup_select = {};\n var FUNCTION_NOT_SUPPORTED_ERROR_MESSAGE = $.rup.i18nParse($.rup.i18n.base, 'rup_global.functionNotSupportedError');\n var FUNCTION_NOT_SUPPORTED_ERROR_TITLE = $.rup.i18nParse($.rup.i18n.base, 'rup_global.error'); // Se configura el arranque de UDA para que alberge el nuevo patrón\n\n $.extend($.rup.iniRup, $.rup.rupSelectorObjectConstructor('rup_select', rup_select)); // *******************************\n // DEFINICIÓN DE MÉTODOS PÚBLICOS\n // *******************************\n\n $.fn.rup_select('extend', {\n /**\r\n * Método utilizado para obtener el valor del componente. Este método es\r\n * el utilizado por el resto de componentes RUP para estandarizar la\r\n * obtención del valor del select.\r\n * \r\n * @function getRupValue\r\n * @return {string | number} - Devuelve el valor actual del componente\r\n * seleccionado por el usuario.\r\n * @example $(\"#idSelect\").rup_select(\"getRupValue\");\r\n */\n getRupValue: function getRupValue() {\n var $self = $(this),\n settings = $self.data('settings'),\n value;\n var values = $self.select2('data');\n\n if (values == undefined || values.length == 0) {\n value = '';\n } else if (values.length == 1) {\n value = values[0].id;\n } else {\n value = [];\n $.each(values, function (ind, elem) {\n value.push(elem.id);\n });\n }\n\n if (settings !== undefined && settings.submitAsJSON !== undefined && settings.submitAsJSON) {\n var name = $self.attr('name');\n\n if (name == undefined) {\n name = $self.attr('id');\n }\n\n return jQuery.rup_utils.getRupValueAsJson(name, value);\n }\n\n return value;\n },\n\n /**\r\n * Método utilizado para asignar el valor al componente. Este método es\r\n * el utilizado por el resto de componentes RUP para estandarizar la\r\n * asignación del valor al Select.\r\n * \r\n * @function setRupValue\r\n * @param {string |\r\n * number} param - Valor que se va a asignar al componente.\r\n * @example $(\"#idSelect\").rup_select('setRupValue', 'Si');\r\n */\n setRupValue: function setRupValue(param) {\n var $self = $(this),\n settings = $self.data('settings'); // Tipo de select\n\n if (this.length === 0 || settings !== undefined && !settings.multiple) {\n var texto = undefined; // normal.\n // Simple\n\n if (settings !== undefined && settings.data === undefined && settings.options !== undefined) {\n // si\n // es\n // remoto\n // crear\n // el\n // option\n var data = {};\n\n if (settings.groups) {\n data = $.grep(settings.optionsGroups, function (v) {\n return v.nid === param || v.id == param;\n });\n } else {\n data = $.grep(settings.options, function (v) {\n return v.nid === param || v.id == param;\n });\n }\n\n if (data[0] !== undefined) {\n if ($('#' + settings.id).find(\"option[value='\" + data[0].id + \"']\").length == 0) {\n data = data[0];\n\n _this._createOption(settings, data);\n\n param = data.id; // mantenga el cifrado\n\n texto = data.text;\n } else {\n param = data[0].id; // mantenga el cifrado\n\n texto = data[0].text;\n }\n }\n }\n\n var dataSelect2 = $self.data('select2');\n\n if (dataSelect2 !== undefined) {\n if (dataSelect2.$selection.find('input').length == 1) {\n dataSelect2.$selection.find('input').val('');\n }\n\n var $search = dataSelect2.dropdown.$search || dataSelect2.selection.$search;\n\n if ($search != undefined && texto !== undefined) {\n //sifnifica que esta abierto\n var lis = dataSelect2.dropdown.$dropdown.find('li');\n var selectedDate = $.grep(lis, function (v) {\n return $(v).text() === texto;\n });\n lis.attr('aria-selected', false);\n $(selectedDate).attr('aria-selected', true);\n }\n\n $self.val(param).trigger('change');\n $('#' + settings.id).rup_select('change');\n }\n } else {\n // Multiple > multiselect - falta\n if (_typeof(param) === 'object' && settings.options !== undefined) {\n // si\n // es\n // remoto\n // crear\n // el\n // option\n var arrayDatos = [];\n $.each(param, function (key, value) {\n var data = {};\n\n if (settings.groups) {\n data = $.grep(settings.optionsGroups, function (v) {\n return v.nid === value || v.id == value;\n });\n } else {\n data = $.grep(settings.options, function (v) {\n return v.nid === value || v.id == value;\n });\n }\n\n if (data[0] != undefined && $('#' + settings.id).find(\"option[value='\" + data[0].id + \"']\").length == 0) {\n data = data[0];\n\n _this._createOption(settings, data);\n\n arrayDatos.push(data.id);\n } else {\n arrayDatos.push(value);\n }\n });\n $('#' + settings.id).val(arrayDatos).trigger('change');\n }\n }\n },\n\n /**\r\n * Método que limpia el valor seleccionado en el select. En el caso de\r\n * selección múltiple los valores seleccionados.\r\n * \r\n * @function clear\r\n * @example $(\"#idSelect\").rup_select(\"clear\");\r\n */\n clear: function clear() {\n var $self = $(this); // init de select\n\n if (this.length > 0) {\n // Simple y multi\n if ($self.data('settings').blank !== undefined) {\n $self.val($self.data('settings').blank).trigger('change');\n } else {\n $self.val(null).trigger('change');\n }\n }\n },\n\n /**\r\n * Método que lanza el evento change del componente.\r\n * \r\n * @function change\r\n * @example $(\"#idSelect\").rup_select(\"change\");\r\n */\n change: function change() {\n // Tipo de select\n if ($(this).data('settings').change) {\n $(this).data('settings').change();\n }\n },\n\n /**\r\n * Selecciona todos los elementos en el caso de tratarse de un select\r\n * multilesección.\r\n * \r\n * @function checkAll\r\n * @example $(\"#idSelect\").rup_select(\"checkAll\");\r\n */\n checkAll: function checkAll() {\n // Tipo de select\n if ($(this).data('settings').multiple) {\n // Multiple > multiselect\n var selectedItems = [];\n var allOptions = $(\"#\" + $(this)[0].id + \" option\");\n allOptions.each(function () {\n selectedItems.push($(this).val());\n });\n $(this).rup_select('setRupValue', selectedItems);\n } else {\n // Simple > selectmenu\n alert('Función no soportada.');\n }\n },\n\n /**\r\n * Selecciona el elemento del select que contiene como texto el\r\n * indicado. En caso de no existir el texto a buscar el se no sufrirá\r\n * cambios En el caso de selección múltiple el parámetro será un array.\r\n * \r\n * @function selectByLabel\r\n * @param {string |\r\n * string[]} param - Parámetro utilzado para determinar los\r\n * elementos a seleccionar.\r\n * @example // Simple $(\"#idSelect\").rup_select(\"selectByLabel\", \"No\"); //\r\n * Multiple $(\"#idSelect\").rup_select(\"selectByLabel\",\r\n * [\"No\",\"Si\"]);\r\n */\n selectByLabel: function selectByLabel(param) {\n // Tipo de select\n var settings = $(this).data('settings');\n\n if (settings.options !== undefined) {\n var options = settings.options;\n\n if (settings.groups) {\n options = settings.optionsGroups;\n }\n\n if (!settings.multiple) {\n // Simple > selectmenu\n var data = $.grep(options, function (v) {\n return v.text === param;\n });\n\n if (data[0] !== undefined) {\n $(this).rup_select('setRupValue', data[0].id);\n }\n } else {\n // Ejemplo\n // $('#idSelect').rup_select('selectByLabel',['php_value','java_value'])\n var datos = [];\n $.each(param, function (key, value) {\n var data = $.grep(options, function (v) {\n return v.text === value;\n });\n\n if (data[0] !== undefined) {\n datos.push(data[0].id);\n }\n });\n $(this).rup_select('setRupValue', datos);\n }\n }\n },\n\n /**\r\n * Selecciona el elemento enviado como parámetro. En caso de ser un numérico se selecciona por la posición (comenzando en 0) y si es un literal se selecciona por el valor. En el caso de selección múltiple el parámetro será un array.\r\n *\r\n * @function select\r\n * @param {string | number | string[] | number[]} param - Parámetro utilzado para determinar los elementos a seleccionar.\r\n * @example\r\n * // Simple\r\n * $(\"#idSelect\").rup_select(\"select\", 2);\r\n * // Multiple\r\n * $(\"#idSelect\").rup_select(\"select\", [0,2]);\r\n */\n select: function select(param) {\n var settings = $(this).data().settings;\n var datas = settings.data || settings.options;\n\n if (settings.groups) {\n datas = settings.optionsGroups;\n }\n\n if (settings.multiple) {\n var datos = [];\n $.each(param, function (key, value) {\n if (datas.length >= value) {\n datos.push(datas[value].id);\n }\n });\n $(this).rup_select('setRupValue', datos);\n } else {\n if (datas.length >= param) {\n $(this).rup_select('setRupValue', datas[param].id);\n }\n }\n },\n\n /**\r\n * Método que devuelve el label asociado al valor seleccionado en el\r\n * select. En el caso de la selección múltiple se devolverá un array.\r\n * \r\n * @function label\r\n * @return {string | string[]} - Texto del elemento o elementos\r\n * seleccionado.\r\n * @example $(\"#idSelect\").rup_select(\"label\");\r\n */\n label: function label() {\n // Tipo de select\n var data = $(this).select2('data');\n\n if (!$(this).data('settings').multiple) {\n return data[0].text;\n } else {\n // Multiple > multiselect\n var retorno = [];\n\n for (var i = 0; i < data.length; i++) {\n retorno.push(data[i].text);\n }\n\n return retorno;\n }\n },\n\n /**\r\n * Devuelve el índice de la opción seleccionada en el select (empezando\r\n * en 1). En el caso de la selección múltiple se devolverá un array.\r\n * \r\n * @function index\r\n * @return {number | number[]} - Índice del elemento o elementos\r\n * seleccionados.\r\n * @example $(\"#idSelect\").rup_select(\"index\");\r\n */\n index: function index() {\n // Tipo de select\n var settings = $(this).data('settings');\n\n if (settings.options !== undefined) {\n var options = settings.options;\n\n if (settings.groups) {\n options = settings.optionsGroups;\n }\n\n var count = 0;\n var data = $(this).select2('data');\n\n if (!settings.multiple) {\n // Simple > selectmenu\n $.each(options, function (key, value) {\n if (settings.blank !== value.id.toString()) {\n count = count + 1;\n }\n\n if (value.id.toString() === data[0].id.toString()) {\n return false;\n }\n });\n } else {\n var listaCount = [];\n $.each(data, function (key, value) {\n count = 0;\n $.each(options, function (cont, valor) {\n if (settings.blank !== value.id.toString()) {\n count = count + 1;\n }\n\n if (value.id.toString() === valor.id.toString()) {\n listaCount.push(count);\n return false;\n }\n });\n });\n return listaCount;\n }\n\n return count;\n }\n },\n\n /**\r\n * Deshabilita el select.\r\n * \r\n * @function disable\r\n * @example $(\"#idSelect\").rup_select(\"disable\");\r\n */\n disable: function disable() {\n // Tipo de select\n var $self = $(this);\n $self.prop(\"disabled\", true);\n },\n\n /**\r\n * Habilita el select.\r\n * \r\n * @function enable\r\n * @example $(\"#idSelect\").rup_select(\"enable\");\r\n */\n enable: function enable() {\n var $self = $(this);\n $self.prop(\"disabled\", false);\n },\n\n /**\r\n * Indica si el select está deshabilitado o no.\r\n * \r\n * @function isDisabled\r\n * @param {boolean} -\r\n * Devuelve si el select está deshabilitado o no.\r\n * @example $(\"#idSelect\").rup_select(\"isDisabled\");\r\n */\n isDisabled: function isDisabled() {\n if ($(this).attr('disabled') === 'disabled') {\n return true;\n } else {\n return false;\n }\n },\n\n /**\r\n * Realiza una recarga de los select.\r\n * \r\n * @function reload\r\n * @example $(\"#idSelect\").rup_select(\"reload\");\r\n */\n reload: function reload(removeOptions) {\n var settings = $(this).data('settings');\n $(this).select2(\"destroy\");\n\n if (removeOptions) {\n $(this).find('option').remove();\n }\n\n $(this).rup_select(settings);\n },\n\n /**\r\n * Cambia el source del select y recarga el componente para que este\r\n * comience a usarlo.\r\n * \r\n * @function setSource\r\n * @param {string}\r\n * source - Source desde el cual se obtendran los datos a\r\n * sourceParam - Se puede cambiar los parámetros de la cabecera..\r\n * @example $(\"#idSelect\").rup_select(\"setSource\", source, sourceParam);\r\n */\n setSource: function setSource(source, sourceParam) {\n if (source !== undefined && source !== '') {\n var $self = $(this);\n var settings = $self.data().settings;\n var dataSelect2 = $self.data('select2');\n\n if ($self.data().settings.data === undefined) {\n // remoto\n dataSelect2.dataAdapter.ajaxOptions.url = source;\n\n if (sourceParam != undefined) {\n dataSelect2.dataAdapter.ajaxOptions.headers = $.toJSON(sourceParam);\n }\n } else {\n // local\n settings.data = source;\n settings.options = undefined;\n $self.data('settings', settings);\n\n if (dataSelect2.$selection != undefined) {\n dataSelect2.$selection.find('input').val('');\n }\n\n $self.empty();\n\n if (settings.data !== undefined && settings.autocomplete) {\n $.each(settings.data, function () {\n _this._createOption(settings, this);\n });\n } else {\n $self.select2({\n data: settings.data\n });\n }\n }\n }\n },\n\n /**\r\n * Método que devuelve los datos, de los elementos seleccionados.\r\n * \r\n * @function getDataSelected\r\n * @return {string | string[]} - Texto del elemento o elementos\r\n * seleccionado.\r\n * @example $(\"#idSelect\").rup_select(\"label\");\r\n */\n getDataSelected: function getDataSelected() {\n // Tipo de select\n var data = $(this).select2('data');\n\n if (!$(this).data('settings').multiple) {\n //Validar que venga el nid\n if (data[0] != undefined && data[0].nid == undefined && $(this).data('settings').options != undefined) {\n var seleccionado = $.grep($(this).data('settings').options, function (v, index) {\n return v.id === data[0].id;\n });\n\n if (seleccionado != undefined && seleccionado.length == 1) {\n data[0].nid = seleccionado[0].nid;\n }\n }\n\n return data[0];\n } else {\n return data;\n }\n },\n\n /**\r\n * Método que añade un option al select en local\r\n * \r\n * @function addOption\r\n * id:\tidentificador del nuevo option\r\n * text: texto del nuevo option\r\n * label: en Caso de ser grupos, el label donde se va a meter(obligatorio)\r\n * @example $(\"#idSelect\").rup_select(\"label\");\r\n */\n addOption: function addOption(id, text, label) {\n // Tipo de select\n var newOpt = new Option(id, text);\n\n if ($(this).data('settings').groups && label != undefined) {\n var options = $(this).data('select2').options.options;\n $(this).find('optgroup[label=\"' + label + '\"]').append(newOpt);\n var seleccionado = $.grep(options.data, function (v, index) {\n return v.text === label;\n });\n\n if (seleccionado != undefined && seleccionado.length == 1) {\n seleccionado[0].children[seleccionado[0].children.length] = {\n id: id,\n text: text\n };\n }\n } else {\n $(this).append(newOpt);\n }\n },\n\n /**\r\n * Deshabilita una opción de un select multiselección.\r\n *\r\n * @function disableOpt\r\n * @param {string} optValue - Value del option que queremos deshabilitar.\r\n * @example\r\n * $(\"#idSelect\").rup_select(\"disableOpt\", \"opt1\");\r\n */\n disableOpt: function disableOpt(optValue) {\n if ($(this).data('settings').multiple) {\n //Deshabilitar select\n this.find('[value=\\'' + optValue + '\\']').attr('disabled', 'disabled'); //Si pertenece a OptGroup y es el último en deshabilitarse > Cambiar estilos optGroupLabel\n\n if ($(this).data('settings').sourceGroup != undefined) {\n //Obtener inicio optGroup\n var li = obj.parentsUntil('ul').last().prevAll('li.ui-multiselect-optgroup-label').first(),\n inputs = li.nextUntil('li.ui-multiselect-optgroup-label').find('input'),\n allDisabled = true;\n\n for (var i = 0; i < inputs.length; i++) {\n if (!inputs[i].disabled) {\n allDisabled = false;\n break;\n }\n }\n\n if (allDisabled) {\n //Estilos optGroup\n li.css('color', 'grey');\n li.children('a').remove();\n li.children('span').not('.rup-combo_multiOptgroupLabel').remove();\n }\n }\n } else {\n $.rup.errorGestor(FUNCTION_NOT_SUPPORTED_ERROR_MESSAGE, FUNCTION_NOT_SUPPORTED_ERROR_TITLE);\n }\n },\n\n /**\r\n * Deshabilita varias opciones del select. Las opciones se identifican mediante un array.\r\n *\r\n * @function disableOptArr\r\n * @param {string[]} optValueArr - Array en el que se indican los values de las opciones a deshabilitar.\r\n * @example\r\n * $(\"#idSelect\").rup_select(\"disableOptArr\", [\"opt1\",\"opt2\"]);\r\n */\n disableOptArr: function disableOptArr(optValueArr) {\n if ($(this).data('settings').multiple) {\n for (var i = 0; i < optValueArr.length; i++) {\n $(this).rup_select('disableOpt', optValueArr[i]);\n }\n } else {\n $.rup.errorGestor(FUNCTION_NOT_SUPPORTED_ERROR_MESSAGE, FUNCTION_NOT_SUPPORTED_ERROR_TITLE);\n }\n },\n\n /**\r\n * Habilita una opción de un select multiselección.\r\n *\r\n * @function enableOpt\r\n * @param {string} enableOpt - Value del option que queremos habilitar.\r\n * @example\r\n * $(\"#idSelect\").rup_select(\"enableOpt\", \"opt1\");\r\n */\n enableOpt: function enableOpt(optValue) {\n if ($(this).data('settings').multiple) {\n //Habilitar select\n this.find('[value=\\'' + optValue + '\\']').removeAttr('disabled');\n var obj = $('#rup-multiCombo_' + $(this).attr('id')).find('[value=\\'' + optValue + '\\']'); //Habilitar input\n\n obj.removeAttr('disabled'); //Estilos línea (label)\n\n obj.parent().css('color', 'black'); //Si pertenece a OptGroup y es el primero en habilitarse > Cambiar estilos optGroupLabel\n\n if ($(this).data('settings').sourceGroup != undefined) {\n //Obtener inicio optGroup\n var li = obj.parentsUntil('ul').last().prevAll('li.ui-multiselect-optgroup-label').first(); //Estilos optGroup\n\n if (li.children('a').length === 0) {\n li.css('color', 'black');\n\n this._generateOptGroupLabel(li, $(this).data('settings').multiOptgroupIconText);\n }\n }\n } else {\n $.rup.errorGestor(FUNCTION_NOT_SUPPORTED_ERROR_MESSAGE, FUNCTION_NOT_SUPPORTED_ERROR_TITLE);\n }\n },\n\n /**\r\n * Habilita varias opciones del select. Las opciones se identifican mediante un array.\r\n *\r\n * @function enableOptArr\r\n * @param {string[]} optValueArr - Array en el que se indican los values de las opciones a habilitar.\r\n * @example\r\n * $(\"#idSelect\").rup_select(\"enableOptArr\", [\"opt1\",\"opt2\"]);\r\n */\n enableOptArr: function enableOptArr(optValueArr) {\n if ($(this).data('settings').multiple) {\n for (var i = 0; i < optValueArr.length; i++) {\n $(this).rup_select('enableOpt', optValueArr[i]);\n }\n } else {\n $.rup.errorGestor(FUNCTION_NOT_SUPPORTED_ERROR_MESSAGE, FUNCTION_NOT_SUPPORTED_ERROR_TITLE);\n }\n },\n\n /**\r\n * Ordena alfanumericamente y en orden ascendente el combo sobre el que se aplica. Se invoca por defecto al cargarse los combos a no ser que se cambie el valor del atributo ordered en la creación.\r\n *\r\n * @function order\r\n * @param {boolean} orderedByValue - Indica si la búsqueda es por texto (por defecto) o si la búsqueda es por el valor.\r\n * @param {boolean} orderAsNumber - Indica si se debe ordenar como valores numéricos en vez de alfabéticos.\r\n * @param {boolean} skipFirst - Determina si se debe obviar el primer elemento.\r\n * @example\r\n * $(\"#idSelect\").rup_select(\"order\", orderedByValue, orderAsNumber, skipFirst);\r\n */\n order: function order(groups, orderedByValue, orderAsNumber) {\n /* Get options */\n var selector = $(this).data('select2') || $(this).parent().data('select2');\n var settings = selector.options.options;\n\n if (groups) {\n $(this).find('optgroup').each(function () {\n $(this).rup_select('order', false, orderedByValue, orderAsNumber);\n }); //Order children\n\n if (settings.data != undefined) {\n $(settings.data).each(function () {\n if (this.children != undefined && this.children.length > 0) {\n this.children = this.children.sort(function (a, b) {\n return a.text.localeCompare(b.text);\n });\n }\n });\n }\n } else {\n var selectList = $(this).find('option').not('[value=' + settings.blank + ']');\n var option = $(this).find('option[value=' + settings.blank + ']');\n /* Order by innerText (case insensitive) */\n\n selectList.sort(function (a, b) {\n return a.innerText.localeCompare(b.innerText);\n });\n /* Re-do select HTML */\n\n $(this).html(selectList);\n\n if (option.length == 1) {\n $(this).prepend(option);\n }\n }\n },\n\n /**\r\n * Lanza una búsqueda en el autocomplete con el parámetro indicado y el foco va a parar al input.\r\n *\r\n * @param {string} term - Cadena de texto utilizada para realizar la búsqueda.\r\n * @param {boolean} notOthersClose - Si deseas cerrar el resto de componentes.\r\n * @function search\r\n * \r\n * @example\r\n * $(\"#idSelect\").rup_select(\"search\", \"java\");\r\n */\n search: function search(term, notOthersClose) {\n var $search = $(this).data('select2').dropdown.$search || $(this).data('select2').mySelect.selection.$search;\n\n if (!notOthersClose) {\n $('.select2-hidden-accessible').select2('close');\n }\n\n $(this).data('select2').$container.find('input').val(term);\n\n if ($search != undefined) {\n $search.val(term);\n $search.trigger('keyup');\n }\n },\n\n /**\r\n * Permite consultar y modificar la configuración del componente.\r\n *\r\n * @param {string | object} optionName - Nombre de la propiedad que se desea gestionar o objeto de compuesto de varias propiedades.\r\n * @param {*} [value] - Corresponde al valor de la propiedad en caso de haberse especificado el nombre de la misma en el primér parámetro.\r\n * @param {*} aux - Parámetro extra de confirguración para la propiedad \"source\".\r\n * @function option\r\n * @example\r\n * // Establecer una propiedad\r\n * $(\"#idSelect\").rup_select(\"option\", \"minLegth\", 2);\r\n * // Establecer varias propiedad\r\n * $(\"#idSelect\").rup_select(\"option\", {minLegth:2, delay:1000});\r\n */\n option: function option(optionName, value, removeOptions) {\n var settings = $(this).data('settings');\n settings[optionName] = value;\n $(this).select2(\"destroy\");\n\n if (removeOptions) {\n $(this).find('option').remove();\n }\n\n $(this).rup_select(settings);\n },\n\n /**\r\n * Permite abrir el componente.\r\n *\r\n * @param {boolean} notOthersClose - Si deseas cerrar el resto de componentes.\r\n * @function open\r\n * @example\r\n * // Establecer una propiedad\r\n * $(\"#idSelect\").rup_select(\"option\", true);\r\n */\n open: function open(notOthersClose) {\n if (!notOthersClose) {\n $('.select2-hidden-accessible').select2('close');\n }\n\n $(this).select2('open');\n },\n\n /**\r\n * Permite cerrar el componente.\r\n *\r\n * @param {boolean} notOthersClose - Si deseas cerrar el resto de componentes.\r\n * @function close\r\n * @example\r\n * // Establecer una propiedad\r\n * $(\"#idSelect\").rup_select(\"option\", true);\r\n */\n close: function close(notOthersClose) {\n if (!notOthersClose) {\n $('.select2-hidden-accessible').select2('close');\n }\n\n $(this).select2('close');\n },\n\n /**\r\n * Elimina el autocomplete.\r\n *\r\n * @function destroy\r\n * @example\r\n * $(\"#idSelect\").rup_select(\"destroy\");\r\n */\n destroy: function destroy(notRemoveOptions) {\n $(this).select2(\"destroy\");\n\n if (!notRemoveOptions) {\n $(this).find('option').remove();\n }\n }\n }); // *******************************\n // DEFINICIÓN DE MÉTODOS PRIVADOS\n // *******************************\n\n $.fn.rup_select('extend', {\n /**\r\n * Selecciona el elemento correspondiente al label indicado\r\n * \r\n * @function _selectLabel\r\n * @private\r\n * @param {object}\r\n * selector - Referencia al objeto jQuery del select.\r\n * @param {object}\r\n * param - Value correspondiente.\r\n */\n _selectLabel: function _selectLabel(selector, param) {\n var $option;\n\n for (var i = 0; i < $('option', selector).length; i = i + 1) {\n $option = jQuery(selector).find('option').eq(i);\n\n if (jQuery(selector).find('option').eq(i).text() === param) {\n $(selector).selectmenu('index', $option.prop('index'));\n return true;\n }\n }\n\n return false;\n },\n\n /**\r\n * Obtener la opción vacía a partir del fichero de internacionalización\r\n * de la aplicación o del fichero por defecto.\r\n * \r\n * @function _getBlankLabel\r\n * @private\r\n * @param {string}\r\n * id - Identificador del fichero\r\n */\n _getBlankLabel: function _getBlankLabel(id) {\n var app = $.rup.i18n.app; // Comprueba si el select tiene su propio texto personalizado\n\n if (app[id] && app[id]._blank) {\n return app[id]._blank;\n } // Comprueba si la aplicacion tiene un texto definido para todos los\n // blank\n else if (app.rup_select && app.rup_select.blank) {\n return app.rup_select.blank;\n } // Si no hay textos definidos para los blank obtiene el por defecto\n // de UDA\n\n\n return $.rup.i18n.base.rup_select.blankNotDefined;\n },\n\n /**\r\n * Obtener valores de los selects padres (si no están cargados o valores\r\n * 'vacíos' devuelve null). En caso de disponer de varios selects padres\r\n * se devolverán separados por un caracter delimitador.\r\n * \r\n * @function _getParentsValues\r\n * @private\r\n * @param {object[]}\r\n * settings - Array con los elementos de configuración.\r\n * @param {boolean}\r\n * remote - Determina si la fuente de datos es remota o no.\r\n * @return {string} - Devuelve los values seleccionados de los selects\r\n * padres.\r\n */\n _getParentsValues: function _getParentsValues(settings, remote, multiValueToken) {\n var retorno = '';\n var parent = [];\n\n if (settings.parent == undefined) {\n return '';\n }\n\n if (typeof settings.parent == 'string') {\n parent.push(settings.parent);\n } else {\n parent = settings.parent;\n }\n\n var parentsFull = 0;\n $.each(parent, function (idx, parentId) {\n if (parentId != undefined && $('#' + parentId).val() != null && $('#' + parentId).val().trim() !== '') {\n if (settings.blank == $('#' + parentId).val()) {\n retorno = '';\n } else {\n if (remote) {\n // PAra remoto\n retorno += $('#' + parentId).attr('name') + '=' + $('#' + parentId).val() + '&';\n } else {\n // PAra local\n if (retorno != '') {\n retorno = retorno + multiValueToken + $('#' + parentId).val();\n } else {\n retorno = $('#' + parentId).val();\n }\n }\n\n parentsFull = parentsFull + 1;\n }\n }\n });\n\n if (parentsFull < parent.length) {\n // si no estan todos los padres no\n // se busca.\n return '';\n } // Evitar & o multiValueToken finales\n\n\n if (retorno !== '' && remote) {\n retorno = retorno.substring(0, retorno.length - 1);\n }\n\n return retorno;\n },\n\n /**\r\n * Procesa el conjunto de registros devueltos por una petición sobre un\r\n * origen de datos local.\r\n * \r\n * @function _parseLOCAL\r\n * @private\r\n * @param {object[]}\r\n * data - Array de registros obtenidos a partir del origen de\r\n * datos.\r\n * @param {object}\r\n * i18nId - Opciones de idioma.\r\n * @param {jQuery}\r\n * isParent - Si tiene datos en forma parent.\r\n */\n _parseLOCAL: function _parseLOCAL(data, i18nId, isParent) {\n var text;\n var array = data;\n\n if (isParent) {\n // Si es padre llamar a la recursividad\n if (Array.isArray(data)) {\n data = data[0];\n }\n\n $.each(data, function (key, value) {\n data[key] = _this._parseLOCAL(data[key], i18nId, false);\n });\n } else {\n data = [];\n\n for (var i = 0; i < array.length; i = i + 1) {\n if (_typeof(array[i]) === 'object') {\n // multi-idioma\n if (array[i].i18nCaption) {\n text = $.rup.i18nParse($.rup.i18n.app[i18nId], array[i].i18nCaption);\n } else {\n text = array[i].text;\n }\n\n array[i].text = text;\n } else {\n // El id es el mismo que el texto.\n data[i] = {\n id: array[i],\n text: array[i]\n };\n }\n }\n\n if (data.length > 0) {\n // El id es el mismo que el texto.\n return data;\n }\n }\n\n return array;\n },\n\n /**\r\n * Procesa el conjunto de registros devueltos por una petición sobre un\r\n * origen de datos remoto.\r\n * \r\n * @function _parseRemoteGroup\r\n * @private\r\n * @param {object[]}\r\n * array - Array de registros obtenidos a partir del origen\r\n * de datos.\r\n * @param {object}\r\n * settings - Objeto de propiedades de configuración con el\r\n * que se ha inicializado el componente.\r\n */\n _parseRemoteGroup: function _parseRemoteGroup(array, settings) {\n var item;\n var data = [];\n\n for (var i = 0; i < array.length; i = i + 1) {\n item = array[i];\n var key = Object.keys(item)[0];\n var dato = {};\n dato.text = key;\n dato.children = item[key];\n dato.id = \"group__\" + i;\n data.push(dato);\n }\n\n return data;\n },\n\n /**\r\n * Prepara la petición AJAX que se va a realizar para obtener los\r\n * registros a partir de un origen remoto. Se añaden las cabeceras RUP\r\n * correspondientes para realizar la serialización json de manera\r\n * correcta.\r\n * \r\n * @function _ajaxBeforeSend\r\n * @private\r\n * @param {object}\r\n * xhr - Objeto xhr que se va a enviar en la petición\r\n * @param {object}\r\n * settings - Objeto de propiedades de configuración con el\r\n * que se ha inicializado el componente.\r\n * @param {jQuery}\r\n * html - Referencia al objeto jQuery que contiene los\r\n * elementos.\r\n */\n _ajaxBeforeSend: function _ajaxBeforeSend(xhr, settings, html) {\n // Crear select (vacío) y deshabilitarlo\n if (html !== undefined) {\n $('#' + settings.id).replaceWith(html);\n } // Si no es 'reload' se debe inicializar vacío\n\n\n $('#' + settings.id).rup_select('disable'); // LOADING...\n\n $('#' + settings.id + '-button span:first-child').removeClass(\"ui-icon ui-icon-triangle-1-s\").addClass('rup-select_loadingText').text($.rup.i18n.base.rup_select.loadingText);\n var icon = $('#' + settings.id + '-button span:last-child');\n $(icon).removeClass('ui-icon-triangle-1-s');\n $(icon).text(''); // Evita errores de visualización con el icono\n\n $(icon).addClass('rup-select_loading'); // Cabecera RUP\n\n xhr.setRequestHeader('RUP', $.toJSON(settings.sourceParam));\n },\n\n /**\r\n * Procesa la respuesta de la petición AJAX en el caso de que se haya\r\n * producido un error en la misma.\r\n * \r\n * @function _ajaxError\r\n * @private\r\n * @param {object}\r\n * xhr - Objeto xhr enviado en la respuesta.\r\n * @param {string}\r\n * textStatus - Cadena identificadora del error que se ha\r\n * producido en la petición.\r\n * @param {object}\r\n * errorThrown - Objeto error correspondiente al que se ha\r\n * producido en la petición.\r\n * @param {object}\r\n * settings - Objeto de propiedades de configuración con el\r\n * que se ha inicializado el componente.\r\n */\n _ajaxError: function _ajaxError(xhr) {\n if (xhr.responseText !== null && xhr.responseTex !== undefined && xhr.responseText.length < 200) {\n $.rup.showErrorToUser(xhr.responseText);\n } else {\n $.rup.showErrorToUser($.rup.i18n.base.rup_select.ajaxError);\n }\n },\n\n /**\r\n * Carga la opción remoto.\r\n * \r\n * @function _loadRemote\r\n * @private\r\n * @param {object}\r\n * settings - Objeto de propiedades de configuración con\r\n * el que se ha inicializado el componente.\r\n * @return {jQuery} - Objeto jQuery con referencia al elemento que\r\n * contiene el foco.\r\n */\n _loadRemote: function _loadRemote(settings, first) {\n var rupSelect = this;\n settings.ajax = {\n url: function url() {\n return rupSelect._generateUrl(settings, _this._getParentsValues(settings, true));\n },\n dataType: settings.dataType,\n processResults: function processResults(response) {\n // Require id y text, podemos permitir que no venga.\n if (settings.placeholder != undefined && !settings.multiple) {\n var elBlank = response.find(function (x) {\n return x.id == settings.blank;\n });\n\n if (elBlank == undefined && !settings.autocomplete) {\n response.unshift({\n id: settings.blank,\n text: settings.placeholder\n });\n }\n }\n\n if (settings.groups) {\n // PArsear para grupos.\n var results = [];\n $.each(response, function (index, value) {\n var key = Object.keys(value)[0];\n results[index] = {\n 'text': key,\n 'children': value[key]\n };\n });\n response = results;\n }\n\n settings.options = response;\n $('#' + settings.id).data('settings', settings);\n return {\n results: response\n };\n },\n cache: false,\n data: function data() {\n // Es necesario enviarlo vacío para que el componente subyacente no genere parámetros extra que Hdiv bloqueará.\n //se hará en el transport\n return _this._getParentsValues(settings, true);\n },\n error: function error(xhr, textStatus, errorThrown) {\n if (settings.onLoadError !== null) {\n jQuery(settings.onLoadError(xhr, textStatus, errorThrown));\n } else {\n if (textStatus != 'abort') {\n //Si se hacen 2 llamadas se cancela la primera.\n rupSelect._ajaxError(xhr, textStatus, errorThrown);\n }\n\n console.log(textStatus);\n }\n }\n };\n\n if (settings.selected || settings.autocomplete && settings.defaultValue != undefined) {\n settings.firstLoad = true;\n }\n\n if (settings.parent != undefined && ($('#' + settings.parent).val() == null || $('#' + settings.parent).val().trim() === '')) {\n settings.firstLoad = false;\n }\n\n var __cache = [];\n var __lastQuery = null;\n\n settings.ajax.transport = function (params, success, failure) {\n // retrieve the cached key or default to _ALL_\n var __cachekey = params.data || '_ALL_'; //Se actualiza el data, para mantener la misma función, con hdiv ya no se mandan los data\n\n\n if (!settings.autocomplete) {\n params.data = \"\";\n }\n\n var mySelect = $('#' + settings.id).data('select2');\n\n if (settings.autocomplete) {\n params.data.q = mySelect.$container.find('input').val();\n __cachekey = params.data.q;\n }\n\n if (__lastQuery !== __cachekey) {\n // remove caches not from last query\n __cache = [];\n }\n\n __lastQuery = __cachekey; //Si esta cacheado, no busca\n\n if (settings.cache == true && 'undefined' !== typeof __cache[__cachekey]) {\n // display the cached results\n success(__cache[__cachekey]);\n return;\n }\n\n mySelect.$results.find('li').addClass('disabledButtonsTable');\n mySelect.$selection.find('input').addClass('disabledButtonsTable');\n mySelect.$selection.find('input').blur(); //Si tiene padres deshabilitarlos\n\n if (settings.parent) {\n if (typeof settings.parent === 'string') {\n $('#' + settings.parent).rup_select(\"disable\");\n } else {\n $.each(settings.parent, function (ind, elem) {\n $('#' + elem).rup_select(\"disable\");\n });\n }\n }\n\n var $request = undefined;\n\n if (settings.autocomplete) {\n //Meter busqueda accentFolding\n var term = '';\n term = params.data.q;\n term = term.replace(/%/g, '\\\\%').replace(/_/g, '\\\\_');\n params.data = $.extend({\n q: term,\n c: settings.contains\n }, settings.extraParams);\n }\n\n if (settings.parent) {\n var datosParent = _this._getParentsValues(settings, true);\n\n if (datosParent != '') {\n if (settings.autocomplete) {\n //añadir el data del padre\n var padres = datosParent.split('&'); //split por si tiene varios padres\t\n\n $.each(padres, function () {\n if (this !== undefined) {\n var cad = this.split('=');\n\n if (cad != undefined && cad.length > 0) {\n params.data[cad[0]] = cad[1];\n __cachekey = __cachekey + cad[1]; //se añade la parte del padre\n }\n }\n });\n }\n\n $request = $.ajax(params);\n }\n } else {\n $request = $.ajax(params);\n }\n\n if ($request != undefined) {\n $request.then(function (data) {\n // Vuelve la peticion\n // store data in cache\n __cache[__cachekey] = data; // display the results\n\n $('#' + settings.id).rup_select(\"enable\"); //Si tiene padres deshabilitarlos\n\n if (settings.parent) {\n if (typeof settings.parent === 'string') {\n $('#' + settings.parent).rup_select(\"enable\");\n } else {\n $.each(settings.parent, function (ind, elem) {\n $('#' + elem).rup_select(\"enable\");\n });\n }\n }\n\n success(__cache[__cachekey]); // Actualizar seleccionado en la lista//css\n\n var positions = [];\n var valueSelect = $('#' + settings.id).rup_select('getRupValue');\n\n if (settings.groups) {\n var i;\n\n (function () {\n // Parseo de grupos para\n // seleccionar\n var allFacts = []; // grupos\n\n for (i = 0; i < data.length; i = i + 1) {\n if (_typeof(data[i]) === 'object') {\n $.each(data[i], function (key, value) {\n if (_typeof(value) === 'object') {\n $.each(value, function () {\n allFacts.push(this);\n });\n }\n });\n }\n }\n\n data = allFacts;\n settings.optionsGroups = data;\n })();\n }\n\n var seleccionado = $.grep(data, function (v, index) {\n if (v.id == valueSelect) {\n positions.push(index);\n }\n\n return v.nid == settings.selected || v.id == settings.selected;\n });\n\n if ($('#' + settings.id).rup_select('getRupValue') != '') {\n seleccionado = $.grep(data, function (v) {\n return v.id == $('#' + settings.id).rup_select('getRupValue');\n });\n } // Si es el mismo, no cambia porque esta abirendo\n\n\n var mySelect = $('#' + settings.id).data('select2');\n\n if (seleccionado !== undefined && seleccionado.length == 1 && $('#' + settings.id).rup_select('getRupValue') != seleccionado[0].id) {\n if (settings.multiple) {\n // Revisar varios selects\n $('#' + settings.id).rup_select('setRupValue', [seleccionado[0].id]);\n } else {\n $('#' + settings.id).rup_select('setRupValue', seleccionado[0].id);\n }\n\n $.each(positions, function (index, valor) {\n var $option = mySelect.$results.find('li')[valor];\n\n if ($option != undefined) {\n $($option).attr('aria-selected', 'true');\n }\n });\n } else {\n if (settings.autocomplete) {\n var valorInput = mySelect.selection.$selection.find('input').val();\n $('#' + settings.id).rup_select('setRupValue', settings.blank);\n mySelect.selection.$selection.find('input').val(valorInput);\n mySelect.selection.$selection.find('input').focus();\n } else {\n $('#' + settings.id).rup_select('setRupValue', settings.blank);\n }\n }\n\n if (settings.onLoadSuccess !== null && settings.onLoadSuccess !== undefined) {\n jQuery(settings.onLoadSuccess($('#' + settings.id)));\n }\n\n $('#' + settings.id).data('settings', settings);\n $('#' + settings.id).triggerHandler('selectAjaxSuccess', [data]);\n\n if (settings.firstLoad) {\n if (settings.autocomplete && settings.selected == undefined && settings.defaultValue != undefined && data != undefined && ($('#' + settings.id).rup_select('getRupValue') == '' || $('#' + settings.id).rup_select('getRupValue') == settings.blank)) {\n //setear el valor para el defaultValue\n var datos2 = $.grep(data, function (v) {\n return v.text.toUpperCase() === settings.defaultValue.toUpperCase();\n });\n\n if (datos2[0] != undefined) {\n $('#' + settings.id).rup_select('setRupValue', datos2[0].id);\n }\n }\n\n settings.firstLoad = false;\n settings.selected = '';\n }\n });\n $request.fail(failure);\n } else {\n // cerrar\n $('#' + settings.id).select2('close');\n\n if (settings.parent) {\n if (typeof settings.parent === 'string') {\n $('#' + settings.parent).rup_select(\"enable\");\n } else {\n $.each(settings.parent, function (ind, elem) {\n $('#' + elem).rup_select(\"enable\");\n });\n }\n }\n }\n\n return $request;\n };\n\n if (settings.ajax !== undefined) {\n if (settings.data !== undefined) {\n // PAra añadir más parametros de\n // busqueda\n settings.ajax.data = settings.data;\n }\n\n if (settings.autocomplete) {\n //busqueda accentFolding\n var term = '';\n var mySelect = $('#' + settings.id).data('select2');\n\n if ($('input.select2-search__field') != undefined && $('input.select2-search__field').val() != undefined) {\n term = $('input.select2-search__field').val();\n }\n\n if (settings.contains == undefined) {\n settings.contains = true;\n }\n\n term = term.replace(/%/g, '\\\\%').replace(/_/g, '\\\\_');\n settings.ajax.data = $.extend({\n q: term,\n c: settings.contains\n }, settings.extraParams);\n }\n\n if (settings.sourceParam) {\n // modifica el header para parsear\n // la response\n settings.ajax.headers = {\n 'RUP': $.toJSON(settings.sourceParam)\n };\n }\n\n if (settings.processResults) {\n // modifica los results\n settings.ajax.processResults = settings.processResults;\n }\n }\n\n if (settings.multiple) {\n $('#' + settings.id).select2MultiCheckboxes(settings);\n } else {\n if (settings.placeholder == undefined || settings.placeholder == '') {\n // si es vació se asigna el label\n settings.placeholder = rupSelect._getBlankLabel(settings.id);\n }\n\n if (settings.autocomplete) {\n $('#' + settings.id).select2MultiCheckboxes(settings);\n } else {\n $('#' + settings.id).select2(settings);\n }\n }\n\n if (settings.firstLoad) {\n // ejecutar los datos\n var $el = $('#' + settings.id);\n\n var _mySelect = $el.data('select2');\n\n var $search = _mySelect.dropdown.$search || _mySelect.selection.$search;\n\n if (settings.autocomplete && settings.defaultValue != undefined) {\n _mySelect.$container.find('input').val(settings.defaultValue);\n }\n\n if ($search != undefined) {\n $search.trigger('keyup');\n $el.select2('close');\n } else {\n _mySelect.selection.trigger('toggle');\n\n $el.select2('close');\n }\n }\n },\n\n /**\r\n * Método de inicialización del componente.\r\n * \r\n * @function _textIcon\r\n * @private\r\n * @param {object}\r\n * data - Dato que llega, por cada registro.\r\n */\n _textIcon: function _textIcon(data) {\n var stylePosition = 'M'; // B - Before , M - middle , A - After\n // adjust for custom placeholder values, restaurar\n\n if (data.stylePosition === undefined) {\n // usar la de defecto\n data.stylePosition = stylePosition;\n }\n\n var _span = $('
');\n\n var icon = $('
');\n\n if (data.imgStyle) {\n // en lugar d mdi,clase icon.\n _span.addClass(data.style);\n\n icon = $('');\n\n if (data.stylePosition.toUpperCase() === 'M') {\n data.stylePosition = 'B'; // en caso de ser span, no\n // admite texto en medio\n }\n }\n\n if (data.stylePosition.toUpperCase() === 'M') {\n icon.prepend(data.text);\n } else if (data.stylePosition.toUpperCase() === 'B') {\n _span.prepend(data.text);\n }\n\n _span.prepend(icon);\n\n if (data.stylePosition.toUpperCase() === 'A') {\n _span.prepend(data.text);\n }\n\n return _span;\n },\n\n /**\r\n * Método de inicialización del componente.\r\n * \r\n * @function _createOption\r\n * @private\r\n * @param {object}\r\n * settings - Objeto de propiedades de configuración con el\r\n * que se ha inicializado el componente.\r\n * @param {object}\r\n * data - Dato que llega, por cada registro.\r\n */\n _createOption: function _createOption(settings, data) {\n var newOption = new Option(data.text, data.id, false, false);\n\n if (data.style != null) {\n newOption.setAttribute('style', data.style);\n newOption.setAttribute('imgStyle', data.imgStyle);\n }\n\n $('#' + settings.id).append(newOption);\n },\n\n /**\r\n * Gestiona los parámetros a añadir en la URL para que Hdiv permita la llamada.\r\n *\r\n * @function _generateUrl\r\n * @since UDA 5.2.0\r\n * @private\r\n * @param {object} settings - Configuración del componente.\r\n * @param {string} [data] - Valores de búsqueda cuando tiene autocompletado e identificador de los padres en caso de ser enlazados.\r\n */\n _generateUrl: function _generateUrl(settings, data) {\n var _settings$inlineEdit, _settings$inlineEdit2, _settings$inlineEdit3, _settings$inlineEdit4;\n\n var $form = (_settings$inlineEdit = settings.inlineEdit) !== null && _settings$inlineEdit !== void 0 && _settings$inlineEdit.$auxForm ? (_settings$inlineEdit2 = settings.inlineEdit) === null || _settings$inlineEdit2 === void 0 ? void 0 : _settings$inlineEdit2.$auxForm : $('#' + settings.id).closest('form');\n var name = (_settings$inlineEdit3 = settings.inlineEdit) !== null && _settings$inlineEdit3 !== void 0 && _settings$inlineEdit3.auxSiblingFieldName ? (_settings$inlineEdit4 = settings.inlineEdit) === null || _settings$inlineEdit4 === void 0 ? void 0 : _settings$inlineEdit4.auxSiblingFieldName : settings.name;\n\n if ($form.length === 1) {\n var url = settings.url + '?_MODIFY_HDIV_STATE_=' + $.fn.getHDIV_STATE(undefined, $form);\n\n if (data) {\n // Escapa los caracteres '#' para evitar problemas en la petición.\n url += \"&\" + data.replaceAll('#', '%23');\n }\n\n return url + '&MODIFY_FORM_FIELD_NAME=' + name;\n } else {\n return settings.url;\n }\n },\n\n /**\r\n * Método de inicialización del componente.\r\n * \r\n * @function _init\r\n * @private\r\n * @param {object}\r\n * args - Parámetros de inicialización del componente.\r\n */\n _init: function _init(args) {\n var _this2 = this;\n\n _this = this;\n global.initRupI18nPromise.then(function () {\n if (args.length > 1) {\n $.rup.errorGestor($.rup.i18nParse($.rup.i18n.base, 'rup_global.initError') + $(_this2).attr('id'));\n } else {\n // Se recogen y cruzan las paremetrizaciones del objeto\n var settings = $.extend({}, $.fn.rup_select.defaults, args[0]),\n html,\n loadAsLocal = false,\n isValidableElem = false,\n attrs; // Se recoge el tabindex indicado en el elemento\n\n settings.tabindex = $(_this2).attr('tabindex'); // Sobreescribir literales por defecto para\n // multiselect:REVISAR\n // $.extend($.ech.multiselect.prototype.options,\n // $.rup.i18n.base.rup_select.multiselect);\n // Se carga el identificador del padre del patron\n\n settings.id = $.rup_utils.escapeId($(_this2).attr('id'));\n\n if ($(_this2).attr('name') === undefined) {\n $(_this2).attr('name', settings.id);\n }\n\n settings.name = $(_this2).attr('name');\n $('#' + settings.id).attr('ruptype', 'select'); // Si no se recibe identificador para el acceso a literales\n // se usa el ID del objeto\n\n if (!settings.i18nId) {\n settings.i18nId = settings.id;\n } // Guardar valor del INPUT\n\n\n settings.inputValue = $('#' + settings.id).val() === null ? $('#' + settings.id).prop('value') : $('#' + settings.id).val();\n attrs = $(_this2).prop('attributes'); // Revisar apra el select\n\n if (settings.firstLoad === null && $(_this2).is('select') && settings.loadFromSelect) {\n loadAsLocal = true;\n } // Asociar evento CHANGE para propagar cambios a los hijos\n\n\n $('#' + settings.id).on('change', function () {}); // tratar placeHolder\n\n if (settings.placeholder !== undefined && typeof settings.placeholder == 'string') {\n if (!settings.allowClear) {\n settings.templateSelection = function (data, span) {\n if (data.id === settings.blank) {\n // adjust\n // for\n // custom\n // placeholder\n // values,\n // restaurar\n return $('
' + data.text + '');\n }\n\n chargedStyles(data);\n\n if (data.style != null && data.id !== settings.blank) {\n // adjust for custom placeholder values,\n // restaurar\n return _this._textIcon(data);\n }\n\n return data.text;\n };\n\n if (settings.placeholder == '') {\n // si es vació se\n // asigna el label\n settings.placeholder = _this2._getBlankLabel(settings.id);\n }\n\n if (settings.data !== undefined && !settings.multiple) {\n // y si\n // no\n // es\n // multiple\n if (settings.parent == undefined) {\n // Si no tiene padre se mete en todos los\n // valores, sino solo al data,\n settings.data.unshift({\n id: settings.blank,\n text: settings.placeholder\n });\n } else {\n $.each(settings.data, function (index, value) {\n value.unshift({\n id: settings.blank,\n text: settings.placeholder\n });\n });\n }\n }\n } else if ($('#' + settings.id).find('option').length == 0) {\n // revisar\n // y\n // crear\n // option\n // vacio.\n $('#' + settings.id).append(new Option(\"\", \"\"));\n }\n } // Crear mi template, myTemplate\n\n\n if (settings.myTemplate !== undefined) {\n settings.templateSelection = settings.myTemplate;\n }\n\n if (settings.templateResult === undefined) {\n if (settings.multiple && settings.udaSkill) {\n // Si es\n // multiple,\n // los\n // results\n // cambian\n // settings.templateSelection\n settings.templateSelection = function (data, span) {\n // Template de Uda\n return data.text;\n };\n } else {\n // si no es multiple\n if (settings.templateSelection !== undefined) {\n // mirar\n // los\n // iconos\n settings.templateResult = function (data, span) {\n chargedStyles(data);\n\n if (data.id === settings.blank) {\n return $('
' + data.text + '');\n } else if (data.style != null && data.id !== settings.blank) {\n // adjust\n // for\n // custom\n // placeholder\n // values,\n // restaurar\n return _this._textIcon(data);\n }\n\n return data.text;\n };\n } else {\n settings.templateResult = function (data, span) {\n chargedStyles(data);\n\n if (data.style != null && data.id !== settings.blank) {\n // adjust\n // for\n // custom\n // placeholder\n // values,\n // restaurar\n return _this._textIcon(data);\n }\n\n return data.text;\n };\n\n settings.templateSelection = settings.templateResult;\n }\n }\n } // Borrar referencia\n // delete html;\n // Ocultar posibles elementos de fechas/horas\n\n\n $('#' + settings.id).next('a').click(function () {\n $('#ui-datepicker-div').hide();\n }); // Se audita el componente\n\n $.rup.auditComponent('rup_select', 'init'); // Añade clase Personalizada\n\n if (settings.customClasses) {\n $.each(settings.customClasses, function (index, value) {\n $('#' + settings.id + '-button' + ', #' + settings.id + '-menu').addClass(value);\n $('[for=' + settings.id + ']').addClass(value);\n });\n } // Si no se recibe identificador para el acceso a literales\n // se usa el ID del objeto\n\n\n if (!settings.i18nId) {\n settings.i18nId = settings.id;\n } // ORDEN\n\n\n var ordenFunction = function ordenFunction(data) {\n if (typeof data === 'string') {\n var dates = data.sort(function (a, b) {\n return a.text.localeCompare(b.text);\n });\n var mySettings = $('#' + settings.id).data('settings');\n mySettings.options = dates;\n $('#' + settings.id).data('settings', mySettings);\n return dates;\n }\n\n return data;\n };\n\n if (settings.data || settings.dataGroups) {\n // local y\n // groups\n if (settings.sortered === true) {\n // PAra añadir\n // ordenación, en local\n // hay que marcarlo\n settings.sorter = ordenFunction;\n } else if (settings.sortered !== false) {\n settings.sorter = settings.sortered;\n }\n\n if (settings.dataGroups === undefined) {\n // LOcal\n settings.data = _this2._parseLOCAL(settings.data, settings.i18nId, settings.parent);\n } else {\n // grupos\n var optionsGroups = [];\n\n for (var i = 0; i < settings.dataGroups.length; i = i + 1) {\n if (_typeof(settings.dataGroups[i]) === 'object') {\n settings.dataGroups[i].children = _this2._parseLOCAL(settings.dataGroups[i].children, settings.i18nId, settings.parent);\n\n for (var j = 0; j < settings.dataGroups[i].children.length; j = j + 1) {\n optionsGroups.push(settings.dataGroups[i].children[j]);\n }\n }\n }\n\n settings.optionsGroups = optionsGroups;\n settings.data = settings.dataGroups;\n }\n } else if (!settings.ajax && settings.url != null) {\n // remoto\n if (settings.sortered === undefined) {\n // PAra añadir\n // ordenación, en\n // remoto siempre se\n // ordena por\n // defecto.\n settings.sorter = ordenFunction;\n } else if (settings.sortered !== false) {\n settings.sorter = settings.sortered;\n }\n\n _this2._loadRemote(settings, true);\n } else {\n // por si viene cargado de un select\n settings.data = true;\n\n if (settings.parent) {\n //convertir el data, formato parent\t\n settings.data = [];\n $('#' + settings.id).find('option').each(function () {\n var idPadre = $(this).data('idpadre');\n\n if (idPadre != undefined) {\n //si no existe\n if (settings.data[idPadre] === undefined) {\n settings.data[idPadre] = [];\n\n if (settings.placeholder != undefined || settings.placeholder != '') {\n settings.data[idPadre].push({\n id: settings.blank,\n text: settings.placeholder\n });\n }\n }\n\n settings.data[idPadre].push({\n id: $(this).val(),\n text: $(this).text()\n });\n }\n });\n }\n } // Init eventos: El resto van en el propio subyacente\n // Change\n\n\n if (settings.change) {\n if (!settings.clean) {\n $('#' + settings.id).off('select2:clearing');\n $('#' + settings.id).on('select2:clearing', function (e) {\n settings.change(e);\n });\n }\n } // clean\n\n\n if (settings.clean) {\n $('#' + settings.id).off('select2:clearing');\n $('#' + settings.id).on('select2:clearing', function (e) {\n settings.clean(e);\n });\n } // event select\n\n\n $('#' + settings.id).off('select2:select');\n $('#' + settings.id).on('select2:select', function (e) {\n if (settings.autocomplete) {\n //Change input\n var mySelect2 = $('#' + settings.id).data('select2');\n var data = $(this).select2('data')[0];\n mySelect2.$selection.find('input').val(data.text);\n }\n\n if (settings.select) {\n settings.select(e);\n }\n\n if (settings.change) {\n settings.change(e);\n }\n });\n\n if (settings.data) {\n // local y groups\n if (settings.parent) {\n // si depende de otro selects.\n // Si es uno meterlo como string - local\n if (_typeof(settings.parent) == 'object' && settings.parent.length == 1) {\n settings.parent = settings.parent[0];\n }\n\n if (settings.dataParents === undefined) {\n // la\n // primera\n // vez carga\n // los datos\n // fijos.\n settings.dataParents = settings.data;\n }\n\n var valorValue = _this._getParentsValues(settings, false, settings.multiValueToken);\n\n if (valorValue != '') {\n valoresParent = settings.dataParents[valorValue];\n\n if (valoresParent == undefined && settings.dataParents[0] != undefined) {\n valoresParent = settings.dataParents[0][valorValue];\n }\n\n settings.data = valoresParent;\n\n if (settings.data == undefined) {\n settings.data = [];\n }\n }\n }\n\n if (settings.multiple) {\n $('#' + settings.id).select2MultiCheckboxes(settings);\n } else {\n if (settings.placeholder == undefined || settings.placeholder == '') {\n // si es vació se asigna el label\n settings.placeholder = _this._getBlankLabel(settings.id);\n }\n\n if (settings.autocomplete) {\n //local y autocomplete\n if (settings.matcher == undefined && settings.accentFolding == false) {\n settings.matcher = udaMatcher;\n }\n\n $('#' + settings.id).select2MultiCheckboxes(settings);\n\n if (settings.defaultValue != undefined) {\n var mySelect2 = $('#' + settings.id).data('select2');\n mySelect2.$selection.find('input').val(settings.defaultValue);\n\n if (settings.selected == undefined && mySelect2.dataAdapter._dataToConvert != undefined && mySelect2.dataAdapter._dataToConvert.length > 0) {\n var data = $.grep(mySelect2.dataAdapter._dataToConvert, function (v) {\n return v.text.toUpperCase() === settings.defaultValue.toUpperCase();\n });\n\n if (data[0] != undefined) {\n settings.selected = data[0].id;\n }\n }\n }\n } else {\n $('#' + settings.id).select2(settings);\n } //Propiedad para deselecionar una mismo en simple.\n\n\n if (settings.deleteOnDeselect) {\n var _mySelect2 = $('#' + settings.id).data('select2');\n\n _mySelect2.on('close', function (e) {\n if (Object.keys(e).length === 1) {\n _mySelect2.$selection.find('input').val('');\n\n $('#' + settings.id).val(null).trigger('change');\n\n if (!settings.closeOnSelect) {\n $('#' + settings.id).select2('open');\n }\n }\n });\n }\n }\n\n if (settings.selected) {\n $('#' + settings.id).val(settings.selected).trigger('change');\n } // cargar los options\n\n\n settings.options = settings.data;\n } else {\n //Remotos\n //Propiedad para deselecionar una mismo en simple.\n if (settings.deleteOnDeselect) {\n var remotoSelect = $('#' + settings.id).data('select2');\n remotoSelect.on('close', function (e) {\n if (Object.keys(e).length === 1) {\n remotoSelect.$selection.find('input').val('');\n $('#' + settings.id).val(null).trigger('change');\n\n if (!settings.closeOnSelect) {\n $('#' + settings.id).select2('open');\n }\n }\n });\n }\n }\n\n if (settings.parent) {\n // si dependen de otros selects\n // Mirar si es simple o no\n var parent = [];\n\n if (typeof settings.parent == 'string') {\n parent.push(settings.parent);\n } else {\n // Si es uno meterlo como string -remoto\n if (settings.parent.length == 1) {\n settings.parent = settings.parent[0];\n parent.push(settings.parent);\n } else {\n parent = settings.parent;\n }\n } // Bucle para eventos Padres\n\n\n $.each(parent, function (idx, eventoPadre) {\n $('#' + eventoPadre).off('change.parent' + settings.id);\n $('#' + eventoPadre).on('change.parent' + settings.id, function () {\n // Cambios\n // para\n // los\n // hijos,onchange\n // del\n // padre\n // Si soy local\n if (settings.data !== undefined) {\n if (_typeof(settings.parent) == 'object') {\n // Si\n // tiene\n // más\n // de\n // un\n // padre\n var clave = '';\n var ClaveNoCifrar = '';\n\n if (settings.multiValueToken == undefined) {\n settings.multiValueToken = '';\n }\n\n $.each(settings.parent, function (ind, elem) {\n var val = $('#' + elem).rup_select('getRupValue');\n clave = clave + val + settings.multiValueToken;\n var dataSelected = $('#' + elem).rup_select(\"getDataSelected\");\n\n if (dataSelected !== undefined) {\n val = dataSelected.nid || dataSelected.id;\n ClaveNoCifrar = ClaveNoCifrar + val + settings.multiValueToken;\n }\n });\n clave = clave.substring(0, clave.length - settings.multiValueToken.length);\n ClaveNoCifrar = ClaveNoCifrar.substring(0, ClaveNoCifrar.length - settings.multiValueToken.length);\n var datosParents = settings.dataParents[0] || settings.dataParents;\n\n if (datosParents[clave] != undefined || datosParents[ClaveNoCifrar] != undefined) {\n // Datos\n // Cargados\n var valores = datosParents[clave] || datosParents[ClaveNoCifrar];\n settings.data = datosParents;\n $('#' + settings.id).rup_select(\"setSource\", valores);\n }\n } else {\n // si tiene un solo padre\n var val = $('#' + settings.parent).rup_select('getRupValue');\n\n if (val != settings.blank && val != '') {\n $('#' + settings.id).rup_select(\"enable\");\n var _valores = settings.dataParents[val];\n\n if (_valores == undefined && $('#' + settings.parent).rup_select(\"getDataSelected\") !== undefined) {\n var nid = $('#' + settings.parent).rup_select(\"getDataSelected\").nid;\n _valores = settings.dataParents[nid]; //si vine cifrado de un remoto.\n }\n\n settings.data = settings.dataParents;\n\n if (_valores == undefined) {\n // Si no\n // hay\n // valor,\n // se\n // inicializa\n _valores = [];\n }\n\n $('#' + settings.id).rup_select(\"setSource\", _valores);\n } else {\n //deshabilitamos el hijo\n $('#' + settings.id).rup_select(\"disable\");\n }\n } // Aseguramos el valor limpio al cambiar el\n // padre\n\n\n $('#' + settings.id).rup_select(\"setRupValue\", settings.blank);\n } else {\n // si soy Remoto\n var datosParent = _this._getParentsValues(settings, true); // Sola llamar si el padre tiene valor.\n\n\n if (datosParent != '') {\n $('#' + settings.id).rup_select(\"disable\"); // ejecutar los datos\n\n var $el = $('#' + settings.id);\n var $search = $el.data('select2').dropdown.$search || $el.data('select2').selection.$search;\n\n if (settings.autocomplete) {\n $el.data('select2').$container.find('input').val('');\n }\n\n if ($search != undefined) {\n $search.trigger('keyup');\n $el.select2('close');\n }\n\n if ($(\"#\" + settings.id).val() != null && $(\"#\" + settings.id).val().trim() != '') {\n $(\"#\" + settings.id).val(null).trigger('change');\n }\n\n setTimeout($('#' + settings.id).rup_select(\"enable\"), 200);\n } else if ($(\"#\" + settings.id).val() != null && $(\"#\" + settings.id).val().trim() != '') {\n // Se llama al cambio del trigger.\n $(\"#\" + settings.id).val(null).trigger('change');\n $('#' + settings.id).rup_select(\"disable\");\n }\n }\n });\n }); // Fin funcion evento padre\n }\n\n $('#' + settings.id).data('settings', settings); //Si es remoto, el último evento es: selectAjaxSuccess\n\n $('#' + settings.id).triggerHandler('selectFinish', settings);\n }\n })[\"catch\"](function (error) {\n console.error('Error al inicializar el componente:\\n', error);\n });\n }\n }); // ******************************************************\n // DEFINICIÓN DE LA CONFIGURACION POR DEFECTO DEL PATRON\n // ******************************************************\n\n /**\r\n * Función a ejecutar en caso de producirse un error a la hora de obtener\r\n * los elementos a mostrar.\r\n * \r\n * @callback jQuery.rup_select~onLoadError\r\n * @param {Object}\r\n * xhr - Objeto XHR que contiene la respuesta de la petición\r\n * realizada.\r\n * @param {string}\r\n * textStatus - Texto que identifica el error producido.\r\n * @param {Object}\r\n * errorThrown - Objeto error que contiene las propiedades del\r\n * error devuelto en la petición.\r\n */\n\n /**\r\n * Función a ejecutar en caso de producirse un error a la hora de obtener\r\n * los elementos a mostrar.\r\n * \r\n * @callback jQuery.rup_select~onLoadSuccess\r\n * @param {jQuery}\r\n * self - Referencia al objeto jQuery del propio select.\r\n */\n\n /**\r\n * @description Opciones por defecto de configuración del componente.\r\n * \r\n * @name defaults\r\n * \r\n * @property {jQuery.rup_select~onLoadError} [onLoadError] - Función de\r\n * callback a ejecutar en caso de que se produzca un error en la\r\n * petición de obtención de la lista de elementos a mostrar.\r\n * @property {string} [width='100%'] - Determina el tamaño del componente \r\n * tanto en píxeles como en porcentaje. Su valor por defecto es '100%'.\r\n * @property {string} [blank=null] - Se utiliza para declarar un valor\r\n * independiente de la lógica de negocio y en ocasiones se\r\n * representa como \"Seleccione un elemento\". Permite establecer un\r\n * mensaje independiente por cada select haciendo uso de\r\n * $.rup.i18n.app.id._blank (sustituyendo id por el propio de cada\r\n * select) o uno genérico por aplicación haciendo uso de\r\n * $.rup.i18n.app.rup_select.blank. En caso de no definir ninguno,\r\n * se usará el genérico de UDA,\r\n * $.rup.i18n.base.rup_select.blankNotDefined.\r\n * @property {string} [token=\"|\"] - Define el separador a utilizar cuando se\r\n * muestra el valor asociado al select concatenado al literal.\r\n * @property {string} [multiValueToken=\"##\"] - Define el separador a\r\n * utilizar en selects enlazados locales.\r\n * @property {boolean} [ordered=true] - Indica si el select debe ordenarse.\r\n * @property {boolean} [orderedByValue=false] - Indica si el la ordenación\r\n * del seelct debe realizarse por el valor de los elementos en\r\n * lugar de por el texto.\r\n * @property {jQuery.rup_select~onLoadSuccess} [onLoadSuccess=null] - Función\r\n * de callback a ejecutar en el caso de que la petición de carga\r\n * de datos se haya producido correctamente.\r\n * @property {boolean} [loadFromSelect=false] - Determina si se debe de\r\n * utilizar los elementos option del elemento html sobre el que se\r\n * inicializa el componente para inicializar los datos del\r\n * elemento.\r\n * @property {boolean} [multiOptgroupIconText=false] - Indica si se desea\r\n * que en la selección múltiple con grupos, el nombre del grupo\r\n * tenga descripción en los iconos para seleccionar/deseleccionar\r\n * los elementos del grupo.\r\n * @property {boolean} [submitAsString=false] - Indica si el envío de los\r\n * elementos seleccionados en la selección múltiple se realiza\r\n * como un literal separados por coma.\r\n * @property {boolean} [submitAsJSON=false] - Indica si el envío de los\r\n * elementos seleccionados en la selección múltiple se realiza\r\n * como un array JSON donde el nombre del mapa será el nombre del\r\n * select. En el caso de que el nombre contenga notación dot se\r\n * tomará el último literal. Ej: [{id:1}, {id:2}, …].\r\n * @property {boolean} [readAsString=false] - Determina si la asignación de\r\n * un valor inicial se va a realizar a partir de un string con los\r\n * ids de los elementos separados por comas en vez de un array de\r\n * json.\r\n * @property {boolean} [rowStriping=false] - Indica si se debe aplicar un\r\n * estilo diferente a las filas pares e impares para poder\r\n * distinguirlas mediante un color diferente.\r\n * @property {number} [typeAhead=false] - Especifica en milisegundos el\r\n * tiempo de espera que toma el componente antes de procesar los\r\n * eventos de escritura realizados por el usuario.\r\n * @property {number} [legacyWrapMode=false] - Determina si se emplea el\r\n * método obsoleto a la hora de empaquetar en objetos json los\r\n * elementos seleccionados. Su propósito es mantener la\r\n * retrocompatibilidad.\r\n */\n\n $.fn.rup_select.defaults = {\n onLoadError: null,\n width: '100%',\n customClasses: ['select-material'],\n blank: \"-1\",\n minimumResultsForSearch: Infinity,\n submitAsJSON: false,\n dataType: 'json',\n cache: true,\n multiple: false,\n multiValueToken: '##'\n };\n});\n\nfunction chargedStyles(data) {\n if (data.style === undefined && data.element !== undefined) {\n // mirar estilo\n data.style = data.element.getAttribute('style');\n data.imgStyle = data.element.getAttribute('imgStyle');\n\n if (data.style == null || data.style == 'undefined') {\n data.style = undefined;\n }\n\n if (data.style == null || data.imgStyle == 'undefined') {\n data.imgStyle = undefined;\n }\n }\n}\n\nfunction udaMatcher(params, data) {\n // Always return the object if there is nothing to compare\n if ($.trim(params.term) === '') {\n return data;\n } // Do a recursive check for options with children\n\n\n if (data.children && data.children.length > 0) {\n // Clone the data object if there are children\n // This is required as we modify the object to remove any non-matches\n var match = $.extend(true, {}, data); // Check each child of the option\n\n for (var c = data.children.length - 1; c >= 0; c--) {\n var child = data.children[c];\n var matches = matcher(params, child); // If there wasn't a match, remove the object in the array\n\n if (matches == null) {\n match.children.splice(c, 1);\n }\n } // If any children matched, return the new object\n\n\n if (match.children.length > 0) {\n return match;\n } // If there were no matching children, check just the plain object\n\n\n return matcher(params, match);\n }\n\n var original = data.text.toUpperCase();\n var term = params.term.toUpperCase(); // Check if the text contains the term\n\n if (original.indexOf(term) > -1) {\n return data;\n } // If it doesn't contain the term, don't return anything\n\n\n return null;\n}\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\"), __webpack_require__(/*! ./../node_modules/webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\"), __webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\")))\n\n//# sourceURL=webpack://rup/./src/rup.select.js?");
+eval("/* WEBPACK VAR INJECTION */(function(jQuery, global, $) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\n/* eslint-disable no-useless-escape */\n\n/*!\r\n * Copyright 2021 E.J.I.E., S.A.\r\n *\r\n * Licencia con arreglo a la EUPL, Versión 1.1 exclusivamente (la «Licencia»);\r\n * Solo podrá usarse esta obra si se respeta la Licencia.\r\n * Puede obtenerse una copia de la Licencia en\r\n *\r\n * http://ec.europa.eu/idabc/eupl.html\r\n *\r\n * Salvo cuando lo exija la legislación aplicable o se acuerde por escrito,\r\n * el programa distribuido con arreglo a la Licencia se distribuye «TAL CUAL»,\r\n * SIN GARANTÍAS NI CONDICIONES DE NINGÚN TIPO, ni expresas ni implícitas.\r\n * Véase la Licencia en el idioma concreto que rige los permisos y limitaciones\r\n * que establece la Licencia.\r\n */\n\n/**\r\n * Permite al usuario recuperar un elemento de una gran lista de elementos o de\r\n * varias listas dependientes de forma sencilla y ocupando poco espacio en la\r\n * interfaz.\r\n * \r\n * @summary Componente RUP Select.\r\n * @module rup_select\r\n * @see El componente está basado en el plugin\r\n * {@link https://select2.org//|Select2}. Para mas información acerca de\r\n * las funcionalidades y opciones de configuración pinche\r\n * {@link https://select2.org//|aquí}.\r\n * @example $(\"#idSelect\").rup_select({ source : \"selectSimple/remote\",\r\n * sourceParam : {label:\"desc\"+$.rup_utils.capitalizedLang(),\r\n * value:\"code\", style:\"css\"} });\r\n */\n\n/* global define */\n\n/* global jQuery */\n(function (factory) {\n if (true) {\n // AMD. Register as an anonymous module.\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\"), __webpack_require__(/*! ./rup.base */ \"./src/rup.base.js\"), __webpack_require__(/*! select2 */ \"./node_modules/select2/dist/js/select2.js\"), __webpack_require__(/*! ./external/select2MultiCheckboxes */ \"./src/external/select2MultiCheckboxes.js\")], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?\n\t\t\t\t(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n } else {}\n})(function ($) {\n // ****************************************************************************************************************\n // DEFINICIÓN BASE DEL PATRÓN (definición de la variable privada que\n // contendrá los métodos y la función de jQuery)\n // ****************************************************************************************************************\n var rup_select = {};\n var FUNCTION_NOT_SUPPORTED_ERROR_MESSAGE = $.rup.i18nParse($.rup.i18n.base, 'rup_global.functionNotSupportedError');\n var FUNCTION_NOT_SUPPORTED_ERROR_TITLE = $.rup.i18nParse($.rup.i18n.base, 'rup_global.error'); // Se configura el arranque de UDA para que alberge el nuevo patrón\n\n $.extend($.rup.iniRup, $.rup.rupSelectorObjectConstructor('rup_select', rup_select)); // *******************************\n // DEFINICIÓN DE MÉTODOS PÚBLICOS\n // *******************************\n\n $.fn.rup_select('extend', {\n /**\r\n * Método utilizado para obtener el valor del componente. Este método es\r\n * el utilizado por el resto de componentes RUP para estandarizar la\r\n * obtención del valor del select.\r\n * \r\n * @function getRupValue\r\n * @return {string | number} - Devuelve el valor actual del componente\r\n * seleccionado por el usuario.\r\n * @example $(\"#idSelect\").rup_select(\"getRupValue\");\r\n */\n getRupValue: function getRupValue() {\n var $self = $(this),\n settings = $self.data('settings'),\n value;\n var values = $self.select2('data');\n\n if ((values == undefined || values.length == 0) && !settings.multiple) {\n value = '';\n } else if (values.length == 1 && !settings.multiple) {\n value = values[0].id;\n } else {\n value = [];\n $.each(values, function (ind, elem) {\n value.push(elem.id);\n });\n }\n\n if (settings !== undefined && settings.submitAsJSON !== undefined && settings.submitAsJSON) {\n var name = $self.attr('name');\n\n if (name == undefined) {\n name = $self.attr('id');\n }\n\n return jQuery.rup_utils.getRupValueAsJson(name, value);\n }\n\n return value;\n },\n\n /**\r\n * Método utilizado para asignar el valor al componente. Este método es\r\n * el utilizado por el resto de componentes RUP para estandarizar la\r\n * asignación del valor al Select.\r\n * \r\n * @function setRupValue\r\n * @param {string |\r\n * number} param - Valor que se va a asignar al componente.\r\n * @example $(\"#idSelect\").rup_select('setRupValue', 'Si');\r\n */\n setRupValue: function setRupValue(param) {\n var $self = $(this),\n settings = $self.data('settings'); // Tipo de select\n\n if (this.length === 0 || settings !== undefined && !settings.multiple) {\n var texto = undefined; // normal.\n // Simple\n\n if (settings !== undefined && settings.data === undefined && settings.options !== undefined) {\n // si\n // es\n // remoto\n // crear\n // el\n // option\n var data = {};\n\n if (settings.groups) {\n data = $.grep(settings.optionsGroups, function (v) {\n return v.nid === param || v.id == param;\n });\n } else {\n data = $.grep(settings.options, function (v) {\n return v.nid === param || v.id == param;\n });\n }\n\n if (data[0] !== undefined) {\n if ($('#' + settings.id).find(\"option[value='\" + data[0].id + \"']\").length == 0) {\n data = data[0];\n\n _this._createOption(settings, data);\n\n param = data.id; // mantenga el cifrado\n\n texto = data.text;\n } else {\n param = data[0].id; // mantenga el cifrado\n\n texto = data[0].text;\n }\n }\n }\n\n var dataSelect2 = $self.data('select2');\n\n if (dataSelect2 !== undefined) {\n if (dataSelect2.$selection.find('input').length == 1) {\n dataSelect2.$selection.find('input').val('');\n }\n\n var $search = dataSelect2.dropdown.$search || dataSelect2.selection.$search;\n\n if ($search != undefined && texto !== undefined) {\n //sifnifica que esta abierto\n var lis = dataSelect2.dropdown.$dropdown.find('li');\n var selectedDate = $.grep(lis, function (v) {\n return $(v).text() === texto;\n });\n lis.attr('aria-selected', false);\n $(selectedDate).attr('aria-selected', true);\n }\n\n $self.val(param).trigger('change');\n $('#' + settings.id).rup_select('change');\n }\n } else {\n // Multiple > multiselect - falta\n if (_typeof(param) === 'object' && settings.options !== undefined) {\n // si\n // es\n // remoto\n // crear\n // el\n // option\n var arrayDatos = [];\n $.each(param, function (key, value) {\n var data = {};\n\n if (settings.groups) {\n data = $.grep(settings.optionsGroups, function (v) {\n return v.nid === value || v.id == value;\n });\n } else {\n data = $.grep(settings.options, function (v) {\n return v.nid === value || v.id == value;\n });\n }\n\n if (data[0] != undefined && $('#' + settings.id).find(\"option[value='\" + data[0].id + \"']\").length == 0) {\n data = data[0];\n\n _this._createOption(settings, data);\n\n arrayDatos.push(data.id);\n } else {\n arrayDatos.push(value);\n }\n });\n $('#' + settings.id).val(arrayDatos).trigger('change');\n }\n }\n },\n\n /**\r\n * Método que limpia el valor seleccionado en el select. En el caso de\r\n * selección múltiple los valores seleccionados.\r\n * \r\n * @function clear\r\n * @example $(\"#idSelect\").rup_select(\"clear\");\r\n */\n clear: function clear() {\n var $self = $(this); // init de select\n\n if (this.length > 0) {\n // Simple y multi\n if ($self.data('settings').blank !== undefined) {\n $self.val($self.data('settings').blank).trigger('change');\n } else {\n $self.val(null).trigger('change');\n }\n }\n },\n\n /**\r\n * Método que lanza el evento change del componente.\r\n * \r\n * @function change\r\n * @example $(\"#idSelect\").rup_select(\"change\");\r\n */\n change: function change() {\n // Tipo de select\n if ($(this).data('settings').change) {\n $(this).data('settings').change();\n }\n },\n\n /**\r\n * Selecciona todos los elementos en el caso de tratarse de un select\r\n * multilesección.\r\n * \r\n * @function checkAll\r\n * @example $(\"#idSelect\").rup_select(\"checkAll\");\r\n */\n checkAll: function checkAll() {\n // Tipo de select\n if ($(this).data('settings').multiple) {\n // Multiple > multiselect\n var selectedItems = [];\n var allOptions = $(\"#\" + $(this)[0].id + \" option\");\n allOptions.each(function () {\n selectedItems.push($(this).val());\n });\n $(this).rup_select('setRupValue', selectedItems);\n } else {\n // Simple > selectmenu\n alert('Función no soportada.');\n }\n },\n\n /**\r\n * Selecciona el elemento del select que contiene como texto el\r\n * indicado. En caso de no existir el texto a buscar el se no sufrirá\r\n * cambios En el caso de selección múltiple el parámetro será un array.\r\n * \r\n * @function selectByLabel\r\n * @param {string |\r\n * string[]} param - Parámetro utilzado para determinar los\r\n * elementos a seleccionar.\r\n * @example // Simple $(\"#idSelect\").rup_select(\"selectByLabel\", \"No\"); //\r\n * Multiple $(\"#idSelect\").rup_select(\"selectByLabel\",\r\n * [\"No\",\"Si\"]);\r\n */\n selectByLabel: function selectByLabel(param) {\n // Tipo de select\n var settings = $(this).data('settings');\n\n if (settings.options !== undefined) {\n var options = settings.options;\n\n if (settings.groups) {\n options = settings.optionsGroups;\n }\n\n if (!settings.multiple) {\n // Simple > selectmenu\n var data = $.grep(options, function (v) {\n return v.text === param;\n });\n\n if (data[0] !== undefined) {\n $(this).rup_select('setRupValue', data[0].id);\n }\n } else {\n // Ejemplo\n // $('#idSelect').rup_select('selectByLabel',['php_value','java_value'])\n var datos = [];\n $.each(param, function (key, value) {\n var data = $.grep(options, function (v) {\n return v.text === value;\n });\n\n if (data[0] !== undefined) {\n datos.push(data[0].id);\n }\n });\n $(this).rup_select('setRupValue', datos);\n }\n }\n },\n\n /**\r\n * Selecciona el elemento enviado como parámetro. En caso de ser un numérico se selecciona por la posición (comenzando en 0) y si es un literal se selecciona por el valor. En el caso de selección múltiple el parámetro será un array.\r\n *\r\n * @function select\r\n * @param {string | number | string[] | number[]} param - Parámetro utilzado para determinar los elementos a seleccionar.\r\n * @example\r\n * // Simple\r\n * $(\"#idSelect\").rup_select(\"select\", 2);\r\n * // Multiple\r\n * $(\"#idSelect\").rup_select(\"select\", [0,2]);\r\n */\n select: function select(param) {\n var settings = $(this).data().settings;\n var datas = settings.data || settings.options;\n\n if (settings.groups) {\n datas = settings.optionsGroups;\n }\n\n if (settings.multiple) {\n var datos = [];\n $.each(param, function (key, value) {\n if (datas.length >= value) {\n datos.push(datas[value].id);\n }\n });\n $(this).rup_select('setRupValue', datos);\n } else {\n if (datas.length >= param) {\n $(this).rup_select('setRupValue', datas[param].id);\n }\n }\n },\n\n /**\r\n * Método que devuelve el label asociado al valor seleccionado en el\r\n * select. En el caso de la selección múltiple se devolverá un array.\r\n * \r\n * @function label\r\n * @return {string | string[]} - Texto del elemento o elementos\r\n * seleccionado.\r\n * @example $(\"#idSelect\").rup_select(\"label\");\r\n */\n label: function label() {\n // Tipo de select\n var data = $(this).select2('data');\n\n if (!$(this).data('settings').multiple) {\n return data[0].text;\n } else {\n // Multiple > multiselect\n var retorno = [];\n\n for (var i = 0; i < data.length; i++) {\n retorno.push(data[i].text);\n }\n\n return retorno;\n }\n },\n\n /**\r\n * Devuelve el índice de la opción seleccionada en el select (empezando\r\n * en 1). En el caso de la selección múltiple se devolverá un array.\r\n * \r\n * @function index\r\n * @return {number | number[]} - Índice del elemento o elementos\r\n * seleccionados.\r\n * @example $(\"#idSelect\").rup_select(\"index\");\r\n */\n index: function index() {\n // Tipo de select\n var settings = $(this).data('settings');\n\n if (settings.options !== undefined) {\n var options = settings.options;\n\n if (settings.groups) {\n options = settings.optionsGroups;\n }\n\n var count = 0;\n var data = $(this).select2('data');\n\n if (!settings.multiple) {\n // Simple > selectmenu\n $.each(options, function (key, value) {\n if (settings.blank !== value.id.toString()) {\n count = count + 1;\n }\n\n if (value.id.toString() === data[0].id.toString()) {\n return false;\n }\n });\n } else {\n var listaCount = [];\n $.each(data, function (key, value) {\n count = 0;\n $.each(options, function (cont, valor) {\n if (settings.blank !== value.id.toString()) {\n count = count + 1;\n }\n\n if (value.id.toString() === valor.id.toString()) {\n listaCount.push(count);\n return false;\n }\n });\n });\n return listaCount;\n }\n\n return count;\n }\n },\n\n /**\r\n * Deshabilita el select.\r\n * \r\n * @function disable\r\n * @example $(\"#idSelect\").rup_select(\"disable\");\r\n */\n disable: function disable() {\n // Tipo de select\n var $self = $(this);\n $self.prop(\"disabled\", true);\n },\n\n /**\r\n * Habilita el select.\r\n * \r\n * @function enable\r\n * @example $(\"#idSelect\").rup_select(\"enable\");\r\n */\n enable: function enable() {\n var $self = $(this);\n $self.prop(\"disabled\", false);\n },\n\n /**\r\n * Indica si el select está deshabilitado o no.\r\n * \r\n * @function isDisabled\r\n * @param {boolean} -\r\n * Devuelve si el select está deshabilitado o no.\r\n * @example $(\"#idSelect\").rup_select(\"isDisabled\");\r\n */\n isDisabled: function isDisabled() {\n if ($(this).attr('disabled') === 'disabled') {\n return true;\n } else {\n return false;\n }\n },\n\n /**\r\n * Realiza una recarga de los select.\r\n * \r\n * @function reload\r\n * @example $(\"#idSelect\").rup_select(\"reload\");\r\n */\n reload: function reload(removeOptions) {\n var settings = $(this).data('settings');\n $(this).select2(\"destroy\");\n\n if (removeOptions) {\n $(this).find('option').remove();\n }\n\n $(this).rup_select(settings);\n },\n\n /**\r\n * Cambia el source del select y recarga el componente para que este\r\n * comience a usarlo.\r\n * \r\n * @function setSource\r\n * @param {string}\r\n * source - Source desde el cual se obtendran los datos a\r\n * sourceParam - Se puede cambiar los parámetros de la cabecera..\r\n * @example $(\"#idSelect\").rup_select(\"setSource\", source, sourceParam);\r\n */\n setSource: function setSource(source, sourceParam) {\n if (source !== undefined && source !== '') {\n var $self = $(this);\n var settings = $self.data().settings;\n var dataSelect2 = $self.data('select2');\n\n if ($self.data().settings.data === undefined) {\n // remoto\n dataSelect2.dataAdapter.ajaxOptions.url = source;\n\n if (sourceParam != undefined) {\n dataSelect2.dataAdapter.ajaxOptions.headers = $.toJSON(sourceParam);\n }\n } else {\n // local\n settings.data = source;\n settings.options = undefined;\n $self.data('settings', settings);\n\n if (dataSelect2.$selection != undefined) {\n dataSelect2.$selection.find('input').val('');\n }\n\n $self.empty();\n\n if (settings.data !== undefined && settings.autocomplete) {\n $.each(settings.data, function () {\n _this._createOption(settings, this);\n });\n } else {\n $self.select2({\n data: settings.data\n });\n }\n }\n\n if (settings.multiple == true) {\n $self.rup_select('reload');\n }\n }\n },\n\n /**\r\n * Método que devuelve los datos, de los elementos seleccionados.\r\n * \r\n * @function getDataSelected\r\n * @return {string | string[]} - Texto del elemento o elementos\r\n * seleccionado.\r\n * @example $(\"#idSelect\").rup_select(\"label\");\r\n */\n getDataSelected: function getDataSelected() {\n // Tipo de select\n var data = $(this).select2('data');\n\n if (!$(this).data('settings').multiple) {\n //Validar que venga el nid\n if (data[0] != undefined && data[0].nid == undefined && $(this).data('settings').options != undefined) {\n var seleccionado = $.grep($(this).data('settings').options, function (v, index) {\n return v.id === data[0].id;\n });\n\n if (seleccionado != undefined && seleccionado.length == 1) {\n data[0].nid = seleccionado[0].nid;\n }\n }\n\n return data[0];\n } else {\n return data;\n }\n },\n\n /**\r\n * Método que añade un option al select en local\r\n * \r\n * @function addOption\r\n * id:\tidentificador del nuevo option\r\n * text: texto del nuevo option\r\n * label: en Caso de ser grupos, el label donde se va a meter(obligatorio)\r\n * @example $(\"#idSelect\").rup_select(\"label\");\r\n */\n addOption: function addOption(id, text, label) {\n // Tipo de select\n var newOpt = new Option(id, text);\n\n if ($(this).data('settings').groups && label != undefined) {\n var options = $(this).data('select2').options.options;\n $(this).find('optgroup[label=\"' + label + '\"]').append(newOpt);\n var seleccionado = $.grep(options.data, function (v, index) {\n return v.text === label;\n });\n\n if (seleccionado != undefined && seleccionado.length == 1) {\n seleccionado[0].children[seleccionado[0].children.length] = {\n id: id,\n text: text\n };\n }\n } else {\n $(this).append(newOpt);\n }\n },\n\n /**\r\n * Deshabilita una opción de un select multiselección.\r\n *\r\n * @function disableOpt\r\n * @param {string} optValue - Value del option que queremos deshabilitar.\r\n * @example\r\n * $(\"#idSelect\").rup_select(\"disableOpt\", \"opt1\");\r\n */\n disableOpt: function disableOpt(optValue) {\n if ($(this).data('settings').multiple) {\n //Deshabilitar select\n this.find('[value=\\'' + optValue + '\\']').attr('disabled', 'disabled'); //Si pertenece a OptGroup y es el último en deshabilitarse > Cambiar estilos optGroupLabel\n\n if ($(this).data('settings').sourceGroup != undefined) {\n //Obtener inicio optGroup\n var li = obj.parentsUntil('ul').last().prevAll('li.ui-multiselect-optgroup-label').first(),\n inputs = li.nextUntil('li.ui-multiselect-optgroup-label').find('input'),\n allDisabled = true;\n\n for (var i = 0; i < inputs.length; i++) {\n if (!inputs[i].disabled) {\n allDisabled = false;\n break;\n }\n }\n\n if (allDisabled) {\n //Estilos optGroup\n li.css('color', 'grey');\n li.children('a').remove();\n li.children('span').not('.rup-combo_multiOptgroupLabel').remove();\n }\n }\n } else {\n $.rup.errorGestor(FUNCTION_NOT_SUPPORTED_ERROR_MESSAGE, FUNCTION_NOT_SUPPORTED_ERROR_TITLE);\n }\n },\n\n /**\r\n * Deshabilita varias opciones del select. Las opciones se identifican mediante un array.\r\n *\r\n * @function disableOptArr\r\n * @param {string[]} optValueArr - Array en el que se indican los values de las opciones a deshabilitar.\r\n * @example\r\n * $(\"#idSelect\").rup_select(\"disableOptArr\", [\"opt1\",\"opt2\"]);\r\n */\n disableOptArr: function disableOptArr(optValueArr) {\n if ($(this).data('settings').multiple) {\n for (var i = 0; i < optValueArr.length; i++) {\n $(this).rup_select('disableOpt', optValueArr[i]);\n }\n } else {\n $.rup.errorGestor(FUNCTION_NOT_SUPPORTED_ERROR_MESSAGE, FUNCTION_NOT_SUPPORTED_ERROR_TITLE);\n }\n },\n\n /**\r\n * Habilita una opción de un select multiselección.\r\n *\r\n * @function enableOpt\r\n * @param {string} enableOpt - Value del option que queremos habilitar.\r\n * @example\r\n * $(\"#idSelect\").rup_select(\"enableOpt\", \"opt1\");\r\n */\n enableOpt: function enableOpt(optValue) {\n if ($(this).data('settings').multiple) {\n //Habilitar select\n this.find('[value=\\'' + optValue + '\\']').removeAttr('disabled');\n var obj = $('#rup-multiCombo_' + $(this).attr('id')).find('[value=\\'' + optValue + '\\']'); //Habilitar input\n\n obj.removeAttr('disabled'); //Estilos línea (label)\n\n obj.parent().css('color', 'black'); //Si pertenece a OptGroup y es el primero en habilitarse > Cambiar estilos optGroupLabel\n\n if ($(this).data('settings').sourceGroup != undefined) {\n //Obtener inicio optGroup\n var li = obj.parentsUntil('ul').last().prevAll('li.ui-multiselect-optgroup-label').first(); //Estilos optGroup\n\n if (li.children('a').length === 0) {\n li.css('color', 'black');\n\n this._generateOptGroupLabel(li, $(this).data('settings').multiOptgroupIconText);\n }\n }\n } else {\n $.rup.errorGestor(FUNCTION_NOT_SUPPORTED_ERROR_MESSAGE, FUNCTION_NOT_SUPPORTED_ERROR_TITLE);\n }\n },\n\n /**\r\n * Habilita varias opciones del select. Las opciones se identifican mediante un array.\r\n *\r\n * @function enableOptArr\r\n * @param {string[]} optValueArr - Array en el que se indican los values de las opciones a habilitar.\r\n * @example\r\n * $(\"#idSelect\").rup_select(\"enableOptArr\", [\"opt1\",\"opt2\"]);\r\n */\n enableOptArr: function enableOptArr(optValueArr) {\n if ($(this).data('settings').multiple) {\n for (var i = 0; i < optValueArr.length; i++) {\n $(this).rup_select('enableOpt', optValueArr[i]);\n }\n } else {\n $.rup.errorGestor(FUNCTION_NOT_SUPPORTED_ERROR_MESSAGE, FUNCTION_NOT_SUPPORTED_ERROR_TITLE);\n }\n },\n\n /**\r\n * Ordena alfanumericamente y en orden ascendente el combo sobre el que se aplica. Se invoca por defecto al cargarse los combos a no ser que se cambie el valor del atributo ordered en la creación.\r\n *\r\n * @function order\r\n * @param {boolean} orderedByValue - Indica si la búsqueda es por texto (por defecto) o si la búsqueda es por el valor.\r\n * @param {boolean} orderAsNumber - Indica si se debe ordenar como valores numéricos en vez de alfabéticos.\r\n * @param {boolean} skipFirst - Determina si se debe obviar el primer elemento.\r\n * @example\r\n * $(\"#idSelect\").rup_select(\"order\", orderedByValue, orderAsNumber, skipFirst);\r\n */\n order: function order(groups, orderedByValue, orderAsNumber) {\n /* Get options */\n var selector = $(this).data('select2') || $(this).parent().data('select2');\n var settings = selector.options.options;\n\n if (groups) {\n $(this).find('optgroup').each(function () {\n $(this).rup_select('order', false, orderedByValue, orderAsNumber);\n }); //Order children\n\n if (settings.data != undefined) {\n $(settings.data).each(function () {\n if (this.children != undefined && this.children.length > 0) {\n this.children = this.children.sort(function (a, b) {\n return a.text.localeCompare(b.text);\n });\n }\n });\n }\n } else {\n var selectList = $(this).find('option').not('[value=' + settings.blank + ']');\n var option = $(this).find('option[value=' + settings.blank + ']');\n /* Order by innerText (case insensitive) */\n\n selectList.sort(function (a, b) {\n return a.innerText.localeCompare(b.innerText);\n });\n /* Re-do select HTML */\n\n $(this).html(selectList);\n\n if (option.length == 1) {\n $(this).prepend(option);\n }\n }\n },\n\n /**\r\n * Lanza una búsqueda en el autocomplete con el parámetro indicado y el foco va a parar al input.\r\n *\r\n * @param {string} term - Cadena de texto utilizada para realizar la búsqueda.\r\n * @param {boolean} notOthersClose - Si deseas cerrar el resto de componentes.\r\n * @function search\r\n * \r\n * @example\r\n * $(\"#idSelect\").rup_select(\"search\", \"java\");\r\n */\n search: function search(term, notOthersClose) {\n var $search = $(this).data('select2').dropdown.$search || $(this).data('select2').mySelect.selection.$search;\n\n if (!notOthersClose) {\n $('.select2-hidden-accessible').select2('close');\n }\n\n $(this).data('select2').$container.find('input').val(term);\n\n if ($search != undefined) {\n $search.val(term);\n $search.trigger('keyup');\n }\n },\n\n /**\r\n * Permite consultar y modificar la configuración del componente.\r\n *\r\n * @param {string | object} optionName - Nombre de la propiedad que se desea gestionar o objeto de compuesto de varias propiedades.\r\n * @param {*} [value] - Corresponde al valor de la propiedad en caso de haberse especificado el nombre de la misma en el primér parámetro.\r\n * @param {*} aux - Parámetro extra de confirguración para la propiedad \"source\".\r\n * @function option\r\n * @example\r\n * // Establecer una propiedad\r\n * $(\"#idSelect\").rup_select(\"option\", \"minLegth\", 2);\r\n * // Establecer varias propiedad\r\n * $(\"#idSelect\").rup_select(\"option\", {minLegth:2, delay:1000});\r\n */\n option: function option(optionName, value, removeOptions) {\n var settings = $(this).data('settings');\n settings[optionName] = value;\n $(this).select2(\"destroy\");\n\n if (removeOptions) {\n $(this).find('option').remove();\n }\n\n $(this).rup_select(settings);\n },\n\n /**\r\n * Permite abrir el componente.\r\n *\r\n * @param {boolean} notOthersClose - Si deseas cerrar el resto de componentes.\r\n * @function open\r\n * @example\r\n * // Establecer una propiedad\r\n * $(\"#idSelect\").rup_select(\"option\", true);\r\n */\n open: function open(notOthersClose) {\n if (!notOthersClose) {\n $('.select2-hidden-accessible').select2('close');\n }\n\n $(this).select2('open');\n },\n\n /**\r\n * Permite cerrar el componente.\r\n *\r\n * @param {boolean} notOthersClose - Si deseas cerrar el resto de componentes.\r\n * @function close\r\n * @example\r\n * // Establecer una propiedad\r\n * $(\"#idSelect\").rup_select(\"option\", true);\r\n */\n close: function close(notOthersClose) {\n if (!notOthersClose) {\n $('.select2-hidden-accessible').select2('close');\n }\n\n $(this).select2('close');\n },\n\n /**\r\n * Elimina el autocomplete.\r\n *\r\n * @function destroy\r\n * @example\r\n * $(\"#idSelect\").rup_select(\"destroy\");\r\n */\n destroy: function destroy(notRemoveOptions) {\n $(this).select2(\"destroy\");\n\n if (!notRemoveOptions) {\n $(this).find('option').remove();\n }\n }\n }); // *******************************\n // DEFINICIÓN DE MÉTODOS PRIVADOS\n // *******************************\n\n $.fn.rup_select('extend', {\n /**\r\n * Selecciona el elemento correspondiente al label indicado\r\n * \r\n * @function _selectLabel\r\n * @private\r\n * @param {object}\r\n * selector - Referencia al objeto jQuery del select.\r\n * @param {object}\r\n * param - Value correspondiente.\r\n */\n _selectLabel: function _selectLabel(selector, param) {\n var $option;\n\n for (var i = 0; i < $('option', selector).length; i = i + 1) {\n $option = jQuery(selector).find('option').eq(i);\n\n if (jQuery(selector).find('option').eq(i).text() === param) {\n $(selector).selectmenu('index', $option.prop('index'));\n return true;\n }\n }\n\n return false;\n },\n\n /**\r\n * Obtener la opción vacía a partir del fichero de internacionalización\r\n * de la aplicación o del fichero por defecto.\r\n * \r\n * @function _getBlankLabel\r\n * @private\r\n * @param {string}\r\n * id - Identificador del fichero\r\n */\n _getBlankLabel: function _getBlankLabel(id) {\n var app = $.rup.i18n.app; // Comprueba si el select tiene su propio texto personalizado\n\n if (app[id] && app[id]._blank) {\n return app[id]._blank;\n } // Comprueba si la aplicacion tiene un texto definido para todos los\n // blank\n else if (app.rup_select && app.rup_select.blank) {\n return app.rup_select.blank;\n } // Si no hay textos definidos para los blank obtiene el por defecto\n // de UDA\n\n\n return $.rup.i18n.base.rup_select.blankNotDefined;\n },\n\n /**\r\n * Obtener valores de los selects padres (si no están cargados o valores\r\n * 'vacíos' devuelve null). En caso de disponer de varios selects padres\r\n * se devolverán separados por un caracter delimitador.\r\n * \r\n * @function _getParentsValues\r\n * @private\r\n * @param {object[]}\r\n * settings - Array con los elementos de configuración.\r\n * @param {boolean}\r\n * remote - Determina si la fuente de datos es remota o no.\r\n * @return {string} - Devuelve los values seleccionados de los selects\r\n * padres.\r\n */\n _getParentsValues: function _getParentsValues(settings, remote, multiValueToken) {\n var retorno = '';\n var parent = [];\n\n if (settings.parent == undefined) {\n return '';\n }\n\n if (typeof settings.parent == 'string') {\n parent.push(settings.parent);\n } else {\n parent = settings.parent;\n }\n\n var parentsFull = 0;\n $.each(parent, function (idx, parentId) {\n if (parentId != undefined && $('#' + parentId).val() != null && $('#' + parentId).val().trim() !== '') {\n if (settings.blank == $('#' + parentId).val()) {\n retorno = '';\n } else {\n if (remote) {\n // PAra remoto\n retorno += $('#' + parentId).attr('name') + '=' + $('#' + parentId).val() + '&';\n } else {\n // PAra local\n if (retorno != '') {\n retorno = retorno + multiValueToken + $('#' + parentId).val();\n } else {\n retorno = $('#' + parentId).val();\n }\n }\n\n parentsFull = parentsFull + 1;\n }\n }\n });\n\n if (parentsFull < parent.length) {\n // si no estan todos los padres no\n // se busca.\n return '';\n } // Evitar & o multiValueToken finales\n\n\n if (retorno !== '' && remote) {\n retorno = retorno.substring(0, retorno.length - 1);\n }\n\n return retorno;\n },\n\n /**\r\n * Procesa el conjunto de registros devueltos por una petición sobre un\r\n * origen de datos local.\r\n * \r\n * @function _parseLOCAL\r\n * @private\r\n * @param {object[]}\r\n * data - Array de registros obtenidos a partir del origen de\r\n * datos.\r\n * @param {object}\r\n * i18nId - Opciones de idioma.\r\n * @param {jQuery}\r\n * isParent - Si tiene datos en forma parent.\r\n */\n _parseLOCAL: function _parseLOCAL(data, i18nId, isParent) {\n var text;\n var array = data;\n\n if (isParent) {\n // Si es padre llamar a la recursividad\n if (Array.isArray(data)) {\n data = data[0];\n }\n\n $.each(data, function (key, value) {\n data[key] = _this._parseLOCAL(data[key], i18nId, false);\n });\n } else {\n data = [];\n\n for (var i = 0; i < array.length; i = i + 1) {\n if (_typeof(array[i]) === 'object') {\n // multi-idioma\n if (array[i].i18nCaption) {\n text = $.rup.i18nParse($.rup.i18n.app[i18nId], array[i].i18nCaption);\n } else {\n text = array[i].text;\n }\n\n array[i].text = text;\n } else {\n // El id es el mismo que el texto.\n data[i] = {\n id: array[i],\n text: array[i]\n };\n }\n }\n\n if (data.length > 0) {\n // El id es el mismo que el texto.\n return data;\n }\n }\n\n return array;\n },\n\n /**\r\n * Procesa el conjunto de registros devueltos por una petición sobre un\r\n * origen de datos remoto.\r\n * \r\n * @function _parseRemoteGroup\r\n * @private\r\n * @param {object[]}\r\n * array - Array de registros obtenidos a partir del origen\r\n * de datos.\r\n * @param {object}\r\n * settings - Objeto de propiedades de configuración con el\r\n * que se ha inicializado el componente.\r\n */\n _parseRemoteGroup: function _parseRemoteGroup(array, settings) {\n var item;\n var data = [];\n\n for (var i = 0; i < array.length; i = i + 1) {\n item = array[i];\n var key = Object.keys(item)[0];\n var dato = {};\n dato.text = key;\n dato.children = item[key];\n dato.id = \"group__\" + i;\n data.push(dato);\n }\n\n return data;\n },\n\n /**\r\n * Prepara la petición AJAX que se va a realizar para obtener los\r\n * registros a partir de un origen remoto. Se añaden las cabeceras RUP\r\n * correspondientes para realizar la serialización json de manera\r\n * correcta.\r\n * \r\n * @function _ajaxBeforeSend\r\n * @private\r\n * @param {object}\r\n * xhr - Objeto xhr que se va a enviar en la petición\r\n * @param {object}\r\n * settings - Objeto de propiedades de configuración con el\r\n * que se ha inicializado el componente.\r\n * @param {jQuery}\r\n * html - Referencia al objeto jQuery que contiene los\r\n * elementos.\r\n */\n _ajaxBeforeSend: function _ajaxBeforeSend(xhr, settings, html) {\n // Crear select (vacío) y deshabilitarlo\n if (html !== undefined) {\n $('#' + settings.id).replaceWith(html);\n } // Si no es 'reload' se debe inicializar vacío\n\n\n $('#' + settings.id).rup_select('disable'); // LOADING...\n\n $('#' + settings.id + '-button span:first-child').removeClass(\"ui-icon ui-icon-triangle-1-s\").addClass('rup-select_loadingText').text($.rup.i18n.base.rup_select.loadingText);\n var icon = $('#' + settings.id + '-button span:last-child');\n $(icon).removeClass('ui-icon-triangle-1-s');\n $(icon).text(''); // Evita errores de visualización con el icono\n\n $(icon).addClass('rup-select_loading'); // Cabecera RUP\n\n xhr.setRequestHeader('RUP', $.toJSON(settings.sourceParam));\n },\n\n /**\r\n * Procesa la respuesta de la petición AJAX en el caso de que se haya\r\n * producido un error en la misma.\r\n * \r\n * @function _ajaxError\r\n * @private\r\n * @param {object}\r\n * xhr - Objeto xhr enviado en la respuesta.\r\n * @param {string}\r\n * textStatus - Cadena identificadora del error que se ha\r\n * producido en la petición.\r\n * @param {object}\r\n * errorThrown - Objeto error correspondiente al que se ha\r\n * producido en la petición.\r\n * @param {object}\r\n * settings - Objeto de propiedades de configuración con el\r\n * que se ha inicializado el componente.\r\n */\n _ajaxError: function _ajaxError(xhr) {\n if (xhr.responseText !== null && xhr.responseTex !== undefined && xhr.responseText.length < 200) {\n $.rup.showErrorToUser(xhr.responseText);\n } else {\n $.rup.showErrorToUser($.rup.i18n.base.rup_select.ajaxError);\n }\n },\n\n /**\r\n * Carga la opción remoto.\r\n * \r\n * @function _loadRemote\r\n * @private\r\n * @param {object}\r\n * settings - Objeto de propiedades de configuración con\r\n * el que se ha inicializado el componente.\r\n * @return {jQuery} - Objeto jQuery con referencia al elemento que\r\n * contiene el foco.\r\n */\n _loadRemote: function _loadRemote(settings, first) {\n var rupSelect = this;\n settings.ajax = {\n url: function url() {\n return rupSelect._generateUrl(settings, _this._getParentsValues(settings, true));\n },\n dataType: settings.dataType,\n processResults: function processResults(response) {\n // Require id y text, podemos permitir que no venga.\n if (settings.placeholder != undefined && !settings.multiple) {\n var elBlank = response.find(function (x) {\n return x.id == settings.blank;\n });\n\n if (elBlank == undefined && !settings.autocomplete) {\n response.unshift({\n id: settings.blank,\n text: settings.placeholder\n });\n }\n }\n\n if (settings.groups) {\n // PArsear para grupos.\n var results = [];\n $.each(response, function (index, value) {\n var key = Object.keys(value)[0];\n results[index] = {\n 'text': key,\n 'children': value[key]\n };\n });\n response = results;\n }\n\n settings.options = response;\n $('#' + settings.id).data('settings', settings);\n return {\n results: response\n };\n },\n cache: false,\n data: function data() {\n // Es necesario enviarlo vacío para que el componente subyacente no genere parámetros extra que Hdiv bloqueará.\n //se hará en el transport\n return _this._getParentsValues(settings, true);\n },\n error: function error(xhr, textStatus, errorThrown) {\n if (settings.onLoadError !== null) {\n jQuery(settings.onLoadError(xhr, textStatus, errorThrown));\n } else {\n if (textStatus != 'abort') {\n //Si se hacen 2 llamadas se cancela la primera.\n rupSelect._ajaxError(xhr, textStatus, errorThrown);\n }\n\n console.log(textStatus);\n }\n }\n };\n\n if (settings.selected || settings.autocomplete && settings.defaultValue != undefined) {\n settings.firstLoad = true;\n }\n\n if (settings.parent != undefined && ($('#' + settings.parent).val() == null || $('#' + settings.parent).val().trim() === '')) {\n settings.firstLoad = false;\n }\n\n var __cache = [];\n var __lastQuery = null;\n\n settings.ajax.transport = function (params, success, failure) {\n // retrieve the cached key or default to _ALL_\n var __cachekey = params.data || '_ALL_'; //Se actualiza el data, para mantener la misma función, con hdiv ya no se mandan los data\n\n\n if (!settings.autocomplete) {\n params.data = \"\";\n }\n\n var mySelect = $('#' + settings.id).data('select2');\n\n if (settings.autocomplete) {\n params.data.q = mySelect.$container.find('input').val();\n __cachekey = params.data.q;\n }\n\n if (__lastQuery !== __cachekey) {\n // remove caches not from last query\n __cache = [];\n }\n\n __lastQuery = __cachekey; //Si esta cacheado, no busca\n\n if (settings.cache == true && 'undefined' !== typeof __cache[__cachekey]) {\n // display the cached results\n success(__cache[__cachekey]);\n return;\n }\n\n mySelect.$results.find('li').addClass('disabledButtonsTable');\n mySelect.$selection.find('input').addClass('disabledButtonsTable');\n mySelect.$selection.find('input').blur(); //Si tiene padres deshabilitarlos\n\n if (settings.parent) {\n if (typeof settings.parent === 'string') {\n $('#' + settings.parent).rup_select(\"disable\");\n } else {\n $.each(settings.parent, function (ind, elem) {\n $('#' + elem).rup_select(\"disable\");\n });\n }\n }\n\n var $request = undefined;\n\n if (settings.autocomplete) {\n //Meter busqueda accentFolding\n var term = '';\n term = params.data.q;\n term = term.replace(/%/g, '\\\\%').replace(/_/g, '\\\\_');\n params.data = $.extend({\n q: term,\n c: settings.contains\n }, settings.extraParams);\n }\n\n if (settings.parent) {\n var datosParent = _this._getParentsValues(settings, true);\n\n if (datosParent != '') {\n if (settings.autocomplete) {\n //añadir el data del padre\n var padres = datosParent.split('&'); //split por si tiene varios padres\t\n\n $.each(padres, function () {\n if (this !== undefined) {\n var cad = this.split('=');\n\n if (cad != undefined && cad.length > 0) {\n params.data[cad[0]] = cad[1];\n __cachekey = __cachekey + cad[1]; //se añade la parte del padre\n }\n }\n });\n }\n\n $request = $.ajax(params);\n }\n } else {\n $request = $.ajax(params);\n }\n\n if ($request != undefined) {\n $request.then(function (data) {\n // Vuelve la peticion\n // store data in cache\n __cache[__cachekey] = data; // display the results\n\n $('#' + settings.id).rup_select(\"enable\"); //Si tiene padres deshabilitarlos\n\n if (settings.parent) {\n if (typeof settings.parent === 'string') {\n $('#' + settings.parent).rup_select(\"enable\");\n } else {\n $.each(settings.parent, function (ind, elem) {\n $('#' + elem).rup_select(\"enable\");\n });\n }\n }\n\n success(__cache[__cachekey]); // Actualizar seleccionado en la lista//css\n\n var positions = [];\n var valueSelect = $('#' + settings.id).rup_select('getRupValue');\n\n if (settings.groups) {\n var i;\n\n (function () {\n // Parseo de grupos para\n // seleccionar\n var allFacts = []; // grupos\n\n for (i = 0; i < data.length; i = i + 1) {\n if (_typeof(data[i]) === 'object') {\n $.each(data[i], function (key, value) {\n if (_typeof(value) === 'object') {\n $.each(value, function () {\n allFacts.push(this);\n });\n }\n });\n }\n }\n\n data = allFacts;\n settings.optionsGroups = data;\n })();\n }\n\n var seleccionado = $.grep(data, function (v, index) {\n if (v.id == valueSelect) {\n positions.push(index);\n }\n\n return v.nid == settings.selected || v.id == settings.selected;\n });\n\n if ($('#' + settings.id).rup_select('getRupValue') != '') {\n seleccionado = $.grep(data, function (v) {\n return v.id == $('#' + settings.id).rup_select('getRupValue');\n });\n } // Si es el mismo, no cambia porque esta abirendo\n\n\n var mySelect = $('#' + settings.id).data('select2');\n\n if (seleccionado !== undefined && seleccionado.length == 1 && $('#' + settings.id).rup_select('getRupValue') != seleccionado[0].id) {\n if (settings.multiple) {\n // Revisar varios selects\n $('#' + settings.id).rup_select('setRupValue', [seleccionado[0].id]);\n } else {\n $('#' + settings.id).rup_select('setRupValue', seleccionado[0].id);\n }\n\n $.each(positions, function (index, valor) {\n var $option = mySelect.$results.find('li')[valor];\n\n if ($option != undefined) {\n $($option).attr('aria-selected', 'true');\n }\n });\n } else {\n if (settings.autocomplete) {\n var valorInput = mySelect.selection.$selection.find('input').val();\n $('#' + settings.id).rup_select('setRupValue', settings.blank);\n mySelect.selection.$selection.find('input').val(valorInput);\n mySelect.selection.$selection.find('input').focus();\n } else {\n $('#' + settings.id).rup_select('setRupValue', settings.blank);\n }\n }\n\n if (settings.onLoadSuccess !== null && settings.onLoadSuccess !== undefined) {\n jQuery(settings.onLoadSuccess($('#' + settings.id)));\n }\n\n $('#' + settings.id).data('settings', settings);\n $('#' + settings.id).triggerHandler('selectAjaxSuccess', [data]);\n\n if (settings.firstLoad) {\n if (settings.autocomplete && settings.selected == undefined && settings.defaultValue != undefined && data != undefined && ($('#' + settings.id).rup_select('getRupValue') == '' || $('#' + settings.id).rup_select('getRupValue') == settings.blank)) {\n //setear el valor para el defaultValue\n var datos2 = $.grep(data, function (v) {\n return v.text.toUpperCase() === settings.defaultValue.toUpperCase();\n });\n\n if (datos2[0] != undefined) {\n $('#' + settings.id).rup_select('setRupValue', datos2[0].id);\n }\n }\n\n settings.firstLoad = false;\n settings.selected = '';\n }\n });\n $request.fail(failure);\n } else {\n // cerrar\n $('#' + settings.id).select2('close');\n\n if (settings.parent) {\n if (typeof settings.parent === 'string') {\n $('#' + settings.parent).rup_select(\"enable\");\n } else {\n $.each(settings.parent, function (ind, elem) {\n $('#' + elem).rup_select(\"enable\");\n });\n }\n }\n }\n\n return $request;\n };\n\n if (settings.ajax !== undefined) {\n if (settings.data !== undefined) {\n // PAra añadir más parametros de\n // busqueda\n settings.ajax.data = settings.data;\n }\n\n if (settings.autocomplete) {\n //busqueda accentFolding\n var term = '';\n var mySelect = $('#' + settings.id).data('select2');\n\n if ($('input.select2-search__field') != undefined && $('input.select2-search__field').val() != undefined) {\n term = $('input.select2-search__field').val();\n }\n\n if (settings.contains == undefined) {\n settings.contains = true;\n }\n\n term = term.replace(/%/g, '\\\\%').replace(/_/g, '\\\\_');\n settings.ajax.data = $.extend({\n q: term,\n c: settings.contains\n }, settings.extraParams);\n }\n\n if (settings.sourceParam) {\n // modifica el header para parsear\n // la response\n settings.ajax.headers = {\n 'RUP': $.toJSON(settings.sourceParam)\n };\n }\n\n if (settings.processResults) {\n // modifica los results\n settings.ajax.processResults = settings.processResults;\n }\n }\n\n if (settings.multiple) {\n $('#' + settings.id).select2MultiCheckboxes(settings);\n } else {\n if (settings.placeholder == undefined || settings.placeholder == '') {\n // si es vació se asigna el label\n settings.placeholder = rupSelect._getBlankLabel(settings.id);\n }\n\n if (settings.autocomplete) {\n $('#' + settings.id).select2MultiCheckboxes(settings);\n } else {\n $('#' + settings.id).select2(settings);\n }\n }\n\n if (settings.firstLoad) {\n // ejecutar los datos\n var $el = $('#' + settings.id);\n\n var _mySelect = $el.data('select2');\n\n var $search = _mySelect.dropdown.$search || _mySelect.selection.$search;\n\n if (settings.autocomplete && settings.defaultValue != undefined) {\n _mySelect.$container.find('input').val(settings.defaultValue);\n }\n\n if ($search != undefined) {\n $search.trigger('keyup');\n $el.select2('close');\n } else {\n _mySelect.selection.trigger('toggle');\n\n $el.select2('close');\n }\n }\n },\n\n /**\r\n * Método de inicialización del componente.\r\n * \r\n * @function _textIcon\r\n * @private\r\n * @param {object}\r\n * data - Dato que llega, por cada registro.\r\n */\n _textIcon: function _textIcon(data) {\n var stylePosition = 'M'; // B - Before , M - middle , A - After\n // adjust for custom placeholder values, restaurar\n\n if (data.stylePosition === undefined) {\n // usar la de defecto\n data.stylePosition = stylePosition;\n }\n\n var _span = $('
');\n\n var icon = $('
');\n\n if (data.imgStyle) {\n // en lugar d mdi,clase icon.\n _span.addClass(data.style);\n\n icon = $('');\n\n if (data.stylePosition.toUpperCase() === 'M') {\n data.stylePosition = 'B'; // en caso de ser span, no\n // admite texto en medio\n }\n }\n\n if (data.stylePosition.toUpperCase() === 'M') {\n icon.prepend(data.text);\n } else if (data.stylePosition.toUpperCase() === 'B') {\n _span.prepend(data.text);\n }\n\n _span.prepend(icon);\n\n if (data.stylePosition.toUpperCase() === 'A') {\n _span.prepend(data.text);\n }\n\n return _span;\n },\n\n /**\r\n * Método de inicialización del componente.\r\n * \r\n * @function _createOption\r\n * @private\r\n * @param {object}\r\n * settings - Objeto de propiedades de configuración con el\r\n * que se ha inicializado el componente.\r\n * @param {object}\r\n * data - Dato que llega, por cada registro.\r\n */\n _createOption: function _createOption(settings, data) {\n var newOption = new Option(data.text, data.id, false, false);\n\n if (data.style != null) {\n newOption.setAttribute('style', data.style);\n newOption.setAttribute('imgStyle', data.imgStyle);\n }\n\n $('#' + settings.id).append(newOption);\n },\n\n /**\r\n * Gestiona los parámetros a añadir en la URL para que Hdiv permita la llamada.\r\n *\r\n * @function _generateUrl\r\n * @since UDA 5.2.0\r\n * @private\r\n * @param {object} settings - Configuración del componente.\r\n * @param {string} [data] - Valores de búsqueda cuando tiene autocompletado e identificador de los padres en caso de ser enlazados.\r\n */\n _generateUrl: function _generateUrl(settings, data) {\n var _settings$inlineEdit, _settings$inlineEdit2, _settings$inlineEdit3, _settings$inlineEdit4;\n\n var $form = (_settings$inlineEdit = settings.inlineEdit) !== null && _settings$inlineEdit !== void 0 && _settings$inlineEdit.$auxForm ? (_settings$inlineEdit2 = settings.inlineEdit) === null || _settings$inlineEdit2 === void 0 ? void 0 : _settings$inlineEdit2.$auxForm : $('#' + settings.id).closest('form');\n var name = (_settings$inlineEdit3 = settings.inlineEdit) !== null && _settings$inlineEdit3 !== void 0 && _settings$inlineEdit3.auxSiblingFieldName ? (_settings$inlineEdit4 = settings.inlineEdit) === null || _settings$inlineEdit4 === void 0 ? void 0 : _settings$inlineEdit4.auxSiblingFieldName : settings.name;\n\n if ($form.length === 1) {\n var url = settings.url + (settings.url.includes('?') ? '&' : '?') + '_MODIFY_HDIV_STATE_=' + $.fn.getHDIV_STATE(undefined, $form);\n\n if (data) {\n // Escapa los caracteres '#' para evitar problemas en la petición.\n url += \"&\" + data.replaceAll('#', '%23');\n }\n\n return url + '&MODIFY_FORM_FIELD_NAME=' + name;\n } else {\n return settings.url;\n }\n },\n\n /**\r\n * Método de inicialización del componente.\r\n * \r\n * @function _init\r\n * @private\r\n * @param {object}\r\n * args - Parámetros de inicialización del componente.\r\n */\n _init: function _init(args) {\n var _this2 = this;\n\n _this = this;\n global.initRupI18nPromise.then(function () {\n if (args.length > 1) {\n $.rup.errorGestor($.rup.i18nParse($.rup.i18n.base, 'rup_global.initError') + $(_this2).attr('id'));\n } else {\n // Se recogen y cruzan las paremetrizaciones del objeto\n var settings = $.extend({}, $.fn.rup_select.defaults, args[0]),\n html,\n loadAsLocal = false,\n isValidableElem = false,\n attrs; // Se recoge el tabindex indicado en el elemento\n\n settings.tabindex = $(_this2).attr('tabindex'); // Sobreescribir literales por defecto para\n // multiselect:REVISAR\n // $.extend($.ech.multiselect.prototype.options,\n // $.rup.i18n.base.rup_select.multiselect);\n // Se carga el identificador del padre del patron\n\n settings.id = $.rup_utils.escapeId($(_this2).attr('id'));\n\n if ($(_this2).attr('name') === undefined) {\n $(_this2).attr('name', settings.id);\n }\n\n settings.name = $(_this2).attr('name');\n $('#' + settings.id).attr('ruptype', 'select'); // Si no se recibe identificador para el acceso a literales\n // se usa el ID del objeto\n\n if (!settings.i18nId) {\n settings.i18nId = settings.id;\n } // Guardar valor del INPUT\n\n\n settings.inputValue = $('#' + settings.id).val() === null ? $('#' + settings.id).prop('value') : $('#' + settings.id).val();\n attrs = $(_this2).prop('attributes'); // Revisar apra el select\n\n if (settings.firstLoad === null && $(_this2).is('select') && settings.loadFromSelect) {\n loadAsLocal = true;\n } // Asociar evento CHANGE para propagar cambios a los hijos\n\n\n $('#' + settings.id).on('change', function () {}); // tratar placeHolder\n\n if (settings.placeholder !== undefined && typeof settings.placeholder == 'string') {\n if (!settings.allowClear) {\n settings.templateSelection = function (data, span) {\n if (data.id === settings.blank) {\n // adjust\n // for\n // custom\n // placeholder\n // values,\n // restaurar\n return $('
' + data.text + '');\n }\n\n chargedStyles(data);\n\n if (data.style != null && data.id !== settings.blank) {\n // adjust for custom placeholder values,\n // restaurar\n return _this._textIcon(data);\n }\n\n return data.text;\n };\n\n if (settings.placeholder == '') {\n // si es vació se\n // asigna el label\n settings.placeholder = _this2._getBlankLabel(settings.id);\n }\n\n if (settings.data !== undefined && !settings.multiple) {\n // y si\n // no\n // es\n // multiple\n if (settings.parent == undefined) {\n // Si no tiene padre se mete en todos los\n // valores, sino solo al data,\n settings.data.unshift({\n id: settings.blank,\n text: settings.placeholder\n });\n } else {\n $.each(settings.data, function (index, value) {\n value.unshift({\n id: settings.blank,\n text: settings.placeholder\n });\n });\n }\n }\n } else if ($('#' + settings.id).find('option').length == 0) {\n // revisar\n // y\n // crear\n // option\n // vacio.\n $('#' + settings.id).append(new Option(\"\", \"\"));\n }\n } // Crear mi template, myTemplate\n\n\n if (settings.myTemplate !== undefined) {\n settings.templateSelection = settings.myTemplate;\n }\n\n if (settings.templateResult === undefined) {\n if (settings.multiple && settings.udaSkill) {\n // Si es\n // multiple,\n // los\n // results\n // cambian\n // settings.templateSelection\n settings.templateSelection = function (data, span) {\n // Template de Uda\n return data.text;\n };\n } else {\n // si no es multiple\n if (settings.templateSelection !== undefined) {\n // mirar\n // los\n // iconos\n settings.templateResult = function (data, span) {\n chargedStyles(data);\n\n if (data.id === settings.blank) {\n return $('
' + data.text + '');\n } else if (data.style != null && data.id !== settings.blank) {\n // adjust\n // for\n // custom\n // placeholder\n // values,\n // restaurar\n return _this._textIcon(data);\n }\n\n return data.text;\n };\n } else {\n settings.templateResult = function (data, span) {\n chargedStyles(data);\n\n if (data.style != null && data.id !== settings.blank) {\n // adjust\n // for\n // custom\n // placeholder\n // values,\n // restaurar\n return _this._textIcon(data);\n }\n\n return data.text;\n };\n\n settings.templateSelection = settings.templateResult;\n }\n }\n } // Borrar referencia\n // delete html;\n // Ocultar posibles elementos de fechas/horas\n\n\n $('#' + settings.id).next('a').click(function () {\n $('#ui-datepicker-div').hide();\n }); // Se audita el componente\n\n $.rup.auditComponent('rup_select', 'init'); // Añade clase Personalizada\n\n if (settings.customClasses) {\n $.each(settings.customClasses, function (index, value) {\n $('#' + settings.id + '-button' + ', #' + settings.id + '-menu').addClass(value);\n $('[for=' + settings.id + ']').addClass(value);\n });\n } // Si no se recibe identificador para el acceso a literales\n // se usa el ID del objeto\n\n\n if (!settings.i18nId) {\n settings.i18nId = settings.id;\n } // ORDEN\n\n\n var ordenFunction = function ordenFunction(data) {\n if (typeof data === 'string') {\n var dates = data.sort(function (a, b) {\n return a.text.localeCompare(b.text);\n });\n var mySettings = $('#' + settings.id).data('settings');\n mySettings.options = dates;\n $('#' + settings.id).data('settings', mySettings);\n return dates;\n }\n\n return data;\n };\n\n if (settings.data || settings.dataGroups) {\n // local y\n // groups\n if (settings.sortered === true) {\n // PAra añadir\n // ordenación, en local\n // hay que marcarlo\n settings.sorter = ordenFunction;\n } else if (settings.sortered !== false) {\n settings.sorter = settings.sortered;\n }\n\n if (settings.dataGroups === undefined) {\n // LOcal\n settings.data = _this2._parseLOCAL(settings.data, settings.i18nId, settings.parent);\n } else {\n // grupos\n var optionsGroups = [];\n\n for (var i = 0; i < settings.dataGroups.length; i = i + 1) {\n if (_typeof(settings.dataGroups[i]) === 'object') {\n settings.dataGroups[i].children = _this2._parseLOCAL(settings.dataGroups[i].children, settings.i18nId, settings.parent);\n\n for (var j = 0; j < settings.dataGroups[i].children.length; j = j + 1) {\n optionsGroups.push(settings.dataGroups[i].children[j]);\n }\n }\n }\n\n settings.optionsGroups = optionsGroups;\n settings.data = settings.dataGroups;\n }\n } else if (!settings.ajax && settings.url != null) {\n // remoto\n if (settings.sortered === undefined) {\n // PAra añadir\n // ordenación, en\n // remoto siempre se\n // ordena por\n // defecto.\n settings.sorter = ordenFunction;\n } else if (settings.sortered !== false) {\n settings.sorter = settings.sortered;\n }\n\n _this2._loadRemote(settings, true);\n } else {\n // por si viene cargado de un select\n settings.data = true;\n\n if (settings.parent) {\n //convertir el data, formato parent\t\n settings.data = [];\n $('#' + settings.id).find('option').each(function () {\n var idPadre = $(this).data('idpadre');\n\n if (idPadre != undefined) {\n //si no existe\n if (settings.data[idPadre] === undefined) {\n settings.data[idPadre] = [];\n\n if (settings.placeholder != undefined || settings.placeholder != '') {\n settings.data[idPadre].push({\n id: settings.blank,\n text: settings.placeholder\n });\n }\n }\n\n settings.data[idPadre].push({\n id: $(this).val(),\n text: $(this).text()\n });\n }\n });\n }\n } // Init eventos: El resto van en el propio subyacente\n // Change\n\n\n if (settings.change) {\n if (!settings.clean) {\n $('#' + settings.id).off('select2:clearing');\n $('#' + settings.id).on('select2:clearing', function (e) {\n settings.change(e);\n });\n }\n } // clean\n\n\n if (settings.clean) {\n $('#' + settings.id).off('select2:clearing');\n $('#' + settings.id).on('select2:clearing', function (e) {\n settings.clean(e);\n });\n } // event select\n\n\n $('#' + settings.id).off('select2:select');\n $('#' + settings.id).on('select2:select', function (e) {\n if (settings.autocomplete) {\n //Change input\n var mySelect2 = $('#' + settings.id).data('select2');\n var data = $(this).select2('data')[0];\n mySelect2.$selection.find('input').val(data.text);\n }\n\n if (settings.select) {\n settings.select(e);\n }\n\n if (settings.change) {\n settings.change(e);\n }\n });\n\n if (settings.data) {\n // local y groups\n if (settings.parent) {\n // si depende de otro selects.\n // Si es uno meterlo como string - local\n if (_typeof(settings.parent) == 'object' && settings.parent.length == 1) {\n settings.parent = settings.parent[0];\n }\n\n if (settings.dataParents === undefined) {\n // la\n // primera\n // vez carga\n // los datos\n // fijos.\n settings.dataParents = settings.data;\n }\n\n var valorValue = _this._getParentsValues(settings, false, settings.multiValueToken);\n\n if (valorValue != '') {\n valoresParent = settings.dataParents[valorValue];\n\n if (valoresParent == undefined && settings.dataParents[0] != undefined) {\n valoresParent = settings.dataParents[0][valorValue];\n }\n\n settings.data = valoresParent;\n\n if (settings.data == undefined) {\n settings.data = [];\n }\n }\n }\n\n if (settings.multiple) {\n $('#' + settings.id).select2MultiCheckboxes(settings);\n } else {\n if (settings.placeholder == undefined || settings.placeholder == '') {\n // si es vació se asigna el label\n settings.placeholder = _this._getBlankLabel(settings.id);\n }\n\n if (settings.autocomplete) {\n //local y autocomplete\n if (settings.matcher == undefined && settings.accentFolding == false) {\n settings.matcher = udaMatcher;\n }\n\n $('#' + settings.id).select2MultiCheckboxes(settings);\n\n if (settings.defaultValue != undefined) {\n var mySelect2 = $('#' + settings.id).data('select2');\n mySelect2.$selection.find('input').val(settings.defaultValue);\n\n if (settings.selected == undefined && mySelect2.dataAdapter._dataToConvert != undefined && mySelect2.dataAdapter._dataToConvert.length > 0) {\n var data = $.grep(mySelect2.dataAdapter._dataToConvert, function (v) {\n return v.text.toUpperCase() === settings.defaultValue.toUpperCase();\n });\n\n if (data[0] != undefined) {\n settings.selected = data[0].id;\n }\n }\n }\n } else {\n $('#' + settings.id).select2(settings);\n } //Propiedad para deselecionar una mismo en simple.\n\n\n if (settings.deleteOnDeselect) {\n var _mySelect2 = $('#' + settings.id).data('select2');\n\n _mySelect2.on('close', function (e) {\n if (Object.keys(e).length === 1) {\n _mySelect2.$selection.find('input').val('');\n\n $('#' + settings.id).val(null).trigger('change');\n\n if (!settings.closeOnSelect) {\n $('#' + settings.id).select2('open');\n }\n }\n });\n }\n }\n\n if (settings.selected) {\n $('#' + settings.id).val(settings.selected).trigger('change');\n } // cargar los options\n\n\n settings.options = settings.data;\n } else {\n //Remotos\n //Propiedad para deselecionar una mismo en simple.\n if (settings.deleteOnDeselect) {\n var remotoSelect = $('#' + settings.id).data('select2');\n remotoSelect.on('close', function (e) {\n if (Object.keys(e).length === 1) {\n remotoSelect.$selection.find('input').val('');\n $('#' + settings.id).val(null).trigger('change');\n\n if (!settings.closeOnSelect) {\n $('#' + settings.id).select2('open');\n }\n }\n });\n }\n }\n\n if (settings.parent) {\n // si dependen de otros selects\n // Mirar si es simple o no\n var parent = [];\n\n if (typeof settings.parent == 'string') {\n parent.push(settings.parent);\n } else {\n // Si es uno meterlo como string -remoto\n if (settings.parent.length == 1) {\n settings.parent = settings.parent[0];\n parent.push(settings.parent);\n } else {\n parent = settings.parent;\n }\n } // Bucle para eventos Padres\n\n\n $.each(parent, function (idx, eventoPadre) {\n $('#' + eventoPadre).off('change.parent' + settings.id);\n $('#' + eventoPadre).on('change.parent' + settings.id, function () {\n // Cambios\n // para\n // los\n // hijos,onchange\n // del\n // padre\n // Si soy local\n if (settings.data !== undefined) {\n if (_typeof(settings.parent) == 'object') {\n // Si\n // tiene\n // más\n // de\n // un\n // padre\n var clave = '';\n var ClaveNoCifrar = '';\n\n if (settings.multiValueToken == undefined) {\n settings.multiValueToken = '';\n }\n\n $.each(settings.parent, function (ind, elem) {\n var val = $('#' + elem).rup_select('getRupValue');\n clave = clave + val + settings.multiValueToken;\n var dataSelected = $('#' + elem).rup_select(\"getDataSelected\");\n\n if (dataSelected !== undefined) {\n val = dataSelected.nid || dataSelected.id;\n ClaveNoCifrar = ClaveNoCifrar + val + settings.multiValueToken;\n }\n });\n clave = clave.substring(0, clave.length - settings.multiValueToken.length);\n ClaveNoCifrar = ClaveNoCifrar.substring(0, ClaveNoCifrar.length - settings.multiValueToken.length);\n var datosParents = settings.dataParents[0] || settings.dataParents;\n\n if (datosParents[clave] != undefined || datosParents[ClaveNoCifrar] != undefined) {\n // Datos\n // Cargados\n var valores = datosParents[clave] || datosParents[ClaveNoCifrar];\n settings.data = datosParents;\n $('#' + settings.id).rup_select(\"setSource\", valores);\n }\n } else {\n // si tiene un solo padre\n var val = $('#' + settings.parent).rup_select('getRupValue');\n\n if (val != settings.blank && val != '') {\n $('#' + settings.id).rup_select(\"enable\");\n var _valores = settings.dataParents[val];\n\n if (_valores == undefined && $('#' + settings.parent).rup_select(\"getDataSelected\") !== undefined) {\n var nid = $('#' + settings.parent).rup_select(\"getDataSelected\").nid;\n _valores = settings.dataParents[nid]; //si vine cifrado de un remoto.\n }\n\n settings.data = settings.dataParents;\n\n if (_valores == undefined) {\n // Si no\n // hay\n // valor,\n // se\n // inicializa\n _valores = [];\n }\n\n $('#' + settings.id).rup_select(\"setSource\", _valores);\n } else {\n //deshabilitamos el hijo\n $('#' + settings.id).rup_select(\"disable\");\n }\n } // Aseguramos el valor limpio al cambiar el\n // padre\n\n\n $('#' + settings.id).rup_select(\"setRupValue\", settings.blank);\n } else {\n // si soy Remoto\n var datosParent = _this._getParentsValues(settings, true); // Sola llamar si el padre tiene valor.\n\n\n if (datosParent != '') {\n $('#' + settings.id).rup_select(\"disable\"); // ejecutar los datos\n\n var $el = $('#' + settings.id);\n var $search = $el.data('select2').dropdown.$search || $el.data('select2').selection.$search;\n\n if (settings.autocomplete) {\n $el.data('select2').$container.find('input').val('');\n }\n\n if ($search != undefined) {\n $search.trigger('keyup');\n $el.select2('close');\n }\n\n if ($(\"#\" + settings.id).val() != null && $(\"#\" + settings.id).val().trim() != '') {\n $(\"#\" + settings.id).val(null).trigger('change');\n }\n\n setTimeout($('#' + settings.id).rup_select(\"enable\"), 200);\n } else if ($(\"#\" + settings.id).val() != null && $(\"#\" + settings.id).val().trim() != '') {\n // Se llama al cambio del trigger.\n $(\"#\" + settings.id).val(null).trigger('change');\n $('#' + settings.id).rup_select(\"disable\");\n }\n }\n });\n }); // Fin funcion evento padre\n }\n\n $('#' + settings.id).data('settings', settings); //Si es remoto, el último evento es: selectAjaxSuccess\n\n $('#' + settings.id).triggerHandler('selectFinish', settings);\n }\n })[\"catch\"](function (error) {\n console.error('Error al inicializar el componente:\\n', error);\n });\n }\n }); // ******************************************************\n // DEFINICIÓN DE LA CONFIGURACION POR DEFECTO DEL PATRON\n // ******************************************************\n\n /**\r\n * Función a ejecutar en caso de producirse un error a la hora de obtener\r\n * los elementos a mostrar.\r\n * \r\n * @callback jQuery.rup_select~onLoadError\r\n * @param {Object}\r\n * xhr - Objeto XHR que contiene la respuesta de la petición\r\n * realizada.\r\n * @param {string}\r\n * textStatus - Texto que identifica el error producido.\r\n * @param {Object}\r\n * errorThrown - Objeto error que contiene las propiedades del\r\n * error devuelto en la petición.\r\n */\n\n /**\r\n * Función a ejecutar en caso de producirse un error a la hora de obtener\r\n * los elementos a mostrar.\r\n * \r\n * @callback jQuery.rup_select~onLoadSuccess\r\n * @param {jQuery}\r\n * self - Referencia al objeto jQuery del propio select.\r\n */\n\n /**\r\n * @description Opciones por defecto de configuración del componente.\r\n * \r\n * @name defaults\r\n * \r\n * @property {jQuery.rup_select~onLoadError} [onLoadError] - Función de\r\n * callback a ejecutar en caso de que se produzca un error en la\r\n * petición de obtención de la lista de elementos a mostrar.\r\n * @property {string} [width='100%'] - Determina el tamaño del componente \r\n * tanto en píxeles como en porcentaje. Su valor por defecto es '100%'.\r\n * @property {string} [blank=null] - Se utiliza para declarar un valor\r\n * independiente de la lógica de negocio y en ocasiones se\r\n * representa como \"Seleccione un elemento\". Permite establecer un\r\n * mensaje independiente por cada select haciendo uso de\r\n * $.rup.i18n.app.id._blank (sustituyendo id por el propio de cada\r\n * select) o uno genérico por aplicación haciendo uso de\r\n * $.rup.i18n.app.rup_select.blank. En caso de no definir ninguno,\r\n * se usará el genérico de UDA,\r\n * $.rup.i18n.base.rup_select.blankNotDefined.\r\n * @property {string} [token=\"|\"] - Define el separador a utilizar cuando se\r\n * muestra el valor asociado al select concatenado al literal.\r\n * @property {string} [multiValueToken=\"##\"] - Define el separador a\r\n * utilizar en selects enlazados locales.\r\n * @property {boolean} [ordered=true] - Indica si el select debe ordenarse.\r\n * @property {boolean} [orderedByValue=false] - Indica si el la ordenación\r\n * del seelct debe realizarse por el valor de los elementos en\r\n * lugar de por el texto.\r\n * @property {jQuery.rup_select~onLoadSuccess} [onLoadSuccess=null] - Función\r\n * de callback a ejecutar en el caso de que la petición de carga\r\n * de datos se haya producido correctamente.\r\n * @property {boolean} [loadFromSelect=false] - Determina si se debe de\r\n * utilizar los elementos option del elemento html sobre el que se\r\n * inicializa el componente para inicializar los datos del\r\n * elemento.\r\n * @property {boolean} [multiOptgroupIconText=false] - Indica si se desea\r\n * que en la selección múltiple con grupos, el nombre del grupo\r\n * tenga descripción en los iconos para seleccionar/deseleccionar\r\n * los elementos del grupo.\r\n * @property {boolean} [submitAsString=false] - Indica si el envío de los\r\n * elementos seleccionados en la selección múltiple se realiza\r\n * como un literal separados por coma.\r\n * @property {boolean} [submitAsJSON=false] - Indica si el envío de los\r\n * elementos seleccionados en la selección múltiple se realiza\r\n * como un array JSON donde el nombre del mapa será el nombre del\r\n * select. En el caso de que el nombre contenga notación dot se\r\n * tomará el último literal. Ej: [{id:1}, {id:2}, …].\r\n * @property {boolean} [readAsString=false] - Determina si la asignación de\r\n * un valor inicial se va a realizar a partir de un string con los\r\n * ids de los elementos separados por comas en vez de un array de\r\n * json.\r\n * @property {boolean} [rowStriping=false] - Indica si se debe aplicar un\r\n * estilo diferente a las filas pares e impares para poder\r\n * distinguirlas mediante un color diferente.\r\n * @property {number} [typeAhead=false] - Especifica en milisegundos el\r\n * tiempo de espera que toma el componente antes de procesar los\r\n * eventos de escritura realizados por el usuario.\r\n * @property {number} [legacyWrapMode=false] - Determina si se emplea el\r\n * método obsoleto a la hora de empaquetar en objetos json los\r\n * elementos seleccionados. Su propósito es mantener la\r\n * retrocompatibilidad.\r\n */\n\n $.fn.rup_select.defaults = {\n onLoadError: null,\n width: '100%',\n customClasses: ['select-material'],\n blank: \"-1\",\n minimumResultsForSearch: Infinity,\n submitAsJSON: false,\n dataType: 'json',\n cache: true,\n multiple: false,\n multiValueToken: '##'\n };\n});\n\nfunction chargedStyles(data) {\n if (data.style === undefined && data.element !== undefined) {\n // mirar estilo\n data.style = data.element.getAttribute('style');\n data.imgStyle = data.element.getAttribute('imgStyle');\n\n if (data.style == null || data.style == 'undefined') {\n data.style = undefined;\n }\n\n if (data.style == null || data.imgStyle == 'undefined') {\n data.imgStyle = undefined;\n }\n }\n}\n\nfunction udaMatcher(params, data) {\n // Always return the object if there is nothing to compare\n if ($.trim(params.term) === '') {\n return data;\n } // Do a recursive check for options with children\n\n\n if (data.children && data.children.length > 0) {\n // Clone the data object if there are children\n // This is required as we modify the object to remove any non-matches\n var match = $.extend(true, {}, data); // Check each child of the option\n\n for (var c = data.children.length - 1; c >= 0; c--) {\n var child = data.children[c];\n var matches = matcher(params, child); // If there wasn't a match, remove the object in the array\n\n if (matches == null) {\n match.children.splice(c, 1);\n }\n } // If any children matched, return the new object\n\n\n if (match.children.length > 0) {\n return match;\n } // If there were no matching children, check just the plain object\n\n\n return matcher(params, match);\n }\n\n var original = data.text.toUpperCase();\n var term = params.term.toUpperCase(); // Check if the text contains the term\n\n if (original.indexOf(term) > -1) {\n return data;\n } // If it doesn't contain the term, don't return anything\n\n\n return null;\n}\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\"), __webpack_require__(/*! ./../node_modules/webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\"), __webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\")))\n\n//# sourceURL=webpack://rup/./src/rup.select.js?");
/***/ }),
@@ -8656,7 +8656,7 @@ eval("/* WEBPACK VAR INJECTION */(function(jQuery) {var __WEBPACK_AMD_DEFINE_FAC
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
-eval("/* WEBPACK VAR INJECTION */(function(jQuery) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/*!\r\n * Copyright 2016 E.J.I.E., S.A.\r\n *\r\n * Licencia con arreglo a la EUPL, Versión 1.1 exclusivamente (la «Licencia»);\r\n * Solo podrá usarse esta obra si se respeta la Licencia.\r\n * Puede obtenerse una copia de la Licencia en\r\n *\r\n * http://ec.europa.eu/idabc/eupl.html\r\n *\r\n * Salvo cuando lo exija la legislación aplicable o se acuerde por escrito,\r\n * el programa distribuido con arreglo a la Licencia se distribuye «TAL CUAL»,\r\n * SIN GARANTÍAS NI CONDICIONES DE NINGÚN TIPO, ni expresas ni implícitas.\r\n * Véase la Licencia en el idioma concreto que rige los permisos y limitaciones\r\n * que establece la Licencia.\r\n */\n\n/**\r\n * Módulo de utilidades comunes a todos los componentes RUP.
\r\n * Implementa métodos para la manipulación de JSON, formularios, formatos...\r\n *\r\n * @summary Librería de utilidades para los componentes RUP.\r\n * @module rup_utils\r\n * @memberOf jQuery\r\n */\n(function (factory) {\n if (true) {\n // AMD. Register as an anonymous module.\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\"), __webpack_require__(/*! jqueryUI */ \"./node_modules/jquery-ui-dist/jquery-ui.js\"), __webpack_require__(/*! ./core/utils/jquery.json-2.2 */ \"./src/core/utils/jquery.json-2.2.js\")], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?\n\t\t\t\t(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n } else {}\n})(function ($) {\n $.rup_utils = {};\n $.rup_utils.arr = [];\n $.rup_utils.autoGenerateIdNum = 0;\n $.rup_utils.swinging = false;\n $.extend($.rup_utils, {\n /**\r\n * Retorna el idioma actual capitalizado.\r\n *\r\n * El idioma actual se obtiene de la variable $.rup.lang\r\n *\r\n * @name jQuery.rup_utils#capitalizedLang\r\n * @function\r\n * @example\r\n * // Retorna \"Es\" para un valor \"es\" en $.rup.lang.\r\n * $.rup_utils.capitalizedLang();\r\n * @returns {string} - Idioma actual capitalizado\r\n */\n capitalizedLang: function capitalizedLang() {\n if ($.rup.lang == null) {\n return '';\n }\n\n return $.rup.lang.charAt(0).toUpperCase() + $.rup.lang.slice(1);\n },\n getJson: function getJson(obj, path) {\n var ret = $.extend({}, obj),\n split = path.split('.');\n\n if (split.length === 1) {\n return obj[split[0]];\n }\n\n for (var i = 0; i < split.length; i++) {\n ret = ret[split[i]];\n }\n\n return ret;\n },\n setJson: function setJson(obj, path, value) {\n var aux = obj,\n split = path.split('.');\n\n if (split.length === 1) {\n obj[split[0]] = value;\n } else {\n for (var i = 0; i < split.length - 1; i++) {\n aux = aux[split[i]];\n }\n\n aux[split[split.length - 1]] = value;\n }\n },\n\n /**\r\n * Transforma un objeto JSON en un array Javascript.\r\n *\r\n * @name jQuery.rup_utils#jsontoarray\r\n * @function\r\n * @param {Object} obj - Objeto JSON que se desea transformar en un array.\r\n * @returns {Object} - Array JavaScript.\r\n * @example\r\n * // Transforma un json obj={'prop':'value'} en un array arr['prop'] -> 'value'\r\n * var obj={'prop':'value'};\r\n * $.rup_utils.jsontoarray(obj);\r\n * @example\r\n * // Transforma un json obj={'propA':{'propAA':'value'}} en un array arr['propA.propAA'] -> 'value'\r\n * var obj={'propA':{'propAA':'value'}};\r\n * $.rup_utils.jsontoarray(obj);\r\n * @example\r\n * // Transforma un json obj={'propA':{'propAA':['a','b','c','d']}} en un array arr['propA.propAA[0]']\r\n * var obj={'propA':{'propAA':['a','b','c','d']}};\r\n * $.rup_utils.jsontoarray(obj);\r\n */\n jsontoarray: function jsontoarray(obj) {\n var arr = [];\n\n function parseJSON(obj, path) {\n // parsea un json a un array\n path = path || ''; // iteracion a traves (objects / arrays)\n\n if (obj === undefined || obj === null) {\n // Si no existe un valor para el path indicado se envia ''\n parseJSON('', path);\n } else if (obj.constructor == Object) {\n for (var prop in obj) {\n //var name = path + (path == '' ? prop : '[' + prop + ']');\n var name = path + (path == '' ? prop : '.' + prop);\n parseJSON(obj[prop], name);\n }\n } else if (obj.constructor == Array) {\n if (obj.length == 0) {\n parseJSON('[]', path);\n } else {\n for (var i = 0; i < obj.length; i++) {\n var index = '[' + i + ']',\n _name = path + index;\n\n parseJSON(obj[i], _name);\n }\n }\n } else {\n // assignment (values) if the element name hasn't yet been defined, create it as a single value\n if (arr[path] == undefined) {\n arr[path] = obj;\n } else if (arr[path].constructor != Array) {\n // if the element name HAS been defined, but it's a single value, convert to an array and add the new value\n arr[path] = [arr[path], obj];\n } else {\n // if the element name HAS been defined, and is already an array, push the single value on the end of the stack\n arr[path].push(obj);\n }\n }\n }\n\n parseJSON(obj);\n return arr;\n },\n\n /**\r\n * Realiza una desanidacion del json pasado (p.e.: {entidad:{propiedad:valor}} --> {'entidad.propiedad':valor}.\r\n *\r\n * @name jQuery.rup_utils#unnestjson\r\n * @function\r\n * @param {Object} obj - Objeto JSON que se desea desanidar.\r\n * @returns {Object} - Objeto JSON desanidado.\r\n * @example\r\n * // Transforma un json obj={'propA':{'propAA':'valueAA'}} en un json obj={'propA.propAA':'valueAA'}}\r\n * var obj={'propA':{'propAA':'valueAA'}};\r\n * $.rup_utils.unnestjson(obj);\r\n */\n unnestjson: function unnestjson(obj) {\n var array = $.rup_utils.jsontoarray(obj);\n var json = {};\n\n for (var key in array) {\n if (typeof array[key] !== \"function\") {\n json[key] = array[key];\n }\n }\n\n return json;\n },\n\n /**\r\n * Devuelve el objeto del dom existente en la posición indicada.\r\n *\r\n * @name jQuery.rup_utils#elementFromPoint\r\n * @function\r\n * @param {number} x - Coordenada x de la posición en la pantalla.\r\n * @param {number} y - Coordenada y de la posición en la pantalla.\r\n * @param {boolean} [argCheck=true] - Determina si debe de ajustarse en base al scroll realizado en la pantalla .\r\n * @returns {Object} - Objeto del DOM correspodiente a la posición indicada.\r\n * @example\r\n * $.rup_utils.elementFromPoint(120,140);\r\n */\n elementFromPoint: function elementFromPoint(x, y, argCheck) {\n var isRelative = true,\n check = argCheck || true;\n if (!document.elementFromPoint) return null;\n\n if (!check) {\n var sl;\n\n if ((sl = $(document).scrollTop()) > 0) {\n isRelative = document.elementFromPoint(0, sl + $(window).height() - 1) == null;\n } else if ((sl = $(document).scrollLeft()) > 0) {\n isRelative = document.elementFromPoint(sl + $(window).width() - 1, 0) == null;\n }\n\n check = sl > 0;\n }\n\n if (!isRelative) {\n x += $(document).scrollLeft();\n y += $(document).scrollTop();\n }\n\n return document.elementFromPoint(x, y);\n },\n\n /**\r\n * Convierte en mínusculas el primer caracter de la cadena de caracteres pasada como parámetro.\r\n *\r\n * @name jQuery.rup_utils#firstCharToLowerCase\r\n * @function\r\n * @param {string} cadena - Cadena de caracteres inicial.\r\n * @returns {string} - Cadena de caracteres resultante con su primer caracter convertido a minúsculas.\r\n * @example\r\n * // Convierte a minúsculas el primer caracter de la cadena \"AbCdEfg\" -> \"abCdEfg\"\r\n * $.rup_utils.firstCharToLowerCase(\"AbCdEfg\");\r\n */\n firstCharToLowerCase: function firstCharToLowerCase(cadena) {\n return cadena.substring(0, 1).toLowerCase() + cadena.substring(1);\n },\n\n /**\r\n * Devuelve un string que puede ser utilizado como selector de jQuery mediante el id ('#'). El método permite también escapar los caracteres reservados en los selectores de jQuery\r\n *\r\n * @name jQuery.rup_utils#firstCharToLowerCase\r\n * @function\r\n * @param {string} cadena - Cadena de caracteres inicial.\r\n * @returns {string} - Cadena de caracteres resultante con su primer caracter convertido a minúsculas.\r\n * @example\r\n * // Convierte a minúsculas el primer caracter de la cadena \"AbCdEfg\" -> \"abCdEfg\"\r\n * $.rup_utils.firstCharToLowerCase(\"AbCdEfg\");\r\n */\n getJQueryId: function getJQueryId(sid, escaped) {\n var returnIdSelector;\n\n if (typeof sid === 'string') {\n returnIdSelector = sid;\n\n if (escaped === true) {\n returnIdSelector = String(returnIdSelector).replace(/[!\"#$%&'()*+,./:; <=>?@[\\\\\\]^`{|}~]/g, '\\\\$&');\n }\n\n return returnIdSelector[0] === '#' ? returnIdSelector : '#' + returnIdSelector;\n }\n\n return null;\n },\n\n /**\r\n * Convierte una cadena querystring en un objeto json.\r\n *\r\n * @name jQuery.rup_utils#queryStringToJson\r\n * @function\r\n * @param {string} queryString - Query string a transformar en un objeto json.\r\n * @param {string} [serializerSplitter=&] - Cadena a usar para separar los campos.\r\n * @param {boolean} [allowAllCharacters=false] - Habilita la posibilidad de incluir cualquier carácter en los campos.\r\n * @returns {object} - Objeto JSON creado a partir de la query string indicada.\r\n * @example\r\n * // Obtene un json a partir del query string \"keyA=valueA&keyB=valueB&keyC=valueC\" -> \"{keyA:'valueA', keyB:'valueB', keyC:'valueC'}\"\r\n * $.rup_utils.queryStringToJson(\"keyA=valueA&keyB=valueB&keyC=valueC\");\r\n */\n queryStringToJson: function queryStringToJson(queryString) {\n var serializerSplitter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '&';\n var allowAllCharacters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\n function setValue(root, path, value) {\n if (path.length > 1) {\n var dir = path.shift();\n\n if (typeof root[dir] == 'undefined') {\n root[dir] = path[0] == '' ? [] : {};\n }\n\n arguments.callee(root[dir], path, value);\n } else {\n if (root instanceof Array) {\n root.push(value);\n } else if (path[0].indexOf('.') != -1) {\n // Entra por aquí en caso de que uno de los path sea un objeto\n var padre = path[0].slice(0, path[0].indexOf('.'));\n var hijo = path[0].slice(path[0].indexOf('.') + 1, path[0].length);\n\n if (root[padre] != undefined) {\n root[padre][hijo] = value;\n } else {\n root[padre] = _defineProperty({}, hijo, value);\n }\n } else {\n root[path] = value;\n }\n }\n }\n\n var nvp = [],\n nvpBruto = queryString.split(serializerSplitter),\n data = {},\n pair,\n name,\n value,\n path,\n first; //Se revisa la correcta gestion de los campos\n\n for (var i = 0; i < nvpBruto.length; i++) {\n pair = nvpBruto[i].split('=');\n\n if (pair.length >= 2) {\n nvp.push(nvpBruto[i]);\n } else if (pair.length == 1) {\n nvp[i - 1] = nvp[i - 1] + serializerSplitter + nvpBruto[i];\n }\n }\n\n for (var i = 0; i < nvp.length; i++) {\n pair = nvp[i].split('=');\n\n if (pair.length > 2) {\n var pairAux = '';\n\n for (var j = 1; j < pair.length; j++) {\n if (j == 1) {\n pairAux = pair[j];\n } else {\n pairAux = pairAux + \"=\" + pair[j];\n }\n }\n\n pair[pair.length - 1] = pairAux;\n }\n\n name = decodeURIComponent(pair[0]);\n\n if (pair[pair.length - 1].includes(\"%\")) {\n if (allowAllCharacters && !pair[pair.length - 1].includes(\"%25\")) {\n pair[pair.length - 1] = encodeURIComponent(pair[pair.length - 1]);\n } else if (!allowAllCharacters) {\n $.rup.errorGestor($.rup.i18nParse($.rup.i18n.base, 'rup_utils.illegalChar'));\n }\n }\n\n value = decodeURIComponent(pair[pair.length - 1]);\n path = name.match(/(^[^[]+)(\\[.*\\]$)?/);\n first = path[1];\n\n if (path[2]) {\n // case of 'array[level1]' ||\n // 'array[level1][level2]'\n path = path[2].match(/(?=\\[(.*)\\]$)/)[1].split('][');\n } else {\n // case of 'name'\n path = [];\n }\n\n path.unshift(first);\n setValue(data, path, value);\n }\n\n return data;\n },\n\n /**\r\n * Devuelve un string con los caracteres sencillos.\r\n *\r\n * @name normalize\r\n * @function\r\n * @since UDA 3.3.0\r\n * \r\n * @param {string} texto - Cadena de caracteres inicial.\r\n * @returns {string} - Cadena de caracteres sin accentFolding.\r\n * \r\n * @example\r\n * // Convierte los caracteres de la cadena \"áéíóu\" a \"aeiou\"\r\n * $.rup_utils.normalize(\"áéíóu\");\r\n */\n normalize: function normalize(texto) {\n var accentMap = {\n 'á': 'a',\n 'é': 'e',\n 'í': 'i',\n 'ó': 'o',\n 'ú': 'u',\n 'Á': 'A',\n 'É': 'E',\n 'Í': 'I',\n 'Ó': 'O',\n 'Ú': 'U'\n };\n var cadena = '';\n\n for (var i = 0; i < texto.length; i++) {\n cadena += accentMap[texto.charAt(i)] || texto.charAt(i);\n }\n\n return cadena;\n },\n populateForm: function populateForm(aData, formid) {\n //rellena un formulario que recibe como segundo parametro con los datos que recibe en el segundo parametro\n var formElem;\n var tree_data, selectorArray;\n\n function loadedJstreeEvent() {\n var selectorArbol = this.id; //$(this).rup_tree(\"setRupValue\",$arbol[selectorArbol]);\n\n $(this).trigger('rup_filter_treeLoaded', $arbol[selectorArbol]);\n }\n\n function populateRadioCheckbox() {\n if ($(this).val() == aData[i]) {\n $(this).prop('checked', true);\n } else {\n $(this).prop('checked', false);\n }\n }\n\n if (aData) {\n for (var i in aData) {\n tree_data = [];\n formElem = $('[name=\\'' + i + '\\']', formid);\n\n if (formElem.length == 0) {\n selectorArray = i.substr(0, i.indexOf('['));\n formElem = $('[name=\\'' + selectorArray + '\\']', formid);\n }\n\n if (formElem.is('[ruptype]')) {\n if (formElem.hasClass('jstree')) {\n for (var a in aData) {\n if (a.substr(0, a.indexOf('[')) == selectorArray) {\n tree_data.push(aData[a]);\n }\n }\n\n formElem['rup_' + formElem.attr('ruptype')]('setRupValue', tree_data);\n var $arbol = [];\n $arbol[selectorArray] = tree_data;\n formElem.on('loaded.jstree', loadedJstreeEvent);\n } else {\n // Forma de evitar el EVAL\n formElem['rup_' + formElem.attr('ruptype')]('setRupValue', aData[i]);\n }\n } else if (formElem.is('input:radio') || formElem.is('input:checkbox')) {\n formElem.each(populateRadioCheckbox);\n } else if (formElem.is('select')) {\n formElem.val(aData[i]).click();\n } else if (formElem.is(':not(img)')) {\n // this is very slow on big table and form.\n formElem.val(aData[i]);\n }\n }\n }\n },\n //DATE UTILS\n createDate: function createDate(day, month, year) {\n return $.datepicker.formatDate($.rup.i18n.base.rup_date.dateFormat, new Date(year, month - 1, day));\n },\n createTime: function createTime(hour, minute, second) {\n return new Date(null, null, null, hour, minute, second);\n },\n\n /*!\r\n * jQuery CooQuery Plugin v2\r\n * http://cooquery.lenonmarcel.com.br/\r\n *\r\n * Copyright 2009, 2010 Lenon Marcel\r\n * Dual licensed under the MIT and GPL licenses.\r\n * http://www.opensource.org/licenses/mit-license.php\r\n * http://www.gnu.org/licenses/gpl.html\r\n *\r\n * Date: 2010-01-24 (Sun, 24 January 2010)\r\n */\n //TODO: Documentacion -> http://plugins.jquery.com/project/cooquery\n setCookie: function setCookie(name, value, options) {\n if (typeof name === 'undefined' || typeof value === 'undefined' || name === null || value === null) {\n $.rup.errorGestor('[' + $.rup.i18nParse($.rup.i18n.base, 'rup_global.metodError') + 'setCookie] - ' + $.rup.i18nParse($.rup.i18n.base, 'rup_utils.paramsError'));\n return false;\n }\n\n var str = name + '=' + encodeURIComponent(value);\n\n if (typeof options !== 'undefined' && options !== null) {\n if (options.domain) str += '; domain=' + options.domain;\n if (options.path) str += '; path=' + options.path;\n\n if (options.duration) {\n var date = new Date();\n date.setTime(date.getTime() + options.duration * 24 * 60 * 60 * 1000);\n str += '; expires=' + date.toGMTString();\n }\n\n if (options.secure) str += '; secure';\n }\n\n return document.cookie = str;\n },\n delCookie: function delCookie(name) {\n if (typeof name === 'undefined' || name === null) {\n $.rup.errorGestor('[' + $.rup.i18nParse($.rup.i18n.base, 'rup_global.metodError') + 'delCookie] - ' + $.rup.i18nParse($.rup.i18n.base, 'rup_utils.paramsError'));\n return false;\n }\n\n return $.rup_utils.setCookie(name, '', {\n duration: -1\n });\n },\n readCookie: function readCookie(name) {\n if (typeof name === 'undefined' || name === null) {\n $.rup.errorGestor('[' + $.rup.i18nParse($.rup.i18n.base, 'rup_global.metodError') + 'readCookie] - ' + $.rup.i18nParse($.rup.i18n.base, 'rup_utils.paramsError'));\n return false;\n }\n\n var value = document.cookie.match('(?:^|;)\\\\s*' + name.replace(/([-.*+?^${}()|[\\]/\\\\])/g, '\\\\$1') + '=([^;]*)');\n return value ? decodeURIComponent(value[1]) : null;\n },\n get: function get(name, json) {\n var cookieValue = null;\n\n if (document.cookie && document.cookie != '') {\n var cookies = document.cookie.split(';');\n\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i].trim();\n\n if (cookie.substring(0, name.length + 1) == name + '=') {\n cookieValue = json ? $.JSON.decode(decodeURIComponent(cookie.substring(name.length + 1))) : decodeURIComponent(cookie.substring(name.length + 1));\n break;\n }\n }\n }\n\n return cookieValue;\n },\n set: function set(name, value, options) {\n options = $.extend({}, options);\n\n if (value === null) {\n value = '';\n options.expires = -1;\n }\n\n var expires = '';\n\n if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {\n var date;\n\n if (typeof options.expires == 'number') {\n date = new Date();\n date.setTime(date.getTime() + options.expires * 24 * 60 * 60 * 1000);\n } else {\n date = options.expires;\n }\n\n expires = '; expires=' + date.toUTCString();\n }\n\n value = options.json ? encodeURIComponent($.JSON.encode(value)) : encodeURIComponent(value);\n var path = options.path ? '; path=' + options.path : '';\n var domain = options.domain ? '; domain=' + options.domain : '';\n var secure = options.secure ? '; secure' : '';\n document.cookie = [name, '=', value, expires, path, domain, secure].join('');\n },\n //compare objects function\n compareObjects: function compareObjects(x, y) {\n var objectsAreSame = true;\n\n if (Object.keys(x).length !== Object.keys(y).length) {\n return false;\n }\n\n for (var propertyName in x) {\n if (_typeof(x[propertyName]) == 'object' && _typeof(y[propertyName]) == 'object') {\n objectsAreSame = this.compareObjects(x[propertyName], y[propertyName]);\n if (!objectsAreSame) break;\n } else {\n if (x[propertyName] !== y[propertyName]) {\n objectsAreSame = false;\n break;\n }\n }\n }\n\n return objectsAreSame;\n },\n escapeId: function escapeId(id) {\n if (id) {\n return id.replace(/([ #;&,.+*~':\"!^$[\\]()=>|/@])/g, '\\\\$1');\n }\n\n return '';\n },\n selectorId: function selectorId(id) {\n if (typeof id === 'string' && id.substring(0, 1) !== '#') {\n return '#' + id;\n } else {\n return id;\n }\n },\n //Genera un identificador aleatorio para un objeto determinado\n randomIdGenerator: function randomIdGenerator(selectObject) {\n var id = 'rupRandomLayerId-' + $.rup_utils.autoGenerateIdNum;\n selectObject.attr('id', id).addClass('rupRandomLayerId');\n $.rup_utils.autoGenerateIdNum = $.rup_utils.autoGenerateIdNum + 1;\n return id;\n },\n //Función encargada de gestionar las url's de las aplicaciones en portal\n setNoPortalParam: function setNoPortalParam(url) {\n if (url !== undefined && url !== null) {\n if ($.rup_utils.readCookie('r01PortalInfo') !== null && url.match('R01HNoPortal') === null && $('div.r01gContainer').length > 0 || $('div.r01gApplication').length > 0) {\n return url + (url.match('\\\\?') === null ? '?' : '&') + 'R01HNoPortal=true';\n }\n }\n\n return url;\n },\n //Función encargada de detectar si la aplicación esta integrada en portal\n aplicatioInPortal: function aplicatioInPortal() {\n if (!($.rup_utils.readCookie('r01PortalInfo') !== null && $('div.r01gContainer').length > 0)) {\n return false;\n } else {\n return true;\n }\n },\n //Funcion encargada de pasar las urls relativas a absolutas.\n //Esta diseñado para terminar con los problemas de comportamientos anómalo de los navegadores en la redirecciones relativas\n relToAbsUrl: function relToAbsUrl(url) {\n var urlPage = $(location);\n\n if (typeof url === 'string') {\n var fChar1 = url.substring(0, 1);\n var fChar2 = url.substring(1, 2);\n\n if ($.url(url).attr('protocol') === undefined || $.url(url).attr('protocol') === '') {\n if (fChar1 === '/') {\n if (fChar2 === undefined || fChar2 !== '/') {\n return urlPage.attr('protocol') + '//' + urlPage.attr('host') + url;\n } else {\n return urlPage.attr('protocol') + url;\n }\n } else if (fChar1 === '.') {\n if (fChar2 === undefined) {\n $.rup.errorGestor($.rup.i18nParse($.rup.i18n.base, 'rup_utils.relToAbsUrlParamError') + url + $.rup.i18nParse($.rup.i18n.base, 'rup_utils.relToAbsUrlParamErrorEnd'));\n return undefined;\n } else if (fChar2 === '/') {\n var analyzedUrl = $.url(urlPage.attr('href'), true);\n return analyzedUrl.attr('base') + analyzedUrl.attr('directory') + url.substring(2, url.length);\n } else if (fChar2 === '.') {\n var urlPageFragments = urlPage.attr('pathname').split('/');\n var urlPageLength = urlPageFragments.length - 2;\n\n if (url.substring(2, 3) !== undefined && url.substring(2, 3) === '/') {\n var urlFragments = url.split('../');\n var urlLength = urlFragments.length - 1;\n\n if (urlLength >= urlPageLength) {\n return urlPage.attr('protocol') + '//' + urlPage.attr('host') + '/' + urlFragments[urlFragments.length - 1];\n } else {\n var cade = '';\n\n for (var i = urlPageLength - urlLength; i > 0; i--) {\n cade = urlPageFragments[i] + '/' + cade;\n }\n\n return urlPage.attr('protocol') + '//' + urlPage.attr('host') + '/' + cade + urlFragments[urlFragments.length - 1];\n }\n } else {\n var _urlFragments = url.split('..');\n\n var _urlLength = _urlFragments.length - 1;\n\n if (_urlLength >= urlPageLength) {\n return urlPage.attr('protocol') + '//' + urlPage.attr('host') + _urlFragments[_urlFragments.length - 1];\n } else {\n var _cade = '';\n\n for (var _i = urlPageLength - _urlLength; _i > 0; _i--) {\n _cade = urlPageFragments[_i] + '/' + _cade;\n }\n\n return urlPage.attr('protocol') + '//' + urlPage.attr('host') + '/' + _cade + _urlFragments[_urlFragments.length - 1];\n }\n }\n } else {\n $.rup.errorGestor($.rup.i18nParse($.rup.i18n.base, 'rup_utils.relToAbsUrlParamError') + url + $.rup.i18nParse($.rup.i18n.base, 'rup_utils.relToAbsUrlParamErrorEnd'));\n return undefined;\n }\n } else {\n var _analyzedUrl = $.url(urlPage.attr('href'), true);\n\n return _analyzedUrl.attr('base') + _analyzedUrl.attr('directory') + url;\n }\n } else {\n return url;\n }\n } else {\n $.rup.errorGestor($.rup.i18nParse($.rup.i18n.base, 'rup_utils.relToAbsUrlParamFormatError'));\n return undefined;\n }\n },\n printMsg: function printMsg(msg) {\n var ret = '';\n\n if (typeof msg === 'string') {\n return msg + '
';\n } else if (_typeof(msg) === 'object') {\n if (Array.isArray(msg)) {\n for (var i = 0; i < msg.length; i++) {\n ret += $.rup_utils.printMsgAux(msg[i], 1);\n }\n\n return ret;\n } else {\n ret += $.rup_utils.printMsgAux(msg, 1);\n }\n }\n\n return ret;\n },\n printMsgAux: function printMsgAux(msg, nivel) {\n var ret = '';\n\n if (typeof msg === 'string') {\n return $('
').append(msg)[0].outerHTML + '
';\n } else if (_typeof(msg) === 'object') {\n if (Array.isArray(msg)) {\n var ul = $('').addClass('rup-maint_feedbackUL');\n\n for (var i = 0; i < msg.length; i++) {\n //\t\t\t\t\t\tif (typeof msg[i]===\"string\" || (typeof msg[i]===\"object\" && !Array.isArray(msg))){\n if (nivel === 1) {\n ul.append($('- ').append($.rup_utils.printMsgAux(msg[i], nivel + 1)));\n } else {\n ul.append($.rup_utils.printMsgAux(msg[i], nivel + 1));\n }\n }\n\n return ret += ul[0].outerHTML;\n } else {\n var span = $('');\n\n if (msg.style !== undefined) {\n span.addClass(msg.style);\n }\n\n if (msg.label !== undefined) {\n span.append(msg.label);\n }\n\n return span[0].outerHTML + '
';\n }\n }\n },\n //Función encargada de recuperar todas las variables pasadas por QueryString (en la url)\n getUrlVars: function getUrlVars() {\n if ($.rup.getParams === undefined) {\n var vars = {},\n hash;\n var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');\n\n for (var i = 0; i < hashes.length; i++) {\n hash = decodeURIComponent(hashes[i]).split('=');\n vars[hash[0]] = hash[1];\n }\n\n $.rup.getParams = vars;\n }\n\n return $.rup.getParams;\n },\n //Función encargada de recuperar una variable especifica de las pasadas por QueryString (en la url)\n getUrlVar: function getUrlVar(name) {\n return $.rup_utils.getUrlVars()[name];\n },\n sortArray: function sortArray(array, sortFnc) {\n function defaultSortFnc(obj1, obj2) {\n return obj1 - obj2;\n }\n\n function bubbleSort(a, fnc) {\n var swapped;\n\n do {\n swapped = false;\n\n for (var i = 0; i < a.length - 1; i++) {\n if (fnc(a[i], a[i + 1]) < 0) {\n var temp = a[i];\n a[i] = a[i + 1];\n a[i + 1] = temp;\n swapped = true;\n }\n }\n } while (swapped);\n }\n\n if (!Array.isArray(array)) {\n return undefined;\n }\n\n if (typeof sortFnc === \"function\") {\n bubbleSort(array, sortFnc);\n } else {\n bubbleSort(array, defaultSortFnc);\n }\n },\n insertSorted: function insertSorted(array, elem, sortFnc) {\n function defaultSortFnc(obj1, obj2) {\n return obj2 - obj1;\n }\n\n if (!Array.isArray(array)) {\n return undefined;\n }\n\n array.push(elem);\n\n if (typeof sortFnc === \"function\") {\n $.rup_utils.sortArray(array, sortFnc);\n } else {\n $.rup_utils.sortArray(array, defaultSortFnc);\n }\n\n return $.inArray(elem, array);\n },\n getRupValueAsJson: function getRupValueAsJson(name, value) {\n var arrTmp,\n dotNotation = false,\n dotProperty,\n tmpJson,\n returnArray = [];\n\n if (name) {\n // Miramos si el name contiene notación dot\n arrTmp = name.split('.');\n\n if (arrTmp.length > 1) {\n dotNotation = true;\n dotProperty = arrTmp[arrTmp.length - 1];\n } else {\n dotProperty = arrTmp[0];\n }\n\n if (Array.isArray(value)) {\n //issue [utils] getRupValueAsJson provoca error con los arrays vacíos #24\n //https://github.com/UDA-EJIE/udaRUP/issues/24\n if (value.length !== 0) {\n // Devolvemos un array de resultados.\n for (var i = 0; i < value.length; i++) {\n tmpJson = {};\n\n if (dotNotation) {\n tmpJson[dotProperty] = value[i];\n returnArray.push(tmpJson);\n } else {\n tmpJson[dotProperty] = value[i];\n returnArray.push(tmpJson);\n }\n }\n\n return returnArray;\n }\n } else {\n // Devolvemos un único valor.\n tmpJson = {};\n tmpJson[dotProperty] = value;\n return tmpJson;\n }\n }\n\n return null;\n },\n getRupValueWrapped: function getRupValueWrapped(name, value) {\n var arrTmp,\n dotProperty,\n wrapObj = {};\n\n if (name) {\n // Miramos si el name contiene notación dot\n arrTmp = name.split('.');\n\n if (arrTmp.length > 1) {\n dotProperty = arrTmp[arrTmp.length - 1];\n } else {\n return value;\n }\n\n wrapObj[dotProperty] = value;\n return wrapObj;\n }\n\n return null;\n },\n swing2Top: function swing2Top() {\n if (!$.rup_utils.swinging) {\n $.rup_utils.swinging = true;\n $('html, body').animate({\n scrollTop: 0\n }, '1000', 'swing', function () {\n $.rup_utils.swinging = false;\n });\n }\n },\n format: function format(_format) {\n var args = $.makeArray(arguments).slice(1);\n\n if (_format == null) {\n _format = '';\n }\n\n return _format.replace(/\\{(\\d+)\\}/g, function (m, i) {\n return args[i];\n });\n },\n deepCopy: function deepCopy(obj, deep) {\n var deepCont = 0;\n var objBox = [];\n\n var fnc = function fnc(obj) {\n var objtmp;\n\n if (obj instanceof Array) {\n objtmp = [];\n } else {\n objtmp = {};\n }\n\n if (obj === null || obj === undefined) {\n return {};\n }\n\n Object.keys(obj).forEach(function (e) {\n if (['string', 'number', 'boolean', 'function'].includes(_typeof(obj[e]))) {\n objtmp[e] = obj[e];\n } else {\n if (!objBox.includes(obj[e]) && deepCont <= deep) {\n objBox.push(obj[e]);\n deepCont++;\n objtmp[e] = $.rup_utils.deepCopy(obj[e]);\n } else {\n if (deepCont > deep) {\n objtmp[e] = obj[e];\n } else {\n objtmp[e] = '__ciclico__';\n }\n }\n }\n });\n return objtmp;\n };\n\n return fnc(obj);\n },\n\n /**\r\n * Comprueba si el parámetro es un número. \r\n * Sustituye al método isNumeric de jQuery que fue deprecado en la versión 3.3.\r\n *\r\n * @name isNumeric\r\n * @function\r\n * @since UDA 5.1.0\r\n *\r\n * @param {number|string|boolean|object} field - Campo a comprobar.\r\n *\r\n * @return {boolean} Indica si es un número.\r\n * \r\n * @example\r\n * $.rup_utils.isNumeric(6);\r\n */\n isNumeric: function isNumeric(field) {\n return !isNaN(parseFloat(field)) && isFinite(field);\n }\n }); //Utilidades de los formularios\n\n $.fn.serializeToObject = function () {\n //Para enviar los campos que contienen valor (!= \"\")\n var o = {},\n a = this.serializeArrayWithoutNulls();\n $.each(a, function () {\n if (o[this.name]) {\n if (!o[this.name].push) {\n o[this.name] = [o[this.name]];\n }\n\n o[this.name].push(this.value || '');\n } else {\n o[this.name] = this.value;\n }\n });\n return o;\n };\n\n $.fn.serializeArrayWithoutNulls = function () {\n //crea un array con campos de un formulario que tienen valor !=\"\"\n return this.map(function () {\n return this.elements ? jQuery.makeArray(this.elements) : this;\n }).filter(function () {\n return this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i.test(this.type));\n }).map(function (i, elem) {\n var val = jQuery(this).val();\n\n if (jQuery(this).hasClass('numeric') || jQuery(this).hasClass('datepicker')\n /*&& val === \"\"*/\n ) {\n return {\n name: elem.name,\n value: null\n };\n }\n\n return val === null || val === '' ? null : Array.isArray(val) ? jQuery.map(val, function (val) {\n return {\n name: elem.name,\n value: val\n };\n }) : {\n name: elem.name,\n value: val\n };\n }).get();\n };\n\n $.fn.serializeObject = function () {\n //Para enviar los campos nulos con null en vez de en blanco\n var o = {},\n a = this.serializeArrayNull();\n $.each(a, function () {\n if (o[this.name]) {\n if (!o[this.name].push) {\n o[this.name] = [o[this.name]];\n }\n\n o[this.name].push(this.value || '');\n } else {\n o[this.name] = this.value;\n }\n });\n return o;\n };\n\n $.fn.serializeArrayNull = function () {\n return this.map(function () {\n return this.elements ? jQuery.makeArray(this.elements) : this;\n }).filter(function () {\n return this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i.test(this.type));\n }).map(function (i, elem) {\n var val = jQuery(this).val();\n\n if ((jQuery(this).hasClass('numeric') || jQuery(this).hasClass('datepicker')) && val === '') {\n return {\n name: elem.name,\n value: null\n };\n }\n\n return val === null ? null : Array.isArray(val) ? jQuery.map(val, function (val) {\n return {\n name: elem.name,\n value: val\n };\n }) : {\n name: elem.name,\n value: val\n };\n }).get();\n };\n /**\r\n * Elimina el campo autogenerado por el componente combo de un objeto. \r\n * Dicho campo sólo sirve para gestión interna, por lo tanto, es seguro y recomendable eliminarlo.\r\n *\r\n * @name deleteMulticomboLabelFromObject\r\n * @function\r\n * @since UDA 4.2.2\r\n *\r\n * @param {object} obj - Objeto del que se quiere eliminar el campo autogenerado.\r\n * @param {object} container - Contenedor del componente.\r\n */\n\n\n $.fn.deleteMulticomboLabelFromObject = function (obj, container) {\n if (obj !== undefined && obj !== null && container !== undefined && container !== null) {\n Object.keys(obj).filter(function (key) {\n // Se escapan todos los puntos para evitar errores sintácticos\n var escapedKey = key.replaceAll('.', '\\\\.'); // Si container es un fila de la tabla (tr) significa que la función ha sido llamada desde rup.table.inlineEdit y es necesario añadir el sufijo _inline\n\n var suffix = container.is('tr') ? '_inline' : '';\n var element = container.find(\"[name$=\" + escapedKey + suffix + \"]\");\n\n if (element.length > 1 && $(element[0]).prop('multiple')) {\n delete obj[\"_\" + key];\n }\n });\n }\n };\n /**\r\n * Elimina el campo autogenerado por el componente autocomplete de un objeto. \r\n * Dicho campo sólo sirve para gestión interna, por lo tanto, es seguro y recomendable eliminarlo.\r\n *\r\n * @name deleteAutocompleteLabelFromObject\r\n * @function\r\n * @since UDA 4.2.2\r\n *\r\n * @param {object} obj - Objeto del que se quiere eliminar el campo autogenerado.\r\n */\n\n\n $.fn.deleteAutocompleteLabelFromObject = function (obj) {\n if (obj !== undefined && obj !== null) {\n var flattenedObj = $.fn.flattenJSON(obj); // Nos aseguramos de que el campo _label provenga de un autocomplete\n\n Object.keys(flattenedObj).filter(function (key) {\n if (/_label$/.test(key)) {\n if (Object.prototype.hasOwnProperty.call(flattenedObj, key.substring(0, key.indexOf('_label')))) {\n // Necesario hacer un split por si la clave a usar está anidada\n var keys = key.split('.'); // Eliminamos el _label\n\n var recursiveRemoveKey = function recursiveRemoveKey(object, deleteKey) {\n if (object[deleteKey] != undefined) {\n delete object[deleteKey];\n } else {\n Object.values(object).forEach(function (val) {\n if (_typeof(val) === 'object') {\n recursiveRemoveKey(val, deleteKey);\n }\n });\n }\n };\n\n recursiveRemoveKey(obj, keys[keys.length - 1]);\n }\n }\n });\n }\n };\n /**\r\n * Convierte un JSON con múltiples niveles en un JSON con un único nivel.\r\n *\r\n * @name flattenJSON\r\n * @function\r\n * @since UDA 5.0.2\r\n *\r\n * @param {object} originalObj - Objeto con varios niveles (admite también un único nivel, pero no tiene sentido llamar a la función en ese caso).\r\n * @param {object} flattenedObj - Objeto con un único nivel. Se incluye entre los parámetros porque la función lo usará si se llama a sí misma.\r\n * @param {string} extraKey - Clave necesaria cuando hay más de un nivel. Se incluye entre los parámetros porque la función lo usará si se llama a sí misma.\r\n * \r\n * @return {object} Objeto con un único nivel.\r\n */\n\n\n $.fn.flattenJSON = function (originalObj) {\n var flattenedObj = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var extraKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';\n\n for (var key in originalObj) {\n if (_typeof(originalObj[key]) !== 'object') {\n flattenedObj[extraKey + key] = originalObj[key];\n } else {\n $.fn.flattenJSON(originalObj[key], flattenedObj, \"\".concat(extraKey).concat(key, \".\"));\n }\n }\n\n return flattenedObj;\n };\n /**\r\n * Comprueba si el parámetro ha sido cifrado por Hdiv.\r\n *\r\n * @name isHdiv\r\n * @function\r\n * @since UDA 5.0.0\r\n *\r\n * @param {string} id - Identificador de la entidad.\r\n *\r\n * @return {boolean} Verdadero si el parámetro ha sido cifrado por Hdiv.\r\n */\n\n\n $.fn.isHdiv = function (id) {\n return /^([a-zA-Z0-9]*-){4}[a-zA-Z0-9]*-:\\$:-[a-zA-Z0-9]{1,}$/.test(id);\n };\n /**\r\n * Procesa el identificador recibido para poder devolver la parte que no altera su cifrado entre peticiones.\r\n * Es útil cuando se necesita comparar identificadores cifrados. Nota: desde la versión 5.2.0, los identificadores\r\n * no alteran su cifrado entre peticiones, por lo que ha dejado de ser necesario usar este método.\r\n *\r\n * @deprecated since version 5.2.0\r\n * @name getStaticHdivID\r\n * @function\r\n * @since UDA 5.0.0\r\n *\r\n * @param {string} id - Identificador de la entidad.\r\n *\r\n * @return {string} Identificador de la entidad con la parte dinámica del cifrado eliminada.\r\n */\n\n\n $.fn.getStaticHdivID = function (id) {\n return id;\n };\n /**\r\n * Obtiene el parámetro HDIV_STATE de la URL o de un formulario.\r\n *\r\n * @name getHDIV_STATE\r\n * @function\r\n * @since UDA 5.0.0\r\n *\r\n * @param {boolean} hasMoreParams - Parámetro necesario para peticiones GET. Se utilizará para saber si el parámetro HDIV_STATE es el único existente en la URL.\r\n * @param {object} $form - Formulario del que extraer el parámetro HDIV_STATE. Este parámetro tiene prioridad respecto a hasMoreParams, por lo tanto, si se recibe será el que se use.\r\n *\r\n * @return {string} Parámetro HDIV_STATE.\r\n */\n\n\n $.fn.getHDIV_STATE = function (hasMoreParams, $form) {\n var hdivStateParam = ''; // Cuando se recibe un formulario se extrae directamente de ahí el parámetro HDIV_STATE\n\n if ($form != undefined && $form.length == 1) {\n var fieldHdiv = $form.find('input[name=\"_HDIV_STATE_\"]');\n hdivStateParam = fieldHdiv.length == 1 ? fieldHdiv.val() : '';\n } else {\n // Si el parámetro HDIV_STATE está disponible se obtiene y se devuelve, en caso contrario, se devuelve vacío\n var searchParams = new URLSearchParams(window.location.search);\n hdivStateParam = searchParams.get('_HDIV_STATE_');\n var prefix = ''; // Si se ha especificado un valor booleano en el parámetro recibido es porque se trata de una petición GET\n\n if (hasMoreParams !== undefined && hasMoreParams !== null && typeof hasMoreParams === \"boolean\") {\n prefix = (hasMoreParams ? '&' : '?') + '_HDIV_STATE_=';\n }\n\n if (hdivStateParam != undefined && hdivStateParam != null && hdivStateParam != '') {\n hdivStateParam = prefix + hdivStateParam;\n } else {\n hdivStateParam = '';\n }\n }\n\n return hdivStateParam;\n };\n /**\r\n * Reinicia por completo los autocomplete de un formulario para que no sigan filtrando.\r\n *\r\n * @name resetAutocomplete\r\n * @function\r\n * @since UDA 4.2.2\r\n *\r\n * @param {string} type - Valor del atributo type.\r\n * @param {object} obj - Formulario del que obtener los autocompletes a reiniciar.\r\n */\n\n\n $.fn.resetAutocomplete = function (type, obj) {\n jQuery.each($('input[ruptype=autocomplete][type=' + type + ']', obj), function (index, elem) {\n $(\"#\" + elem.id).rup_autocomplete(\"setRupValue\", \"\");\n });\n };\n\n jQuery.rup_utils.base64 = {\n // private property\n _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n // public method for encoding\n encode: function encode(input) {\n var output = '';\n var chr1, chr2, chr3, enc1, enc2, enc3, enc4;\n var i = 0;\n input = jQuery.rup_utils.base64._utf8_encode(input);\n\n while (i < input.length) {\n chr1 = input.charCodeAt(i++);\n chr2 = input.charCodeAt(i++);\n chr3 = input.charCodeAt(i++);\n enc1 = chr1 >> 2;\n enc2 = (chr1 & 3) << 4 | chr2 >> 4;\n enc3 = (chr2 & 15) << 2 | chr3 >> 6;\n enc4 = chr3 & 63;\n\n if (isNaN(chr2)) {\n enc3 = enc4 = 64;\n } else if (isNaN(chr3)) {\n enc4 = 64;\n }\n\n output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);\n }\n\n return output;\n },\n // public method for decoding\n decode: function decode(input) {\n var output = '';\n var chr1, chr2, chr3;\n var enc1, enc2, enc3, enc4;\n var i = 0;\n input = input.replace(/[^A-Za-z0-9+/=]/g, '');\n\n while (i < input.length) {\n enc1 = this._keyStr.indexOf(input.charAt(i++));\n enc2 = this._keyStr.indexOf(input.charAt(i++));\n enc3 = this._keyStr.indexOf(input.charAt(i++));\n enc4 = this._keyStr.indexOf(input.charAt(i++));\n chr1 = enc1 << 2 | enc2 >> 4;\n chr2 = (enc2 & 15) << 4 | enc3 >> 2;\n chr3 = (enc3 & 3) << 6 | enc4;\n output = output + String.fromCharCode(chr1);\n\n if (enc3 != 64) {\n output = output + String.fromCharCode(chr2);\n }\n\n if (enc4 != 64) {\n output = output + String.fromCharCode(chr3);\n }\n }\n\n output = jQuery.rup_utils.base64._utf8_decode(output);\n return output;\n },\n // private method for UTF-8 encoding\n _utf8_encode: function _utf8_encode(string) {\n string = string.replace(/\\r\\n/g, '\\n');\n var utftext = '';\n\n for (var n = 0; n < string.length; n++) {\n var c = string.charCodeAt(n);\n\n if (c < 128) {\n utftext += String.fromCharCode(c);\n } else if (c > 127 && c < 2048) {\n utftext += String.fromCharCode(c >> 6 | 192);\n utftext += String.fromCharCode(c & 63 | 128);\n } else {\n utftext += String.fromCharCode(c >> 12 | 224);\n utftext += String.fromCharCode(c >> 6 & 63 | 128);\n utftext += String.fromCharCode(c & 63 | 128);\n }\n }\n\n return utftext;\n },\n // private method for UTF-8 decoding\n _utf8_decode: function _utf8_decode(utftext) {\n var string = '';\n var i = 0;\n var c1 = 0;\n var c2 = 0;\n var c3 = 0;\n\n while (i < utftext.length) {\n c1 = utftext.charCodeAt(i);\n\n if (c1 < 128) {\n string += String.fromCharCode(c1);\n i++;\n } else if (c1 > 191 && c1 < 224) {\n c2 = utftext.charCodeAt(i + 1);\n string += String.fromCharCode((c1 & 31) << 6 | c2 & 63);\n i += 2;\n } else {\n c2 = utftext.charCodeAt(i + 1);\n c3 = utftext.charCodeAt(i + 2);\n string += String.fromCharCode((c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63);\n i += 3;\n }\n }\n\n return string;\n }\n };\n});\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\")))\n\n//# sourceURL=webpack://rup/./src/rup.utils.js?");
+eval("/* WEBPACK VAR INJECTION */(function(jQuery) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/*!\r\n * Copyright 2016 E.J.I.E., S.A.\r\n *\r\n * Licencia con arreglo a la EUPL, Versión 1.1 exclusivamente (la «Licencia»);\r\n * Solo podrá usarse esta obra si se respeta la Licencia.\r\n * Puede obtenerse una copia de la Licencia en\r\n *\r\n * http://ec.europa.eu/idabc/eupl.html\r\n *\r\n * Salvo cuando lo exija la legislación aplicable o se acuerde por escrito,\r\n * el programa distribuido con arreglo a la Licencia se distribuye «TAL CUAL»,\r\n * SIN GARANTÍAS NI CONDICIONES DE NINGÚN TIPO, ni expresas ni implícitas.\r\n * Véase la Licencia en el idioma concreto que rige los permisos y limitaciones\r\n * que establece la Licencia.\r\n */\n\n/**\r\n * Módulo de utilidades comunes a todos los componentes RUP.
\r\n * Implementa métodos para la manipulación de JSON, formularios, formatos...\r\n *\r\n * @summary Librería de utilidades para los componentes RUP.\r\n * @module rup_utils\r\n * @memberOf jQuery\r\n */\n(function (factory) {\n if (true) {\n // AMD. Register as an anonymous module.\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\"), __webpack_require__(/*! jqueryUI */ \"./node_modules/jquery-ui-dist/jquery-ui.js\"), __webpack_require__(/*! ./core/utils/jquery.json-2.2 */ \"./src/core/utils/jquery.json-2.2.js\")], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?\n\t\t\t\t(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n } else {}\n})(function ($) {\n $.rup_utils = {};\n $.rup_utils.arr = [];\n $.rup_utils.autoGenerateIdNum = 0;\n $.rup_utils.swinging = false;\n $.extend($.rup_utils, {\n /**\r\n * Retorna el idioma actual capitalizado.\r\n *\r\n * El idioma actual se obtiene de la variable $.rup.lang\r\n *\r\n * @name jQuery.rup_utils#capitalizedLang\r\n * @function\r\n * @example\r\n * // Retorna \"Es\" para un valor \"es\" en $.rup.lang.\r\n * $.rup_utils.capitalizedLang();\r\n * @returns {string} - Idioma actual capitalizado\r\n */\n capitalizedLang: function capitalizedLang() {\n if ($.rup.lang == null) {\n return '';\n }\n\n return $.rup.lang.charAt(0).toUpperCase() + $.rup.lang.slice(1);\n },\n getJson: function getJson(obj, path) {\n var ret = $.extend({}, obj),\n split = path.split('.');\n\n if (split.length === 1) {\n return obj[split[0]];\n }\n\n for (var i = 0; i < split.length; i++) {\n ret = ret[split[i]];\n }\n\n return ret;\n },\n setJson: function setJson(obj, path, value) {\n var aux = obj,\n split = path.split('.');\n\n if (split.length === 1) {\n obj[split[0]] = value;\n } else {\n for (var i = 0; i < split.length - 1; i++) {\n aux = aux[split[i]];\n }\n\n aux[split[split.length - 1]] = value;\n }\n },\n\n /**\r\n * Transforma un objeto JSON en un array Javascript.\r\n *\r\n * @name jQuery.rup_utils#jsontoarray\r\n * @function\r\n * @param {Object} obj - Objeto JSON que se desea transformar en un array.\r\n * @returns {Object} - Array JavaScript.\r\n * @example\r\n * // Transforma un json obj={'prop':'value'} en un array arr['prop'] -> 'value'\r\n * var obj={'prop':'value'};\r\n * $.rup_utils.jsontoarray(obj);\r\n * @example\r\n * // Transforma un json obj={'propA':{'propAA':'value'}} en un array arr['propA.propAA'] -> 'value'\r\n * var obj={'propA':{'propAA':'value'}};\r\n * $.rup_utils.jsontoarray(obj);\r\n * @example\r\n * // Transforma un json obj={'propA':{'propAA':['a','b','c','d']}} en un array arr['propA.propAA[0]']\r\n * var obj={'propA':{'propAA':['a','b','c','d']}};\r\n * $.rup_utils.jsontoarray(obj);\r\n */\n jsontoarray: function jsontoarray(obj) {\n var arr = [];\n\n function parseJSON(obj, path) {\n // parsea un json a un array\n path = path || ''; // iteracion a traves (objects / arrays)\n\n if (obj === undefined || obj === null) {\n // Si no existe un valor para el path indicado se envia ''\n parseJSON('', path);\n } else if (obj.constructor == Object) {\n for (var prop in obj) {\n //var name = path + (path == '' ? prop : '[' + prop + ']');\n var name = path + (path == '' ? prop : '.' + prop);\n parseJSON(obj[prop], name);\n }\n } else if (obj.constructor == Array) {\n if (obj.length == 0) {\n parseJSON('[]', path);\n } else {\n for (var i = 0; i < obj.length; i++) {\n var index = '[' + i + ']',\n _name = path + index;\n\n parseJSON(obj[i], _name);\n }\n }\n } else {\n // assignment (values) if the element name hasn't yet been defined, create it as a single value\n if (arr[path] == undefined) {\n arr[path] = obj;\n } else if (arr[path].constructor != Array) {\n // if the element name HAS been defined, but it's a single value, convert to an array and add the new value\n arr[path] = [arr[path], obj];\n } else {\n // if the element name HAS been defined, and is already an array, push the single value on the end of the stack\n arr[path].push(obj);\n }\n }\n }\n\n parseJSON(obj);\n return arr;\n },\n\n /**\r\n * Realiza una desanidacion del json pasado (p.e.: {entidad:{propiedad:valor}} --> {'entidad.propiedad':valor}.\r\n *\r\n * @name jQuery.rup_utils#unnestjson\r\n * @function\r\n * @param {Object} obj - Objeto JSON que se desea desanidar.\r\n * @returns {Object} - Objeto JSON desanidado.\r\n * @example\r\n * // Transforma un json obj={'propA':{'propAA':'valueAA'}} en un json obj={'propA.propAA':'valueAA'}}\r\n * var obj={'propA':{'propAA':'valueAA'}};\r\n * $.rup_utils.unnestjson(obj);\r\n */\n unnestjson: function unnestjson(obj) {\n var array = $.rup_utils.jsontoarray(obj);\n var json = {};\n\n for (var key in array) {\n if (typeof array[key] !== \"function\") {\n json[key] = array[key];\n }\n }\n\n return json;\n },\n\n /**\r\n * Devuelve el objeto del dom existente en la posición indicada.\r\n *\r\n * @name jQuery.rup_utils#elementFromPoint\r\n * @function\r\n * @param {number} x - Coordenada x de la posición en la pantalla.\r\n * @param {number} y - Coordenada y de la posición en la pantalla.\r\n * @param {boolean} [argCheck=true] - Determina si debe de ajustarse en base al scroll realizado en la pantalla .\r\n * @returns {Object} - Objeto del DOM correspodiente a la posición indicada.\r\n * @example\r\n * $.rup_utils.elementFromPoint(120,140);\r\n */\n elementFromPoint: function elementFromPoint(x, y, argCheck) {\n var isRelative = true,\n check = argCheck || true;\n if (!document.elementFromPoint) return null;\n\n if (!check) {\n var sl;\n\n if ((sl = $(document).scrollTop()) > 0) {\n isRelative = document.elementFromPoint(0, sl + $(window).height() - 1) == null;\n } else if ((sl = $(document).scrollLeft()) > 0) {\n isRelative = document.elementFromPoint(sl + $(window).width() - 1, 0) == null;\n }\n\n check = sl > 0;\n }\n\n if (!isRelative) {\n x += $(document).scrollLeft();\n y += $(document).scrollTop();\n }\n\n return document.elementFromPoint(x, y);\n },\n\n /**\r\n * Convierte en mínusculas el primer caracter de la cadena de caracteres pasada como parámetro.\r\n *\r\n * @name jQuery.rup_utils#firstCharToLowerCase\r\n * @function\r\n * @param {string} cadena - Cadena de caracteres inicial.\r\n * @returns {string} - Cadena de caracteres resultante con su primer caracter convertido a minúsculas.\r\n * @example\r\n * // Convierte a minúsculas el primer caracter de la cadena \"AbCdEfg\" -> \"abCdEfg\"\r\n * $.rup_utils.firstCharToLowerCase(\"AbCdEfg\");\r\n */\n firstCharToLowerCase: function firstCharToLowerCase(cadena) {\n return cadena.substring(0, 1).toLowerCase() + cadena.substring(1);\n },\n\n /**\r\n * Devuelve un string que puede ser utilizado como selector de jQuery mediante el id ('#'). El método permite también escapar los caracteres reservados en los selectores de jQuery\r\n *\r\n * @name jQuery.rup_utils#firstCharToLowerCase\r\n * @function\r\n * @param {string} cadena - Cadena de caracteres inicial.\r\n * @returns {string} - Cadena de caracteres resultante con su primer caracter convertido a minúsculas.\r\n * @example\r\n * // Convierte a minúsculas el primer caracter de la cadena \"AbCdEfg\" -> \"abCdEfg\"\r\n * $.rup_utils.firstCharToLowerCase(\"AbCdEfg\");\r\n */\n getJQueryId: function getJQueryId(sid, escaped) {\n var returnIdSelector;\n\n if (typeof sid === 'string') {\n returnIdSelector = sid;\n\n if (escaped === true) {\n returnIdSelector = String(returnIdSelector).replace(/[!\"#$%&'()*+,./:; <=>?@[\\\\\\]^`{|}~]/g, '\\\\$&');\n }\n\n return returnIdSelector[0] === '#' ? returnIdSelector : '#' + returnIdSelector;\n }\n\n return null;\n },\n\n /**\r\n * Convierte una cadena querystring en un objeto json.\r\n *\r\n * @name jQuery.rup_utils#queryStringToJson\r\n * @function\r\n * @param {string} queryString - Query string a transformar en un objeto json.\r\n * @param {string} [serializerSplitter=&] - Cadena a usar para separar los campos.\r\n * @param {boolean} [allowAllCharacters=false] - Habilita la posibilidad de incluir cualquier carácter en los campos.\r\n * @returns {object} - Objeto JSON creado a partir de la query string indicada.\r\n * @example\r\n * // Obtene un json a partir del query string \"keyA=valueA&keyB=valueB&keyC=valueC\" -> \"{keyA:'valueA', keyB:'valueB', keyC:'valueC'}\"\r\n * $.rup_utils.queryStringToJson(\"keyA=valueA&keyB=valueB&keyC=valueC\");\r\n */\n queryStringToJson: function queryStringToJson(queryString) {\n var serializerSplitter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '&';\n var allowAllCharacters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\n function setValue(root, path, value) {\n if (path.length > 1) {\n var dir = path.shift();\n\n if (typeof root[dir] == 'undefined') {\n root[dir] = path[0] == '' ? [] : {};\n }\n\n arguments.callee(root[dir], path, value);\n } else {\n if (root instanceof Array) {\n root.push(value);\n } else if (path[0].indexOf('.') != -1) {\n // Entra por aquí en caso de que uno de los path sea un objeto\n var padre = path[0].slice(0, path[0].indexOf('.'));\n var hijo = path[0].slice(path[0].indexOf('.') + 1, path[0].length);\n\n if (root[padre] != undefined) {\n root[padre][hijo] = value;\n } else {\n root[padre] = _defineProperty({}, hijo, value);\n }\n } else {\n root[path] = value;\n }\n }\n }\n\n var nvp = [],\n nvpBruto = queryString.split(serializerSplitter),\n data = {},\n pair,\n name,\n value,\n path,\n first; //Se revisa la correcta gestion de los campos\n\n for (var i = 0; i < nvpBruto.length; i++) {\n pair = nvpBruto[i].split('=');\n\n if (pair.length >= 2) {\n nvp.push(nvpBruto[i]);\n } else if (pair.length == 1) {\n nvp[i - 1] = nvp[i - 1] + serializerSplitter + nvpBruto[i];\n }\n }\n\n for (var i = 0; i < nvp.length; i++) {\n pair = nvp[i].split('=');\n\n if (pair.length > 2) {\n var pairAux = '';\n\n for (var j = 1; j < pair.length; j++) {\n if (j == 1) {\n pairAux = pair[j];\n } else {\n pairAux = pairAux + \"=\" + pair[j];\n }\n }\n\n pair[pair.length - 1] = pairAux;\n }\n\n name = decodeURIComponent(pair[0]);\n\n if (pair[pair.length - 1].includes(\"%\")) {\n if (allowAllCharacters && !pair[pair.length - 1].includes(\"%25\")) {\n pair[pair.length - 1] = encodeURIComponent(pair[pair.length - 1]);\n } else if (!allowAllCharacters) {\n $.rup.errorGestor($.rup.i18nParse($.rup.i18n.base, 'rup_utils.illegalChar'));\n }\n }\n\n value = decodeURIComponent(pair[pair.length - 1]);\n path = name.match(/(^[^[]+)(\\[.*\\]$)?/);\n first = path[1];\n\n if (path[2]) {\n // case of 'array[level1]' ||\n // 'array[level1][level2]'\n path = path[2].match(/(?=\\[(.*)\\]$)/)[1].split('][');\n } else {\n // case of 'name'\n path = [];\n }\n\n path.unshift(first);\n setValue(data, path, value);\n }\n\n return data;\n },\n\n /**\r\n * Devuelve un string con los caracteres sencillos.\r\n *\r\n * @name normalize\r\n * @function\r\n * @since UDA 3.3.0\r\n * \r\n * @param {string} texto - Cadena de caracteres inicial.\r\n * @returns {string} - Cadena de caracteres sin accentFolding.\r\n * \r\n * @example\r\n * // Convierte los caracteres de la cadena \"áéíóu\" a \"aeiou\"\r\n * $.rup_utils.normalize(\"áéíóu\");\r\n */\n normalize: function normalize(texto) {\n var accentMap = {\n 'á': 'a',\n 'é': 'e',\n 'í': 'i',\n 'ó': 'o',\n 'ú': 'u',\n 'Á': 'A',\n 'É': 'E',\n 'Í': 'I',\n 'Ó': 'O',\n 'Ú': 'U'\n };\n var cadena = '';\n\n for (var i = 0; i < texto.length; i++) {\n cadena += accentMap[texto.charAt(i)] || texto.charAt(i);\n }\n\n return cadena;\n },\n populateForm: function populateForm(aData, formid) {\n //rellena un formulario que recibe como segundo parametro con los datos que recibe en el segundo parametro\n var formElem;\n var tree_data, selectorArray;\n\n function loadedJstreeEvent() {\n var selectorArbol = this.id; //$(this).rup_tree(\"setRupValue\",$arbol[selectorArbol]);\n\n $(this).trigger('rup_filter_treeLoaded', $arbol[selectorArbol]);\n }\n\n function populateRadioCheckbox() {\n if ($(this).val() == aData[i]) {\n $(this).prop('checked', true);\n } else {\n $(this).prop('checked', false);\n }\n }\n\n if (aData) {\n for (var i in aData) {\n tree_data = [];\n formElem = $('[name=\\'' + i + '\\']', formid);\n\n if (formElem.length == 0) {\n selectorArray = i.substr(0, i.indexOf('['));\n formElem = $('[name=\\'' + selectorArray + '\\']', formid);\n }\n\n if (formElem.is('[ruptype]')) {\n if (formElem.hasClass('jstree')) {\n for (var a in aData) {\n if (a.substr(0, a.indexOf('[')) == selectorArray) {\n tree_data.push(aData[a]);\n }\n }\n\n formElem['rup_' + formElem.attr('ruptype')]('setRupValue', tree_data);\n var $arbol = [];\n $arbol[selectorArray] = tree_data;\n formElem.on('loaded.jstree', loadedJstreeEvent);\n } else {\n // Forma de evitar el EVAL\n formElem['rup_' + formElem.attr('ruptype')]('setRupValue', aData[i]);\n }\n } else if (formElem.is('input:radio') || formElem.is('input:checkbox')) {\n formElem.each(populateRadioCheckbox);\n } else if (formElem.is('select')) {\n formElem.val(aData[i]).click();\n } else if (formElem.is(':not(img)')) {\n // this is very slow on big table and form.\n formElem.val(aData[i]);\n }\n }\n }\n },\n //DATE UTILS\n createDate: function createDate(day, month, year) {\n return $.datepicker.formatDate($.rup.i18n.base.rup_date.dateFormat, new Date(year, month - 1, day));\n },\n createTime: function createTime(hour, minute, second) {\n return new Date(null, null, null, hour, minute, second);\n },\n\n /*!\r\n * jQuery CooQuery Plugin v2\r\n * http://cooquery.lenonmarcel.com.br/\r\n *\r\n * Copyright 2009, 2010 Lenon Marcel\r\n * Dual licensed under the MIT and GPL licenses.\r\n * http://www.opensource.org/licenses/mit-license.php\r\n * http://www.gnu.org/licenses/gpl.html\r\n *\r\n * Date: 2010-01-24 (Sun, 24 January 2010)\r\n */\n //TODO: Documentacion -> http://plugins.jquery.com/project/cooquery\n setCookie: function setCookie(name, value, options) {\n if (typeof name === 'undefined' || typeof value === 'undefined' || name === null || value === null) {\n $.rup.errorGestor('[' + $.rup.i18nParse($.rup.i18n.base, 'rup_global.metodError') + 'setCookie] - ' + $.rup.i18nParse($.rup.i18n.base, 'rup_utils.paramsError'));\n return false;\n }\n\n var str = name + '=' + encodeURIComponent(value);\n\n if (typeof options !== 'undefined' && options !== null) {\n if (options.domain) str += '; domain=' + options.domain;\n if (options.path) str += '; path=' + options.path;\n\n if (options.duration) {\n var date = new Date();\n date.setTime(date.getTime() + options.duration * 24 * 60 * 60 * 1000);\n str += '; expires=' + date.toGMTString();\n }\n\n if (options.secure) str += '; secure';\n }\n\n return document.cookie = str;\n },\n delCookie: function delCookie(name) {\n if (typeof name === 'undefined' || name === null) {\n $.rup.errorGestor('[' + $.rup.i18nParse($.rup.i18n.base, 'rup_global.metodError') + 'delCookie] - ' + $.rup.i18nParse($.rup.i18n.base, 'rup_utils.paramsError'));\n return false;\n }\n\n return $.rup_utils.setCookie(name, '', {\n duration: -1\n });\n },\n readCookie: function readCookie(name) {\n if (typeof name === 'undefined' || name === null) {\n $.rup.errorGestor('[' + $.rup.i18nParse($.rup.i18n.base, 'rup_global.metodError') + 'readCookie] - ' + $.rup.i18nParse($.rup.i18n.base, 'rup_utils.paramsError'));\n return false;\n }\n\n var value = document.cookie.match('(?:^|;)\\\\s*' + name.replace(/([-.*+?^${}()|[\\]/\\\\])/g, '\\\\$1') + '=([^;]*)');\n return value ? decodeURIComponent(value[1]) : null;\n },\n get: function get(name, json) {\n var cookieValue = null;\n\n if (document.cookie && document.cookie != '') {\n var cookies = document.cookie.split(';');\n\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i].trim();\n\n if (cookie.substring(0, name.length + 1) == name + '=') {\n cookieValue = json ? $.JSON.decode(decodeURIComponent(cookie.substring(name.length + 1))) : decodeURIComponent(cookie.substring(name.length + 1));\n break;\n }\n }\n }\n\n return cookieValue;\n },\n set: function set(name, value, options) {\n options = $.extend({}, options);\n\n if (value === null) {\n value = '';\n options.expires = -1;\n }\n\n var expires = '';\n\n if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {\n var date;\n\n if (typeof options.expires == 'number') {\n date = new Date();\n date.setTime(date.getTime() + options.expires * 24 * 60 * 60 * 1000);\n } else {\n date = options.expires;\n }\n\n expires = '; expires=' + date.toUTCString();\n }\n\n value = options.json ? encodeURIComponent($.JSON.encode(value)) : encodeURIComponent(value);\n var path = options.path ? '; path=' + options.path : '';\n var domain = options.domain ? '; domain=' + options.domain : '';\n var secure = options.secure ? '; secure' : '';\n document.cookie = [name, '=', value, expires, path, domain, secure].join('');\n },\n //compare objects function\n compareObjects: function compareObjects(x, y) {\n var objectsAreSame = true;\n\n if (Object.keys(x).length !== Object.keys(y).length) {\n return false;\n }\n\n for (var propertyName in x) {\n if (_typeof(x[propertyName]) == 'object' && _typeof(y[propertyName]) == 'object') {\n objectsAreSame = this.compareObjects(x[propertyName], y[propertyName]);\n if (!objectsAreSame) break;\n } else {\n if (x[propertyName] !== y[propertyName]) {\n objectsAreSame = false;\n break;\n }\n }\n }\n\n return objectsAreSame;\n },\n escapeId: function escapeId(id) {\n if (id) {\n return id.replace(/([ #;&,.+*~':\"!^$[\\]()=>|/@])/g, '\\\\$1');\n }\n\n return '';\n },\n selectorId: function selectorId(id) {\n if (typeof id === 'string' && id.substring(0, 1) !== '#') {\n return '#' + id;\n } else {\n return id;\n }\n },\n //Genera un identificador aleatorio para un objeto determinado\n randomIdGenerator: function randomIdGenerator(selectObject) {\n var id = 'rupRandomLayerId-' + $.rup_utils.autoGenerateIdNum;\n selectObject.attr('id', id).addClass('rupRandomLayerId');\n $.rup_utils.autoGenerateIdNum = $.rup_utils.autoGenerateIdNum + 1;\n return id;\n },\n //Función encargada de gestionar las url's de las aplicaciones en portal\n setNoPortalParam: function setNoPortalParam(url) {\n if (url !== undefined && url !== null) {\n if ($.rup_utils.readCookie('r01PortalInfo') !== null && url.match('R01HNoPortal') === null && $('div.r01gContainer').length > 0 || $('div.r01gApplication').length > 0) {\n return url + (url.match('\\\\?') === null ? '?' : '&') + 'R01HNoPortal=true';\n }\n }\n\n return url;\n },\n //Función encargada de detectar si la aplicación esta integrada en portal\n aplicatioInPortal: function aplicatioInPortal() {\n if (!($.rup_utils.readCookie('r01PortalInfo') !== null && $('div.r01gContainer').length > 0)) {\n return false;\n } else {\n return true;\n }\n },\n //Funcion encargada de pasar las urls relativas a absolutas.\n //Esta diseñado para terminar con los problemas de comportamientos anómalo de los navegadores en la redirecciones relativas\n relToAbsUrl: function relToAbsUrl(url) {\n var urlPage = $(location);\n\n if (typeof url === 'string') {\n var fChar1 = url.substring(0, 1);\n var fChar2 = url.substring(1, 2);\n\n if ($.url(url).attr('protocol') === undefined || $.url(url).attr('protocol') === '') {\n if (fChar1 === '/') {\n if (fChar2 === undefined || fChar2 !== '/') {\n return urlPage.attr('protocol') + '//' + urlPage.attr('host') + url;\n } else {\n return urlPage.attr('protocol') + url;\n }\n } else if (fChar1 === '.') {\n if (fChar2 === undefined) {\n $.rup.errorGestor($.rup.i18nParse($.rup.i18n.base, 'rup_utils.relToAbsUrlParamError') + url + $.rup.i18nParse($.rup.i18n.base, 'rup_utils.relToAbsUrlParamErrorEnd'));\n return undefined;\n } else if (fChar2 === '/') {\n var analyzedUrl = $.url(urlPage.attr('href'), true);\n return analyzedUrl.attr('base') + analyzedUrl.attr('directory') + url.substring(2, url.length);\n } else if (fChar2 === '.') {\n var urlPageFragments = urlPage.attr('pathname').split('/');\n var urlPageLength = urlPageFragments.length - 2;\n\n if (url.substring(2, 3) !== undefined && url.substring(2, 3) === '/') {\n var urlFragments = url.split('../');\n var urlLength = urlFragments.length - 1;\n\n if (urlLength >= urlPageLength) {\n return urlPage.attr('protocol') + '//' + urlPage.attr('host') + '/' + urlFragments[urlFragments.length - 1];\n } else {\n var cade = '';\n\n for (var i = urlPageLength - urlLength; i > 0; i--) {\n cade = urlPageFragments[i] + '/' + cade;\n }\n\n return urlPage.attr('protocol') + '//' + urlPage.attr('host') + '/' + cade + urlFragments[urlFragments.length - 1];\n }\n } else {\n var _urlFragments = url.split('..');\n\n var _urlLength = _urlFragments.length - 1;\n\n if (_urlLength >= urlPageLength) {\n return urlPage.attr('protocol') + '//' + urlPage.attr('host') + _urlFragments[_urlFragments.length - 1];\n } else {\n var _cade = '';\n\n for (var _i = urlPageLength - _urlLength; _i > 0; _i--) {\n _cade = urlPageFragments[_i] + '/' + _cade;\n }\n\n return urlPage.attr('protocol') + '//' + urlPage.attr('host') + '/' + _cade + _urlFragments[_urlFragments.length - 1];\n }\n }\n } else {\n $.rup.errorGestor($.rup.i18nParse($.rup.i18n.base, 'rup_utils.relToAbsUrlParamError') + url + $.rup.i18nParse($.rup.i18n.base, 'rup_utils.relToAbsUrlParamErrorEnd'));\n return undefined;\n }\n } else {\n var _analyzedUrl = $.url(urlPage.attr('href'), true);\n\n return _analyzedUrl.attr('base') + _analyzedUrl.attr('directory') + url;\n }\n } else {\n return url;\n }\n } else {\n $.rup.errorGestor($.rup.i18nParse($.rup.i18n.base, 'rup_utils.relToAbsUrlParamFormatError'));\n return undefined;\n }\n },\n printMsg: function printMsg(msg) {\n var ret = '';\n\n if (typeof msg === 'string') {\n return msg + '
';\n } else if (_typeof(msg) === 'object') {\n if (Array.isArray(msg)) {\n for (var i = 0; i < msg.length; i++) {\n ret += $.rup_utils.printMsgAux(msg[i], 1);\n }\n\n return ret;\n } else {\n ret += $.rup_utils.printMsgAux(msg, 1);\n }\n }\n\n return ret;\n },\n printMsgAux: function printMsgAux(msg, nivel) {\n var ret = '';\n\n if (typeof msg === 'string') {\n return $('').append(msg)[0].outerHTML + '
';\n } else if (_typeof(msg) === 'object') {\n if (Array.isArray(msg)) {\n var ul = $('').addClass('rup-maint_feedbackUL');\n\n for (var i = 0; i < msg.length; i++) {\n //\t\t\t\t\t\tif (typeof msg[i]===\"string\" || (typeof msg[i]===\"object\" && !Array.isArray(msg))){\n if (nivel === 1) {\n ul.append($('- ').append($.rup_utils.printMsgAux(msg[i], nivel + 1)));\n } else {\n ul.append($.rup_utils.printMsgAux(msg[i], nivel + 1));\n }\n }\n\n return ret += ul[0].outerHTML;\n } else {\n var span = $('');\n\n if (msg.style !== undefined) {\n span.addClass(msg.style);\n }\n\n if (msg.label !== undefined) {\n span.append(msg.label);\n }\n\n return span[0].outerHTML + '
';\n }\n }\n },\n //Función encargada de recuperar todas las variables pasadas por QueryString (en la url)\n getUrlVars: function getUrlVars() {\n if ($.rup.getParams === undefined) {\n var vars = {},\n hash;\n var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');\n\n for (var i = 0; i < hashes.length; i++) {\n hash = decodeURIComponent(hashes[i]).split('=');\n vars[hash[0]] = hash[1];\n }\n\n $.rup.getParams = vars;\n }\n\n return $.rup.getParams;\n },\n //Función encargada de recuperar una variable especifica de las pasadas por QueryString (en la url)\n getUrlVar: function getUrlVar(name) {\n return $.rup_utils.getUrlVars()[name];\n },\n sortArray: function sortArray(array, sortFnc) {\n function defaultSortFnc(obj1, obj2) {\n return obj1 - obj2;\n }\n\n function bubbleSort(a, fnc) {\n var swapped;\n\n do {\n swapped = false;\n\n for (var i = 0; i < a.length - 1; i++) {\n if (fnc(a[i], a[i + 1]) < 0) {\n var temp = a[i];\n a[i] = a[i + 1];\n a[i + 1] = temp;\n swapped = true;\n }\n }\n } while (swapped);\n }\n\n if (!Array.isArray(array)) {\n return undefined;\n }\n\n if (typeof sortFnc === \"function\") {\n bubbleSort(array, sortFnc);\n } else {\n bubbleSort(array, defaultSortFnc);\n }\n },\n insertSorted: function insertSorted(array, elem, sortFnc) {\n function defaultSortFnc(obj1, obj2) {\n return obj2 - obj1;\n }\n\n if (!Array.isArray(array)) {\n return undefined;\n }\n\n array.push(elem);\n\n if (typeof sortFnc === \"function\") {\n $.rup_utils.sortArray(array, sortFnc);\n } else {\n $.rup_utils.sortArray(array, defaultSortFnc);\n }\n\n return $.inArray(elem, array);\n },\n getRupValueAsJson: function getRupValueAsJson(name, value) {\n var arrTmp,\n dotNotation = false,\n dotProperty,\n tmpJson,\n returnArray = [];\n\n if (name) {\n // Miramos si el name contiene notación dot\n arrTmp = name.split('.');\n\n if (arrTmp.length > 1) {\n dotNotation = true;\n dotProperty = arrTmp[arrTmp.length - 1];\n } else {\n dotProperty = arrTmp[0];\n }\n\n if (Array.isArray(value)) {\n //issue [utils] getRupValueAsJson provoca error con los arrays vacíos #24\n //https://github.com/UDA-EJIE/udaRUP/issues/24\n if (value.length !== 0) {\n // Devolvemos un array de resultados.\n for (var i = 0; i < value.length; i++) {\n tmpJson = {};\n\n if (dotNotation) {\n tmpJson[dotProperty] = value[i];\n returnArray.push(tmpJson);\n } else {\n tmpJson[dotProperty] = value[i];\n returnArray.push(tmpJson);\n }\n }\n\n return returnArray;\n }\n } else {\n // Devolvemos un único valor.\n tmpJson = {};\n tmpJson[dotProperty] = value;\n return tmpJson;\n }\n }\n\n return null;\n },\n getRupValueWrapped: function getRupValueWrapped(name, value) {\n var arrTmp,\n dotProperty,\n wrapObj = {};\n\n if (name) {\n // Miramos si el name contiene notación dot\n arrTmp = name.split('.');\n\n if (arrTmp.length > 1) {\n dotProperty = arrTmp[arrTmp.length - 1];\n } else {\n return value;\n }\n\n wrapObj[dotProperty] = value;\n return wrapObj;\n }\n\n return null;\n },\n swing2Top: function swing2Top() {\n if (!$.rup_utils.swinging) {\n $.rup_utils.swinging = true;\n $('html, body').animate({\n scrollTop: 0\n }, '1000', 'swing', function () {\n $.rup_utils.swinging = false;\n });\n }\n },\n format: function format(_format) {\n var args = $.makeArray(arguments).slice(1);\n\n if (_format == null) {\n _format = '';\n }\n\n return _format.replace(/\\{(\\d+)\\}/g, function (m, i) {\n return args[i];\n });\n },\n deepCopy: function deepCopy(obj, deep) {\n var deepCont = 0;\n var objBox = [];\n\n var fnc = function fnc(obj) {\n var objtmp;\n\n if (obj instanceof Array) {\n objtmp = [];\n } else {\n objtmp = {};\n }\n\n if (obj === null || obj === undefined) {\n return {};\n }\n\n Object.keys(obj).forEach(function (e) {\n if (['string', 'number', 'boolean', 'function'].includes(_typeof(obj[e]))) {\n objtmp[e] = obj[e];\n } else {\n if (!objBox.includes(obj[e]) && deepCont <= deep) {\n objBox.push(obj[e]);\n deepCont++;\n objtmp[e] = $.rup_utils.deepCopy(obj[e]);\n } else {\n if (deepCont > deep) {\n objtmp[e] = obj[e];\n } else {\n objtmp[e] = '__ciclico__';\n }\n }\n }\n });\n return objtmp;\n };\n\n return fnc(obj);\n },\n\n /**\r\n * Comprueba si el parámetro es un número. \r\n * Sustituye al método isNumeric de jQuery que fue deprecado en la versión 3.3.\r\n *\r\n * @name isNumeric\r\n * @function\r\n * @since UDA 5.1.0\r\n *\r\n * @param {number|string|boolean|object} field - Campo a comprobar.\r\n *\r\n * @return {boolean} Indica si es un número.\r\n * \r\n * @example\r\n * $.rup_utils.isNumeric(6);\r\n */\n isNumeric: function isNumeric(field) {\n return !isNaN(parseFloat(field)) && isFinite(field);\n }\n }); //Utilidades de los formularios\n\n $.fn.serializeToObject = function () {\n //Para enviar los campos que contienen valor (!= \"\")\n var o = {},\n a = this.serializeArrayWithoutNulls();\n $.each(a, function () {\n if (o[this.name]) {\n if (!o[this.name].push) {\n o[this.name] = [o[this.name]];\n }\n\n o[this.name].push(this.value || '');\n } else {\n o[this.name] = this.value;\n }\n });\n return o;\n };\n\n $.fn.serializeArrayWithoutNulls = function () {\n //crea un array con campos de un formulario que tienen valor !=\"\"\n return this.map(function () {\n return this.elements ? jQuery.makeArray(this.elements) : this;\n }).filter(function () {\n return this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i.test(this.type));\n }).map(function (i, elem) {\n var val = jQuery(this).val();\n\n if (jQuery(this).hasClass('numeric') || jQuery(this).hasClass('datepicker')\n /*&& val === \"\"*/\n ) {\n return {\n name: elem.name,\n value: null\n };\n }\n\n return val === null || val === '' ? null : Array.isArray(val) ? jQuery.map(val, function (val) {\n return {\n name: elem.name,\n value: val\n };\n }) : {\n name: elem.name,\n value: val\n };\n }).get();\n };\n\n $.fn.serializeObject = function () {\n //Para enviar los campos nulos con null en vez de en blanco\n var o = {},\n a = this.serializeArrayNull();\n $.each(a, function () {\n if (o[this.name]) {\n if (!o[this.name].push) {\n o[this.name] = [o[this.name]];\n }\n\n o[this.name].push(this.value || '');\n } else {\n o[this.name] = this.value;\n }\n });\n return o;\n };\n\n $.fn.serializeArrayNull = function () {\n return this.map(function () {\n return this.elements ? jQuery.makeArray(this.elements) : this;\n }).filter(function () {\n return this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i.test(this.type));\n }).map(function (i, elem) {\n var val = jQuery(this).val();\n\n if ((jQuery(this).hasClass('numeric') || jQuery(this).hasClass('datepicker')) && val === '') {\n return {\n name: elem.name,\n value: null\n };\n }\n\n return val === null ? null : Array.isArray(val) ? jQuery.map(val, function (val) {\n return {\n name: elem.name,\n value: val\n };\n }) : {\n name: elem.name,\n value: val\n };\n }).get();\n };\n /**\r\n * Elimina el campo autogenerado por el componente combo de un objeto. \r\n * Dicho campo sólo sirve para gestión interna, por lo tanto, es seguro y recomendable eliminarlo.\r\n *\r\n * @name deleteMulticomboLabelFromObject\r\n * @function\r\n * @since UDA 4.2.2\r\n *\r\n * @param {object} obj - Objeto del que se quiere eliminar el campo autogenerado.\r\n * @param {object} container - Contenedor del componente.\r\n */\n\n\n $.fn.deleteMulticomboLabelFromObject = function (obj, container) {\n if (obj !== undefined && obj !== null && container !== undefined && container !== null) {\n Object.keys(obj).filter(function (key) {\n // Se escapan todos los puntos para evitar errores sintácticos\n var escapedKey = key.replaceAll('.', '\\\\.'); // Si container es un fila de la tabla (tr) significa que la función ha sido llamada desde rup.table.inlineEdit y es necesario añadir el sufijo _inline\n\n var suffix = container.is('tr') ? '_inline' : '';\n var element = container.find(\"[name$=\" + escapedKey + suffix + \"]\");\n\n if ($(element[0]).prop('multiple')) {\n if (element.length > 1) {\n delete obj[\"_\" + key];\n }\n\n if (element.length == 1) {\n delete obj[\"multiselect_\" + $(element[0]).attr('id')];\n }\n }\n });\n }\n };\n /**\r\n * Elimina el campo autogenerado por el componente autocomplete de un objeto. \r\n * Dicho campo sólo sirve para gestión interna, por lo tanto, es seguro y recomendable eliminarlo.\r\n *\r\n * @name deleteAutocompleteLabelFromObject\r\n * @function\r\n * @since UDA 4.2.2\r\n *\r\n * @param {object} obj - Objeto del que se quiere eliminar el campo autogenerado.\r\n */\n\n\n $.fn.deleteAutocompleteLabelFromObject = function (obj) {\n if (obj !== undefined && obj !== null) {\n var flattenedObj = $.fn.flattenJSON(obj); // Nos aseguramos de que el campo _label provenga de un autocomplete\n\n Object.keys(flattenedObj).filter(function (key) {\n if (/_label$/.test(key)) {\n if (Object.prototype.hasOwnProperty.call(flattenedObj, key.substring(0, key.indexOf('_label')))) {\n // Necesario hacer un split por si la clave a usar está anidada\n var keys = key.split('.'); // Eliminamos el _label\n\n var recursiveRemoveKey = function recursiveRemoveKey(object, deleteKey) {\n if (object[deleteKey] != undefined) {\n delete object[deleteKey];\n } else {\n Object.values(object).forEach(function (val) {\n if (_typeof(val) === 'object') {\n recursiveRemoveKey(val, deleteKey);\n }\n });\n }\n };\n\n recursiveRemoveKey(obj, keys[keys.length - 1]);\n }\n }\n });\n }\n };\n /**\r\n * Convierte un JSON con múltiples niveles en un JSON con un único nivel.\r\n *\r\n * @name flattenJSON\r\n * @function\r\n * @since UDA 5.0.2\r\n *\r\n * @param {object} originalObj - Objeto con varios niveles (admite también un único nivel, pero no tiene sentido llamar a la función en ese caso).\r\n * @param {object} flattenedObj - Objeto con un único nivel. Se incluye entre los parámetros porque la función lo usará si se llama a sí misma.\r\n * @param {string} extraKey - Clave necesaria cuando hay más de un nivel. Se incluye entre los parámetros porque la función lo usará si se llama a sí misma.\r\n * \r\n * @return {object} Objeto con un único nivel.\r\n */\n\n\n $.fn.flattenJSON = function (originalObj) {\n var flattenedObj = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var extraKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';\n\n for (var key in originalObj) {\n if (_typeof(originalObj[key]) !== 'object') {\n flattenedObj[extraKey + key] = originalObj[key];\n } else {\n $.fn.flattenJSON(originalObj[key], flattenedObj, \"\".concat(extraKey).concat(key, \".\"));\n }\n }\n\n return flattenedObj;\n };\n /**\r\n * Comprueba si el parámetro ha sido cifrado por Hdiv.\r\n *\r\n * @name isHdiv\r\n * @function\r\n * @since UDA 5.0.0\r\n *\r\n * @param {string} id - Identificador de la entidad.\r\n *\r\n * @return {boolean} Verdadero si el parámetro ha sido cifrado por Hdiv.\r\n */\n\n\n $.fn.isHdiv = function (id) {\n return /^([a-zA-Z0-9]*-){4}[a-zA-Z0-9]*-:\\$:-[a-zA-Z0-9]{1,}$/.test(id);\n };\n /**\r\n * Procesa el identificador recibido para poder devolver la parte que no altera su cifrado entre peticiones.\r\n * Es útil cuando se necesita comparar identificadores cifrados. Nota: desde la versión 5.2.0, los identificadores\r\n * no alteran su cifrado entre peticiones, por lo que ha dejado de ser necesario usar este método.\r\n *\r\n * @deprecated since version 5.2.0\r\n * @name getStaticHdivID\r\n * @function\r\n * @since UDA 5.0.0\r\n *\r\n * @param {string} id - Identificador de la entidad.\r\n *\r\n * @return {string} Identificador de la entidad con la parte dinámica del cifrado eliminada.\r\n */\n\n\n $.fn.getStaticHdivID = function (id) {\n return id;\n };\n /**\r\n * Obtiene el parámetro HDIV_STATE de la URL o de un formulario.\r\n *\r\n * @name getHDIV_STATE\r\n * @function\r\n * @since UDA 5.0.0\r\n *\r\n * @param {boolean} hasMoreParams - Parámetro necesario para peticiones GET. Se utilizará para saber si el parámetro HDIV_STATE es el único existente en la URL.\r\n * @param {object} $form - Formulario del que extraer el parámetro HDIV_STATE. Este parámetro tiene prioridad respecto a hasMoreParams, por lo tanto, si se recibe será el que se use.\r\n *\r\n * @return {string} Parámetro HDIV_STATE.\r\n */\n\n\n $.fn.getHDIV_STATE = function (hasMoreParams, $form) {\n var hdivStateParam = ''; // Cuando se recibe un formulario se extrae directamente de ahí el parámetro HDIV_STATE\n\n if ($form != undefined && $form.length == 1) {\n var fieldHdiv = $form.find('input[name=\"_HDIV_STATE_\"]');\n hdivStateParam = fieldHdiv.length == 1 ? fieldHdiv.val() : '';\n } else {\n // Si el parámetro HDIV_STATE está disponible se obtiene y se devuelve, en caso contrario, se devuelve vacío\n var searchParams = new URLSearchParams(window.location.search);\n hdivStateParam = searchParams.get('_HDIV_STATE_');\n var prefix = ''; // Si se ha especificado un valor booleano en el parámetro recibido es porque se trata de una petición GET\n\n if (hasMoreParams !== undefined && hasMoreParams !== null && typeof hasMoreParams === \"boolean\") {\n prefix = (hasMoreParams ? '&' : '?') + '_HDIV_STATE_=';\n }\n\n if (hdivStateParam != undefined && hdivStateParam != null && hdivStateParam != '') {\n hdivStateParam = prefix + hdivStateParam;\n } else {\n hdivStateParam = '';\n }\n }\n\n return hdivStateParam;\n };\n /**\r\n * Reinicia por completo los autocomplete de un formulario para que no sigan filtrando.\r\n *\r\n * @name resetAutocomplete\r\n * @function\r\n * @since UDA 4.2.2\r\n *\r\n * @param {string} type - Valor del atributo type.\r\n * @param {object} obj - Formulario del que obtener los autocompletes a reiniciar.\r\n */\n\n\n $.fn.resetAutocomplete = function (type, obj) {\n jQuery.each($('input[ruptype=autocomplete][type=' + type + ']', obj), function (index, elem) {\n $(\"#\" + elem.id).rup_autocomplete(\"setRupValue\", \"\");\n });\n };\n\n jQuery.rup_utils.base64 = {\n // private property\n _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n // public method for encoding\n encode: function encode(input) {\n var output = '';\n var chr1, chr2, chr3, enc1, enc2, enc3, enc4;\n var i = 0;\n input = jQuery.rup_utils.base64._utf8_encode(input);\n\n while (i < input.length) {\n chr1 = input.charCodeAt(i++);\n chr2 = input.charCodeAt(i++);\n chr3 = input.charCodeAt(i++);\n enc1 = chr1 >> 2;\n enc2 = (chr1 & 3) << 4 | chr2 >> 4;\n enc3 = (chr2 & 15) << 2 | chr3 >> 6;\n enc4 = chr3 & 63;\n\n if (isNaN(chr2)) {\n enc3 = enc4 = 64;\n } else if (isNaN(chr3)) {\n enc4 = 64;\n }\n\n output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);\n }\n\n return output;\n },\n // public method for decoding\n decode: function decode(input) {\n var output = '';\n var chr1, chr2, chr3;\n var enc1, enc2, enc3, enc4;\n var i = 0;\n input = input.replace(/[^A-Za-z0-9+/=]/g, '');\n\n while (i < input.length) {\n enc1 = this._keyStr.indexOf(input.charAt(i++));\n enc2 = this._keyStr.indexOf(input.charAt(i++));\n enc3 = this._keyStr.indexOf(input.charAt(i++));\n enc4 = this._keyStr.indexOf(input.charAt(i++));\n chr1 = enc1 << 2 | enc2 >> 4;\n chr2 = (enc2 & 15) << 4 | enc3 >> 2;\n chr3 = (enc3 & 3) << 6 | enc4;\n output = output + String.fromCharCode(chr1);\n\n if (enc3 != 64) {\n output = output + String.fromCharCode(chr2);\n }\n\n if (enc4 != 64) {\n output = output + String.fromCharCode(chr3);\n }\n }\n\n output = jQuery.rup_utils.base64._utf8_decode(output);\n return output;\n },\n // private method for UTF-8 encoding\n _utf8_encode: function _utf8_encode(string) {\n string = string.replace(/\\r\\n/g, '\\n');\n var utftext = '';\n\n for (var n = 0; n < string.length; n++) {\n var c = string.charCodeAt(n);\n\n if (c < 128) {\n utftext += String.fromCharCode(c);\n } else if (c > 127 && c < 2048) {\n utftext += String.fromCharCode(c >> 6 | 192);\n utftext += String.fromCharCode(c & 63 | 128);\n } else {\n utftext += String.fromCharCode(c >> 12 | 224);\n utftext += String.fromCharCode(c >> 6 & 63 | 128);\n utftext += String.fromCharCode(c & 63 | 128);\n }\n }\n\n return utftext;\n },\n // private method for UTF-8 decoding\n _utf8_decode: function _utf8_decode(utftext) {\n var string = '';\n var i = 0;\n var c1 = 0;\n var c2 = 0;\n var c3 = 0;\n\n while (i < utftext.length) {\n c1 = utftext.charCodeAt(i);\n\n if (c1 < 128) {\n string += String.fromCharCode(c1);\n i++;\n } else if (c1 > 191 && c1 < 224) {\n c2 = utftext.charCodeAt(i + 1);\n string += String.fromCharCode((c1 & 31) << 6 | c2 & 63);\n i += 2;\n } else {\n c2 = utftext.charCodeAt(i + 1);\n c3 = utftext.charCodeAt(i + 2);\n string += String.fromCharCode((c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63);\n i += 3;\n }\n }\n\n return string;\n }\n };\n});\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\")))\n\n//# sourceURL=webpack://rup/./src/rup.utils.js?");
/***/ }),
@@ -8689,7 +8689,7 @@ eval("/* WEBPACK VAR INJECTION */(function(jQuery) {var __WEBPACK_AMD_DEFINE_FAC
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
-eval("/* WEBPACK VAR INJECTION */(function(jQuery) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\n/**\r\n * Genera los botones del table\r\n *\r\n * @summary \t\tExtensión del componente RUP Datatable\r\n * @module\t\t\t\"rup.table.buttons\"\r\n * @version 1.5.1\r\n * @license\r\n * Licencia con arreglo a la EUPL, Versión 1.1 exclusivamente (la «Licencia»);\r\n * Solo podrá usarse esta obra si se respeta la Licencia.\r\n * Puede obtenerse una copia de la Licencia en\r\n *\r\n * http://ec.europa.eu/idabc/eupl.html\r\n *\r\n * Salvo cuando lo exija la legislación aplicable o se acuerde por escrito,\r\n * el programa distribuido con arreglo a la Licencia se distribuye «TAL CUAL»,\r\n * SIN GARANTÍAS NI CONDICIONES DE NINGÚN TIPO, ni expresas ni implícitas.\r\n * Véase la Licencia en el idioma concreto que rige los permisos y limitaciones\r\n * que establece la Licencia.\r\n * @copyright Copyright 2018 E.J.I.E., S.A.\r\n *\r\n */\n(function (factory) {\n if (true) {\n // AMD\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\"), __webpack_require__(/*! datatables.net */ \"./node_modules/datatables.net/js/jquery.dataTables.js\")], __WEBPACK_AMD_DEFINE_RESULT__ = (function ($) {\n return factory($, window, document);\n }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n } else {}\n})(function ($, window, document, undefined) {\n 'use strict';\n\n var DataTable = $.fn.dataTable; // Used for namespacing events added to the document by each instance, so they\n // can be removed on destroy\n\n var _instCounter = 0; // Button namespacing counter for namespacing events on individual buttons\n\n var _buttonCounter = 0; // Default ID naming counter\n\n var _buttonIdCounter = 1;\n var _dtButtons = DataTable.ext.buttons;\n /**\r\n * Botones\r\n *\r\n * @name Buttons\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {object} dt\r\n * @param {object} config\r\n *\r\n */\n\n var Buttons = function Buttons(dt, config) {\n var idTable = dt.context[0].sTableId;\n var ctx = dt.context[0];\n ctx.ext = DataTable.ext;\n ctx.ext.buttons = {};\n ctx.ext.buttons.defaults = {\n buttons: ['addButton', 'editButton', 'cloneButton', 'deleteButton', 'reportsButton'],\n name: 'main',\n tabIndex: 0,\n dom: {\n container: {\n tag: 'div',\n className: 'dt-buttons row'\n },\n collection: {\n tag: 'div',\n className: 'dt-button-collection'\n },\n button: {\n tag: 'button',\n className: 'col-12 col-sm-auto btn-material',\n active: 'active',\n disabled: 'disabled'\n },\n buttonLiner: {\n tag: 'span',\n className: ''\n }\n }\n };\n ctx.ext.buttons.copyButton = {\n text: function text(dt) {\n return $.rup.i18nParse($.rup.i18n.base, 'rup_table.toolbar.reports.copyButton');\n },\n id: idTable + 'copyButton_1',\n // Campo obligatorio si se quiere usar desde el contextMenu\n className: 'btn-material-primary-low-emphasis buttons-copyButton',\n displayRegex: /^\\d+$/,\n // Se muestra siempre que sea un numero positivo o neutro\n insideContextMenu: ctx.oInit.buttons.contextMenu,\n // Independientemente de este valor, sera 'false' si no tiene un id definido\n type: 'copyButton',\n request: {\n url: '/filter?clipboardReport=true',\n method: 'POST',\n contentType: 'application/json',\n dataType: 'json',\n reportsExportAllColumns: false\n },\n init: function init(dt, node, config) {\n ctx.ext.buttons.copyButton.eventDT = dt;\n },\n action: function action(e, dt, button, config) {\n // Si es llamado desde el contextMenu este paso es innecesario y la condicion\n // del if evita un error\n if (this.processing !== undefined) {\n this.processing(true);\n }\n\n var that = this;\n $('#' + ctx.sTableId).triggerHandler('tableButtonsBeforeCopyClick', [dt, button, config]);\n\n _reports(dt, that, config);\n\n $('#' + ctx.sTableId).triggerHandler('tableButtonsAfterCopyClick', [dt, button, config]);\n }\n };\n ctx.ext.buttons.excelButton = {\n text: function text(dt) {\n return $.rup.i18nParse($.rup.i18n.base, 'rup_table.toolbar.reports.excelButton');\n },\n id: idTable + 'excelButton_1',\n // Campo obligatorio si se quiere usar desde el contextMenu\n className: 'btn-material-primary-low-emphasis buttons-copyButton',\n displayRegex: /^\\d+$/,\n // Se muestra siempre que sea un numero positivo o neutro\n insideContextMenu: ctx.oInit.buttons.contextMenu,\n // Independientemente de este valor, sera 'false' si no tiene un id definido\n type: 'excelButton',\n request: {\n url: '/xlsxReport',\n method: 'POST',\n contentType: 'application/json',\n dataType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n reportsExportAllColumns: false,\n fileName: 'reportExcel',\n sheetTitle: 'Usuario'\n },\n action: function action(e, dt, button, config) {\n // Si es llamado desde el contextMenu este paso es innecesario y la condicion\n // del if evita un error\n if (this.processing !== undefined) {\n this.processing(true);\n }\n\n var that = this;\n $('#' + ctx.sTableId).triggerHandler('tableButtonsBeforeExcelClick', [dt, button, config]);\n\n _reports(dt, that, config);\n\n $('#' + ctx.sTableId).triggerHandler('tableButtonsAfterExcelClick', [dt, button, config]);\n }\n };\n ctx.ext.buttons.pdfButton = {\n text: function text(dt) {\n return $.rup.i18nParse($.rup.i18n.base, 'rup_table.toolbar.reports.pdfButton');\n },\n id: idTable + 'pdfButton_1',\n // Campo obligatorio si se quiere usar desde el contextMenu\n className: 'btn-material-primary-low-emphasis buttons-copyButton',\n displayRegex: /^\\d+$/,\n // Se muestra siempre que sea un numero positivo o neutro\n insideContextMenu: ctx.oInit.buttons.contextMenu,\n // Independientemente de este valor, sera 'false' si no tiene un id definido\n type: 'pdfButton',\n request: {\n url: '/pdfReport',\n method: 'POST',\n contentType: 'application/json',\n dataType: 'application/pdf',\n reportsExportAllColumns: false,\n fileName: 'reportPDF'\n },\n action: function action(e, dt, button, config) {\n // Si es llamado desde el contextMenu este paso es innecesario y la condicion\n // del if evita un error\n if (this.processing !== undefined) {\n this.processing(true);\n }\n\n var that = this;\n $('#' + ctx.sTableId).triggerHandler('tableButtonsBeforePdfClick', [dt, button, config]);\n\n _reports(dt, that, config);\n\n $('#' + ctx.sTableId).triggerHandler('tableButtonsAfterPdfClick', [dt, button, config]);\n }\n };\n ctx.ext.buttons.odsButton = {\n text: function text(dt) {\n return $.rup.i18nParse($.rup.i18n.base, 'rup_table.toolbar.reports.odsButton');\n },\n id: idTable + 'odsButton_1',\n // Campo obligatorio si se quiere usar desde el contextMenu\n className: 'btn-material-primary-low-emphasis buttons-copyButton',\n displayRegex: /^\\d+$/,\n // Se muestra siempre que sea un numero positivo o neutro\n insideContextMenu: ctx.oInit.buttons.contextMenu,\n // Independientemente de este valor, sera 'false' si no tiene un id definido\n type: 'odsButton',\n request: {\n url: '/odsReport',\n method: 'POST',\n contentType: 'application/json',\n dataType: 'application/vnd.oasis.opendocument.spreadsheet',\n reportsExportAllColumns: false,\n fileName: 'reportODS',\n sheetTitle: 'Usuario'\n },\n action: function action(e, dt, button, config) {\n // Si es llamado desde el contextMenu este paso es innecesario y la condicion\n // del if evita un error\n if (this.processing !== undefined) {\n this.processing(true);\n }\n\n var that = this;\n $('#' + ctx.sTableId).triggerHandler('tableButtonsBeforeOdsClick', [dt, button, config]);\n\n _reports(dt, that, config);\n\n $('#' + ctx.sTableId).triggerHandler('tableButtonsAfterOdsClick', [dt, button, config]);\n }\n };\n ctx.ext.buttons.csvButton = {\n text: function text(dt) {\n return $.rup.i18nParse($.rup.i18n.base, 'rup_table.toolbar.reports.csvButton');\n },\n id: idTable + 'csvButton_1',\n // Campo obligatorio si se quiere usar desde el contextMenu\n className: 'btn-material-primary-low-emphasis buttons-copyButton',\n displayRegex: /^\\d+$/,\n // Se muestra siempre que sea un numero positivo o neutro\n insideContextMenu: ctx.oInit.buttons.contextMenu,\n // Independientemente de este valor, sera 'false' si no tiene un id definido\n type: 'csvButton',\n request: {\n url: '/csvReport',\n method: 'POST',\n contentType: 'application/json',\n dataType: 'text/csv',\n reportsExportAllColumns: false,\n fileName: 'reportCSV',\n sheetTitle: 'Usuario'\n },\n action: function action(e, dt, button, config) {\n // Si es llamado desde el contextMenu este paso es innecesario y la condicion\n // del if evita un error\n if (this.processing !== undefined) {\n this.processing(true);\n }\n\n var that = this;\n $('#' + ctx.sTableId).triggerHandler('tableButtonsBeforeCsvClick', [dt, button, config]);\n\n _reports(dt, that, config);\n\n $('#' + ctx.sTableId).triggerHandler('tableButtonsAfterCsvClick', [dt, button, config]);\n }\n };\n ctx.ext.buttons.addButton = {\n text: function text(dt) {\n return $.rup.i18nParse($.rup.i18n.base, 'rup_table.toolbar.add');\n },\n id: idTable + 'addButton_1',\n // Campo obligatorio si se quiere usar desde el contextMenu\n className: 'btn-material-primary-high-emphasis table_toolbar_btnAdd order-1',\n displayRegex: /^\\d+$/,\n // Se muestra siempre que sea un numero positivo o neutro\n insideContextMenu: ctx.oInit.buttons.contextMenu,\n // Independientemente de este valor, sera 'false' si no tiene un id definido\n type: 'add',\n init: function init(dt, button, config) {\n ctx.ext.buttons.addButton.eventDT = dt;\n },\n action: function action(e, dt, button, config) {\n $('#' + ctx.sTableId).triggerHandler('tableButtonsBeforeAddClick', [dt, button, config]);\n DataTable.Api().buttons.actions(dt, config);\n $('#' + ctx.sTableId).triggerHandler('tableButtonsAfterAddClick', [dt, button, config]);\n }\n };\n ctx.ext.buttons.editButton = {\n text: function text(dt) {\n return $.rup.i18nParse($.rup.i18n.base, 'rup_table.toolbar.edit');\n },\n id: idTable + 'editButton_1',\n // Campo obligatorio si se quiere usar desde el contextMenu\n className: 'btn-material-primary-high-emphasis table_toolbar_btnEdit order-2',\n displayRegex: /^[1-9][0-9]*$/,\n // Se muestra siempre que sea un numero mayor a 0\n insideContextMenu: ctx.oInit.buttons.contextMenu,\n // Independientemente de este valor, sera 'false' si no tiene un id definido\n type: 'edit',\n init: function init(dt, button, config) {\n ctx.ext.buttons.editButton.eventDT = dt;\n },\n action: function action(e, dt, button, config) {\n $('#' + ctx.sTableId).triggerHandler('tableButtonsBeforeEditClick', [dt, button, config]);\n DataTable.Api().buttons.actions(dt, config);\n $('#' + ctx.sTableId).triggerHandler('tableButtonsAfterEditClick', [dt, button, config]);\n }\n };\n ctx.ext.buttons.cloneButton = {\n text: function text(dt) {\n return $.rup.i18nParse($.rup.i18n.base, 'rup_table.toolbar.clone');\n },\n id: idTable + 'cloneButton_1',\n // Campo obligatorio si se quiere usar desde el contextMenu\n className: 'btn-material-primary-high-emphasis table_toolbar_btnClone order-3',\n displayRegex: /^1$/,\n // Se muestra solo cuando sea igual a 1\n insideContextMenu: ctx.oInit.buttons.contextMenu,\n // Independientemente de este valor, sera 'false' si no tiene un id definido\n type: 'clone',\n init: function init(dt, button, config) {\n ctx.ext.buttons.cloneButton.eventDT = dt;\n },\n action: function action(e, dt, button, config) {\n $('#' + ctx.sTableId).triggerHandler('tableButtonsBeforeCloneClick', [dt, button, config]);\n DataTable.Api().buttons.actions(dt, config);\n $('#' + ctx.sTableId).triggerHandler('tableButtonsAfterCloneClick', [dt, button, config]);\n }\n };\n ctx.ext.buttons.deleteButton = {\n text: function text(dt) {\n return $.rup.i18nParse($.rup.i18n.base, 'rup_table.toolbar.delete');\n },\n id: idTable + 'deleteButton_1',\n // Campo obligatorio si se quiere usar desde el contextMenu\n className: 'btn-material-primary-high-emphasis table_toolbar_btnDelete order-4',\n displayRegex: /^[1-9][0-9]*$/,\n // Se muestra siempre que sea un numero mayor a 0\n insideContextMenu: ctx.oInit.buttons.contextMenu,\n // Independientemente de este valor, sera 'false' si no tiene un id definido\n type: 'delete',\n init: function init(dt, button, config) {\n ctx.ext.buttons.deleteButton.eventDT = dt;\n },\n action: function action(e, dt, button, config) {\n $('#' + ctx.sTableId).triggerHandler('tableButtonsBeforeDeleteClick', [dt, button, config]);\n DataTable.Api().buttons.actions(dt, config);\n $('#' + ctx.sTableId).triggerHandler('tableButtonsAfterDeleteClick', [dt, button, config]);\n }\n };\n var listadoExports = ['copyButton', 'excelButton', 'pdfButton', 'odsButton', 'csvButton'];\n ctx.ext.buttons.reportsButton = {\n extend: 'collection',\n text: function text(dt) {\n return $.rup.i18nParse($.rup.i18n.base, 'rup_table.toolbar.reports.main');\n },\n id: idTable + 'informes_01',\n className: 'btn-material-primary-medium-emphasis order-last ml-1 ml-lg-auto',\n displayRegex: /^\\d+$/,\n // Se muestra siempre que sea un numero positivo o neutro\n autoClose: true,\n type: 'reports',\n reportsExportAllColumns: false,\n buttons: listadoExports\n }; // Almacena los identificadores de los botones personalizados.\n\n ctx.ext.buttons.custom = []; // Ajusta el tamaño de los botones por defecto en caso de que haya sido especificado en las preferencias\n\n if (ctx.oInit.buttons.size !== undefined) {\n $.each(ctx.ext.buttons, function (name, item) {\n if (item.className !== undefined) {\n if (ctx.oInit.buttons.size === 'lg') {\n item.className += \" btn-material-lg\";\n } else if (ctx.oInit.buttons.size === 'sm') {\n item.className += \" btn-material-sm\";\n }\n }\n });\n }\n\n if (ctx.oInit.buttons.blackListButtons !== undefined) {\n if (ctx.oInit.buttons.blackListButtons === 'all') {\n //si no se quiere ninguno se elimina\n listadoExports = [];\n ctx.ext.buttons.defaults.buttons = [];\n } else if (ctx.oInit.buttons.blackListButtons && ctx.oInit.buttons.blackListButtons.length > 0) {\n $.each(ctx.oInit.buttons.blackListButtons, function () {\n var name = this;\n var pos = $.inArray(name, listadoExports);\n\n if (pos >= 0) {\n listadoExports.splice(pos, 1);\n } //Resto de botones\n\n\n var posBoton = $.inArray(name, ctx.ext.buttons.defaults.buttons);\n\n if (posBoton >= 0) {\n ctx.ext.buttons.defaults.buttons.splice(posBoton, 1);\n }\n });\n }\n } // Añadir los botones de la edición en línea.\n\n\n if (!ctx.oInit.noEdit && ctx.oInit.inlineEdit !== undefined) {\n $.extend(ctx.ext.buttons, ctx.oInit.inlineEdit.myButtons);\n\n for (var nameButton in ctx.oInit.inlineEdit.myButtons) {\n ctx.ext.buttons.defaults.buttons.push(nameButton);\n }\n } // Añadir los botones personalizados.\n\n\n if (ctx.oInit.buttons.myButtons !== undefined) {\n $.extend(ctx.ext.buttons, ctx.oInit.buttons.myButtons);\n\n for (var _nameButton in ctx.oInit.buttons.myButtons) {\n ctx.ext.buttons.defaults.buttons.push(_nameButton);\n ctx.ext.buttons.custom.push(ctx.oInit.buttons.myButtons[_nameButton].id);\n }\n } // If there is no config set it to an empty object\n\n\n if (typeof config === 'undefined') {\n config = {};\n } // Allow a boolean true for defaults\n\n\n if (config === true) {\n config = {};\n } // For easy configuration of buttons an array can be given\n\n\n if (Array.isArray(config)) {\n config = {\n buttons: config\n };\n }\n\n this.c = $.extend(true, {}, ctx.ext.buttons.defaults, config); // Don't want a deep copy for the buttons\n\n if (config.buttons) {\n this.c.buttons = config.buttons;\n }\n\n this.s = {\n dt: new DataTable.Api(dt),\n buttons: [],\n listenKeys: '',\n namespace: 'dtb' + _instCounter++\n };\n this.dom = {\n container: $('<' + this.c.dom.container.tag + '>' + this.c.dom.container.tag + '>').addClass(this.c.dom.container.className).attr('id', ctx.sTableId + '_containerToolbar')\n };\n\n this._constructor();\n };\n\n $.extend(Buttons.prototype, {\n /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n * Public methods\r\n */\n\n /**\r\n * Get the action of a button\r\n *\r\n * @name action\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {int|string} Button index\r\n * @return {function}\r\n *\r\n */\n\n /**\r\n * Set the action of a button\r\n *\r\n * @name action\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {node} node Button element\r\n * @param {function} action Function to set\r\n * @return {Buttons} Self for chaining\r\n *\r\n */\n action: function action(node, _action) {\n var button = this._nodeToButton(node);\n\n if (_action === undefined) {\n return button.conf.action;\n }\n\n button.conf.action = _action;\n return this;\n },\n\n /**\r\n * Add an active class to the button to make to look active or get current\r\n * active state.\r\n *\r\n * @name active\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {node} node Button element\r\n * @param {boolean} [flag] Enable / disable flag\r\n * @return {Buttons} Self for chaining or boolean for getter\r\n *\r\n */\n active: function active(node, flag) {\n var button = this._nodeToButton(node);\n\n var klass = this.c.dom.button.active;\n var jqNode = $(button.node);\n\n if (flag === undefined) {\n return jqNode.hasClass(klass);\n }\n\n jqNode.toggleClass(klass, flag === undefined ? true : flag);\n return this;\n },\n\n /**\r\n * Add a new button\r\n *\r\n * @name add\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {object} config Button configuration object, base string name or function\r\n * @param {int|string} [idx] Button index for where to insert the button\r\n * @return {Buttons} Self for chaining\r\n *\r\n */\n add: function add(config, idx) {\n var buttons = this.s.buttons;\n\n if (typeof idx === 'string') {\n var split = idx.split('-');\n var base = this.s;\n\n for (var i = 0, ien = split.length - 1; i < ien; i++) {\n base = base.buttons[split[i] * 1];\n }\n\n buttons = base.buttons;\n idx = split[split.length - 1] * 1;\n }\n\n this._expandButton(buttons, config, false, idx);\n\n this._draw();\n\n return this;\n },\n\n /**\r\n * Get the container node for the buttons\r\n *\r\n * @name container\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @return {jQuery} Buttons node\r\n *\r\n */\n container: function container() {\n return this.dom.container;\n },\n\n /**\r\n * Disable a button\r\n *\r\n * @name disable\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {node} node Button node\r\n * @return {Buttons} Self for chaining\r\n *\r\n */\n disable: function disable(node, contextMenu) {\n var button = this._nodeToButton(node);\n\n $(button.node).addClass(this.c.dom.button.disabled);\n\n if (contextMenu) {\n $('#' + button.node.id + '_contextMenuToolbar').addClass(this.c.dom.button.disabled);\n }\n\n return this;\n },\n\n /**\r\n * Destroy the instance, cleaning up event handlers and removing DOM\r\n * elements\r\n *\r\n * @name destroy\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @return {Buttons} Self for chaining\r\n *\r\n */\n destroy: function destroy() {\n // Key event listener\n $('body').off('keyup.' + this.s.namespace); // Individual button destroy (so they can remove their own events if\n // needed). Take a copy as the array is modified by `remove`\n\n var buttons = this.s.buttons.slice();\n var i, ien;\n\n for (i = 0, ien = buttons.length; i < ien; i++) {\n this.remove(buttons[i].node);\n } // Container\n\n\n this.dom.container.remove(); // Remove from the settings object collection\n\n var buttonInsts = this.s.dt.settings()[0];\n\n for (i = 0, ien = buttonInsts.length; i < ien; i++) {\n if (buttonInsts.inst === this) {\n buttonInsts.splice(i, 1);\n break;\n }\n }\n\n return this;\n },\n\n /**\r\n * Enable / disable a button\r\n *\r\n * @name enable\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {node} node Button node\r\n * @param {boolean} [flag=true] Enable / disable flag\r\n * @return {Buttons} Self for chaining\r\n *\r\n */\n enable: function enable(node, flag, contextMenu) {\n if (flag === false) {\n return this.disable(node);\n }\n\n var button = this._nodeToButton(node);\n\n $(button.node).removeClass(this.c.dom.button.disabled);\n\n if (contextMenu) {\n $('#' + button.node.id + '_contextMenuToolbar').removeClass(this.c.dom.button.disabled);\n }\n\n return this;\n },\n\n /**\r\n * Get the instance name for the button set selector\r\n *\r\n * @name name\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @return {string} Instance name\r\n *\r\n */\n name: function name() {\n return this.c.name;\n },\n\n /**\r\n * Get a button's node\r\n *\r\n * @name node\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {node} node Button node\r\n * @return {jQuery} Button element\r\n *\r\n */\n node: function node(_node) {\n var button = this._nodeToButton(_node);\n\n return $(button.node);\n },\n\n /**\r\n * Set / get a processing class on the selected button\r\n *\r\n * @name processing\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {boolean} flag true to add, false to remove, undefined to get\r\n * @return {boolean|Buttons} Getter value or this if a setter.\r\n *\r\n */\n processing: function processing(node, flag) {\n var button = this._nodeToButton(node);\n\n if (flag === undefined) {\n return $(button.node).hasClass('processing');\n }\n\n $(button.node).toggleClass('processing', flag);\n return this;\n },\n\n /**\r\n * Remove a button.\r\n *\r\n * @name remove\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {node} node Button node\r\n * @return {Buttons} Self for chaining\r\n *\r\n */\n remove: function remove(node) {\n var button = this._nodeToButton(node);\n\n var host = this._nodeToHost(node);\n\n var dt = this.s.dt; // Remove any child buttons first\n\n if (button.buttons.length) {\n for (var i = button.buttons.length - 1; i >= 0; i--) {\n this.remove(button.buttons[i].node);\n }\n } // Allow the button to remove event handlers, etc\n\n\n if (button.conf.destroy) {\n button.conf.destroy.call(dt.button(node), dt, $(node), button.conf);\n }\n\n this._removeKey(button.conf);\n\n $(button.node).remove();\n var idx = $.inArray(button, host);\n host.splice(idx, 1);\n return this;\n },\n\n /**\r\n * Get the text for a button\r\n *\r\n * @name text\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {int|string} node Button index\r\n * @return {string} Button text\r\n *\r\n */\n\n /**\r\n * Set the text for a button\r\n *\r\n * @name text\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {int|string|function} node Button index\r\n * @param {string} label Text\r\n * @return {Buttons} Self for chaining\r\n *\r\n */\n text: function text(node, label) {\n var button = this._nodeToButton(node);\n\n var buttonLiner = this.c.dom.collection.buttonLiner;\n var linerTag = button.inCollection && buttonLiner && buttonLiner.tag ? buttonLiner.tag : this.c.dom.buttonLiner.tag;\n var dt = this.s.dt;\n var jqNode = $(button.node);\n\n var text = function text(opt) {\n return typeof opt === 'function' ? opt(dt, jqNode, button.conf) : opt;\n };\n\n if (label === undefined) {\n return text(button.conf.text);\n }\n\n button.conf.text = label;\n\n if (linerTag) {\n jqNode.children(linerTag).html(text(label));\n } else {\n jqNode.html(text(label));\n }\n\n return this;\n },\n\n /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n * Constructor\r\n */\n\n /**\r\n * Buttons constructor\r\n *\r\n * @name _constructor\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n */\n _constructor: function _constructor() {\n var that = this;\n var dt = this.s.dt;\n var dtSettings = dt.settings()[0];\n var buttons = this.c.buttons;\n\n if (!dtSettings._buttons) {\n dtSettings._buttons = [];\n }\n\n dtSettings._buttons.push({\n inst: this,\n name: this.c.name\n });\n\n for (var i = 0, ien = buttons.length; i < ien; i++) {\n this.add(buttons[i]);\n }\n\n dt.on('destroy', function () {\n that.destroy();\n }); // Global key event binding to listen for button keys\n\n $('body').on('keyup.' + this.s.namespace, function (e) {\n if (!document.activeElement || document.activeElement === document.body) {\n // SUse a string of characters for fast lookup of if we need to\n // handle this\n var character = String.fromCharCode(e.keyCode).toLowerCase();\n\n if (that.s.listenKeys.toLowerCase().indexOf(character) !== -1) {\n that._keypress(character, e);\n }\n }\n });\n },\n\n /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n * Private methods\r\n */\n\n /**\r\n * Add a new button to the key press listener\r\n *\r\n * @name _addKey\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {object} conf Resolved button configuration object\r\n *\r\n */\n _addKey: function _addKey(conf) {\n if (conf.key) {\n this.s.listenKeys += $.isPlainObject(conf.key) ? conf.key.key : conf.key;\n }\n },\n\n /**\r\n * Insert the buttons into the container. Call without parameters!\r\n *\r\n * @name _draw\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {node} [container] Recursive only - Insert point\r\n * @param {array} [buttons] Recursive only - Buttons array\r\n *\r\n */\n _draw: function _draw(container, buttons) {\n if (!container) {\n container = this.dom.container;\n buttons = this.s.buttons;\n }\n\n container.children().detach();\n\n for (var i = 0, ien = buttons.length; i < ien; i++) {\n container.append(buttons[i].inserter);\n container.append(' ');\n\n if (buttons[i].buttons && buttons[i].buttons.length) {\n this._draw(buttons[i].collection, buttons[i].buttons);\n }\n }\n },\n\n /**\r\n * Create buttons from an array of buttons\r\n *\r\n * @name _expandButton\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {array} attachTo Buttons array to attach to\r\n * @param {object} button Button definition\r\n * @param {boolean} inCollection true if the button is in a collection\r\n *\r\n */\n _expandButton: function _expandButton(attachTo, button, inCollection, attachPoint) {\n var dt = this.s.dt;\n var buttonCounter = 0;\n var buttons = !Array.isArray(button) ? [button] : button;\n\n for (var i = 0, ien = buttons.length; i < ien; i++) {\n var conf = this._resolveExtends(buttons[i]);\n\n if (!conf) {\n continue;\n } // If the configuration is an array, then expand the buttons at this\n // point\n\n\n if (Array.isArray(conf)) {\n this._expandButton(attachTo, conf, inCollection, attachPoint);\n\n continue;\n }\n\n var built = this._buildButton(conf, inCollection);\n\n if (!built) {\n continue;\n }\n\n if (attachPoint !== undefined) {\n attachTo.splice(attachPoint, 0, built);\n attachPoint++;\n } else {\n attachTo.push(built);\n }\n\n if (built.conf.buttons) {\n var collectionDom = this.c.dom.collection;\n built.collection = $('<' + collectionDom.tag + '>' + collectionDom.tag + '>').addClass(collectionDom.className).attr('role', 'menu');\n built.conf._collection = built.collection;\n\n this._expandButton(built.buttons, built.conf.buttons, true, attachPoint);\n } // init call is made here, rather than buildButton as it needs to\n // be selectable, and for that it needs to be in the buttons array\n\n\n if (conf.init) {\n conf.init.call(dt.button(built.node), dt, $(built.node), conf);\n }\n\n buttonCounter++;\n }\n },\n\n /**\r\n * Create an individual button\r\n *\r\n * @name _buildButton\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {object} config Resolved button configuration\r\n * @param {boolean} inCollection `true` if a collection button\r\n * @return {jQuery} Created button node (jQuery)\r\n *\r\n */\n _buildButton: function _buildButton(config, inCollection) {\n var buttonDom = this.c.dom.button;\n var linerDom = this.c.dom.buttonLiner;\n var collectionDom = this.c.dom.collection;\n var dt = this.s.dt;\n var ctx = dt.settings()[0];\n\n var text = function text(opt) {\n return typeof opt === 'function' ? opt(dt, button, config) : opt;\n };\n\n if (inCollection && collectionDom.button) {\n buttonDom = collectionDom.button;\n }\n\n if (inCollection && collectionDom.buttonLiner) {\n linerDom = collectionDom.buttonLiner;\n } // Make sure that the button is available based on whatever requirements\n // it has. For example, Flash buttons require Flash\n\n\n if (config.available && !config.available(dt, config)) {\n return false;\n }\n\n var action = function action(e, dt, button, config) {\n config.action.call(dt.button(button), e, dt, button, config);\n $(dt.table().node()).triggerHandler('buttons-action.dt', [dt.button(button), dt, button, config]);\n };\n\n var button = $('<' + buttonDom.tag + '>' + buttonDom.tag + '>').addClass(buttonDom.className).attr('tabindex', this.s.dt.settings()[0].iTabIndex).attr('aria-controls', this.s.dt.table().node().id).on('click.dtb', function (e) {\n e.preventDefault();\n\n if (!button.hasClass(buttonDom.disabled) && config.action) {\n action(e, dt, button, config);\n }\n\n button.blur();\n }); // Make `a` tags act like a link\n\n if (buttonDom.tag.toLowerCase() === 'a') {\n button.attr('href', '#');\n }\n\n if (linerDom.tag) {\n var liner = $('<' + linerDom.tag + '>' + linerDom.tag + '>').html(text(config.text)).addClass(linerDom.className);\n\n if (linerDom.tag.toLowerCase() === 'a') {\n liner.attr('href', '#');\n }\n\n button.append(liner);\n } else {\n button.html(text(config.text));\n }\n\n if (config.id) {\n button.attr('id', config.id);\n } else {\n // Se desactiva el acceso desde el contextMenu por no tener un id establecido\n config.insideContextMenu = false; // Se asigna un id dinamico en funcion del nombre del table al que pertenece\n\n config.id = ctx.sTableId + '_button_' + _buttonIdCounter++;\n button.attr('id', config.id);\n }\n\n if (config.className) {\n button.addClass(config.className);\n }\n\n if (config.titleAttr) {\n button.attr('title', text(config.titleAttr));\n }\n\n if (config.attr) {\n button.attr(config.attr);\n }\n\n if (!config.namespace) {\n config.namespace = '.dt-button-' + _buttonCounter++;\n }\n\n if (!config.icon) {\n // Comprueba si es alguno de los botones con iconos definidos por defecto\n switch (config.type) {\n case 'add':\n config.icon = 'mdi-plus';\n break;\n\n case 'edit':\n config.icon = 'mdi-playlist-edit';\n break;\n\n case 'clone':\n config.icon = 'mdi-content-copy';\n break;\n\n case 'delete':\n config.icon = 'mdi-trash-can-outline';\n break;\n\n case 'reports':\n config.icon = 'mdi-file-export';\n break;\n\n case 'copyButton':\n config.icon = 'mdi-clipboard-text-outline';\n break;\n\n case 'excelButton':\n config.icon = 'mdi-file-excel';\n break;\n\n case 'pdfButton':\n config.icon = 'mdi-file-pdf';\n break;\n\n case 'odsButton':\n config.icon = 'mdi-file';\n break;\n\n case 'csvButton':\n config.icon = 'mdi-file';\n break;\n\n default:\n config.icon = 'mdi-settings';\n }\n }\n\n var buttonContainer = this.c.dom.buttonContainer;\n var inserter;\n\n if (buttonContainer && buttonContainer.tag) {\n inserter = $('<' + buttonContainer.tag + '>' + buttonContainer.tag + '>').addClass(buttonContainer.className).append(button);\n } else {\n inserter = button;\n }\n\n this._addKey(config);\n\n return {\n conf: config,\n node: button.get(0),\n inserter: inserter,\n buttons: [],\n inCollection: inCollection,\n collection: null\n };\n },\n\n /**\r\n * Get the button object from a node (recursive)\r\n *\r\n * @name _nodeToButton\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {node} node Button node\r\n * @param {array} [buttons] Button array, uses base if not defined\r\n * @return {object} Button object\r\n *\r\n */\n _nodeToButton: function _nodeToButton(node, buttons) {\n if (!buttons) {\n buttons = this.s.buttons;\n }\n\n for (var i = 0, ien = buttons.length; i < ien; i++) {\n if (buttons[i].node === node) {\n return buttons[i];\n }\n\n if (buttons[i].buttons.length) {\n var ret = this._nodeToButton(node, buttons[i].buttons);\n\n if (ret) {\n return ret;\n }\n }\n }\n },\n\n /**\r\n * Get container array for a button from a button node (recursive)\r\n *\r\n * @name _nodeToHost\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {node} node Button node\r\n * @param {array} [buttons] Button array, uses base if not defined\r\n * @return {array} Button's host array\r\n *\r\n */\n _nodeToHost: function _nodeToHost(node, buttons) {\n if (!buttons) {\n buttons = this.s.buttons;\n }\n\n for (var i = 0, ien = buttons.length; i < ien; i++) {\n if (buttons[i].node === node) {\n return buttons;\n }\n\n if (buttons[i].buttons.length) {\n var ret = this._nodeToHost(node, buttons[i].buttons);\n\n if (ret) {\n return ret;\n }\n }\n }\n },\n\n /**\r\n * Handle a key press - determine if any button's key configured matches\r\n * what was typed and trigger the action if so.\r\n *\r\n * @name _keypress\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {string} character The character pressed\r\n * @param {object} e Key event that triggered this call\r\n *\r\n */\n _keypress: function _keypress(character, e) {\n // Check if this button press already activated on another instance of Buttons\n if (e._buttonsHandled) {\n return;\n }\n\n var run = function run(conf, node) {\n if (!conf.key) {\n return;\n }\n\n if (conf.key === character) {\n e._buttonsHandled = true;\n $(node).click();\n } else if ($.isPlainObject(conf.key)) {\n if (conf.key.key !== character) {\n return;\n }\n\n if (conf.key.shiftKey && !e.shiftKey) {\n return;\n }\n\n if (conf.key.altKey && !e.altKey) {\n return;\n }\n\n if (conf.key.ctrlKey && !e.ctrlKey) {\n return;\n }\n\n if (conf.key.metaKey && !e.metaKey) {\n return;\n } // Made it this far - it is good\n\n\n e._buttonsHandled = true;\n $(node).click();\n }\n };\n\n var recurse = function recurse(a) {\n for (var i = 0, ien = a.length; i < ien; i++) {\n run(a[i].conf, a[i].node);\n\n if (a[i].buttons.length) {\n recurse(a[i].buttons);\n }\n }\n };\n\n recurse(this.s.buttons);\n },\n\n /**\r\n * Remove a key from the key listener for this instance (to be used when a\r\n * button is removed)\r\n *\r\n * @name _removeKey\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {object} conf Button configuration\r\n *\r\n */\n _removeKey: function _removeKey(conf) {\n if (conf.key) {\n var character = $.isPlainObject(conf.key) ? conf.key.key : conf.key; // Remove only one character, as multiple buttons could have the\n // same listening key\n\n var a = this.s.listenKeys.split('');\n var idx = $.inArray(character, a);\n a.splice(idx, 1);\n this.s.listenKeys = a.join('');\n }\n },\n\n /**\r\n * Resolve a button configuration\r\n *\r\n * @name _resolveExtends\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {string|function|object} conf Button config to resolve\r\n * @return {object} Button configuration\r\n *\r\n */\n _resolveExtends: function _resolveExtends(conf) {\n var dt = this.s.dt;\n var i, ien;\n var ctx = dt.context[0];\n var _dtButtonsTable = ctx.ext.buttons;\n _dtButtonsTable.collection = _dtButtons.collection;\n\n var toConfObject = function toConfObject(base) {\n var loop = 0; // Loop until we have resolved to a button configuration, or an\n // array of button configurations (which will be iterated\n // separately)\n\n while (!$.isPlainObject(base) && !Array.isArray(base)) {\n if (base === undefined) {\n return;\n }\n\n if (typeof base === 'function') {\n base = base(dt, conf);\n\n if (!base) {\n return false;\n }\n } else if (typeof base === 'string') {\n if (!_dtButtonsTable[base]) {\n throw 'Unknown button type: ' + base;\n }\n\n base = _dtButtonsTable[base];\n }\n\n loop++;\n\n if (loop > 30) {\n // Protect against misconfiguration killing the browser\n throw 'Buttons: Too many iterations';\n }\n }\n\n return Array.isArray(base) ? base : $.extend({}, base);\n };\n\n conf = toConfObject(conf);\n\n while (conf && conf.extend) {\n // Use `toConfObject` in case the button definition being extended\n // is itself a string or a function\n if (!_dtButtonsTable[conf.extend]) {\n throw 'Cannot extend unknown button type: ' + conf.extend;\n }\n\n var objArray = toConfObject(_dtButtonsTable[conf.extend]);\n\n if (Array.isArray(objArray)) {\n return objArray;\n } else if (!objArray) {\n // This is a little brutal as it might be possible to have a\n // valid button without the extend, but if there is no extend\n // then the host button would be acting in an undefined state\n return false;\n } // Stash the current class name\n\n\n var originalClassName = objArray.className;\n conf = $.extend({}, objArray, conf); // The extend will have overwritten the original class name if the\n // `conf` object also assigned a class, but we want to concatenate\n // them so they are list that is combined from all extended buttons\n\n if (originalClassName && conf.className !== originalClassName) {\n conf.className = originalClassName + ' ' + conf.className;\n } // Buttons to be added to a collection -gives the ability to define\n // if buttons should be added to the start or end of a collection\n\n\n var postfixButtons = conf.postfixButtons;\n\n if (postfixButtons) {\n if (!conf.buttons) {\n conf.buttons = [];\n }\n\n for (i = 0, ien = postfixButtons.length; i < ien; i++) {\n conf.buttons.push(postfixButtons[i]);\n }\n\n conf.postfixButtons = null;\n }\n\n var prefixButtons = conf.prefixButtons;\n\n if (prefixButtons) {\n if (!conf.buttons) {\n conf.buttons = [];\n }\n\n for (i = 0, ien = prefixButtons.length; i < ien; i++) {\n conf.buttons.splice(i, 0, prefixButtons[i]);\n }\n\n conf.prefixButtons = null;\n } // Although we want the `conf` object to overwrite almost all of\n // the properties of the object being extended, the `extend`\n // property should come from the object being extended\n\n\n conf.extend = objArray.extend;\n }\n\n return conf;\n }\n });\n /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n * Statics\r\n */\n\n /**\r\n * Show / hide a background layer behind a collection\r\n *\r\n * @name Buttons.background\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {boolean} Flag to indicate if the background should be shown or\r\n * hidden\r\n * @param {string} Class to assign to the background\r\n *\r\n * @static\r\n *\r\n */\n\n Buttons.background = function (show, className, fade) {\n if (fade === undefined) {\n fade = 400;\n }\n\n if (show) {\n $('').addClass(className).css('display', 'none').appendTo('body').fadeIn(fade);\n } else {\n $('body > div.' + className).fadeOut(fade, function () {\n $(this).removeClass(className).remove();\n });\n }\n };\n /**\r\n * Instance selector - select Buttons instances based on an instance selector\r\n * value from the buttons assigned to a DataTable. This is only useful if\r\n * multiple instances are attached to a DataTable.\r\n *\r\n * @name Buttons.instanceSelector\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {string|int|array} Instance selector - see `instance-selector`\r\n * documentation on the DataTables site\r\n * @param {array} Button instance array that was attached to the DataTables\r\n * settings object\r\n * @return {array} Buttons instances\r\n *\r\n * @static\r\n *\r\n */\n\n\n Buttons.instanceSelector = function (group, buttons) {\n if (!group) {\n return $.map(buttons, function (v) {\n return v.inst;\n });\n }\n\n var ret = [];\n var names = $.map(buttons, function (v) {\n return v.name;\n }); // Flatten the group selector into an array of single options\n\n var process = function process(input) {\n if (Array.isArray(input)) {\n for (var i = 0, ien = input.length; i < ien; i++) {\n process(input[i]);\n }\n\n return;\n }\n\n if (typeof input === 'string') {\n if (input.indexOf(',') !== -1) {\n // String selector, list of names\n process(input.split(','));\n } else {\n // String selector individual name\n var idx = $.inArray(input.trim(), names);\n\n if (idx !== -1) {\n ret.push(buttons[idx].inst);\n }\n }\n } else if (typeof input === 'number') {\n // Index selector\n ret.push(buttons[input].inst);\n }\n };\n\n process(group);\n return ret;\n };\n /**\r\n * Button selector - select one or more buttons from a selector input so some\r\n * operation can be performed on them.\r\n *\r\n * @name Buttons.buttonSelector\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {array} Button instances array that the selector should operate on\r\n * @param {string|int|node|jQuery|array} Button selector - see\r\n * `button-selector` documentation on the DataTables site\r\n * @return {array} Array of objects containing `inst` and `idx` properties of\r\n * the selected buttons so you know which instance each button belongs to.\r\n *\r\n * @static\r\n *\r\n */\n\n\n Buttons.buttonSelector = function (insts, selector) {\n var ret = [];\n\n var nodeBuilder = function nodeBuilder(a, buttons, baseIdx) {\n var button;\n var idx;\n\n for (var i = 0, ien = buttons.length; i < ien; i++) {\n button = buttons[i];\n\n if (button) {\n idx = baseIdx !== undefined ? baseIdx + i : i + '';\n a.push({\n node: button.node,\n name: button.conf.name,\n idx: idx\n });\n\n if (button.buttons) {\n nodeBuilder(a, button.buttons, idx + '-');\n }\n }\n }\n };\n\n var run = function run(selector, inst) {\n var i, ien;\n var buttons = [];\n nodeBuilder(buttons, inst.s.buttons);\n var nodes = $.map(buttons, function (v) {\n return v.node;\n });\n\n if (Array.isArray(selector) || selector instanceof $) {\n for (i = 0, ien = selector.length; i < ien; i++) {\n run(selector[i], inst);\n }\n\n return;\n }\n\n if (selector === null || selector === undefined || selector === '*') {\n // Select all\n for (i = 0, ien = buttons.length; i < ien; i++) {\n ret.push({\n inst: inst,\n node: buttons[i].node\n });\n }\n } else if (typeof selector === 'number') {\n // Main button index selector\n ret.push({\n inst: inst,\n node: inst.s.buttons[selector].node\n });\n } else if (typeof selector === 'string') {\n if (selector.indexOf(',') !== -1) {\n // Split\n var a = selector.split(',');\n\n for (i = 0, ien = a.length; i < ien; i++) {\n run(a[i].trim(), inst);\n }\n } else if (selector.match(/^\\d+(\\-\\d+)*$/)) {\n // Sub-button index selector\n var indexes = $.map(buttons, function (v) {\n return v.idx;\n });\n ret.push({\n inst: inst,\n node: buttons[$.inArray(selector, indexes)].node\n });\n } else if (selector.indexOf(':name') !== -1) {\n // Button name selector\n var name = selector.replace(':name', '');\n\n for (i = 0, ien = buttons.length; i < ien; i++) {\n if (buttons[i].name === name) {\n ret.push({\n inst: inst,\n node: buttons[i].node\n });\n }\n }\n } else {\n // jQuery selector on the nodes\n $(nodes).filter(selector).each(function () {\n ret.push({\n inst: inst,\n node: this\n });\n });\n }\n } else if (_typeof(selector) === 'object' && selector.nodeName) {\n // Node selector\n var idx = $.inArray(selector, nodes);\n\n if (idx !== -1) {\n ret.push({\n inst: inst,\n node: nodes[idx]\n });\n }\n }\n };\n\n for (var i = 0, ien = insts.length; i < ien; i++) {\n var inst = insts[i];\n run(selector, inst);\n }\n\n return ret;\n };\n /**\r\n * Version information\r\n *\r\n * @name Buttons.version\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @type {string}\r\n *\r\n * @static\r\n *\r\n */\n\n\n Buttons.version = '1.5.1';\n $.extend(_dtButtons, {\n collection: {\n text: function text(dt) {\n return $.rup.i18nParse($.rup.i18n.base, 'rup_table.collection');\n },\n className: 'buttons-collection',\n action: function action(e, dt, button, config) {\n var host = button;\n var collectionParent = $(button).parents('div.dt-button-collection');\n var hostPosition = {\n top: host.position().top + parseInt(host.css('marginTop'), 10),\n left: host.position().left + parseInt(host.css('marginLeft'), 10)\n };\n var tableContainer = $(dt.table().container());\n var multiLevel = false;\n var insertPoint = host; // Remove any old collection\n\n if (collectionParent.length) {\n multiLevel = $('.dt-button-collection').position();\n insertPoint = collectionParent;\n $('body').trigger('click.dtb-collection');\n }\n\n config._collection.addClass(config.collectionLayout).css('display', 'none').insertAfter(insertPoint).fadeIn(config.fade);\n\n var position = config._collection.css('position');\n\n if (multiLevel && position === 'absolute') {\n config._collection.css({\n top: multiLevel.top,\n left: multiLevel.left\n });\n } else if (position === 'absolute') {\n config._collection.css({\n top: hostPosition.top + host.outerHeight(),\n left: hostPosition.left\n }); // calculate overflow when positioned beneath\n\n\n var tableBottom = tableContainer.offset().top + tableContainer.height();\n\n var listBottom = hostPosition.top + host.outerHeight() + config._collection.outerHeight();\n\n var bottomOverflow = listBottom - tableBottom; // calculate overflow when positioned above\n\n var listTop = hostPosition.top - config._collection.outerHeight();\n\n var tableTop = tableContainer.offset().top;\n var topOverflow = tableTop - listTop; // if bottom overflow is larger, move to the top because it fits better\n\n if (bottomOverflow > topOverflow) {\n config._collection.css('top', hostPosition.top - config._collection.outerHeight() - 5);\n }\n\n var listRight = hostPosition.left + config._collection.outerWidth();\n\n var tableRight = tableContainer.offset().left + tableContainer.width();\n\n if (listRight > tableRight) {\n config._collection.css('left', hostPosition.left - (listRight - tableRight));\n }\n } else {\n // Fix position - centre on screen\n var top = config._collection.height() / 2;\n\n if (top > $(window).height() / 2) {\n top = $(window).height() / 2;\n }\n\n config._collection.css('marginTop', top * -1);\n }\n\n if (config.background) {\n // Si la tabla se encuentra en un dialogo insertamos el background dentro del dialogo\n if ($('div.rup-dialog').has('#' + dt.context[0].sTableId + '_wrapper').length ? true : false) {\n $('div.rup-dialog #' + dt.context[0].sTableId + '_wrapper').append('');\n } // Si no usamos el funcionamiento por defecto\n else {\n Buttons.background(true, config.backgroundClassName, config.fade);\n }\n } // Need to break the 'thread' for the collection button being\n // activated by a click - it would also trigger this event\n\n\n setTimeout(function () {\n // This is bonkers, but if we don't have a click listener on the\n // background element, iOS Safari will ignore the body click\n // listener below. An empty function here is all that is\n // required to make it work...\n $('div.dt-button-background').on('click.dtb-collection', function () {});\n $('body').on('click.dtb-collection', function (e) {\n // andSelf is deprecated in jQ1.8, but we want 1.7 compat\n var back = $.fn.addBack ? 'addBack' : 'andSelf';\n\n if (!$(e.target).parents()[back]().filter(config._collection).length) {\n config._collection.fadeOut(config.fade, function () {\n config._collection.detach();\n });\n\n $('div.dt-button-background').off('click.dtb-collection'); // Si la tabla se encuentra en un dialogo eliminamos el background de dentro del dialogo\n\n if ($('div.rup-dialog').has('#' + dt.context[0].sTableId + '_wrapper').length ? true : false) {\n $('div.dt-button-background').remove();\n } // Si no usamos el funcionamiento por defecto\n else {\n Buttons.background(false, config.backgroundClassName, config.fade);\n }\n\n $('body').off('click.dtb-collection');\n dt.off('buttons-action.b-internal');\n }\n });\n }, 10); // Como el boton se posiciona de manera absoluta hay que establecerle la posicion\n // cada vez que se cambia el tamaño de la pantalla.\n\n $(window).on('resize.ajustarCollection', function () {\n if (!$('div.dt-button-collection').is(':visible')) {\n $(window).off('resize.ajustarCollection');\n } else {\n hostPosition = {\n top: host.position().top + parseInt(host.css('marginTop'), 10),\n left: host.position().left + parseInt(host.css('marginLeft'), 10)\n };\n\n config._collection.css({\n top: hostPosition.top + host.outerHeight(),\n left: hostPosition.left\n });\n }\n });\n\n if (config.autoClose) {\n dt.on('buttons-action.b-internal', function () {\n $('div.dt-button-background').click();\n });\n }\n },\n background: true,\n collectionLayout: '',\n backgroundClassName: 'dt-button-background',\n autoClose: false,\n fade: 400,\n attr: {\n 'aria-haspopup': true\n }\n },\n addButton: function addButton(dt, conf) {\n var ctx = dt.context[0];\n var collection = _dtButtons['collection'];\n _dtButtons = ctx.ext.buttons;\n _dtButtons.collection = collection;\n\n if (_dtButtons.addButton) {\n return 'addButton';\n }\n },\n editButton: function editButton(dt, conf) {\n if (_dtButtons.editButton) {\n return 'editButton';\n }\n },\n cloneButton: function cloneButton(dt, conf) {\n if (_dtButtons.cloneButton) {\n return 'cloneButton';\n }\n },\n deleteButton: function deleteButton(dt, conf) {\n if (_dtButtons.deleteButton) {\n return 'deleteButton';\n }\n },\n reportsButton: function reportsButton(dt, conf) {\n if (_dtButtons.reportsButton) {\n return 'reportsButton';\n }\n },\n pageLength: function pageLength(dt) {\n var lengthMenu = dt.settings()[0].aLengthMenu;\n var vals = Array.isArray(lengthMenu[0]) ? lengthMenu[0] : lengthMenu;\n var lang = Array.isArray(lengthMenu[0]) ? lengthMenu[1] : lengthMenu;\n\n var text = function text(dt) {\n return dt.i18n('rup_table.pageLength', {\n '-1': 'Show all rows',\n _: 'Show %d rows'\n }, dt.page.len());\n };\n\n return {\n extend: 'collection',\n text: text,\n className: 'buttons-page-length',\n autoClose: true,\n buttons: $.map(vals, function (val, i) {\n return {\n text: lang[i],\n className: 'button-page-length',\n action: function action(e, dt) {\n dt.page.len(val).draw();\n },\n init: function init(dt, node, conf) {\n var that = this;\n\n var fn = function fn() {\n that.active(dt.page.len() === val);\n };\n\n dt.on('length.dt' + conf.namespace, fn);\n fn();\n },\n destroy: function destroy(dt, node, conf) {\n dt.off('length.dt' + conf.namespace);\n }\n };\n }),\n init: function init(dt, node, conf) {\n var that = this;\n dt.on('length.dt' + conf.namespace, function () {\n that.text(text(dt));\n });\n },\n destroy: function destroy(dt, node, conf) {\n dt.off('length.dt' + conf.namespace);\n }\n };\n }\n });\n /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n * DataTables API\r\n *\r\n * For complete documentation, please refer to the docs/api directory or the\r\n * DataTables site\r\n */\n // Buttons group and individual button selector\n\n DataTable.Api.register('buttons()', function (group, selector) {\n // Argument shifting\n if (selector === undefined) {\n selector = group;\n group = undefined;\n }\n\n this.selector.buttonGroup = group;\n var res = this.iterator(true, 'table', function (ctx) {\n if (ctx._buttons) {\n return Buttons.buttonSelector(Buttons.instanceSelector(group, ctx._buttons), selector);\n }\n }, true);\n res._groupSelector = group;\n return res;\n }); // Individual button selector\n\n DataTable.Api.register('button()', function (group, selector) {\n // just run buttons() and truncate\n var buttons = this.buttons(group, selector);\n\n if (buttons.length > 1) {\n buttons.splice(1, buttons.length);\n }\n\n return buttons;\n }); // Active buttons\n\n DataTable.Api.registerPlural('buttons().active()', 'button().active()', function (flag) {\n if (flag === undefined) {\n return this.map(function (set) {\n return set.inst.active(set.node);\n });\n }\n\n return this.each(function (set) {\n set.inst.active(set.node, flag);\n });\n }); // Get / set button action\n\n DataTable.Api.registerPlural('buttons().action()', 'button().action()', function (action) {\n if (action === undefined) {\n return this.map(function (set) {\n return set.inst.action(set.node);\n });\n }\n\n return this.each(function (set) {\n set.inst.action(set.node, action);\n });\n }); // Enable / disable buttons\n\n DataTable.Api.register(['buttons().enable()', 'button().enable()'], function (flag, contextMenu) {\n return this.each(function (set) {\n set.inst.enable(set.node, flag, contextMenu);\n });\n }); // Disable buttons\n\n DataTable.Api.register(['buttons().disable()', 'button().disable()'], function (contextMenu) {\n return this.each(function (set) {\n set.inst.disable(set.node, contextMenu);\n });\n }); // Get button nodes\n\n DataTable.Api.registerPlural('buttons().nodes()', 'button().node()', function () {\n var jq = $(); // jQuery will automatically reduce duplicates to a single entry\n\n $(this.each(function (set) {\n jq = jq.add(set.inst.node(set.node));\n }));\n return jq;\n }); // Get / set button processing state\n\n DataTable.Api.registerPlural('buttons().processing()', 'button().processing()', function (flag) {\n if (flag === undefined) {\n return this.map(function (set) {\n return set.inst.processing(set.node);\n });\n }\n\n return this.each(function (set) {\n set.inst.processing(set.node, flag);\n });\n }); // Get / set button text (i.e. the button labels)\n\n DataTable.Api.registerPlural('buttons().text()', 'button().text()', function (label) {\n if (label === undefined) {\n return this.map(function (set) {\n return set.inst.text(set.node);\n });\n }\n\n return this.each(function (set) {\n set.inst.text(set.node, label);\n });\n }); // Trigger a button's action\n\n DataTable.Api.registerPlural('buttons().trigger()', 'button().trigger()', function () {\n return this.each(function (set) {\n set.inst.node(set.node).trigger('click');\n });\n }); // Get the container elements\n\n DataTable.Api.registerPlural('buttons().containers()', 'buttons().container()', function () {\n var jq = $();\n var groupSelector = this._groupSelector; // We need to use the group selector directly, since if there are no buttons\n // the result set will be empty\n\n this.iterator(true, 'table', function (ctx) {\n if (ctx._buttons) {\n var insts = Buttons.instanceSelector(groupSelector, ctx._buttons);\n\n for (var i = 0, ien = insts.length; i < ien; i++) {\n jq = jq.add(insts[i].container());\n }\n }\n });\n return jq;\n }); // Add a new button\n\n DataTable.Api.register('button().add()', function (idx, conf) {\n var ctx = this.context;\n var api = new DataTable.Api(ctx); // Don't use `this` as it could be empty - select the instances directly\n\n if (ctx.length) {\n var inst = Buttons.instanceSelector(this._groupSelector, ctx[0]._buttons);\n\n if (inst.length) {\n inst[0].add(conf, idx); // Nuevo botón al contextMenu\n\n _updateContextMenu(this[0].inst.s.buttons, api, ctx[0]);\n }\n }\n\n return this.button(this._groupSelector, idx);\n }); // Destroy the button sets selected\n\n DataTable.Api.register('buttons().destroy()', function () {\n this.pluck('inst').each(function (inst) {\n inst.destroy();\n });\n return this;\n }); // Remove a button\n\n DataTable.Api.registerPlural('buttons().remove()', 'buttons().remove()', function () {\n this.each(function (set) {\n set.inst.remove(set.node);\n });\n return this;\n }); // Information box that can be used by buttons\n\n var _infoTimer;\n\n DataTable.Api.register('buttons.info()', function (title, message, time) {\n var that = this;\n\n if (title === false) {\n $('#table_buttons_info').fadeOut(function () {\n $(this).remove();\n });\n clearTimeout(_infoTimer);\n _infoTimer = null;\n return this;\n }\n\n if (_infoTimer) {\n clearTimeout(_infoTimer);\n }\n\n if ($('#table_buttons_info').length) {\n $('#table_buttons_info').remove();\n }\n\n title = title ? '' + title + '
' : '';\n $('').html(title).append($('')[typeof message === 'string' ? 'html' : 'append'](message)).css('display', 'none').appendTo('body').fadeIn();\n\n if (time !== undefined && time !== 0) {\n _infoTimer = setTimeout(function () {\n that.buttons.info(false);\n }, time);\n }\n\n return this;\n }); // Get data from the table for export - this is common to a number of plug-in\n // buttons so it is included in the Buttons core library\n\n DataTable.Api.register('buttons.exportData()', function (options) {\n if (this.context.length) {\n return _exportData(new DataTable.Api(this.context[0]), options);\n }\n }); // Get information about the export that is common to many of the export data\n // types (DRY)\n\n DataTable.Api.register('buttons.exportInfo()', function (conf) {\n if (!conf) {\n conf = {};\n }\n\n return {\n filename: _filename(conf),\n title: _title(conf),\n messageTop: _message(this, conf.message || conf.messageTop, 'top'),\n messageBottom: _message(this, conf.messageBottom, 'bottom')\n };\n }); // Gestiona las acciones de los botones\n\n DataTable.Api.register('buttons.actions()', function (dt, config) {\n var ctx = dt.settings()[0]; // Añade aquí las funciones de tus botones\n\n switch (config.type) {\n case 'add':\n ctx.oInit.buttons.myLastAction = 'add';\n\n if (ctx.oInit.formEdit !== undefined) {\n $.when(DataTable.Api().editForm.loadSaveDialogForm(ctx, 'POST')).then(function () {\n var idTableDetail = ctx.oInit.formEdit.detailForm; // Limpiamos el formulario\n\n if ($(idTableDetail).find('form')[0] !== undefined) {\n $(idTableDetail).find('form')[0].reset();\n jQuery.each($('select.rup_combo', $(idTableDetail)), function (index, elem) {\n jQuery(elem).rup_combo('refresh');\n });\n\n if (ctx.multiselection.numSelected > 0) {\n $.rup_messages('msgConfirm', {\n message: $.rup.i18nParse($.rup.i18n.base, 'rup_table.checkSelectedElems'),\n title: $.rup.i18nParse($.rup.i18n.base, 'rup_table.changes'),\n OKFunction: function OKFunction() {\n // Abrimos el formulario\n if (ctx.oInit.seeker !== undefined && ctx.oInit.seeker.activate) {\n DataTable.Api().seeker.limpiarSeeker(dt, ctx); // Y deselecionamos los checks y seekers\n } else {\n if (ctx.oInit.multiSelect !== undefined) {\n DataTable.Api().multiSelect.deselectAll(dt); // Y deselecionamos los checks y seekers\n } else if (ctx.oInit.select !== undefined) {\n DataTable.Api().select.deselect(ctx); // Y deselecionamos los checks y seekers\n }\n }\n\n DataTable.Api().editForm.openSaveDialog('POST', dt, null, ctx.oInit.formEdit.customTitle);\n }\n });\n } else {\n DataTable.Api().editForm.openSaveDialog('POST', dt, null, ctx.oInit.formEdit.customTitle);\n }\n } else {\n $.rup_messages('msgError', {\n title: 'Error grave',\n message: 'Falta definir \"detailForm\" en la inicialización de la tabla.
'\n });\n }\n });\n } else {\n //edicion en linea\n ctx.oInit.inlineEdit.currentPos = undefined;\n DataTable.Api().inlineEdit.add(dt, ctx);\n }\n\n break;\n\n case 'edit':\n // Abrimos el formulario\n ctx.oInit.buttons.myLastAction = 'edit';\n\n if (ctx.oInit.formEdit !== undefined) {\n // Se busca el idRow con el último seleccionado. En caso de no existir, será el primero.\n $.when(DataTable.Api().editForm.getRowSelected(dt, 'PUT')).then(function (rowInfo) {\n if (ctx.oInit.formEdit.$navigationBar === undefined || ctx.oInit.formEdit.$navigationBar.funcionParams === undefined || ctx.oInit.formEdit.$navigationBar.funcionParams[4] === undefined || dt.page() + 1 === Number(ctx.oInit.formEdit.$navigationBar.funcionParams[4])) {\n DataTable.Api().editForm.openSaveDialog('PUT', dt, rowInfo.line, ctx.oInit.formEdit.customTitle);\n }\n });\n } else {\n //edicion en linea\n ctx.oInit.inlineEdit.currentPos = undefined;\n ctx.oInit.inlineEdit.alta = undefined;\n var idRowInline = DataTable.Api().inlineEdit.getRowSelected(dt, 'PUT').line;\n }\n\n break;\n\n case 'clone':\n ctx.oInit.buttons.myLastAction = 'clone'; // Abrimos el formulario\n\n if (ctx.oInit.formEdit !== undefined) {\n // Se busca el idRow con el último seleccionado. En caso de no existir, será el primero.\n $.when(DataTable.Api().editForm.getRowSelected(dt, 'CLONE')).then(function (rowInfo) {\n DataTable.Api().editForm.openSaveDialog('CLONE', dt, rowInfo.line, ctx.oInit.formEdit.customTitle);\n });\n } else {\n //edicion en linea\n ctx.oInit.inlineEdit.alta = true;\n ctx.oInit.inlineEdit.currentPos = undefined;\n var idRowInline = DataTable.Api().inlineEdit.getRowSelected(dt, 'CLONE').line;\n }\n\n break;\n\n case 'delete':\n var customEliminar = ctx.oInit.validarEliminar;\n\n if (typeof customEliminar === \"function\" && customEliminar(ctx)) {\n return false;\n }\n\n ctx.oInit.buttons.myLastAction = 'delete'; // borramos todos los seleccionados.\n\n if (!ctx.oInit.noEdit && ctx.oInit.formEdit !== undefined) {\n DataTable.Api().editForm.deleteAllSelects(dt);\n } else if (!ctx.oInit.noEdit && ctx.oInit.inlineEdit !== undefined) {\n //edicion en linea\n DataTable.Api().inlineEdit.deleteAllSelects(dt);\n } else {\n //Delete sin formulario\n _deleteAllSelects(dt);\n }\n\n break;\n }\n }); // Detecta el numero de filas seleccionadas y en funcion de eso muestra u oculta los botones.\n\n DataTable.Api.register('buttons.displayRegex()', function (ctx) {\n if (ctx._buttons[0].inst.s.disableAllButtons === undefined) {\n var opts = ctx._buttons[0].inst.s.buttons;\n var collectionObject;\n $.each(opts, function (i) {\n collectionObject = null;\n var numOfSelectedRows = ctx.multiselection.numSelected;\n\n if (ctx.oInit.masterDetail !== undefined && this.conf.id === ctx.sTableId + 'addButton_1') {\n //si es maestro detalle para el boton add ,solo se renderiza cuando hay selección en el padre.\n var table = $(ctx.oInit.masterDetail.master).DataTable();\n numOfSelectedRows = table.context[0].multiselection.numSelected; //Nums del padre\n\n this.conf.displayRegex = /^[1-9][0-9]*$/; //se cambia expresion regular\n }\n\n _manageButtonsAndButtonsContextMenu(opts[i], numOfSelectedRows, collectionObject, ctx); // Comprueba si tiene botones hijos\n\n\n if (this.buttons.length > 0) {\n collectionObject = this;\n\n _manageButtonsAndButtonsContextMenu(opts[i], numOfSelectedRows, collectionObject, ctx);\n }\n });\n }\n });\n DataTable.Api.register('buttons.disableAllButtons()', function (ctx, exception) {\n var s = ctx._buttons[0].inst.s;\n $.each(s.buttons, function () {\n if (ctx.oInit.noEdit && exception !== undefined && !exception.includes(this.node.id)) {\n // Deshabilita permanentemente el botón (tanto de la toolbar como del contextMenu).\n this.conf.displayRegex = undefined;\n } else if (exception === undefined || !exception.includes(this.node.id)) {\n // Deshabilita el botón de la toolbar.\n $(this.node).prop('disabled', true); // Deshabilita el botón del contextMenu.\n\n $('#' + this.node.id + '_contextMenuToolbar').addClass('disabledButtonsTable');\n }\n });\n s.disableAllButtons = true;\n });\n DataTable.Api.register('buttons.initButtons()', function (ctx, opts) {\n _initButtons(ctx, opts);\n });\n DataTable.Api.register('buttons.deleteNotForm()', function (dt) {\n _deleteAllSelects(dt);\n });\n /**\r\n * Get the file name for an exported file.\r\n *\r\n * @name _filename\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {object}\tconfig Button configuration\r\n * @param {boolean} incExtension Include the file name extension\r\n *\r\n */\n\n var _filename = function _filename(config) {\n // Backwards compatibility\n var filename = config.filename === '*' && config.title !== '*' && config.title !== undefined && config.title !== null && config.title !== '' ? config.title : config.filename;\n\n if (typeof filename === 'function') {\n filename = filename();\n }\n\n if (filename === undefined || filename === null) {\n return null;\n }\n\n if (filename.indexOf('*') !== -1) {\n filename = filename.replace('*', $('head > title').text()).trim();\n } // Strip characters which the OS will object to\n\n\n filename = filename.replace(/[^a-zA-Z0-9_\\u00A1-\\uFFFF\\.,\\-_ !\\(\\)]/g, '');\n\n var extension = _stringOrFunction(config.extension);\n\n if (!extension) {\n extension = '';\n }\n\n return filename + extension;\n };\n /**\r\n * Simply utility method to allow parameters to be given as a function\r\n *\r\n * @name _stringOrFunction\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {undefined|string|function} option Option\r\n *\r\n * @return {null|string} Resolved value\r\n *\r\n */\n\n\n var _stringOrFunction = function _stringOrFunction(option) {\n if (option === null || option === undefined) {\n return null;\n } else if (typeof option === 'function') {\n return option();\n }\n\n return option;\n };\n /**\r\n * Get the title for an exported file.\r\n *\r\n * @name _title\r\n * @function\r\n * @since UDA 3.4.0 // Table 1.0.0\r\n *\r\n * @param {object} config\tButton configuration\r\n *\r\n */\n\n\n var _title = function _title(config) {\n var title = _stringOrFunction(config.title);\n\n return title === null ? null : title.indexOf('*') !== -1 ? title.replace('*', $('head > title').text() || 'Exported data') : title;\n };\n\n var _message = function _message(dt, option, position) {\n var message = _stringOrFunction(option);\n\n if (message === null) {\n return null;\n }\n\n var caption = $('caption', dt.table().container()).eq(0);\n\n if (message === '*') {\n var side = caption.css('caption-side');\n\n if (side !== position) {\n return null;\n }\n\n return caption.length ? caption.text() : '';\n }\n\n return message;\n };\n\n var _exportTextarea = $('')[0];\n\n var _exportData = function _exportData(dt, inOpts) {\n var config = $.extend(true, {}, {\n rows: null,\n columns: '',\n modifier: {\n search: 'applied',\n order: 'applied'\n },\n orthogonal: 'display',\n stripHtml: true,\n stripNewlines: true,\n decodeEntities: true,\n trim: true,\n format: {\n header: function header(d) {\n return strip(d);\n },\n footer: function footer(d) {\n return strip(d);\n },\n body: function body(d) {\n return strip(d);\n }\n }\n }, inOpts);\n\n var strip = function strip(str) {\n if (typeof str !== 'string') {\n return str;\n } // Always remove script tags\n\n\n str = str.replace(/