include("lib.prototype"); include("fitbank.proc.clases"); if (!modularjs.loaded["fitbank.util"]) { if (!modularjs.loaded["lib.split"]) { /*! * Cross-Browser Split 1.1.1 * Copyright 2007-2012 Steven Levithan * Available under the MIT License * ECMAScript compliant, uniform cross-browser split method */ /** * Splits a string into an array of strings using a regex or string separator. Matches of the * separator are not included in the result array. However, if `separator` is a regex that contains * capturing groups, backreferences are spliced into the result each time `separator` is matched. * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably * cross-browser. * @param {String} str String to split. * @param {RegExp|String} separator Regex or string to use for separating the string. * @param {Number} [limit] Maximum number of items to include in the result array. * @returns {Array} Array of substrings. * @example * * // Basic use * split('a b c d', ' '); * // -> ['a', 'b', 'c', 'd'] * * // With limit * split('a b c d', ' ', 2); * // -> ['a', 'b'] * * // Backreferences in result array * split('..word1 word2..', /([a-z]+)(\d+)/i); * // -> ['..', 'word', '1', ' ', 'word', '2', '..'] */ var split; // Avoid running twice; that would break the `nativeSplit` reference split = split || function (undef) { var nativeSplit = String.prototype.split, compliantExecNpcg = /()??/.exec("")[1] === undef, // NPCG: nonparticipating capturing group self; self = function (str, separator, limit) { // If `separator` is not a regex, use `nativeSplit` if (Object.prototype.toString.call(separator) !== "[object RegExp]") { return nativeSplit.call(str, separator, limit); } var output = [], flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6 (separator.sticky ? "y" : ""), // Firefox 3+ lastLastIndex = 0, // Make `global` and avoid `lastIndex` issues by working with a copy separator = new RegExp(separator.source, flags + "g"), separator2, match, lastIndex, lastLength; str += ""; // Type-convert if (!compliantExecNpcg) { // Doesn't need flags gy, but they don't hurt separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags); } /* Values for `limit`, per the spec: * If undefined: 4294967295 // Math.pow(2, 32) - 1 * If 0, Infinity, or NaN: 0 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; * If negative number: 4294967296 - Math.floor(Math.abs(limit)) * If other: Type-convert, then use the above rules */ limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1 limit >>> 0; // ToUint32(limit) while (match = separator.exec(str)) { // `separator.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0].length; if (lastIndex > lastLastIndex) { output.push(str.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1) { match[0].replace(separator2, function () { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undef) { match[i] = undef; } } }); } if (match.length > 1 && match.index < str.length) { Array.prototype.push.apply(output, match.slice(1)); } lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= limit) { break; } } if (separator.lastIndex === match.index) { separator.lastIndex++; // Avoid an infinite loop } } if (lastLastIndex === str.length) { if (lastLength || !separator.test("")) { output.push(""); } } else { output.push(str.slice(lastLastIndex)); } return output.length > limit ? output.slice(0, limit) : output; }; // For convenience String.prototype.split = function (separator, limit) { return self(this, separator, limit); }; return self; }(); } modularjs.loaded["lib.split"] = true; /** * Namespace Util - Define funciones utilitarias. */ var Util = { //Selectores para encontrar los elementos candidatos a verificar si su valor //ha cambiado, pueden agregarse mas filtros selectors: [ "input:not([readonly='']), select:not([readonly='']), textarea:not([readonly=''])", "[type!='hidden']", ".record, [class*='control']" ], getCaret: function(elemento) { var caret = ''; return caret; }, //Aplicar selectores para encontrar campos candidatos a revisar cambios applySelectors: function() { var target = new Element("input"); var first = true; this.selectors.each(function(selector) { if (first) { target = c.form; first = false; } var selected = Prototype.Selector.select(selector, target); target = new Element("input"); selected.each(function(el) { if(el.type === "select-one") { var tmpInput = new Element("input", { id: el.id, "class": el.className }); tmpInput.value = el.options[el.selectedIndex].value; target.appendChild(tmpInput); } else if(el.type === "checkbox") { var tmpInput = new Element("input", { id: el.id, "class": el.className }); tmpInput.value = el.value; target.appendChild(tmpInput); } else { target.appendChild(el.clone(true)); } }); }); return target.childElements(); }, //Obtener el estatos actual de campos y valores en el formulario getOriginalElements: function() { var elements = {}; var targetElements = Util.applySelectors(); targetElements.each(function(e) { elements[e.id] = e.value; }); return elements; }, //Revisar si hay cambios en los elementos candidatos, segun su estado original checkForChanges: function(originalElements) { if (!originalElements || !c.form || !c.formulario) { return false; } var changes = false; var currentElements = {}; var targetElements = Util.applySelectors(); targetElements.each(function(e) { if(e.type !== "select-one") { currentElements[e.id] = e.value; } else { currentElements[e.id] = e.options[e.selectedIndex].text; } }); $H(originalElements).each(function(pair) { if (currentElements[pair.key]) { var check = pair.value !== currentElements[pair.key]; changes = changes || check; } }); return changes; }, /** * Función que obtiene el valor del nombre de la clase css. * * @param className * Valor del nombre de la clase css. */ getStyleClass: function(className) { for ( var s = 0; s < document.styleSheets.length; s++) { if (document.styleSheets[s].rules) { for ( var r = 0; r < document.styleSheets[s].rules.length; r++) { if (document.styleSheets[s].rules[r].selectorText == '.' + className) { return document.styleSheets[s].rules[r]; } } } else if (document.styleSheets[s].cssRules) { for ( var r = 0; r < document.styleSheets[s].cssRules.length; r++) { if (document.styleSheets[s].cssRules[r].selectorText == '.' + className) { return document.styleSheets[s].cssRules[r]; } } } } return null; }, encodeHTML: function(string) { return string.replace(/&/g, "&").replace(//g, ">"); }, firstUpperOtherLower: function(string) { return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); }, getContentWindow: function(iframe) { iframe = $(iframe); return iframe.contentWindow || iframe; }, getMensaje: function(mensajes, msg) { var mobileMsg = msg + "_MOBILE"; if(window.Mobile && mensajes[mobileMsg]) { return mensajes[mobileMsg]; } else { return mensajes[msg]; } }, /** * Inicializa un elemento para que use un oculto. */ initHtmlElement: function(elementId, reverse) { var elemento = $(elementId); var oculto = $(elementId + "_oculto"); if (reverse && reverse == "1") { oculto.widget = oculto; oculto.oculto = oculto; } else { oculto.widget = elemento; oculto.oculto = oculto; } elemento.oculto = oculto; elemento.widget = elemento; oculto.hide = Element.hideCurry(elemento); oculto.show = Element.showCurry(elemento); }, /** * Inicializa un elemento para que use un oculto. */ initHiddenInput: function(elemento, suffix) { elemento = $(elemento); if (!elemento) { return; } elemento.sync = function(oculto, e) { elemento.changeValue(oculto.value, e && e.options || e); }; elemento.setValueOculto = function (oculto) { oculto.changeValue(elemento.value); }; Util._initHiddenInput(elemento, suffix); }, /** * Inicializa un checkbox para que use un oculto. */ initCheckBox: function(elemento) { elemento = $(elemento); elemento.valueOn = elemento.getAttribute("value-on"); elemento.valueOff = elemento.getAttribute("value-off"); elemento.hide = Element.hideCurry(elemento.next("label")); elemento.show = Element.showCurry(elemento.next("label")); elemento.sync = function(e) { elemento.setChecked(e.target.value == elemento.valueOn, e && e.options || e); }; elemento.fixValue = function() { var value = elemento.checked ? elemento.valueOn : elemento.valueOff; elemento.value = value; return value; }; elemento.setValueOculto = function (oculto) { oculto.value = elemento.fixValue(); }; Util._initHiddenInput(elemento, "checkbox"); }, /** * Inicializa un combobox para que use un oculto. */ initComboBox: function(elemento) { elemento = $(elemento); elemento.on("keyup", function(e) { elemento.fireDOMEvent("change", { generated: false }); }); elemento.sync = function(e) { for (var i = 0 ; i < elemento.options.length ; i++) { if (e.target && e.target.value == elemento.options[i].value) { elemento.selectedIndex = i; break; } } }; elemento.setValueOculto = function (oculto) { oculto.value = elemento.options[elemento.selectedIndex].value; }; Util._initHiddenInput(elemento, "combobox"); }, /** * Inicializa un elemento para que use un oculto. * Se sincronizan los cambios efectuados por evento onChange */ _initHiddenInput: function(elemento, suffix) { var name = elemento.name; elemento.name = name + "_" + (suffix || "widget"); var oculto = new Element("input", { type: "hidden", name: name, registro: elemento.registro }); elemento.insert( { before: oculto }); oculto.oculto = oculto; elemento.oculto = oculto; oculto.widget = elemento; elemento.widget = elemento; oculto.hide = Element.hide.curry(elemento); oculto.show = Element.show.curry(elemento); if (suffix) { oculto[suffix] = elemento; elemento[suffix] = elemento; } if (elemento.sync) { oculto.on("change", elemento.sync.curry(oculto)); oculto.on("widget:init", elemento.sync.curry(oculto, { load: true })); } if (elemento.setValueOculto) { elemento.on("change", elemento.setValueOculto.curry(oculto)); elemento.setValueOculto(oculto); } return oculto; }, /** * Inicializa una tabla para que tenga scroll. */ initTableScroll: function(elemento, rows, horizontal) { if (Mobile) { return; } elemento = $(elemento); if (elemento.visible()) { Tabs.removeListener(elemento.scrollHandler); Util._initTableScroll(elemento, rows, horizontal); c.resize(elemento); } else if (!elemento.scrollHandler) { elemento.scrollHandler = Util.initTableScroll.curry(elemento, rows, horizontal); Tabs.addListener(elemento.scrollHandler); } }, _initTableScroll: function(elemento, rows, horizontal) { var div = elemento.down("div"); if (div && !div.hasClassName('*-container')) { div = elemento; } var table = elemento.down("table"); var thead = table.down("thead"); var tbody = table.down("tbody"); var tfoot = table.down("tfoot"); var tr = tbody && tbody.down("tr"); var borders = 2; if (!tbody || !tr || (div && div.className.match('dynamic-*').length > 0)) { return; } if (!horizontal) { var resize = function(td) { var w = parseInt(td.getStyle("width")); td.setStyle("width:" + w + "px"); }; table && table.select("th, td").each(resize); var totalHeight = (((thead && thead.getHeight() || 0) + 4) + (rows * ((tr && tr.getHeight() || 0) + borders))); div && div.setStyle({ display: "block", overflowY: "auto", overflowX: "auto", height: totalHeight + "px" }); thead && thead.setStyle({ display: "block" }); tbody && tbody.setStyle({ display: "block" }); tfoot && tfoot.setStyle({ display: "block" }); } else if (horizontal) { // TODO implementar scroll horizontal } else { var height = rows * tr.getHeight() + (thead ? thead.getHeight() : 0) + (tfoot ? tfoot.getHeight() : 0); elemento.setStyle({ overflowY: "auto", overflowX: "hidden", paddingRight: "20px", height: height + "px" }); } }, initDeleteRecord: function(name) { c.$N(name).each(function(elemento) { if (elemento.widget) { elemento = elemento.widget; } elemento.setDisabled(true); elemento.on("change", function(e) { var tr = elemento.up("td").up("tr"); if (elemento.checked) { tr.addClassName("delete-record"); } else { tr.removeClassName("delete-record"); } c.formulario.evalFormulas(elemento); c.calcular(); }); }); }, generarIdUnicoTemporal: function() { // IMPORTANTE: Mantener sincronizado con Servicios.java var id = "_id_"; id += Math.round(Math.random() * 999); id += "_"; id += Math.round(Math.random() * 999); id += "_"; id += Math.round(Math.random() * 999); return id; }, generarIdUnicoPermanente: function() { // IMPORTANTE: Mantener sincronizado con Servicios.java return "ID_" + Util.generarIdUnicoTemporal(); }, eliminarReferenciasCirculares: function(obj) { var seen = {}; function isPrimitive(obj) { var t = typeof obj; return !obj || t == 'string' || t == 'number' || t == 'boolean'; } function deCycle(obj) { var deCycled; if (!isPrimitive(obj)) { seen[obj] = true; } if (obj instanceof Array) { deCycled = []; for (var i = 0; i < obj.length; i += 1) { if (!seen[obj[i]]) { deCycled[i] = deCycle(obj[i]); } } } else if (typeof obj == 'object' && obj) { deCycled = {}; for (var k in obj) { if (obj.hasOwnProperty(k) && !seen[obj[k]]) { try { deCycled[k] = deCycle(obj[k]); } catch(e) { // no hacer nada } } } } else { deCycled = obj; } return deCycled; } return deCycle(obj); }, clean: function(obj) { if (!obj) { return; } try { obj.initialize = null; obj.constructor = null; delete obj.initialize; delete obj.constructor; } catch(e) { // no hacer nada } return obj; }, isError: function(codigo) { // Esto debe ser igual a ManejoExcepcion.isError() return codigo && !/0|.*-0|ok-.*/i.test(codigo); }, /** * Hace un elemento que sea movible. * * @param movableElement El elemento movible * @param handlerElement El elemento que puede mover */ makeMovable: function(movableElement, handlerElement) { handlerElement.unselectable = "on"; handlerElement.onselectstart = function() { return false }; handlerElement.style.userSelect = handlerElement.style.MozUserSelect = "none"; handlerElement.on('mousedown', function(e) { e = $E(e); var initX = e.X; var initY = e.Y; var divx = movableElement.style.left; var divy = movableElement.style.top; var divLeft = divx.substr(0, divx.indexOf('px')) * 1; var divTop = divy.substr(0, divy.indexOf('px')) * 1; var divNewLeft = initX - divLeft; var divNewTop = initY - divTop; handlerElement.moveHandler = Event.on(document.body, 'mousemove', function(e) { e = $E(e); movableElement.style.left = Math.max(0, e.X - divNewLeft) + 'px'; movableElement.style.top = Math.max(0, e.Y - divNewTop) + 'px'; }); }); handlerElement.on('mouseup', function(e) { e = $E(e); if (handlerElement.moveHandler) { handlerElement.moveHandler.stop(); } }); } }; /** * Extensiones para elementos de html */ Element.addMethods({ ensureVisible: function(element) { element = $(element); var parent = element.parentNode; if (parent) { var parentPosition = parent.positionedOffset().top; var minScroll = parentPosition + parent.scrollTop; var maxScroll = parentPosition + parent.scrollTop + parent.getHeight(); var position = element.positionedOffset().top; if (position < minScroll) { parent.scrollTop = position - parentPosition; } else if (position + element.getHeight() > maxScroll) { parent.scrollTop = position + element.getHeight() - parent.getHeight() - parentPosition; } } }, ensureInside: function(element, parent) { element = $(element); parent = ($(parent) || document.viewport); var d = element.getDimensions(); var vd = parent.getDimensions(); var p = element.viewportOffset(); var diff = vd.height - p.top - d.height; if (diff < 0) { element.style.top = (parseInt("0" + element.style.top, 10) + diff) + "px"; } p = element.viewportOffset(); diff = p.top; if (diff < 0) { element.style.top = (parseInt("0" + element.style.top, 10) - diff) + "px"; } p = element.viewportOffset(); diff = vd.width - p.left - d.width; if (diff < 0) { element.style.left = (parseInt("0" + element.style.left, 10) + diff) + "px"; } p = element.viewportOffset(); diff = p.left; if (diff < 0) { element.style.left = (parseInt("0" + element.style.left, 10) - diff) + "px"; } }, center: function(element, parent) { parent = parent || element.getOffsetParent(); var top = (parent.getHeight() - element.getHeight()) / 2; var left = (parent.getWidth() - element.getWidth()) / 2; if (top < 0) { top = 0; } if (left < 0) { left = 0; } element.absolutize(); element.setStyle( { top: top + "px", left: left + "px" }); }, relativize2: function(element) { element = $(element); var pos = element.positionedOffset(); element.relativize(); var newPos = element.positionedOffset(); var dx = pos[0] - newPos[0]; var dy = pos[1] - newPos[1]; element.moveMargin(dx, dy); element.nextSiblings().each(function(sibling) { if (element.visible()) { sibling.moveMargin(dx, dy); } }); }, moveMargin: function(element, dx, dy) { if (dx != 0) { element.style.marginLeft = (parseInt(element.style.marginLeft) + dx) + "px"; } if (dy != 0) { element.style.marginTop = (parseInt(element.style.marginTop) + dy) + "px"; } }, fireDOMEvent: function(element, event, options) { element = $(element); options = Object.extend({ generated: true }, options); if (document.createEventObject){ // dispatch para IE var evt = document.createEventObject(); evt.options = options; return element.fireEvent('on' + event, evt) } else{ // dispatch para firefox + others var evt = document.createEvent("HTMLEvents"); evt.initEvent(event, true, true); // event type,bubbling,cancelable evt.options = options; return !element.dispatchEvent(evt); } }, getOriginalDimensions: function(element) { element = $(element); var currentW; var currentH; if (element.tagName == "IMG") { currentW = element.width; currentH = element.height; } else { currentW = element.getWidth(); currentH = element.getHeight(); } element.removeAttribute("width"); element.removeAttribute("height"); var h = element.getHeight(); var w = element.getWidth(); if (element.tagName == "IMG") { element.width = currentW; element.height = currentH; } else { element.setStyle({ width: currentW + "px", height: currentH + "px" }); } return {width: w, height: h}; }, hide: function(element) { element = $(element); element.style.display = 'none'; var nextElement = element.next(); if (nextElement && nextElement.hasClassName("asistente-icono")) { nextElement.style.display = 'none'; } return element; }, show: function(element) { element = $(element); element.style.display = ''; var nextElement = element.next(); if (nextElement && nextElement.hasClassName("asistente-icono")) { nextElement.style.display = ''; } return element; }, // Metodos para optimizar carga de formularios solamente hideCurry: function(element) { return function() { element.hide(); }; }, showCurry: function(element) { return function() { element.show(); }; }, syncCurry: function(element) { return function(e) { element.sync(e); }; }, setValueOcultoCurry: function(element, oculto) { return function() { element.setValueOculto(oculto); }; } }); /** * Estos metodos sirven para elementos de tipo Form.Element aunque hay que * registrarlos en Element directamente */ Element.addMethods({ /** * Cambia el valor de un elemento de un formulario. * * @param element Elemento donde se cambia el valor * @param newValue Nuevo valor del elemento * @param options Opciones donde se especifica si el evento es parcial */ changeValue: function(element, value, options) { if (element.nodeName == "SPAN" || element.nodeName == "LABEL") { var originalValue = element.innerHTML; if (value != originalValue) { element.update(value); return true; } else { return false; } } var originalValue = element.value; element._formatValue(value, options); if (originalValue != element.value) { element.fireDOMEvent("change", options); return true; } else { return false; } }, _processValue: function(element, options) { element = $(element); var originalValue = element.value; var cambios = false; if (element.value != "") { Validar.ok(element, "required"); } else { Validar.ok(element, "empty"); } element._formatValue(element.value, options); if (originalValue != element.value) { if (!options.partial) { element.fireDOMEvent("change", options); } cambios = true; } c.formulario.evalFormulas(element); return cambios; }, _formatValue: function(element, value, options) { var newValue = value; var className = null; options = options || {}; try { // Formatear valor con todos los formateadores (element.formatters || $A()).each(function(formatter) { className = formatter.constructor.simpleClassName; newValue = formatter.transform(newValue, options.partial); Validar.ok(element, className); }); } catch(e) { Validar.error(element, e, className); return element.value; } newValue = typeof newValue != "undefined" && newValue != null && newValue.toString() || ""; if (element.value != newValue) { var pos = element.value.length - element.getCaretPosition(); //Hack temporal. Ver Incidencia #8266, bug Chrome #152537 element.value = ""; element.value = newValue; element.setCaretPosition(element.value.length - pos, false); } (element.formatters || $A()).each(function(formatter) { formatter.changeValues(element, options.partial); }); }, /** * Obtiene el objectValue o value adecuadamente * * @param element Elemento de donde obtener el objectValue */ getObjectValue: function(element) { element = $(element); return typeof element.objectValue != "undefined" ? element.objectValue : element.value; }, /** * Obtiene el elemento visible de un objeto HTML * * @param element Elemento de referencia */ getWidget: function(element) { element = $(element); return typeof element.widget != "undefined" ? element.widget : element; }, getCaretPosition: function(element) { element = $(element); if (!element.focused) { return -1; } try { if (element.type === "date" || element.type === "number") { return element.value.length; } if (typeof document.selection != "undefined") { // IE var sel = document.selection.createRange(); sel.moveStart('character', -element.value.length); return sel.text.length; } else if (typeof element.selectionStart != "undefined") { // Otros browsers return element.selectionStart; } } catch(e) { console.log("No se puede obtener la posicion en el texto: " + e); } return element.value.length; }, setCaretPosition: function(element, pos, focus) { element = $(element); if (!element.focused && !focus) { return; } else { element.focus(); } if (element.type === "date" || element.type === "number") { return; } if (typeof element.createTextRange != "undefined") { // IE var range = element.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } else if (typeof element.setSelectionRange != "undefined") { // Otros browsers element.setSelectionRange(pos, pos); } }, setChecked: function(elemento, checked, options) { if (!Object.isElement(elemento)) { elemento = c.$(elemento); } if (elemento.widget) { elemento = elemento.widget; } elemento.checked = checked; elemento.fireDOMEvent("change", options); }, setDisabled: function(elemento, disabled) { if (!Object.isElement(elemento)) { elemento = c.$(elemento); } if (elemento.widget) { elemento = elemento.widget; } if (elemento.type != "checkbox" && elemento.type != "radio" && elemento.type != "image" && elemento.type != "select-one" && elemento.type != "button") { elemento.readOnly = disabled; } else { elemento.disabled = disabled; } if (elemento.hasDatePicker) { datePickerController[disabled ? "disable" : "enable"](elemento.id); } elemento.tabIndex = disabled ? -1 : elemento.originalTabIndex; }, getScrollFromBottom: function(elemento) { return elemento.scrollHeight - elemento.clientHeight - elemento.scrollTop; } }); String.prototype.hashCode = function(){ var hash = 0; for (var i = 0; i < this.length; i++) { hash = 31 * hash + this.charCodeAt(i); hash = hash & hash; } return hash; }; String.prototype.capitalizeFirstLetterWords = function() { var l = this.split(" "); var result = ""; var counter = 0; l.map(function(i) { result = result + Util.firstUpperOtherLower(i) + (counter === l.lenght ? "" : " "); }); return result; }; /** * Obtiene un array de elementos dado su name. Los parametros pueden ser así: * * $N(name) => Obtiene un array de elementos buscando en toda la página * $N(name, index) => Obtiene el elemento indicado del array * $N(base, name) => Obtiene un elemento con el name indicado dentro de la base * $N(base, name, index) => Obtiene el elemento indicado del array * * @param a Ver arriba. * @param b Ver arriba. * @param c Ver arriba. */ var $N = function(a, b, c) { var base = null; var index = null; var name = null; if (typeof c == "number") { base = a; name = b; index = c; } else if (typeof b == "number") { base = document; name = a; index = b; } else if (a && (a.querySelectorAll || base.getElementsByName || a.elements || a.select)) { base = a; name = b; } else { base = document; name = a; } var isNumber = (typeof index == "number"); if (!name) { return isNumber ? null : []; } var elements = null; if (base.querySelectorAll) { // Nativo rapido if (isNumber) { return base.querySelector("#c_" + name + "_" + index); } elements = $A(base.querySelectorAll("*[name='" + name + "']")); } else if (base.getElementsByName) { // También rápido elements = $A(base.getElementsByName(name)); } else if (base.elements) { // Optimizado elements = $A(); var els = base.elements; for (var i = 0; i < els.length; i++) { if (els[i].name == name) { elements.push(els[i]); } } } else { // Mas lento elements = base.select("*[name='" + name + "']"); } return isNumber ? elements[index] : elements; }; /** * Obtiene un array de valores de un elemento dado su name. * * @param i, j, k se pasan directo a $N */ var $V = function(i, j, k) { var n = $N(i, j, k); return Object.isArray(n) ? n.invoke("getObjectValue") : n && n.getObjectValue(); }; /** * Obtiene un array de widgets visibles de un elemento dado su name. * * @param i, j, k se pasan directo a $N */ var $W = function(i, j, k) { var n = $N(i, j, k); return Object.isArray(n) ? n.invoke("getWidget") : n && n.getWidget(); }; var trim = function(s) { Logger.trace("Usar mejor s.strip en vez de trim"); return s.strip(); }; var recargar = function(modulo) { modularjs.loading[modulo] = false; modularjs.loaded[modulo] = false; include(modulo); }; var rethrow = function(transport, e) { console && console.log("Exception", transport, e, arguments); Estatus.mensaje(e && e.message || Util.getMensaje(Mensajes, 'fitbank.validar.ERROR'), e && e.stack, "error"); throw e; }; var deepCopy = function(object) { if (!object || typeof object != "object") { return object; } else if (Object.isArray(object)) { var copy = $A(); object.each(function(value) { copy.push(deepCopy(value)); }); return copy; } else { var copy = new object.constructor(); $H(object).each(function(pair) { copy[pair.key] = deepCopy(pair.value); }); return copy; } }; var copyConstructor = function(params) { if (this.id && this.id.startsWith("_id_")) { this.id = Util.generarIdUnicoTemporal(); } $H(this).each(function(pair) { this[pair.key] = deepCopy(pair.value); }, this); if (params) { Object.extend(this, params); } if (this.constructor.className) { this.className = this.constructor.className; this.simpleClassName = this.constructor.simpleClassName; } }; var caducar = function () { window.onbeforeunload = null; document.location.href = "caducidad.html#cerrar"; } Object.extend(Function.prototype, (function() { var slice = Array.prototype.slice; function tryCatch() { var args = slice.call(arguments, 0); try { return this.apply(this, args); } catch (e) { Estatus.mensaje(e, e && e.stack, 'error'); throw e; } } function bindTryCatch() { var args = slice.call(arguments, 0); var f = this.bind.apply(this, args); return f.tryCatch.bind(f); } return { tryCatch: tryCatch, bindTryCatch: bindTryCatch, tryDefer: tryCatch.defer } })()); var tryEval = function(code) { return (function() { eval(code); }).tryCatch(); }; var tryEvent = function(nameOrId, event, func) { var elements = c.$N(nameOrId) || [ $(nameOrId) ]; elements.each(function(element) { if (element.widget) { element = element.widget; } element.on(event, func.bindTryCatch(element)); }); }; Ajax.Request.addMethods({ abort: function() { this.transport.onreadystatechange = Prototype.emptyFunction; this.transport.abort(); if (Ajax.activeRequestCount > 0) { Ajax.activeRequestCount--; } } }); document.disableContextMenu = function() { if (this.captureEvents) { this.captureEvents(Event.MOUSEDOWN); this.onmousedown = function(e) { if (e.which == 2 || e.which == 3) { return false; } }; } this.oncontextmenu = function() { return false; }; }; } modularjs.loaded["fitbank.util"] = true; /** * Namespace Enlace - Define funciones de conexión con el servidor. */ var Enlace = { /** * Usado para guardar los datos en caso de tener que hacer un submit con * archivos. */ callbacks: {}, /** * Funcion envia un submit al servidor. * * @param contexto Contexto sobre el que se ejecuta las acciones * @param opciones Objeto que puede tener estas propiedades: * - tipo: Tipo del pedido * - paginacion: Indica si se debe cambiar de pagina (-1, 0, 1, * null=volver a la página 1) * - callback: Funcion a ser llamada despues de recibir respuesta * @param posSubir Usado internamente despues de un submit de archivos. * @param fullQuery Indica si se debe ejecutar un query completo en una nueva ventana. * * @return true si no hubo problemas o false si hubo problemas */ submit: function(contexto, opciones, posSubir) { opciones = Object.extend({ tipo: null, paginacion: 0, callback: function() {}, target: null, action: null, skipFiles: false, params: $H(), fullQuery: false }, opciones); var files = Form.getInputs(contexto.form, "file"); if (!opciones.target && (opciones.tipo == GeneralRequestTypes.CONSULTA || posSubir || !files.length)) { if (Enlace.idProceso) { Estatus.finalizarProceso("OK", Enlace.idProceso); } contexto.idProceso = Estatus.iniciarProceso( Util.getMensaje(Mensajes, "fitbank.enlace.PROCESANDO")); var fullQueryNewWindow = opciones.fullQuery && !opciones.paginacion; var secondaryId = Math.round(Math.random() * 10000); var request = new Ajax.Request("proc/" + opciones.tipo, { parameters: $H({ _contexto: !fullQueryNewWindow && contexto.id || secondaryId, _contextoPadre: fullQueryNewWindow && contexto.id || "", _controlConFoco: contexto.formulario.controlConFoco, _registroActivo: contexto.formulario.registroActivo, _paginacion: opciones.paginacion, _fullQuery: opciones.fullQuery }).merge(opciones.params).toQueryString() + "&" + Form.serialize(contexto.form), onSuccess: function(response) { var error = response.responseJSON && response.responseJSON.codigo || ""; if (!Util.isError(error.toLowerCase())) { error = ""; } if (fullQueryNewWindow) { var iframe = new Element("iframe", { src: "entorno-min.html" }); iframe.onload = function() { var cw = Util.getContentWindow(iframe); cw.c.id = secondaryId; cw.c.mostrarFormSimple(opciones, response); cw.c.setupAutoScroll(); cw.onbeforeunload = function() {} } var ef = $$(".entorno-html")[0]; var w = parseInt(ef.getStyle("maxWidth")); iframe.setStyle({ width: (w - 40) + "px", height: ef.getStyle("maxHeight") }); var v = new Ventana({ contenido: iframe, titulo: c.formulario.titulo, verFondo: false, w: w - 30, movable: false }); c.resize(iframe); v.ver(); Estatus.finalizarProceso(Util.getMensaje(Mensajes, "fitbank.contexto.RESULTADO_NUEVA_VENTANA"), c.idProceso); } else { if (response.responseJSON) { opciones.drawHtml = response.responseJSON.drawHtml || false; contexto.loadValues(response, error, opciones); if (response.responseJSON.notifica) { NotificacionesComentarios.consultar(contexto, opciones); } } else { Estatus.finalizarProceso("", contexto.idProceso, (Mobile?"processing":"ok")); } if (!error) { opciones.callback(opciones); } } }, onFailure: contexto.onError.bind(contexto), onException: rethrow }); Estatus.getProceso(contexto.idProceso).setRequest(request); } else { if (files.length && !opciones.skipFiles) { Enlace.idProceso = Estatus.iniciarProceso( Util.getMensaje(Mensajes, "fitbank.enlace.CARGANDO_ARCHIVOS")); Enlace.callbacks[Enlace.idProceso] = function() { Enlace.submit(contexto, opciones, true); }; opciones.action = "proc/subir"; } else { Enlace.idProceso = null; } var params = $H({ _contexto: contexto.id, _proceso: Enlace.idProceso }).merge(opciones.params); var action = contexto.form.action; contexto.form.onsubmit = "return true;"; contexto.form.action = opciones.action + "?" + params.toQueryString(); contexto.form.target = opciones.target || "entorno-iframe-ajax"; contexto.form.method = "POST"; contexto.form.enctype = (files.length && !opciones.skipFiles) ? "multipart/form-data" : ""; contexto.form.submit(); contexto.form.action = action; contexto.form.onsubmit = "return false;"; } } };