/* Prototype: an object-oriented Javascript library, version 1.2.0 * (c) 2005 Sam Stephenson * * THIS FILE IS AUTOMATICALLY GENERATED. When sending patches, please diff * against the source tree, available from the Prototype darcs repository. * * Prototype is freely distributable under the terms of an MIT-style license. * * For details, see the Prototype web site: http://prototype.conio.net/ * /*--------------------------------------------------------------------------*/ var Prototype = { Version: '1.2.0' } var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } } } var Abstract = new Object(); Object.prototype.extend = function(object) { for (property in object) { this[property] = object[property]; } return this; } Function.prototype.bind = function(object) { var method = this; return function() { method.apply(object, arguments); } } Function.prototype.bindAsEventListener = function(object) { var method = this; return function(event) { method.call(object, event || window.event); } } Number.prototype.toColorPart = function() { var digits = this.toString(16); if (this < 16) return '0' + digits; return digits; } var Try = { these: function() { var returnValue; for (var i = 0; i < arguments.length; i++) { var lambda = arguments[i]; try { returnValue = lambda(); break; } catch (e) {} } return returnValue; } } /*--------------------------------------------------------------------------*/ var PeriodicalExecuter = Class.create(); PeriodicalExecuter.prototype = { initialize: function(callback, frequency) { this.callback = callback; this.frequency = frequency; this.currentlyExecuting = false; this.registerCallback(); }, registerCallback: function() { setTimeout(this.onTimerEvent.bind(this), this.frequency * 1000); }, onTimerEvent: function() { if (!this.currentlyExecuting) { try { this.currentlyExecuting = true; this.callback(); } finally { this.currentlyExecuting = false; } } this.registerCallback(); } } /*--------------------------------------------------------------------------*/ function $() { var elements = new Array(); for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); } return elements; } /*--------------------------------------------------------------------------*/ if (!Array.prototype.push) { Array.prototype.push = function() { var startLength = this.length; for (var i = 0; i < arguments.length; i++) this[startLength + i] = arguments[i]; return this.length; } } if (!Function.prototype.apply) { // Based on code from http://www.youngpup.net/ Function.prototype.apply = function(object, parameters) { var parameterStrings = new Array(); if (!object) object = window; if (!parameters) parameters = new Array(); for (var i = 0; i < parameters.length; i++) parameterStrings[i] = 'x[' + i + ']'; object.__apply__ = this; var result = eval('obj.__apply__(' + parameterStrings[i].join(', ') + ')'); object.__apply__ = null; return result; } } /*--------------------------------------------------------------------------*/ var Ajax = { getTransport: function() { return Try.these( function() {return new ActiveXObject('Msxml2.XMLHTTP')}, function() {return new ActiveXObject('Microsoft.XMLHTTP')}, function() {return new XMLHttpRequest()} ) || false; }, emptyFunction: function() {} } Ajax.Base = function() {}; Ajax.Base.prototype = { setOptions: function(options) { this.options = { method: 'post', asynchronous: true, parameters: '' }.extend(options || {}); } } Ajax.Request = Class.create(); Ajax.Request.Events = ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; Ajax.Request.prototype = (new Ajax.Base()).extend({ initialize: function(url, options) { this.transport = Ajax.getTransport(); this.setOptions(options); try { if (this.options.method == 'get') url += '?' + this.options.parameters + '&_='; this.transport.open(this.options.method, url, true); if (this.options.asynchronous) { this.transport.onreadystatechange = this.onStateChange.bind(this); setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10); } this.transport.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); this.transport.setRequestHeader('X-Prototype-Version', Prototype.Version); if (this.options.method == 'post') { this.transport.setRequestHeader('Connection', 'close'); this.transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); } this.transport.send(this.options.method == 'post' ? this.options.parameters + '&_=' : null); } catch (e) { } }, onStateChange: function() { var readyState = this.transport.readyState; if (readyState != 1) this.respondToReadyState(this.transport.readyState); }, respondToReadyState: function(readyState) { var event = Ajax.Request.Events[readyState]; (this.options['on' + event] || Ajax.emptyFunction)(this.transport); } }); Ajax.Updater = Class.create(); Ajax.Updater.prototype = (new Ajax.Base()).extend({ initialize: function(container, url, options) { this.container = $(container); this.setOptions(options); if (this.options.asynchronous) { this.onComplete = this.options.onComplete; this.options.onComplete = this.updateContent.bind(this); } this.request = new Ajax.Request(url, this.options); if (!this.options.asynchronous) this.updateContent(); }, updateContent: function() { if (this.options.insertion) { new this.options.insertion(this.container, this.request.transport.responseText); } else { this.container.innerHTML = this.request.transport.responseText; } if (this.onComplete) { setTimeout((function() {this.onComplete(this.request)}).bind(this), 10); } } }); /*--------------------------------------------------------------------------*/ var Field = { clear: function() { for (var i = 0; i < arguments.length; i++) $(arguments[i]).value = ''; }, focus: function(element) { $(element).focus(); }, present: function() { for (var i = 0; i < arguments.length; i++) if ($(arguments[i]).value == '') return false; return true; }, select: function(element) { $(element).select(); }, activate: function(element) { $(element).focus(); $(element).select(); } } /*--------------------------------------------------------------------------*/ var Form = { serialize: function(form) { var elements = Form.getElements($(form)); var queryComponents = new Array(); for (var i = 0; i < elements.length; i++) { var queryComponent = Form.Element.serialize(elements[i]); if (queryComponent) queryComponents.push(queryComponent); } return queryComponents.join('&'); }, getElements: function(form) { form = $(form); var elements = new Array(); for (tagName in Form.Element.Serializers) { var tagElements = form.getElementsByTagName(tagName); for (var j = 0; j < tagElements.length; j++) elements.push(tagElements[j]); } return elements; }, disable: function(form) { var elements = Form.getElements(form); for (var i = 0; i < elements.length; i++) { var element = elements[i]; element.blur(); element.disable = 'true'; } }, focusFirstElement: function(form) { form = $(form); var elements = Form.getElements(form); for (var i = 0; i < elements.length; i++) { var element = elements[i]; if (element.type != 'hidden' && !element.disabled) { Field.activate(element); break; } } }, reset: function(form) { $(form).reset(); } } Form.Element = { serialize: function(element) { element = $(element); var method = element.tagName.toLowerCase(); var parameter = Form.Element.Serializers[method](element); if (parameter) return encodeURIComponent(parameter[0]) + '=' + encodeURIComponent(parameter[1]); }, getValue: function(element) { element = $(element); var method = element.tagName.toLowerCase(); var parameter = Form.Element.Serializers[method](element); if (parameter) return parameter[1]; } } Form.Element.Serializers = { input: function(element) { switch (element.type.toLowerCase()) { case 'hidden': case 'password': case 'text': return Form.Element.Serializers.textarea(element); case 'checkbox': case 'radio': return Form.Element.Serializers.inputSelector(element); } return false; }, inputSelector: function(element) { if (element.checked) return [element.name, element.value]; }, textarea: function(element) { return [element.name, element.value]; }, select: function(element) { var index = element.selectedIndex; var value = element.options[index].value || element.options[index].text; return [element.name, (index >= 0) ? value : '']; } } /*--------------------------------------------------------------------------*/ var $F = Form.Element.getValue; /*--------------------------------------------------------------------------*/ Abstract.TimedObserver = function() {} Abstract.TimedObserver.prototype = { initialize: function(element, frequency, callback) { this.frequency = frequency; this.element = $(element); this.callback = callback; this.lastValue = this.getValue(); this.registerCallback(); }, registerCallback: function() { setTimeout(this.onTimerEvent.bind(this), this.frequency * 1000); }, onTimerEvent: function() { var value = this.getValue(); if (this.lastValue != value) { this.callback(this.element, value); this.lastValue = value; } this.registerCallback(); } } Form.Element.Observer = Class.create(); Form.Element.Observer.prototype = (new Abstract.TimedObserver()).extend({ getValue: function() { return Form.Element.getValue(this.element); } }); Form.Observer = Class.create(); Form.Observer.prototype = (new Abstract.TimedObserver()).extend({ getValue: function() { return Form.serialize(this.element); } }); /*--------------------------------------------------------------------------*/ document.getElementsByClassName = function(className) { var children = document.getElementsByTagName('*') || document.all; var elements = new Array(); for (var i = 0; i < children.length; i++) { var child = children[i]; var classNames = child.className.split(' '); for (var j = 0; j < classNames.length; j++) { if (classNames[j] == className) { elements.push(child); break; } } } return elements; } /*--------------------------------------------------------------------------*/ var Element = { toggle: function() { for (var i = 0; i < arguments.length; i++) { var element = $(arguments[i]); element.style.display = (element.style.display == 'none' ? '' : 'none'); } }, hide: function() { for (var i = 0; i < arguments.length; i++) { var element = $(arguments[i]); element.style.display = 'none'; } }, show: function() { for (var i = 0; i < arguments.length; i++) { var element = $(arguments[i]); element.style.display = ''; } }, remove: function(element) { element = $(element); element.parentNode.removeChild(element); }, getHeight: function(element) { element = $(element); return element.offsetHeight; } } var Toggle = new Object(); Toggle.display = Element.toggle; /*--------------------------------------------------------------------------*/ Abstract.Insertion = function(adjacency) { this.adjacency = adjacency; } Abstract.Insertion.prototype = { initialize: function(element, content) { this.element = $(element); this.content = content; if (this.adjacency && this.element.insertAdjacentHTML) { this.element.insertAdjacentHTML(this.adjacency, this.content); } else { this.range = this.element.ownerDocument.createRange(); if (this.initializeRange) this.initializeRange(); this.fragment = this.range.createContextualFragment(this.content); this.insertContent(); } } } var Insertion = new Object(); Insertion.Before = Class.create(); Insertion.Before.prototype = (new Abstract.Insertion('beforeBegin')).extend({ initializeRange: function() { this.range.setStartBefore(this.element); }, insertContent: function() { this.element.parentNode.insertBefore(this.fragment, this.element); } }); Insertion.Top = Class.create(); Insertion.Top.prototype = (new Abstract.Insertion('afterBegin')).extend({ initializeRange: function() { this.range.selectNodeContents(this.element); this.range.collapse(true); }, insertContent: function() { this.element.insertBefore(this.fragment, this.element.firstChild); } }); Insertion.Bottom = Class.create(); Insertion.Bottom.prototype = (new Abstract.Insertion('beforeEnd')).extend({ initializeRange: function() { this.range.selectNodeContents(this.element); this.range.collapse(this.element); }, insertContent: function() { this.element.appendChild(this.fragment); } }); Insertion.After = Class.create(); Insertion.After.prototype = (new Abstract.Insertion('afterEnd')).extend({ initializeRange: function() { this.range.setStartAfter(this.element); }, insertContent: function() { this.element.parentNode.insertBefore(this.fragment, this.element.nextSibling); } }); /*--------------------------------------------------------------------------*/ var Effect = new Object(); Effect.Highlight = Class.create(); Effect.Highlight.prototype = { initialize: function(element) { this.element = $(element); this.start = 153; this.finish = 255; this.current = this.start; this.fade(); }, fade: function() { if (this.isFinished()) return; if (this.timer) clearTimeout(this.timer); this.highlight(this.element, this.current); this.current += 17; this.timer = setTimeout(this.fade.bind(this), 250); }, isFinished: function() { return this.current > this.finish; }, highlight: function(element, current) { element.style.backgroundColor = "#ffff" + current.toColorPart(); } } Effect.Fade = Class.create(); Effect.Fade.prototype = { initialize: function(element) { this.element = $(element); this.start = 100; this.finish = 0; this.current = this.start; this.fade(); }, fade: function() { if (this.isFinished()) { this.element.style.display = 'none'; return; } if (this.timer) clearTimeout(this.timer); this.setOpacity(this.element, this.current); this.current -= 10; this.timer = setTimeout(this.fade.bind(this), 50); }, isFinished: function() { return this.current <= this.finish; }, setOpacity: function(element, opacity) { opacity = (opacity == 100) ? 99.999 : opacity; element.style.filter = "alpha(opacity:"+opacity+")"; element.style.opacity = opacity/100 /*//*/; } } Effect.Scale = Class.create(); Effect.Scale.prototype = { initialize: function(element, percent) { this.element = $(element); this.startScale = 1.0; this.startHeight = this.element.offsetHeight; this.startWidth = this.element.offsetWidth; this.currentHeight = this.startHeight; this.currentWidth = this.startWidth; this.finishScale = (percent/100) /*//*/; if (this.element.style.fontSize=="") this.sizeEm = 1.0; if (this.element.style.fontSize.indexOf("em")>0) this.sizeEm = parseFloat(this.element.style.fontSize); if(this.element.effect_scale) { clearTimeout(this.element.effect_scale.timer); this.startScale = this.element.effect_scale.currentScale; this.startHeight = this.element.effect_scale.startHeight; this.startWidth = this.element.effect_scale.startWidth; if(this.element.effect_scale.sizeEm) this.sizeEm = this.element.effect_scale.sizeEm; } this.element.effect_scale = this; this.currentScale = this.startScale; this.factor = this.finishScale - this.startScale; this.options = arguments[2] || {}; this.scale(); }, scale: function() { if (this.isFinished()) { this.setDimensions(this.element, this.startWidth*this.finishScale, this.startHeight*this.finishScale); if(this.sizeEm) this.element.style.fontSize = this.sizeEm*this.finishScale + "em"; if(this.options.complete) this.options.complete(this); return; } if (this.timer) clearTimeout(this.timer); if (this.options.step) this.options.step(this); this.setDimensions(this.element, this.currentWidth, this.currentHeight); if(this.sizeEm) this.element.style.fontSize = this.sizeEm*this.currentScale + "em"; this.currentScale += (this.factor/10) /*//*/; this.currentWidth = this.startWidth * this.currentScale; this.currentHeight = this.startHeight * this.currentScale; this.timer = setTimeout(this.scale.bind(this), 50); }, isFinished: function() { return (this.factor < 0) ? this.currentScale <= this.finishScale : this.currentScale >= this.finishScale; }, setDimensions: function(element, width, height) { element.style.width = width + 'px'; element.style.height = height + 'px'; } } Effect.Squish = Class.create(); Effect.Squish.prototype = { initialize: function(element) { this.element = $(element); new Effect.Scale(this.element, 1, { complete: this.hide.bind(this) } ); }, hide: function() { this.element.style.display = 'none'; } } Effect.Puff = Class.create(); Effect.Puff.prototype = { initialize: function(element) { this.element = $(element); this.opacity = 100; this.startTop = this.element.top || this.element.offsetTop; this.startLeft = this.element.left || this.element.offsetLeft; new Effect.Scale(this.element, 200, { step: this.fade.bind(this), complete: this.hide.bind(this) } ); }, fade: function(effect) { topd = (((effect.currentScale)*effect.startHeight) - effect.startHeight)/2; leftd = (((effect.currentScale)*effect.startWidth) - effect.startWidth)/2; this.element.style.position='absolute'; this.element.style.top = this.startTop-topd + "px"; this.element.style.left = this.startLeft-leftd + "px"; this.opacity -= 10; this.setOpacity(this.element, this.opacity); if(navigator.appVersion.indexOf('AppleWebKit')>0) this.element.innerHTML += ''; //force redraw on safari }, hide: function() { this.element.style.display = 'none'; }, setOpacity: function(element, opacity) { opacity = (opacity == 100) ? 99.999 : opacity; element.style.filter = "alpha(opacity:"+opacity+")"; element.style.opacity = opacity/100 /*//*/; } } Effect.Appear = Class.create(); Effect.Appear.prototype = { initialize: function(element) { this.element = $(element); this.start = 0; this.finish = 100; this.current = this.start; this.fade(); }, fade: function() { if (this.isFinished()) return; if (this.timer) clearTimeout(this.timer); this.setOpacity(this.element, this.current); this.current += 10; this.timer = setTimeout(this.fade.bind(this), 50); }, isFinished: function() { return this.current > this.finish; }, setOpacity: function(element, opacity) { opacity = (opacity == 100) ? 99.999 : opacity; element.style.filter = "alpha(opacity:"+opacity+")"; element.style.opacity = opacity/100 /*//*/; element.style.display = 'block'; } } Effect.ContentZoom = Class.create(); Effect.ContentZoom.prototype = { initialize: function(element, percent) { this.element = $(element); if (this.element.style.fontSize=="") this.sizeEm = 1.0; if (this.element.style.fontSize.indexOf("em")>0) this.sizeEm = parseFloat(this.element.style.fontSize); if(this.element.effect_contentzoom) { this.sizeEm = this.element.effect_contentzoom.sizeEm; } this.element.effect_contentzoom = this; this.element.style.fontSize = this.sizeEm*(percent/100) + "em" /*//*/; if(navigator.appVersion.indexOf('AppleWebKit')>0) { this.element.scrollTop -= 1; }; } } var Enumerable = { each: function(iterator) { var index = 0; try { this._each(function(value) { try { iterator(value, index++); } catch (e) { if (e != $continue) throw e; } }); } catch (e) { if (e != $break) throw e; } }, all: function(iterator) { var result = true; this.each(function(value, index) { result = result && !!(iterator || Prototype.K)(value, index); if (!result) throw $break; }); return result; }, any: function(iterator) { var result = true; this.each(function(value, index) { if (result = !!(iterator || Prototype.K)(value, index)) throw $break; }); return result; }, collect: function(iterator) { var results = []; this.each(function(value, index) { results.push(iterator(value, index)); }); return results; }, detect: function (iterator) { var result; this.each(function(value, index) { if (iterator(value, index)) { result = value; throw $break; } }); return result; }, findAll: function(iterator) { var results = []; this.each(function(value, index) { if (iterator(value, index)) results.push(value); }); return results; }, grep: function(pattern, iterator) { var results = []; this.each(function(value, index) { var stringValue = value.toString(); if (stringValue.match(pattern)) results.push((iterator || Prototype.K)(value, index)); }) return results; }, include: function(object) { var found = false; this.each(function(value) { if (value == object) { found = true; throw $break; } }); return found; }, inject: function(memo, iterator) { this.each(function(value, index) { memo = iterator(memo, value, index); }); return memo; }, invoke: function(method) { var args = $A(arguments).slice(1); return this.collect(function(value) { return value[method].apply(value, args); }); }, max: function(iterator) { var result; this.each(function(value, index) { value = (iterator || Prototype.K)(value, index); if (result == undefined || value >= result) result = value; }); return result; }, min: function(iterator) { var result; this.each(function(value, index) { value = (iterator || Prototype.K)(value, index); if (result == undefined || value < result) result = value; }); return result; }, partition: function(iterator) { var trues = [], falses = []; this.each(function(value, index) { ((iterator || Prototype.K)(value, index) ? trues : falses).push(value); }); return [trues, falses]; }, pluck: function(property) { var results = []; this.each(function(value, index) { results.push(value[property]); }); return results; }, reject: function(iterator) { var results = []; this.each(function(value, index) { if (!iterator(value, index)) results.push(value); }); return results; }, sortBy: function(iterator) { return this.collect(function(value, index) { return {value: value, criteria: iterator(value, index)}; }).sort(function(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; }).pluck('value'); }, toArray: function() { return this.collect(Prototype.K); }, zip: function() { var iterator = Prototype.K, args = $A(arguments); if (typeof args.last() == 'function') iterator = args.pop(); var collections = [this].concat(args).map($A); return this.map(function(value, index) { return iterator(collections.pluck(index)); }); }, inspect: function() { return '#'; } } var Hash = { _each: function(iterator) { for (var key in this) { var value = this[key]; if (typeof value == 'function') continue; var pair = [key, value]; pair.key = key; pair.value = value; iterator(pair); } }, keys: function() { return this.pluck('key'); }, values: function() { return this.pluck('value'); }, merge: function(hash) { return $H(hash).inject($H(this), function(mergedHash, pair) { mergedHash[pair.key] = pair.value; return mergedHash; }); }, toQueryString: function() { return this.map(function(pair) { return pair.map(encodeURIComponent).join('='); }).join('&'); }, inspect: function() { return '#'; } } function $H(object) { var hash = Object.extend({}, object || {}); Object.extend(hash, Enumerable); Object.extend(hash, Hash); return hash; } function pegaControle() { qS = unescape(location.search) if(r = qS.match( /c=(\w+)&?/ )) return r[1] return false } //@todo verificar essas fs... function pegaMetodo() { qS = unescape(location.search) if(r = qS.match( /m=(\w+)$/ )) return r[1] return false } function obj2QS(gets) { qS = "" for(i in gets) if(i != 'extend') qS += '&' + i + '=' + gets[i] return qS } function navega(m,c,gets) { if( ! c ) c = pegaControle(); location.href = '?c=' + c + '&m=' + m + (gets ? obj2QS(gets) : '') } Ajax.Requisicao = Class.create(); Ajax.Requisicao.prototype = (new Ajax.Request()).extend({ onStateChange: function() { if (this.transport.readyState == 4) { try{ var retorno = eval("("+this.transport.responseText+")") }catch(e){ if(this.options.msg_erro) var retorno = {numero:1,erro:this.options.msg_erro} else var retorno = {numero:1,erro:'Erro ao avaliar o retorno do servidor.'} } this.options['objeto'][ this.options['metodo'] ]( retorno ) } } }); Ajax.RequisicaoHTML = Class.create(); Ajax.RequisicaoHTML.prototype = (new Ajax.Request()).extend({ onStateChange: function() { if (this.transport.readyState == 4) this.options['objeto'][ this.options['metodo'] ]( this.transport.responseText ) } }); var Objeto = Class.create() Objeto.prototype = { initialize: function(){}, pegaMetodo: function(m) // @todo bind? { return eval("this." + m ) }, ajax: function( controle,metodo,metodoRetorno, gets ) { if( ! metodoRetorno ) metodoRetorno = "emSucessoAjax"; caminho = "index.php?c=" + controle + "&m=" + metodo + obj2QS(gets) return new Ajax.Requisicao( caminho, {objeto:this,metodo:metodoRetorno,msg_erro:gets.msg_erro} ) }, ajax_html: function( controle,metodo,metodoRetorno, parametros ) { qS = "" for(i in parametros) if( i != 'extend' ) qS += '&' + i + '=' + parametros[i] if( ! metodoRetorno ) metodoRetorno = "emSucessoAjaxHTML"; caminho = "?c=" + controle + "&m=" + metodo + qS return new Ajax.RequisicaoHTML( caminho, {objeto:this,metodo:metodoRetorno} ) }, emSucessoAjax: function(resultado){}, emSucessoAjaxHTML: function(resultado){} } var Componente = Class.create() Componente.prototype = (new Objeto()).extend({ focavel: true, adiciona: function( valor ) { this.setaValor( ( this.pegaValor() * 1 ) + valor ) }, subtrai: function( valor ) { this.setaValor( ( this.pegaValor() * 1 ) - valor ) }, initialize: function(){}, unico: function() { return (this.at('unico') == '1' || this.at('unico') == 't' || this.at('unico') == 'true') }, inicializa: function( elemento ) { this.elementos = [] this.adicionaElemento( elemento ) this.setaObrigatorio() // this.setaMascara() this.aviso_invalido = 'Por favor, preencha corretamente o campo "' + this.at('title') + '"' this.setaValorInicial() // this.inicia() --> inicia pelo form! }, adicionaElemento: function( elemento ) { this.elementos.push( elemento ); this.setaAcoes( elemento ) }, inicia: function(){}, elemento: function() { return this.elementos[0]; }, setaValorInicial: function() { this.valorInicial = this.pegaValor() }, alterado: function() { return this.valorInicial != this.pegaValor() }, serializa: function() { return this.pegaNome() + "=" + this.pegaValor() }, setaDesabilitado: function( a ) { this.elemento().disabled = a; }, desabilita: function() { this.setaDesabilitado(true) }, habilita: function() { this.setaDesabilitado(false) }, setaValor: function( valor ) { this.elemento().value = valor }, pegaId: function() { return this.elemento().id }, pegaNome: function() { return this.elemento().name }, pegaTabela: function() { return this.pegaNome().split("[")[0] }, pegaCampo: function() { try { return this.pegaNome().match( /\[(\w+)\]/ )[1] }catch(e){ return false //alert('Erro ao buscar o nome do campo "' + this.pegaNome() + '". O nome deve seguir o padrão tabela[campo]') } }, pegaValor: function() { return this.elemento().value }, setaApresentacao: function(valor) { return false }, pegaApresentacao: function() { return this.pegaValor() }, to_s: function() { return '{"nome":"' + this.pegaNome() + '", "valor":"' + this.pegaValor() + '"}' }, incrementa: function(){ this.elemento().value = this.elemento().value * 1 + 1 }, decrementa: function(){ this.elemento().value = this.elemento().value * 1 - 1 }, concatena: function( texto ){ this.elemento().value += texto }, at: function(at){ return this.elemento().getAttribute(at) }, setaGrupo: function( grupo ) { this.grupo = grupo; }, /* A única forma de fazer isso é no focus dar um onblur... somenteLeitura: function(l) { return this.elemento().readonly = l },*/ emErroVazio: function() { this.foca() this.avisoVazio() return false }, setaAcoes: function( elemento ) { elemento.ref = this // cria uma referência no elemento para o objeto componente elemento.onfocus = function() { this.ref.setaFoco() this.ref.emFoco() } elemento.onblur = function() { this.ref.apagaFoco() this.ref.emDesfoco() } elemento.onclick = function() { this.ref.emClique() } elemento.onkeyup = function( tecla ) { if (!tecla) var tecla = window.event if (tecla.keyCode) var codigo = tecla.keyCode else if (tecla.which) var codigo = tecla.which this.ref.emTecla( codigo ) this.ref.mascara( codigo ) } elemento.onchange = function() { this.ref.emMuda() this.ref.validacao() } }, validacao: function() { if( ! this.valida() ) { this.forcaFoco(); this.seleciona(); this.setaEstilo('background','#fdd') } else this.dessetaEstilo('background') }, emErroInvalido: function() { this.foca() this.avisoInvalido() return false }, /* Implementar nos herdeiros */ mascara: function(){}, // helper para mascaras _mascara: function(posicoes,caracteres) { v = this.pegaValor() vl = v.length; for (var i = 0; i <= posicoes.length; i++) for (var k = 0; k <= vl; k++) v = (k == posicoes[i] && v.substring(k, k+1) != caracteres[i] ? v.substring(0,k) + caracteres[i] + v.substring(k,vl):v) return v; }, // helper para mascaras _mascaraReversa: function(posicao, caracter) { v = this.pegaValor().replace(caracter,''); vl = v.length; if(vl == this.at('maxlength')) return v.substr(0,vl-posicao-1) + caracter + v.substring(vl-posicao-1); if(vl > posicao) return v.substr(0,vl-posicao) + caracter + v.substring(vl-posicao); //@todo usar re? // re = "/^.+.{"+posicao+"})$/"; // v = v.replace(re, "$1"+caracter+"$2"); return v; }, _mascaraReversas: function(posicoes, caracteres) { v = this.pegaValor().replace(caracteres,''); for( i = 0; i <= posicoes.length; i++) { vl = v.length; if(vl == this.at('maxlength')) return v.substr(0,vl-posicoes[i]-1) + caracteres[i] + v.substring(vl-posicoes[i]-1); if(vl > posicao) return v.substr(0,vl-posicoes[i]) + caracteres[i] + v.substring(vl-posicoes[i]); } //@todo usar re? // re = "/^.+.{"+posicao+"})$/"; // v = v.replace(re, "$1"+caracter+"$2"); return v; }, valida: function(){ if( re = this.at('validacao') ) return ( new RegExp(re) ).test( this.pegaValor() ); return true; }, emFoco: function(){}, emDesfoco: function(){}, emClique: function(){}, emTecla: function(){}, emMuda: function(){}, setaFoco: function(){ this.focado = true }, apagaFoco: function(){ this.focado = false }, setaObrigatorio: function() { this.obrigatorio = this.at("obrigatorio") == "t" ? true : false }, // setaMascara: function() { this.mascara = this.at("mascara") ? this.at("mascara") : null }, limpa: function() { this.elemento().value = "" }, preenchido: function() { return this.pegaValor() ? true : false }, dessetaEstilo: function(estilo) { this.elemento().style[estilo] = ""; }, setaEstilo: function(estilo,valor) { this.elemento().style[estilo] = valor; }, foca: function() { this.elemento().focus() return true }, /* * Gambiarra para focar um campo após o onchange */ forcaFoco: function() { id = this.pegaId() setTimeout(function(){$(id).focus()}, 0); }, seleciona: function() { this.elemento().select() return true }, /* * Gambiarra para selecionar um campo após o onchange */ forcaSelecao: function() { id = this.pegaId() setTimeout(function(){$(id).select()}, 0); }, avisoVazio: function() { alert('Por favor, preencha o campo "' + this.at('title') + '"' ) }, avisoInvalido: function() { alert( this.aviso_invalido ) }, validaRegra: function() { regra = this.at("regra") if( ! regra ) return true else { p = new QuestionScriptParser( regra ) return p.compila() } }, /* validacao: function() { if( this.at('validacao') ) { return eval( this.at('validacao')+"('" + this.pegaValor() + "')" ) } return true }, */ erroVazio: function() { return ( ! this.preenchido() && this.obrigatorio ) }, erroInvalido: function() { return ( this.preenchido() && ! this.valida() ) }, setaAt: function(at, valor) { this.elemento().setAttribute(at, valor) } }) Componente.Text = Class.create() Componente.Text.prototype = (new Componente()).extend() Componente.Numerico = Class.create() Componente.Numerico.prototype = (new Componente()).extend({ formata: function( valor, precisao ) { mult = Math.pow(10, precisao) return Math.round(valor * mult) / mult }, mascara: function() { //this.elemento().value = this._mascaraReversa(this.at('precisao'), '.') this.elemento().value = this._mascaraReversa([this.at('precisao')], [',']) }, setaValor: function( valor ) { this.elemento().value = valor ? this.formata( valor, this.at('precisao') ) : '' } }) Componente.Inteiro = Class.create() Componente.Inteiro.prototype = (new Componente()).extend({ pegaValor: function() { return this.elemento().value ? parseInt(this.elemento().value) : '' }, mascara: function() { if( isNaN( this.pegaValor() ) ) return this.setaValor(""); return this.setaValor( this.pegaValor().toString().replace('[^\d]','') ) }, valida: function(){ if( re = this.at('validacao') ) if( ! (new RegExp(re)).test( this.pegaValor() ) ) { this.aviso_invalido = 'O campo "' + this.at('title') + '" deve ser um número inteiro.' return false } if( maximo = this.at('maximo') ) if( this.pegaValor() >= maximo ) { this.aviso_invalido = 'O campo "' + this.at('title') + '" deve ser menor que ' + maximo + '.' return false } return true } }) Componente.Timer = Class.create() Componente.Timer.prototype = (new Componente.Inteiro()).extend({ inicia: function() { this.bt = $( this.pegaId() + '.para'); this.bt.onclick = (function() { if(this.on) this.stop() else this.play() }).bind(this) if( this.preenchido() ) this.stop() else this.play() new PeriodicalExecuter( (function() { if( this.on ) this.operacaoTimer() }).bind(this), 1 ) }, /* A operação padrão é um incremento, mas poderia ser qq coisa, basta extender */ operacaoTimer: function() { this.incrementa(); }, play: function() { this.on = true; this.bt.src = 'img/timer_stop.gif' this.bt.alt = '[]' // this.desabilita() }, stop: function() { this.on = false; this.bt.src = 'img/timer_play.gif' this.bt.alt = '>' // this.habilita() } }) Componente.CNPJ = Class.create() Componente.CNPJ.prototype = (new Componente()).extend({ valida: function() { //@todo olhar http://www.mhavila.com.br/topicos/web/cpf_cnpj.html } }) Componente.CPF = Class.create() Componente.CPF.prototype = (new Componente()).extend({ valida: function() { //@todo olhar http://www.mhavila.com.br/topicos/web/cpf_cnpj.html } }) Componente.Hora = Class.create() Componente.Hora.prototype = (new Componente()).extend({ mascara: function() { this.setaValor( this._mascara([2], [':']) ) } }) Componente.Data = Class.create() Componente.Data.prototype = (new Componente()).extend({ /* mascara: function() { this.setaValor( this._mascara([2,5], ['/','/']) ) },*/ dia: function(){ return this.pegaValor().split('/')[0] }, mes: function(){ return this.pegaValor().split('/')[1] }, ano: function(){ return this.pegaValor().split('/')[2] } }) Componente.Momento = Class.create() Componente.Momento.prototype = (new Componente()).extend({ mascara: function() { this.setaValor( this._mascara([2,5,10,13], ['/','/',' ',':']) ) } }) Componente.Password = Class.create() Componente.Password.prototype = (new Componente()).extend({ erroVazio: function() { return ( ! this.preenchido() && this.obrigatorio && $f.acao != 'Edita' ) } }) Componente.TextArea = Class.create() Componente.TextArea.prototype = (new Componente()).extend() Componente.Hidden = Class.create() Componente.Hidden.prototype = (new Componente()).extend({ focavel: false, setaObrigatorio: function() { this.obrigatorio = this.at('obrigatorio') == 't' && ! this.at('chave') == 't' ? true : false }, mostra: function() { this.setaAt('type', 'text') }, foca: function(){ return false } }) Componente.File = Class.create() Componente.File.prototype = (new Componente()).extend({ erroVazio: function() { return ( ! this.preenchido() && this.obrigatorio && $f.acao != 'Edita' ) } }) Componente.Imagem = Class.create() Componente.Imagem.prototype = (new Componente.File()).extend({ emMuda: function() { $('imagem_' + this.pegaId()).src = '' } }) Componente.Seletores = Class.create() Componente.Seletores.prototype = (new Componente()).extend({ setaElemento: function( elemento ) { if( ! this.elementos ) { this.elemento = elemento this.elementos = [] this.setaObrigatorio() } this.elementos.push( elemento ) this.setaAcoes( elemento ) }, avisoVazio: function() { alert('Por favor, selecione algum item no campo "' + this.at('title') + '"' ) }, foca: function() { this.elementos[0].focus() return true }, marca: function(i) { // for( var i = 0 ; i < this.elementos.length ; i++ ) this.elementos[i].checked = true }, limpa: function() { for( var i = 0 ; i < this.elementos.length ; i++ ) this.elementos[i].checked = false }, desmarcaTodos: function(b) { for( var i = 0 ; i < this.elementos.length ; i++ ) this.elementos[i].checked = false }, marcaTodos: function() { for( var i = 0 ; i < this.elementos.length ; i++ ) this.elementos[i].checked = true } }) Componente.Radio = Class.create() Componente.Radio.prototype = (new Componente.Seletores()).extend({ pegaValor: function() { for( var i = 0 ; i < this.elementos.length ; i++ ) if( this.elementos[i].checked ) return this.elementos[i].value return null } }) //@todo Checkbox é dif de Radio, fazer... Componente.CheckBox = Class.create() Componente.CheckBox.prototype = (new Componente.Seletores()).extend({ setaAcoes: function( elemento ) { elemento.ref = this // cria uma referência no elemento para o objeto componente elemento.onclick = function() { this.ref.emClique() } elemento.onchange = function() { this.ref.emMuda() if( this.ref.pegaValor() ) this.ref.emMarca() else this.ref.emDesmarca() } }, emMarca: function(){}, emDesmarca: function(){}, pegaValor: function() { valores = [] for( var i = 0 ; i < this.elementos.length ; i++ ) if( this.elementos[i].checked ) valores.push(this.elementos[i].value) if(!valores.length) return false //em checks se não varca serializa o valor false return valores }, /* por enquanto usa o normal.. pegaNome: function() { return this.elemento().name.replace(/\[.+\]/, '') }, */ pegaSelecionados: function() { }, pegaUltimoValor: function() { for( var i = (this.elementos.length-1) ; i > -1 ; i-- ) if( this.elementos[i].checked ) return this.elementos[i].value }, pegaPrimeiroValor: function() { for( var i = 0 ; i < this.elementos.length ; i++ ) if( this.elementos[i].checked ) return this.elementos[i].value }, contem: function( indice ) { return this.elementos[indice].checked }, soma: function() { v = this.pegaValor() s = 0 for( var i = 0 ; i < v.length ; i++ ) s += parseInt(v[i]) return s }, emMuda: function() { } }) Componente.Select = Class.create() Componente.Select.prototype = (new Componente()).extend ({ pegaApresentacao: function(indice) { return this.elemento().options[ indice ? indice : this.indice() ].text }, indice: function(){ return this.elemento().selectedIndex }, pegaValor: function(indice) { v = this.elemento().options[ indice ? indice : this.indice() ].value return v > 0 ? v : false }, preenchido: function() { return this.pegaValor() ? true : false }, limpa: function() { return this.elemento().selectedIndex = 0 }, tamanho: function(){ return this.elemento().options.length }, excluiTodos: function(){ this.elemento().options.length=0 }, adicionaItem: function(nome, valor) { this.elemento().options[this.elemento().options.length] = new Option(nome, valor); }, seleciona: function() { this.elemento().focus() return true } }) //@todo Componente.Button = Class.create() Componente.Button.prototype = (new Componente()).extend ({ limpa: function() { return true } }) Componente.Busca = Class.create() Componente.Busca.prototype = (new Componente()).extend({ inicia: function() { this.botaoBusca = $( this.pegaId() + '.busca' ) this.divMsg = $( this.pegaId() + '.msg' ) this.iniciaElementos() this.botaoBusca.ref = this this.botaoBusca.onclick = function(){ this.ref.busca() } }, busca: function(){} }) String.prototype.capitaliza = function() { return this.replace(/\w+/g, function(a){ return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase(); }); }; /* @todo Um campo checkbox tem q ter uma apresentação com o title... */ Componente.ListaOpcoes = Class.create() Componente.ListaOpcoes.prototype = (new Componente()).extend({ inicia: function() { this.montaLista() }, montaLista: function() { // alert(">montando lista...>"); this.opcaoSelecionada = -1; this.containerOpcoes = $( this.pegaId() + '.opcoes' ) this.opcoes = this.containerOpcoes.childNodes // alert(">montando lista.2.>"+this.opcoes); for( i = 0 ; i < this.opcoes.length ; i++ ) { this.opcoes[i].ref = this this.opcoes[i].i = i this.opcoes[i].onclick = function() { this.ref.clicouOpcao( this.i ) } this.opcoes[i].onmouseover = function() { this.ref.emSobreOpcao( this.i ) } } this.selecionaOpcao(0) }, clicouOpcao: function(i){ alert(">onclick2>"+this.i); this.focaESelecionaOpcao(i) }, emSobreOpcao: function(i){}, focaESelecionaOpcao: function(i) { this.foca() this.selecionaOpcao(i) }, emTecla: function( codigo ) { switch( codigo ) { case 27: this.elementoApresentacao.limpa() this.itemSelecionado = 0 this.containerLista.style.visibility = 'hidden' break case 40: this.selecionaProximaOpcao() break case 38: this.selecionaOpcaoAnterior() break case 13: this.seleciona() break } }, emFoco: function() { this.containerOpcoes.className = 'lista-opcoes-focada' for( i = 0 ; i < this.opcoes.length ; i++ ) this.opcoes[i].className = 'opcao-focada' }, emDesfoco: function() { this.containerOpcoes.className = 'lista-opcoes' for( i = 0 ; i < this.opcoes.length ; i++ ) this.opcoes[i].className = 'opcao' }, selecionaOpcao: function( i ) { this.focaOpcao(i) this.setaValor( this.opcoes[i].id.split('.')[2] ) }, focaOpcao: function( i ) { if(i<0 || !this.opcoes[i]) return false; if( this.opcaoSelecionada > -1 ) this.opcoes[ this.opcaoSelecionada ].className = 'opcao-focada'; this.opcaoSelecionada = i; this.opcoes[i].className = 'opcao-focada-selecionada'; }, selecionaProximaOpcao: function(){ return this.selecionaOpcao( this.opcaoSelecionada + 1 ) }, selecionaOpcaoAnterior: function(){ return this.selecionaOpcao( this.opcaoSelecionada - 1 ) }, focaProximaOpcao: function(){ return this.focaOpcao( this.opcaoSelecionada + 1 ) }, focaOpcaoAnterior: function(){ return this.focaOpcao( this.opcaoSelecionada - 1 ) }, moveCursor: function( delta ) { if(this.itemSelecionado > 0) this.desfocaItem() this.itemSelecionado += delta if( ! this.selecionado() ) this.itemSelecionado -= delta this.focaItem() } }) Componente.AutoCompletar = Class.create() Componente.AutoCompletar.prototype = (new Componente.ListaOpcoes()).extend ({ habilita: function() { this.elementoApresentacao.habilita() }, desabilita: function() { this.elementoApresentacao.desabilita() }, inicia: function() { this.iniciaElementos() }, iniciaElementos: function() { this.ultima_apresentacao = '' this.itemSelecionado = 0 this.tabela = this.at('tabela') this.controle = this.at('controle') ? this.at('controle') : pegaControle() this.metodo = this.at('metodo') ? this.at('metodo') : 'AutoCompletar' this.containerLista = $( this.pegaId() + '.lista' ) this.loader = $( this.pegaId() + '.loader' ) this.containerLista.mostra = function(){ this.style.visibility = 'visible' } this.containerLista.esconde = function(){ this.innerHTML = ''; this.style.visibility = 'hidden' } this.elementoApresentacao = new Componente.Text() this.elementoApresentacao.inicializa( $( this.pegaId() + '.apresentacao' ) ) this.elementoApresentacao.ref = this; this.elementoApresentacao.emTecla = function( codigo ){ this.ref.emTecla(codigo) } this.elementoApresentacao.emDesfoco = function(){ this.ref.emDesfoco();} this.elementoApresentacao.emFoco = function(){ this.ref.emFoco();} }, emFoco: function() { // alert('focou'); this.teclou = false this.apresentacao_anterior = this.pegaApresentacao(); this.iniciaBuscaPeriodica() }, iniciaBuscaPeriodica: function() { setTimeout(this.buscaEmPeriodo.bind(this), 250); }, buscaEmPeriodo: function() { // alert('period'); if( ! this.teclou && this.apresentacao_anterior != this.pegaApresentacao() ) { this.limpa() this.containerLista.esconde() this.emModificaApresentacao() if( this.pegaApresentacao() ) { this.containerLista.mostra() this.buscaOpcoes() } else { this.itemSelecionado = 0; this.containerLista.style.visibility = 'hidden'; } this.apresentacao_anterior = this.pegaApresentacao(); } this.teclou = false; this.iniciaBuscaPeriodica() }, emDesfoco: function() { if( ! this.pegaValor() ) this.esconde() else this.seleciona() }, emTecla: function( codigo ) { switch( codigo ) { case 9: break case 27: this.esconde() break case 13: this.seleciona() break case 40: this.focaProximaOpcao() break case 38: this.focaOpcaoAnterior() break case 8: default: this.teclou = true; } }, buscaOpcoes: function() { this.loader.src = 'img/loader_on.gif'; this.ajax(this.controle, this.metodo, 'emRecebeOpcoes', {id: this.pegaId(), nome: this.pegaApresentacao()}) }, emEsconde: function(){}, esconde: function() { this.emEsconde() this.elementoApresentacao.limpa() this.itemSelecionado = 0 this.containerLista.esconde() this.limpa() }, emRecebeOpcoes: function( r ) { this.containerLista.innerHTML = '' this.lista = '' if( ! r.length) { this.loader.src = 'img/loader_off.gif'; if(r.erro) alert(r.erro); return } var html = '
' for(i = 0; i < r.length; i++) html += '
' + r[i][1] + '
' html += '
' this.containerLista.innerHTML = html this.montaLista() this.loader.src = 'img/loader_off.gif'; }, emModificaApresentacao: function() {}, seleciona: function(i) { if(i) this.opcaoSelecionada = i if(this.opcoes && this.opcoes[this.opcaoSelecionada]) { var apresentacao = this.opcoes[this.opcaoSelecionada].innerHTML var valor = this.opcoes[this.opcaoSelecionada].id.split('.')[2] this.elementoApresentacao.setaValor( apresentacao ) this.setaValor( valor ) } this.apresentacao_anterior = this.pegaApresentacao(); this.itemSelecionado = 0 this.containerLista.esconde(); //style.visibility = 'hidden' this.emSeleciona() //@todo CONNECT !!! AOP !!! }, emSeleciona: function(){}, avisoVazio: function() { alert('Por favor, selecione algum item no campo "' + this.at('title') + '"' ) }, pegaApresentacao: function() { return this.elementoApresentacao.pegaValor() }, foca: function() { return this.elementoApresentacao.foca() }, clicouOpcao:function(i){}, emSobreOpcao: function(i){ this.focaOpcao(i); }, setaApresentacao: function(valor) { return this.elementoApresentacao.setaValor(valor) } }) Componente.AutoCompletar.Imagem = Class.create() Componente.AutoCompletar.Imagem.prototype = (new Componente.AutoCompletar()).extend ({ emRecebeOpcoes: function( r ) { this.containerLista.innerHTML = '' this.lista = '' if( ! r.length) { this.loader.src = 'img/loader_off.gif'; if(r.erro) alert(r.erro); return } var html = '
' for(i = 0; i < r.length; i++) html += '
' + r[i][1] + '
' html += '
' this.containerLista.innerHTML = html this.montaLista() this.loader.src = 'img/loader_off.gif'; }, seleciona: function() { apresentacao = $( this.opcoes[this.opcaoSelecionada].id + '.apresentacao' ).innerHTML; valor = this.opcoes[this.opcaoSelecionada].id.split('.')[2] this.elementoApresentacao.setaValor( apresentacao ) this.setaValor( valor ) this.itemSelecionado = 0 this.containerLista.esconde(); //style.visibility = 'hidden' this.emSeleciona() //@todo CONNECT !!! AOP !!! } }) //@todo ainda tá incompleto isso... falta alterar excluir... Grade = Class.create() Grade.prototype = { initialize: function( nome, colunas, linhas ) { this.nome = nome if(colunas) this.colunas = colunas else this.colunas = [] if(linhas) this.linhas = linhas else this.linhas = [] this.inicia() }, inicia: function() {}, adicionaColuna: function ( coluna ) { return this.colunas.push( coluna ) }, adicionaLinha: function( linha ) { return this.linhas.push( linha ) }, excluiLinha: function(linha) { return this.linhas.splice( linha, 1 ) }, limpa: function() { this.linhas = [] }, to_s: function() { s = '' if(this.linhas.length) { sEnd = '' s += '' + '' + '' + ''; for( var c = 0; c < this.colunas.length; c++ ) if(this.colunas[c].apresenta) s += '' s+='' for( var l = 0; l < this.linhas.length ; l++ ) { s +='' +'' + '' for( var c = 0; c < this.colunas.length; c++ ) { campo = this.linhas[l][c] nome = this.colunas[c].tabela + '[' + l + ']' + '[' + this.colunas[c].campo + ']' if(this.colunas[c].apresenta) s += ''; else sEnd += '' } s+='' } s += '
ExcluirAlterar' + this.colunas[c].titulo + '
' + 'exclui' + '' + 'altera' + '' + campo.apresentacao + '' + '
' s += sEnd } return s }, pegaIdColuna: function( nome ) { for( var c = 0; c < this.colunas.length ; c++ ) if( this.colunas[c].campo == nome ) return c return false }, existeItem: function( nome, valor ) { c = this.pegaIdColuna( nome ); for( var l = 0; l < this.linhas.length ; l++ ) if( this.linhas[l][c].valor == valor && valor != '' ) return true return false } } function excluiLinhaGrade(nome, linha){ $f.pegaGrupoPorNome(nome).excluiLinha(linha) } function alteraLinhaGrade(nome, linha){ $f.pegaGrupoPorNome(nome).alteraLinha(linha) } var GrupoComponentes = Class.create() GrupoComponentes.prototype = (new Objeto()).extend({ initialize: function() { this.componentes = [] }, inicializa: function() { this.setaAcoesGrupo(); }, serializa: function() { s = [] for( var i = 0 ; i < this.componentes.length ; i++ ) s.push( this.componentes[i].serializa() ) return "&" + s.join("&") }, enviaPorAjax: function() { this.emEnviaPorAjax(); caminho = this.destino; new Ajax.Requisicao( caminho, {parameters:this.serializa(),objeto:this,metodo:'resultadoEnvioAjax'} ) }, resultadoEnvioAjax: function( resultado ) //resultado deve ser bool, senão objeto de erro { if(resultado == true) this.emSucessoEnvioAjax( resultado ) else this.emErroEnvioAjax(resultado.erro,resultado.numero) }, emSucessoEnvioAjax: function( resultado ) { this.limpa() this.mensagem('Registro incluído com sucesso') this.focaPrimeiroComponente() }, emErroEnvioAjax: function(erro) { alert('Ocorreu um erro no envio: ' + erro) }, emEnviaPorAjax: function(){}, // No início de envio assíncrono processaErroEnvio: function(){ return false }, setaFieldset: function ( fs ) { this.fs = fs }, adicionaComponente: function( componente ) { this.componentes.push( componente ) }, to_s: function() { s = "" s += "" for( var i = 0 ; i < this.componentes.length ; i++ ) s += this.componentes[i].to_s() s += "" return s }, limpa: function() { for (var i = 0; i < this.componentes.length; i++) this.componentes[i].limpa() }, setaAcoesGrupo: function(){}, setaClasse: function( classe ) { this.classe = classe }, setaNome: function( nome ) { this.nome = nome }, pegaNome: function() { return this.nome }, pegaPrimeiroComponente: function() { return this.componentes[0] }, pegaUltimoComponente: function() { return this.componentes[ this.componentes.length-1 ] }, pegaComponentePorAtributo: function( at, valorAt ) { for (var i = 0; i < this.componentes.length; i++) if( valorAt == this.componentes[i].at(at) ) return this.componentes[i] return false }, $at: function( at, valorAt ){ return this.pegaComponentePorAtributo(at, valorAt) }, pegaComponentePorNome: function( nome ) { for (var i = 0; i < this.componentes.length; i++) if( nome == this.componentes[i].pegaNome() ) return this.componentes[i] return false }, $nome: function( campo ){ return this.pegaComponentePorNome(nome) }, pegaComponentePorCampo: function( campo ) { for (var i = 0; i < this.componentes.length; i++) if( campo == this.componentes[i].pegaCampo() ) return this.componentes[i] return false }, $: function( campo ){ return this.pegaComponentePorCampo(campo) }, // o mais rápido pegaComponentePorId: function( id ) { for (var i = 0; i < this.componentes.length; i++) if( nome == this.componentes[i].pegaId() ) return this.componentes[i] return false }, $id: function( id ){ return this.pegaComponentePorId(id) }, desabilita: function() { for (var i = 0; i < this.componentes.length; i++) this.componentes[i].desabilita() }, pegaItemFocado: function() { for (var i = 0; i < this.componentes.length; i++) if( this.componentes[i].focado ) return i return false }, pegaComponenteFocado: function() { return this.componentes[ this.pegaItemFocado() ] }, focaPrimeiroComponente: function() { if( (i = this.pegaProximoItemFocavel(0)) !== false ) { this.componentes[i].foca() return true } return false }, focaUltimoComponente: function() { this.componentes[ this.componentes.length - 1 ].foca() }, focaProximoComponente: function() { if( ( item = this.pegaItemFocado() ) !== false ) { item ++ if( (i = this.pegaProximoItemFocavel( item )) !== false ) try{ this.componentes[i].foca() return true }catch(e){} this.eof = true } return false }, pegaProximoItemFocavel: function( itemAtual ) { eof = false if( itemAtual === false) return false for( var i = itemAtual ; i < this.componentes.length ; i++ ) if( this.componentes[i].focavel ) return i eof = true return false }, focaProximoComponenteLoop: function() { if( ! this.focaProximoComponente() && this.eof) if( ! this.focaPrimeiroComponente() ) return false return true }, focaComponenteAnterior: function() { if( i = this.pegaItemFocado() !== false ) try{ this.componentes[ this.pegaItemFocado() - 1 ].foca() return true }catch(e){} return false }, focaComponenteAnteriorLoop: function() { if( this.pegaItemFocado() !== false ) { if( ! this.focaComponenteAnterior() ) this.focaUltimoComponente() return true } return false }, iniciaValida: function(){ return true }, valida: function() { if( ! this.iniciaValida() ) return false for( var i = 0 ; i < this.componentes.length ; i++ ) if( this.componentes[i].erroVazio() ) return this.emErroVazio( i ) else if( this.componentes[i].erroInvalido() ) return emErroInvalido( i ) return true }, validaGrupo: function(){ return true }, emErroVazio: function( i ) { return this.componentes[i].emErroVazio() }, emErroInvalido: function( i ) { return this.componentes[i].emErroInvalido() } }) GrupoComponentes.Detalhe = Class.create() GrupoComponentes.Detalhe.prototype = (new GrupoComponentes()).extend ({ iniciaValida: function() { if( this.bloqueiaAdicao ) { alert('Por favor aguarde, a adição está momentanemente bloqueada'); return false } for( var i = 0; i < this.componentes.length; i++ ) if( this.componentes[i].unico() && this.grade.existeItem(this.componentes[i].pegaCampo(), this.componentes[i].pegaValor()) ) { alert("O campo '" + this.componentes[i].at('title') + "' não pode ser duplicado") return false } return true }, validaGrupo: function() { if( this.grade.linhas.length >= this.minimoItens ) return true this.focaPrimeiroComponente() alert('Você deve inserir pelo menos ' + this.minimoItens + ' ' + this.componentes[0].at('title') + '(s)') return false }, processaErroEnvio: function(){}, setaAcoesGrupo: function() { adicionar = this.pegaComponentePorNome('adicionar') this.minimoItens = this.fs.getAttribute('min') ? this.fs.getAttribute('min') : 0 colunas = [] for( var i = 0; i < this.componentes.length; i++ ) if( this.componentes[i].pegaNome() != 'adicionar' ) colunas.push( { tabela: this.componentes[i].pegaTabela(), campo: this.componentes[i].pegaCampo(), titulo: this.componentes[i].at('title'), apresenta: (this.componentes[i].at('componente_js') == 'Componente.Hidden'?false:true) } ) this.grade = new Grade( this.pegaNome(), colunas ) this.containerGrade = $( 'layer_' + this.pegaNome() ) adicionar.emClique = function() { if(! this.grupo.valida() ) return false linha = this.grupo.pegaLinha() this.grupo.emAdiciona( this.grupo.pegaLinha() ) this.grupo.adicionaLinha( this.grupo.pegaLinha() ) this.grupo.apresentaGrade() } try{ this.leDados( eval("lista_"+this.nome) ) }catch(e){} }, emAdiciona: function(){}, leDados: function( linhas ) { if( ! linhas ) return false for( var i = 0; i < linhas.length; i++ ) this.grade.adicionaLinha( linhas[i] ) this.apresentaGrade() }, pegaLinha: function() { linha = [] for( var i = 0; i < this.componentes.length; i++ ) linha.push( { valor: (this.componentes[i].pegaValor()?this.componentes[i].pegaValor():""), apresentacao: this.componentes[i].pegaApresentacao() } ) return linha }, apresentaGrade: function() { this.containerGrade.innerHTML = this.grade.to_s() }, adicionaLinha: function( linha ) { this.limpa() this.focaPrimeiroComponente() return this.grade.adicionaLinha( linha ) }, excluiLinha: function(numLinha) { this.emExclui( this.grade.linhas[numLinha] ), this.grade.excluiLinha( numLinha ); this.apresentaGrade(); }, emExclui: function(linha){}, alteraLinha: function(numLinha) { linha = this.grade.linhas[numLinha] for(i = 0; i < linha.length; i++) { this.componentes[i].setaValor( linha[i].valor ) this.componentes[i].setaApresentacao( linha[i].apresentacao ) } this.excluiLinha( numLinha ); }, limpaGrade: function() { this.grade.limpa() this.apresentaGrade() }, emLimpa: function(){} }) /* * Classe de Formulario * @author Juan Maiz LFC * Organiza os formulários em objetos, com uma biblioteca de Componentes HTML e funções de foco, envio e validação; */ var Formulario = Class.create() Formulario.prototype = (new GrupoComponentes()).extend({ /* Eventos */ emValida: function(){}, // No início de todo envio //@todo Fazer uma função q receba controle/método e gets inicia: function(iForm) { this.grupos = [] this.componentes = [] this.f = document.forms[ (iForm?iForm:0) ] //alert(iForm +" - " + this.f.name); this.nome = this.f.name; this.metodo = this.f.method ? this.f.method : 'get' this.assinc = this.f.getAttribute('assinc') == 'true' ? true : false this.destino = this.f.action this.f.ref = this this.f.onsubmit = function() { if( ! this.ref.valida() ) return false if( this.ref.assinc ) { this.ref.enviaPorAjax() return false } return true } this.parseElementos( this.f.elements ) return this }, setaAcao: function(m,c,gets) { if( ! c ) c = pegaControle(); acao = '?c=' + c + '&m=' + m + (gets ? obj2QS(gets) : '') this.f.action = acao this.destino = acao return this }, envia: function(m,c,gets) { if( m || c || gets ) this.setaAcao(m,c,gets) if( ! this.valida() ) return false if( this.assinc ) { this.enviaPorAjax() return false } return this.f.submit() }, temAlgumValor: function() { for( var i = 0 ; i < this.componentes.length ; i++ ) if( this.componentes[i].pegaValor() ) return true return false }, alterado: function() { for( var i = 0 ; i < this.componentes.length ; i++ ) if( this.componentes[i].alterado() ) return true return false }, // Valida primeiro os grupos, se estes forem válidos valida os componentes sem grupo. valida: function() { if( ! this.iniciaValida() ) return false; try{ for( var i = 0 ; i < this.grupos.length ; i++ ) if( ! this.grupos[i].validaGrupo() ) return false;//this.grupos }catch(e){} for( var i = 0 ; i < this.componentes.length ; i++ ) if( ! this.componentes[i].grupo ) if( this.componentes[i].erroVazio() ) return this.emErroVazio( i ) else if( this.componentes[i].erroInvalido() ) return this.emErroInvalido( i ) return this.validacaoAdicional() this.emValida(); }, validacaoAdicional: function(){ return true }, pegaGrupoPorNome: function( nome ) { for (var i = 0; i < this.grupos.length; i++) if( nome == this.grupos[i].pegaNome() ) return this.grupos[i] return false }, to_s: function() { s = "" s += "[" for( var i = 0 ; i < this.grupos.length ; i++ ) s += this.grupos[i].to_s() for( var i = 0 ; i < this.componentes.length ; i++ ) if( ! this.componentes[i].g ) s += this.componentes[i].to_s() s += "]" return s }, parseElementos: function( elementos ) { var ultimoNome = "" var grupoAtual = "" for( var i = 0 ; i < elementos.length ; i++) { try{ nome = elementos[i].name.match( /\[(\w+)\]/ )[1] // encontra o valor dentro do primeiro colchete }catch(e){ nome = elementos[i].name } // alert(elementos[i]) if( ( classeGrupo = elementos[i].getAttribute("componente_js") ) && elementos[i].getAttribute("componente_js").split(".")[0] == "GrupoComponentes") { grupoAtual = eval("new " + classeGrupo + "()") grupoAtual.setaFieldset( elementos[i] ) grupoAtual.setaNome( elementos[i].id ) this.grupos.push( grupoAtual ) }else if( ( classeComponente = elementos[i].getAttribute("componente_js") ) && nome != ultimoNome ) { if( this.assinc && classeComponente.split('.')[1] == "File" ) this.assinc = false // não há como fazer upload de arquivo via ajax (só com iframe)...snif! try{ novoComponente = eval("new " + classeComponente + "()") }catch(e){ if(e == "TypeError: " + classeComponente + " is not a constructor") { //@todo Testar, a priori não funciona em real time... usa([classeComponente]) novoComponente = eval("new " + classeComponente + "()") } } this.componentes.push( novoComponente ) if( grupoAtual ) { novoComponente.setaGrupo( grupoAtual ) grupoAtual.adicionaComponente( novoComponente ) } novoComponente.inicializa( elementos[i] ) ultimoNome = nome } else if( classeComponente ) // se o nome é igual apenas adiciona elemento ao componente novoComponente.adicionaElemento( elementos[i] ) } this.inicializaGrupos() this.iniciaComponentes() }, iniciaComponentes: function() { for( var i = 0 ; i < this.componentes.length ; i++ ) this.componentes[i].inicia() }, inicializaGrupos: function() { for( var i = 0 ; i < this.grupos.length ; i++ ) this.grupos[i].inicializa() }, reseta: function() { this.f.reset() }, limpa: function() { for( var i = 0 ; i < this.componentes.length ; i++ ) this.componentes[i].limpa() // xmap( function(c){ c.limpa() } this.componentes) } }) var Consulta = Class.create() Consulta.prototype = { initialize: function() { setaPagina = function( pagina ){ return function(){ $('pagina').value = pagina; $f.envia(); } } try{ $('filtrar').onclick = setaPagina(1); }catch(e){} pagina = $('pagina').value * 1; if( pagina ) { numeroPaginas = $('numeroPaginas').value * 1; linksPaginacao = $('primeira', 'anterior', 'proxima', 'ultima') if(pagina > 1) { linksPaginacao[0].onclick = setaPagina(1); linksPaginacao[1].onclick = setaPagina( pagina - 1 ); } if(numeroPaginas > pagina) { linksPaginacao[2].onclick = setaPagina( pagina + 1 ); linksPaginacao[3].onclick = setaPagina( numeroPaginas ); } } var ths = document.getElementsByTagName("th") for (var i=0;i < ths.length;i++) { ths[i].onclick = function() { if(this.id) { if(document.forms[0].ordem.value != this.id) document.forms[0].direcao.value = 'asc' else document.forms[0].direcao.value = ( document.forms[0].direcao.value != 'asc' ? 'asc' : 'desc' ) document.forms[0].ordem.value = this.id $f.envia() } } } } } Mensagem = Class.create(); Mensagem.prototype = { initialize: function() { // document.body.innerHTML += ''; this.caixa = $('msg') }, setaValor: function( valor ) { this.caixa.innerHTML = valor; }, mostra: function( valor ) { if(valor) this.setaValor(valor); this.caixa.style.display = 'block'; }, esconde: function() { this.caixa.style.display = 'none'; } } $m = new Mensagem();