if (!("console" in window) || !("firebug" in console)) { var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; window.console = {}; for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {} } if(typeof Base !== 'undefined') { Base.provide("system.jext"); } /** * Javascript Extension * * Esse arquivo contém as funções da biblioteca Prototype * utilizadas na Neoconn e funções criadas pela Neoconn * para extender essa biblioteca * * @author Saulo Vallory * @version 0.9 */ function $(element) { if (arguments.length > 1) { for (var i = 0, elements = [], length = arguments.length; i < length; i++) elements.push($(arguments[i])); return elements; } if (typeof element == 'string') element = document.getElementById(element); return element; } var Prototype = { Version: '1.5.0', BrowserFeatures: { XPath: !!document.evaluate }, ScriptFragment: '(?:)((\n|\r|.)*?)(?:<\/script>)', emptyFunction: function() {}, K: function(x) { return x } }; var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } } }; var Try = { these: function() { var returnValue; for (var i = 0, length = arguments.length; i < length; i++) { var lambda = arguments[i]; try { returnValue = lambda(); break; } catch (e) {} } return returnValue; } }; Object.extend = function extend(destination, source) { for (property in source) { destination[property] = source[property]; } return destination; }; Object.clone = function clone(object) { return Object.extend({}, object); }; Object.extend(String.prototype, { isUpperCased : function() { return (this.match(/[a-z]/) == null); }, isLowerCased : function() { return (this.match(/[A-Z]/) == null); }, trim : function() { return( this.replace( /^\s+|\s+$/gi, "" ).replace( /\s{2,}/gi, " " ) ); }, capitalize: function(){ // Modified by Saulo //old code: return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); return this.charAt(0).toUpperCase() + this.substring(1); }, toQueryParams: function(separator) { var match = this.strip().match(/([^?#]*)(#.*)?$/); if (!match) return {}; return match[1].split(separator || '&').inject({}, function(hash, pair) { if ((pair = pair.split('='))[0]) { var name = decodeURIComponent(pair[0]); var value = pair[1] ? decodeURIComponent(pair[1]) : undefined; if (hash[name] !== undefined) { if (hash[name].constructor != Array) hash[name] = [hash[name]]; if (value) hash[name].push(value); } else hash[name] = value; } return hash; }); }, strip: function() { return this.replace(/^\s+/, '').replace(/\s+$/, ''); }, stripTags: function() { return this.replace(/<\/?[^>]+>/gi, ''); }, stripScripts: function() { return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); } }); Object.extend(Array.prototype, { init: function(zero) { if(typeof zero == "undefined") zero = null; for (var i = 0; i < this.length; i++) this[i] = zero; } }); //--------------------------------- ENUMERABLE var $break = new Object(); var $continue = new Object(); 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; } return this; }, eachSlice: function(number, iterator) { var index = -number, slices = [], array = this.toArray(); while ((index += number) < array.length) slices.push(array.slice(index, index+number)); return slices.map(iterator); }, 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 = false; 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 || Prototype.K)(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; }, inGroupsOf: function(number, fillWith) { fillWith = fillWith === undefined ? null : fillWith; return this.eachSlice(number, function(slice) { while(slice.length < number) slice.push(fillWith); return slice; }); }, 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.map(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.map(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.map(); }, 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)); }); }, size: function() { return this.toArray().length; }, inspect: function() { return '#'; } }; Object.extend(Enumerable, { map: Enumerable.collect, find: Enumerable.detect, select: Enumerable.findAll, member: Enumerable.include, entries: Enumerable.toArray }); //-------------------------------------- END ENUMERABLE //-------------------------------------- ARRAY Object.extend(Array.prototype, Enumerable); if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse; Object.extend(Array.prototype, { _each: function(iterator) { for (var i = 0, length = this.length; i < length; i++) iterator(this[i]); }, clear: function() { this.length = 0; return this; }, first: function() { return this[0]; }, last: function() { return this[this.length - 1]; }, compact: function() { return this.select(function(value) { return value != null; }); }, flatten: function() { return this.inject([], function(array, value) { return array.concat(value && value.constructor == Array ? value.flatten() : [value]); }); }, without: function() { var values = $A(arguments); return this.select(function(value) { return !values.include(value); }); }, indexOf: function(object) { for (var i = 0, length = this.length; i < length; i++) if (this[i] == object) return i; return -1; }, reverse: function(inline) { return (inline !== false ? this : this.toArray())._reverse(); }, reduce: function() { return this.length > 1 ? this : this[0]; }, uniq: function() { return this.inject([], function(array, value) { return array.include(value) ? array : array.concat([value]); }); }, clone: function() { return [].concat(this); }, size: function() { return this.length; }, inspect: function() { return '[' + this.map(Object.inspect).join(', ') + ']'; } }); //------------------------------------- END ARRAY /* * This script extends the document.createElement function and * imports the ieBehaviours.htc and pngBehaviour.htc files * to correct some leaks of internet explorer */ if(typeof Node == "undefined") { var __IEcreateElement = document.createElement; document.createElement = function (tagName) { var element = __IEcreateElement(tagName); var interf = new Element; Object.extend(element, interf); return element; }; } if (typeof Element == "undefined") { Element = new Function; } Object.extend(Element.prototype, { /** * @author Edson * @memberOf {Element} * @param {Object} element */ contains: function(element) { if( this.childNodes.length > 0 ) { for( var child = 0; child < this.childNodes.length; child++ ) { if( this.childNodes[ child ] === element ) { return true; } else if( this.childNodes[ child ].contains( element ) ) { return true; } } } return false; }, /** * @author Edson * @memberOf {Element} * @param {Object} element */ isDescendentOf: function(element) { return element.contains( this ); }, /** * @author Edson * @memberOf {Element} * @param {Object} element * @param {Object} attExcept * @param {Object} attValue */ compareTo: function(element, attExcept, attValue) { // testando a quantidade de filhos if( this.childNodes.length != element.childNodes.length ) { return false; } // testando a quantidade de atributos if( this.attributes.length != element.attributes.length ) { return false; } // comparando cada atributo for( var att = 0; att < this.attributes.length; att++ ) { if( this.attributes[att].name.toLowerCase() != element.attributes[att].name.toLowerCase() || this.attributes[att].value != element.attributes[att].value ) { return false; } } // comparando cada filho for( var child = 0; child < this.childNodes.length; child++ ) { if( this.childNodes[ child ].nodeType == 1 && element.childNodes[ child ].nodeType == 1 ) { var attExclude = this.childNodes[ child ].getAttribute( attExcept ); if( attExclude == attValue ) { continue; } if( this.childNodes[ child ].value != element.childNodes[ child ].value ) { return false; } if( this.childNodes[ child ].compareTo( element.childNodes[ child ], attExcept ) == false ) { return false; } } else if( this.childNodes[ child ].value != element.childNodes[ child ].value ) { return false; } } return true; }, isVisible : function isVisible() { return this.style.display != 'none'; }, toggle: function toggle() { this[this.isVisible() ? 'hide' : 'show'](); }, hide: function toggle() { this.style.display = 'none'; }, show: function() { this.style.display = ''; } }); Object.extend(Element, { isVisible: function(element) { if(is_string(element)) { return $(element).style.display != 'none'; } else if(element.nodeType == 1) { return element.style.display != 'none' } throw new Error('Tipo de argumento inválido na função Element.visible. A função espera uma string ou um elemento como parâmetro'); }, toggle: function() { for (var i = 0; i < arguments.length; i++) { if(is_array(arguments[i])) { for(var j = 0; j < arguments[i].length; j++) { var element = $(arguments[i][j]); if(!element) continue; Element[Element.isVisible(element) ? 'hide' : 'show'](element); } } else { var element = $(arguments[i]); Element[Element.isVisible(element) ? 'hide' : 'show'](element); } } }, hide: function() { for (var i = 0; i < arguments.length; i++) { if(is_array(arguments[i])) { for(var j = 0; j < arguments[i].length; j++) { var element = $(arguments[i][j]); if(!element) continue; element.style.display = 'none'; } } else { var element = $(arguments[i]); if(!element) continue; element.style.display = 'none'; } } }, show: function show() { for (var i = 0; i < arguments.length; i++) { if(is_array(arguments[i])) { for(var j = 0; j < arguments[i].length; j++) { var element = $(arguments[i][j]); if(!element) continue; element.style.display = ''; } } else { var element = $(arguments[i]); if(!element) continue; element.style.display = ''; } } } }); var $A = Array.from = function(iterable) { if (!iterable) return []; if (iterable.toArray) { return iterable.toArray(); } else { var results = []; for (var i = 0, length = iterable.length; i < length; i++) results.push(iterable[i]); return results; } }; Function.prototype.bind = function() { var __method = this, args = $A(arguments), object = args.shift(); return function() { return __method.apply(object, args.concat($A(arguments))); } }; Function.prototype.bindAsEventListener = function(object) { var __method = this, args = $A(arguments), object = args.shift(); return function(event) { return __method.apply(object, [event || window.event].concat(args)); } }; if(typeof Base != "undefined") { Base.provide("system.Ajax"); } //------------------------------------- AJAX /** * @author Prototype * @version 1.5 */ var Ajax = { getTransport: function() { return Try.these( function() {return new XMLHttpRequest();}, function() {return new ActiveXObject('Msxml2.XMLHTTP');}, function() {return new ActiveXObject('Microsoft.XMLHTTP');} ) || false; }, activeRequestCount: 0 }; Ajax.Responders = { responders: [], _each: function(iterator) { this.responders._each(iterator); }, register: function(responder) { if (!this.include(responder)) this.responders.push(responder); }, unregister: function(responder) { this.responders = this.responders.without(responder); }, dispatch: function(callback, request, transport, json) { this.each(function(responder) { if (typeof responder[callback] == 'function') { try { responder[callback].apply(responder, [request, transport, json]); } catch (e) {} } }); } }; Object.extend(Ajax.Responders, Enumerable); Ajax.Responders.register({ onCreate: function() { Ajax.activeRequestCount++; }, onComplete: function() { Ajax.activeRequestCount--; } }); Ajax.Base = function() {}; Ajax.Base.prototype = { setOptions: function(options) { this.options = { method: 'post', asynchronous: true, contentType: 'application/x-www-form-urlencoded', encoding: 'UTF-8', parameters: '' }; Object.extend(this.options, options || {}); this.options.method = this.options.method.toLowerCase(); if(typeof this.options.parameters == 'string') this.options.parameters = this.options.parameters.toQueryParams(); } }; Ajax.Request = Class.create(); Ajax.Request.Events = ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; Ajax.Request.prototype = Object.extend(new Ajax.Base(), { _complete: false, initialize: function(url, options) { this.transport = Ajax.getTransport(); this.setOptions(options); this.request(url); }, request: function(url) { this.url = url; this.method = this.options.method; var params = this.options.parameters; if (!['get', 'post'].include(this.method)) { // simulate other verbs over post params['_method'] = this.method; this.method = 'post'; } params = Hash.toQueryString(params); if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='; // when GET, append parameters to URL if (this.method == 'get' && params) this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params; try { Ajax.Responders.dispatch('onCreate', this, this.transport); this.transport.open(this.method.toUpperCase(), this.url, this.options.asynchronous); if (this.options.asynchronous) setTimeout((function() { this.respondToReadyState(1); }).bind(this), 10); this.transport.onreadystatechange = this.onStateChange.bind(this); this.setRequestHeaders(); var body = this.method == 'post' ? (this.options.postBody || params) : null; this.transport.send(body); /* Force Firefox to handle ready state 4 for synchronous requests */ if (!this.options.asynchronous && this.transport.overrideMimeType) this.onStateChange(); } catch (e) { this.dispatchException(e); } }, onStateChange: function() { var readyState = this.transport.readyState; if (readyState > 1 && !((readyState == 4) && this._complete)) this.respondToReadyState(this.transport.readyState); }, setRequestHeaders: function() { var headers = { 'X-Requested-With': 'XMLHttpRequest', 'X-Prototype-Version': Prototype.Version, 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' }; if (this.method == 'post') { headers['Content-type'] = this.options.contentType + (this.options.encoding ? '; charset=' + this.options.encoding : ''); /* Force "Connection: close" for older Mozilla browsers to work * around a bug where XMLHttpRequest sends an incorrect * Content-length header. See Mozilla Bugzilla #246651. */ if (this.transport.overrideMimeType && (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) headers['Connection'] = 'close'; } // user-defined headers if (typeof this.options.requestHeaders == 'object') { var extras = this.options.requestHeaders; if (typeof extras.push == 'function') for (var i = 0, length = extras.length; i < length; i += 2) headers[extras[i]] = extras[i+1]; else $H(extras).each(function(pair) { headers[pair.key] = pair.value }); } for (var name in headers) this.transport.setRequestHeader(name, headers[name]); }, success: function() { return !this.transport.status || (this.transport.status >= 200 && this.transport.status < 300); }, respondToReadyState: function(readyState) { var state = Ajax.Request.Events[readyState]; var transport = this.transport, json = this.evalJSON(); if (state == 'Complete') { try { this._complete = true; (this.options['on' + this.transport.status] || this.options['on' + (this.success() ? 'Success' : 'Failure')] || Prototype.emptyFunction)(transport, json); } catch (e) { this.dispatchException(e); } if ((this.getHeader('Content-type') || 'text/javascript').strip(). match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i)) this.evalResponse(); } try { (this.options['on' + state] || Prototype.emptyFunction)(transport, json); Ajax.Responders.dispatch('on' + state, this, transport, json); } catch (e) { this.dispatchException(e); } if (state == 'Complete') { // avoid memory leak in MSIE: clean up this.transport.onreadystatechange = Prototype.emptyFunction; } }, getHeader: function(name) { try { return this.transport.getResponseHeader(name); } catch (e) { return null } }, evalJSON: function() { try { var json = this.getHeader('X-JSON'); return json ? eval('(' + json + ')') : null; } catch (e) { return null } }, evalResponse: function() { try { return eval(this.transport.responseText); } catch (e) { this.dispatchException(e); } }, dispatchException: function(exception) { (this.options.onException || Prototype.emptyFunction)(this, exception); Ajax.Responders.dispatch('onException', this, exception); } }); Ajax.Updater = Class.create(); Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), { initialize: function(container, url, options) { this.container = { success: (container.success || container), failure: (container.failure || (container.success ? null : container)) }; this.transport = Ajax.getTransport(); this.setOptions(options); var onComplete = this.options.onComplete || Prototype.emptyFunction; this.options.onComplete = (function(transport, param) { this.updateContent(); onComplete(transport, param); }).bind(this); this.request(url); }, updateContent: function() { var receiver = this.container[this.success() ? 'success' : 'failure']; var response = this.transport.responseText; if (!this.options.evalScripts) response = response.stripScripts(); if (receiver = $(receiver)) { if (this.options.insertion) new this.options.insertion(receiver, response); else receiver.update(response); } if (this.success()) { if (this.onComplete) setTimeout(this.onComplete.bind(this), 10); } } }); Ajax.PeriodicalUpdater = Class.create(); Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), { initialize: function(container, url, options) { this.setOptions(options); this.onComplete = this.options.onComplete; this.frequency = (this.options.frequency || 2); this.decay = (this.options.decay || 1); this.updater = {}; this.container = container; this.url = url; this.start(); }, start: function() { this.options.onComplete = this.updateComplete.bind(this); this.onTimerEvent(); }, stop: function() { this.updater.options.onComplete = undefined; clearTimeout(this.timer); (this.onComplete || Prototype.emptyFunction).apply(this, arguments); }, updateComplete: function(request) { if (this.options.decay) { this.decay = (request.responseText == this.lastText ? this.decay * this.options.decay : 1); this.lastText = request.responseText; } this.timer = setTimeout(this.onTimerEvent.bind(this), this.decay * this.frequency * 1000); }, onTimerEvent: function() { this.updater = new Ajax.Updater(this.container, this.url, this.options); } }); //------------------------------------- END AJAX //------------------------------------- HASH var Hash = function(obj) { Object.extend(this, obj || {}); }; Object.extend(Hash, { toQueryString: function(obj) { var parts = []; this.prototype._each.call(obj, function(pair) { if (!pair.key) return; if (pair.value && pair.value.constructor == Array) { var values = pair.value.compact(); if (values.length < 2) pair.value = values.reduce(); else { key = encodeURIComponent(pair.key); values.each(function(value) { value = value != undefined ? encodeURIComponent(value) : ''; parts.push(key + '=' + encodeURIComponent(value)); }); return; } } if (pair.value == undefined) pair[1] = ''; parts.push(pair.map(encodeURIComponent).join('=')); }); return parts.join('&'); } }); Object.extend(Hash.prototype, Enumerable); Object.extend(Hash.prototype, { _each: function(iterator) { for (var key in this) { var value = this[key]; if (value && value == Hash.prototype[key]) 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(this, function(mergedHash, pair) { mergedHash[pair.key] = pair.value; return mergedHash; }); }, remove: function() { var result; for(var i = 0, length = arguments.length; i < length; i++) { var value = this[arguments[i]]; if (value !== undefined){ if (result === undefined) result = value; else { if (result.constructor != Array) result = [result]; result.push(value); } } delete this[arguments[i]]; } return result; }, toQueryString: function() { return Hash.toQueryString(this); }, inspect: function() { return '#'; } }); //------------------------------------- END HASH Object.extend(Event, { KEY_BACKSPACE: 8, KEY_TAB: 9, KEY_RETURN: 13, KEY_ESC: 27, KEY_LEFT: 37, KEY_UP: 38, KEY_RIGHT: 39, KEY_DOWN: 40, KEY_DELETE: 46, KEY_HOME: 36, KEY_END: 35, KEY_PAGEUP: 33, KEY_PAGEDOWN: 34, element: function(event) { return event.target || event.srcElement; }, isLeftClick: function(event) { return (((event.which) && (event.which == 1)) || ((event.button) && (event.button == 1))); }, pointerX: function(event) { return event.pageX || (event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft)); }, pointerY: function(event) { return event.pageY || (event.clientY + (document.documentElement.scrollTop || document.body.scrollTop)); }, stop: function(event) { if (event.preventDefault) { event.preventDefault(); event.stopPropagation(); } else { event.returnValue = false; event.cancelBubble = true; } }, observers: false, _observeAndCache: function(element, name, observer, useCapture) { if (!this.observers) this.observers = []; if (element.addEventListener) { this.observers.push([element, name, observer, useCapture]); element.addEventListener(name, observer, useCapture); } else if (element.attachEvent) { this.observers.push([element, name, observer, useCapture]); element.attachEvent('on' + name, observer); } }, observe: function(element, name, observer, useCapture) { element = $(element); useCapture = useCapture || false; if (name == 'keypress' && (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || element.attachEvent)) name = 'keydown'; Event._observeAndCache(element, name, observer, useCapture); }, stopObserving: function(element, name, observer, useCapture) { element = $(element); useCapture = useCapture || false; if (name == 'keypress' && (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || element.detachEvent)) name = 'keydown'; if (element.removeEventListener) { element.removeEventListener(name, observer, useCapture); } else if (element.detachEvent) { try { element.detachEvent('on' + name, observer); } catch (e) {} } } }); /*INCLUDE>system/Prototype1.5.jscollections/Collection.js= 0) { Base.loadingPanel.style.marginTop = (document.documentElement.scrollTop-50) + "px"; Base.loadingPanel.style.top = "50%"; } Base.loadingPanel.style.display = 'block'; }; /** * Oculta o aviso de carregamento * @private */ var _hideLoading = function _hideLoading() { this.loadingPanel.style.display = 'none'; }; base = Base = { ////////////////////////////////////////////////////////////////////////////////// // Properties // ////////////////////////////////////////////////////////////////////////////////// /** * Informa se o Base foi ou não inicializado * @private * @type {Collection} */ _serverObjs : null, /** * Coleção de commandos disponíveis para serem executados pelo servidor via postback * @private * @type {Collection} */ _commands : null, /** * Array de módulos requeridos pelo Base. Cada posição armazena um valor (boolean) verdadeiro * ou falso que indica se o módulo foi carrega ou não * @private * @type {Array} */ _requiredModules : [], /** * O objeto Base.dom apenas armazena as constantes do DOM para os tipos de nó * @type {Enum} */ dom : { ELEMENT_NODE : 1, ATTRIBUTE_NODE : 2, TEXT_NODE : 3, CDATA_SECTION_NODE : 4, ENTITY_REFERENCE_NODE : 5, ENTITY_NODE : 6, PROCESSING_INSTRUCTION_NODE : 7, COMMENT_NODE : 8, DOCUMENT_NODE : 9, DOCUMENT_TYPE_NODE : 10, DOCUMENT_FRAGMENT_NODE : 11, NOTATION_NODE : 12 }, errorLog : [], ////////////////////////////////////////////////////////////////////////////////// // Private methods // ////////////////////////////////////////////////////////////////////////////////// /** * Function _findServerObjects * * @param {HTMLElement} node * @param {Collection} collection * @private */ _findServerObjects : function _findServerObjects(node, collection) { if (node.attributes["runat"] && node.attributes["runat"].nodeValue == "server" && node.attributes["phpclass"]) { var phpClass = node.getAttribute("phpclass"); //var obj = new ServerObject(node); var obj = Component.factory(phpClass, node); if(!obj) { Base.raise("Constructor for component " + phpClass + " not found.(Base findServerObjects)", new Error()); return; } obj.onPropertyChange.addListener(ClientViewState.objectChanged.bind(ClientViewState)); if(Base.isContainer(obj)) { obj.onChildAdd.addListener(ClientViewState.objectChanged.bind(ClientViewState)); obj.onChildRemove.addListener(ClientViewState.objectChanged.bind(ClientViewState)); } collection.add(obj.getId(), obj); } // find server objects in children if(node.hasChildNodes()) { for (var i = 0; i < node.childNodes.length; i++) { if(node.childNodes[i].nodeType == Base.dom.ELEMENT_NODE) { this._findServerObjects(node.childNodes[i], collection); } } } }, ////////////////////////////////////////////////////////////////////////////////// // Public methods // ////////////////////////////////////////////////////////////////////////////////// initialize: function initialize() { if(initialized) { return; } console.info("Initializing Base"); // loading modules var lang = (typeof CURRENT_LANG != "undefined"? CURRENT_LANG : "pt-br"); Base.require("i18n." + lang); Base.require("system.collections.Collection"); if(this._serverObjs === null) this._serverObjs = new Collection(); if(this._serverObjs === null) this._commands = new Collection(); Base.require("system.viewState.ClientViewState"); Base.require("system.Environment"); Base.require("system.Postback"); //Base.require("web.Component"); //Base.require("web.package-src"); this.env = this.environment = new Environment(); this.loadingPanel = _createLoadingPanel(); Ajax.Responders.register( { onCreate: function(){}, onException : function(xhr, e) { Base.raise(e.message, xhr); }, onComplete: function(){} }); this.initializing = true; this._findServerObjects(document.documentElement, Base._serverObjs); this.initializing = false; initialized = true; }, onLoadComponents : function onLoadComponents() { }, /** * * @param {String} path * @param {Object} options Options: asynchronous (default: false), forceRetry (default: false), onSuccess (defeaul: null), onFailure (defeaul: null) */ require: function require(path, options) { var opt = { asynchronous : false, forceRetry : false, onSuccess : function (){}, onFailure : function (){} }; for(var o in options) opt[o] = options[o]; if(typeof Base._requiredModules[path] !== "undefined" && (Base._requiredModules[path] == true || opt.forceRetry) ) { opt.onSuccess(); return; } Base._requiredModules[path] = false; var url = 'http://' + SYSTEM_SITE_ROOT + 'library/js/' + path.replace(/\./g, '/') + '.js'; function evalAndFeedback(xhr) { try { eval(xhr.responseText); if(Base._requiredModules[path]) opt.onSuccess(); } catch(ex) { Base.raise("Erro executando javascript do módulo " + path, ex, {xhr: reqAjax}); } } var reqAjax = new Ajax.Request(url, { asynchronous : opt.asynchronous, onException : function (req, ex) { Base.raise("Erro requerindo o módulo " + path, ex); }, onSuccess : evalAndFeedback, onFailure : opt.onFailure }); }, provide: function provide(path) { Base._requiredModules[path] = true; }, /** * @return {Collection} */ getServerObjects: function getServerObjects() { return Base._serverObjs; }, /** * * @param {Component} comp */ addComponent: function addComponent(comp) { comp.onPropertyChange.addListener(ClientViewState.objectChanged.bind(ClientViewState)); if(Base.isContainer(comp)) { comp.onChildAdd.addListener(ClientViewState.objectChanged.bind(ClientViewState)); comp.onChildRemove.addListener(ClientViewState.objectChanged.bind(ClientViewState)); } if(!Base.initializing) ClientViewState.addNewObject(comp); return Base._serverObjs.add(comp.getId(), comp); }, /** * * @param {String} id */ getComponentById: function getComponentById(id) { return Base._serverObjs.get(id); }, /** * * @param {String} id * @return {Boolean} */ removeComponent: function removeServerObjeect(id) { var comp = Base._serverObjs.remove(id); var node = null; if(comp === false) { return false; } comp.removeRealElement(); ClientViewState.addRemovedObject(comp); return true; }, /** * FUNCTION doPostBack * * @param {String} e Event that fired the postback * @param {Array} args Event arguments */ doPostBack: function doPostBack(e, args) { if(args['preventDefault']) Event.stop(e); this.initialize(); // a função initialize não executa seu código duas vezes _showLoading(); if(!e) e = window.event; if(e.type == "submit") { Base.require("web.form.Form"); Base.submitFiles(args.targetForm); } var pb = new Postback(POSTBACK_URL); window.lastPostBack = pb; var clientMessage = ""; clientMessage += ClientViewState.getEventMessage(e); clientMessage += ClientViewState.getSyncMessage(); clientMessage += ""; pb.onReceiveMessage.addListener(_hideLoading.bind(this)); pb.send(clientMessage); if(typeof args.preventDefault != 'undefined' && args.preventDefault) { if(typeof e.preventDefault != 'undefined') e.preventDefault(); else e.returnValue = false; return false; } return true; }, synchronize: function synchronize() { this.initialize(); // a função initialize não executa seu código duas vezes _showLoading(); var pb = new Postback(POSTBACK_URL); window.lastPostBack = pb; var clientMessage = ""; clientMessage += ClientViewState.getSyncMessage(); clientMessage += ""; pb.onReceiveMessage.addListener(_hideLoading.bind(this)); pb.send(clientMessage); }, /** * * @param {HTMLElement} object * @param {String} event * @param {Function} func */ addEventListener: function addEventListener(object, event, func) { Event.observe(object, event, func); }, findFileUploads : function findFileUploads(f) { var fileUploads = []; var results = f.getElementsByTagName("input"); for(var i = 0; i< results.length; i++) { if (results[i].type == 'file') { fileUploads[fileUploads.length] = results[i]; } } return fileUploads; }, /** * * @param {HTMLFormElement} f */ submitFiles: function submitFiles(f) { var upFields = Base.findFileUploads(f); var iframe; if(upFields.length === 0) { return; } // adding hidden fields to link name and id for(var i=0; i < upFields.length; i++) { if(upFields[i].name != upFields[i].id) { var hid = document.createElement("input"); hid.type = "hidden"; hid.name = upFields[i].name + "ID"; hid.value = upFields[i].id; f.appendChild(hid); } } if(typeof this.submitIframe === "undefined") { //iframe = document.createElement("iframe"); iframe = window.open("", "_submitIframe", 'toolbar=0,location=0,statusbar=0,menubar=0,width=500,height=500,left = 262,top = 134'); iframe.id = "_submitIframe"; iframe.name = "_submitIframe"; //iframe.style.display = "none"; //document.body.appendChild(iframe); } else { iframe = this.submitIframe; } var oldTarget = f.target; f.target = "_submitIframe"; f.submit(); f.target = oldTarget; iframe.loaded = false; iframe.onload = function() {alert('submit finished. ' + window.location.href); window.loaded = true;}; var maxTime = 3000; var elapsedTime = 0; while(!iframe.loaded && elapsedTime < maxTime) { wait(500); elapsedTime += 500; } this.submitIframe = iframe; return iframe.loaded; }, raise: function raise(message, exception, extraInfo) { var canImakeDebuggerStopHere = "yes"; var msg = message; if(exception && typeof exception.message != "undefined") msg += ': ' + exception.message; console.error(msg); console.trace(); Base.errorLog.push({message: message, exception : exception, info : extraInfo}); }, // JS Commands mannagement /** * @param {string} id * @return {Base.Command} */ getCommand: function getCommand(id) { var cmd = this._commands.get(id); if(!cmd) Base.raise('O commando ' + id + ' nao existe ou nao foi registrado'); return cmd; }, /** * @memberOf {Base} * @alias registerCommand * @param {Base.Command} command */ registerCommand: function Base_registerCommand(command) { if(typeof this._commands == "undefined" || this._commands == null) this._commands = new Collection(); this._commands.add(command.getId(), command); }, /** * @param {Base.Command} command */ unregisterCommand: function Base_unregisterCommand(command) { if(typeof command == "object") { if(!(command instanceof Base.Command)) Base.raise("", new Error("Base.unregisterCommand expects an Base.Command or string as only parameter, "+(typeof command)+" given.")); else command = command.getId(); } this._commands.remove(command); }, /** * Diz se o objeto é uma instancia de Component ou de uma classe que extende Component * @param {Object} object */ isComponent : function isComponet(object) { if(typeof object == "undefined" || object == null) return false; return (typeof object != "undefined" && typeof object.isComponent == "boolean" && object.isComponent == true); }, /** * Diz se o objeto é uma instancia de Container ou de uma classe que extende Container * @param {Object} object */ isContainer : function isContainer(object) { if(typeof object == "undefined" || object == null) return false; return (typeof object.isContainer == "boolean" && object.isContainer == true); }, /** * Diz se o objeto é uma instancia de VisualComponent ou de uma classe que extende VisualComponent * @param {Object} object */ isVisualComponent : function isVisualComponet(object) { if(typeof object == "undefined" || object == null) return false; return (typeof object != "undefined" && typeof object.isVisualComponent == "boolean" && object.isVisualComponent == true); } }; $C = Base.getComponentById; /* if (window.addEventListener) // Mozilla like { window.addEventListener('DOMContentLoaded', Base.initialize.bind(Base),false); } else if (window.attachEvent) // IE { window.attachEvent('onload', Base.initialize.bind(Base)); } */ })(); if(typeof Base !== 'undefined') { Base.provide("system.lang"); } /** * @author Saulo Vallory * * Esses métodos foram emprestados da Yahoo UI Library e então * adaptados para o estilo php. */ /** * Determines whether or not the provided object is an array * @alias is_array * @param {any} obj The object being testing * @return Boolean */ is_array = function(obj) { if (obj instanceof Array) { return true; } else { return is_object(obj) && obj.constructor == Array; } }; /** * Determines whether or not the provided object is a boolean * @alias is_boolean * @param {any} obj The object being testing * @return Boolean */ is_boolean = function(obj) { return typeof obj == 'boolean'; }; /** * Determines whether or not the provided object is a function * @alias is_function * @param {any} obj The object being testing * @return Boolean */ is_function = function(obj) { return typeof obj == 'function'; }; /** * Determines whether or not the provided object is null * @alias is_null * @param {any} obj The object being testing * @return Boolean */ is_null = function(obj) { return obj === null; }; /** * Determines whether or not the provided object is a legal number * @alias is_number * @param {any} obj The object being testing * @return Boolean */ is_number = function(obj) { return typeof obj == 'number' && isFinite(obj); }; /** * Determines whether or not the provided object is of type object * or function * @alias is_object * @param {any} obj The object being testing * @return Boolean */ is_object = function(obj) { return obj && (typeof obj == 'object' || is_function(obj)); }; /** * Determines whether or not the provided object is a string * @alias is_string * @param {any} obj The object being testing * @return Boolean */ is_string = function(obj) { return typeof obj == 'string'; }, /** * Determines whether or not the provided object is undefined * @alias is_undefined * @param {any} obj The object being testing * @return Boolean */ is_undefined = function(obj) { return typeof obj == 'undefined'; }; /** * Determines whether or not the provided object is set * If the evaluate parameter is true, the 'obj' parameter * must be the name of object to test * @alias isset * @param {any} obj The object being testing * @param {boolean} evaluate Evaluates obj parameter to get the real object * @return Boolean */ isset = function(obj, evaluate) { if(typeof evaluate !== 'undefined') { if(!is_string(obj)) return false; // TODO: throw an exception eval('var set = (typeof '+obj.toString()+' !== "undefined");'); return set; } else return typeof obj !== 'undefined'; }; /** * De forma semelhante a função is_a do PHP, essa função diz se o objeto obj * é uma instância da classe "class_name" * @param {Object} obj * @param {String} class_name */ is_a : function is_a(obj, class_name) { if(typeof obj == "object" && typeof constructor == "string") { return (typeof obj.constructor == 'function' && obj.constructor.name == class_name); } //TODO: lançar uma exceção return false; } if(typeof Base !== 'undefined') { Base.provide("i18n.pt-br"); } /** * @author Saulo Vallory */ messages = { lang: "pt-br" }; messages.SERVER_ERROR = "Erro no servidor"; if(typeof Base !== 'undefined') { Base.provide("system.collections.Collection"); } /** * @class Collection * @alias Collection * @author Saulo Vallory * @classDescription the collection cannot contain duplicate elements * @namespace system.collections * @version 0.9 * * @constructor */ Collection = function Collection() { this.index = {}; this.backIndex = []; this.values = []; }; (function Collection_closure() { Object.extend(Collection.prototype, { /** * @method add * @param {string,number} key * @param {Object} value */ add : function Collection_add(key,value) { if(this.index[key] !== undefined) { return false; } if(typeof key !== "string" && typeof key !== "number") { Base.raise("Error in Collection::add", new Error("The key value must be a string or a number")); return false; } this.index[key] = this.values.length; this.backIndex[this.values.length] = key; this.values.push(value); return true; }, count : function Collection_count() { return this.values.length; }, /** * @alias Collection * @private * @constructor */ _compact : function _compact() { this.backIndex = this.backIndex.compact(); this.values = this.values.compact(); for(var i=0; i < this.backIndex.length; i++) { this.index[this.backIndex[i]] = i; } }, get : function Collection_get(key) { if(typeof key == "number") { return this.values[key]; } else { if(this.index[key] == undefined) { return null; } return this.values[this.index[key]]; } }, item : this.get, getValues : function Collection_getValues() { var results = []; for(var i=0; i < this.values.length; i++) { results.push(this.values[i]); } return results; }, remove : function Collection_remove(key) { var bak; if(typeof key == "number") { if(this.values[key] === undefined) { return false; } bak = this.values[key]; delete this.values[key]; delete this.index[this.backIndex[key]]; delete this.backIndex[key]; this._compact(); } else if(typeof key == "string") { if(this.index[key] === undefined) { return false; } bak = this.values[this.index[key]]; delete this.values[this.index[key]]; delete this.backIndex[this.index[key]]; delete this.index[key]; this._compact(); } else { Base.raise("", new Error("Collection.remove expects a number or string as only parameter, "+(typeof key)+" given.")); return null; } return bak; }, /** * @return array */ removeAll : function Collection_removeAll() { var bkpValues = this.values.clone(); this.index = {}; this.backIndex = []; this.values = []; return bkpValues; } }); })(); if(typeof Base != "undefined") { Base.provide("system.Event"); } Base.Event = function Event() { this.listeners = []; }; Object.extend(Base.Event.prototype, { listeners : null, addListener : function (fn) { if(typeof fn !== "function") { return null; } var ind = this.listeners.indexOf(fn); if(ind == -1) this.listeners.push(fn); }, removeListener : function(fn) { var ind = this.listeners.indexOf(fn); if(ind == -1) delete this.listeners[ind]; }, raise : function (obj, args) { for(var i=0; i < this.listeners.length; i++) { this.listeners[i](obj, args); } } }); if(typeof Base !== 'undefined') { Base.provide("system.viewState.Change"); } ChangeType = { PROPERTY_CHANGED : 1, CHILD_ADDED : 2, CHILD_REMOVED : 3 }; /** * @class Change * @alias Change * @classDescription A classe Change representa uma alteração na interface * @package system.viewState * @author Saulo Vallory * @version 0.9 * * @requires system.viewState.ClientViewState * * @constructor * @param {Object} type * @param {Object} data */ Change = function Change(type, data) { this.type = type; // TODO: checar se os dados requeridos pelo tipo da Change existem em data for(var v in data) { this[v] = data[v]; } }; Object.extend(Change.prototype, { type : null, /** * Retorna o xml para ser inserido no postback e informando a * alteração ao servidor * @method getXML * @return {String} xml que representa a alteração */ getXML : function getXML() { var str = ""; switch(this.type) { case ChangeType.CHILD_ADDED : str += ''; break; case ChangeType.CHILD_REMOVED : str = ''; break; case ChangeType.PROPERTY_CHANGED : var propType = ""; if(this.newValue == null) this.newValue = ""; if(is_array(this.newValue)) { propType = "array"; } else { propType = typeof this.newValue; } str = '' + ''; } return str; }, /** * O id foi criado dessa forma para que se possa perceber quando uma alteração se chocar com outra */ getId : function () { switch(this.type) { case ChangeType.PROPERTY_CHANGED : return "PropChange_" + this.propertyName; case ChangeType.CHILD_ADDED : return "ChildAddOrRemove_" + this.child.getId(); case ChangeType.CHILD_REMOVED : return "ChildAddOrRemove_" + this.child.getId(); } }, /** * Checa se a alteração desta instância é anulada pela alteração do objeto passado como parâmetro. * * @memberOf Change * @param {Change} chg */ isMirror : function Change_isMirror(chg) { switch(this.type) { case ChangeType.PROPERTY_CHANGED : if(chg.type == ChangeType.PROPERTY_CHANGED && this.newValue == chg.oldValue && this.oldValue == chg.newValue) { return true; } break; case ChangeType.CHILD_ADDED : if(chg.type == ChangeType.CHILD_REMOVED && chg.child.getId() == this.child.getId()) { return true; } break; case ChangeType.CHILD_REMOVED : if(chg.type == ChangeType.CHILD_ADDED && chg.child.getId() == this.child.getId()) { return true; } break; } return false; }, /** * Soma duas alterções transformando-as em uma só. * * @param {Change} chg */ mergeWith : function Change_mergeWith(chg) { if(this.type !== ChangeType.PROPERTY_CHANGED) { //Base.raise("Only property changes can be merged", new Error()); return null; } if(this.type !== chg.type) { Base.raise("Different types of changes can not be merged", new Error()); return null; } this.newValue = chg.newValue; } }); if(typeof Base != "undefined") { Base.provide("system.viewState.ClientViewState"); Base.require("system.collections.Collection"); Base.require("system.viewState.Change"); } /** * @class ClientViewState * @alias ClientViewState * @classDescription ClientViewState é um singleton que provê * métodos para armazenar as alterações na interface até que * elas sejam enviadas ao servidor * @author Saulo Vallory * @namespace Base * @version 0.8 * * @requires Base * @requires Collection */ (function ClientViewState_closure() { if(typeof ClientViewState !== 'undefined') return; /** * @property cache * @private */ var _cache = { neo : new Collection(), deleted : new Collection(), modified : new Collection() }; ClientViewState = { /** * @method getCache * @return {Array} */ getCache: function ClientViewState_getCache() { return _cache; }, /** * */ addNewObject: function ClientViewState_addNewObject(obj) { _cache.neo.add(obj.getId(), obj); }, addRemovedObject: function ClientViewState_addRemovedObject(obj) { _cache.deleted.add(obj.getId(), obj); }, /** * * @param {NodeList} objects */ updateComponents: function updateComponents(objects) { var object, objectId, objectChanges; var comp, change, cType; for(var i=0; i < objects.length; i++) { object = objects.item(i); objectId = object.getAttribute('id'); objectChanges = object.getElementsByTagName('change'); //pegando o objeto comp = Base.getComponentById(objectId); if(!comp) { Base.raise("Erro atualizando componentes", new Error("Component with id " + objectId + " could not be found.")); continue; } //aplicando as modificações for(var j=0; j < objectChanges.length; j++) { change = objectChanges.item(j); cType = change.getAttribute('type'); switch(Number(cType)) { case ChangeType.PROPERTY_CHANGED : var propertyName = change.getAttribute('propertyName'); if(typeof(change.textContent) != 'undefined') var newValue = change.textContent; else var newValue = change.text; if(change.getAttribute('propertyType') == 'boolean') newValue = (newValue == '1'); if(typeof(newValue) == 'undefined') newValue = null; if(change.getAttribute('eval') == "1") { eval('var ___ = ' + newValue); comp.set(propertyName, ___); } else comp.set(propertyName, newValue); break; case ChangeType.CHILD_ADDED : var childObj = Base.getComponentById(change.getAttribute('childId')); if(!childObj) { Base.raise("", new Error("Child addition error. Object with id (" + change.getAttribute('childId') + ") not found")); return; } comp.addChild(childObj); break; case ChangeType.CHILD_REMOVED : comp.removeChild(change.getAttribute('childId')); break; } } // TODO: checar se .get(objectId) retorna um objeto if(_cache.modified.get(objectId)) _cache.modified.get(objectId).changes.removeAll() } }, /** * * @param {NodeList} objects */ createComponents: function createComponents(objects) { for(var i=0; i < objects.length; i++) { var object = objects.item(i); var objectClass = object.getAttribute('class'); var objectProperties = object.getElementsByTagName('property'); //instanciando o objeto if(objectClass == 'HTMLTag') { var tag = null; for(var j=0; j < objectProperties.length; j++) { var p = objectProperties[j]; if(p.getAttribute('name') == 'tagname') { tag = p.textContent || p.text; break; } } var comp = new HTMLTag(null, tag); } else { var comp = Component.factory(objectClass); } if(!comp) { Base.raise("", new Error(objectClass + " component could not be instantiated")); return; } comp.set("id", object.getAttribute('id')); //atribuindo as propriedades var property, pName, pValue; for(var j=0; j < objectProperties.length; j++) { property = objectProperties.item(j); pName = property.getAttribute('name'); pValue = property.textContent || property.text; if(property.getAttribute('eval') == "1") { eval('var ___ = ' + pValue); comp.set(pName, ___); } else comp.set(pName, pValue); } //inserindo objeto na p???gina Base.addComponent(comp); } }, /** * * @param {NodeList} objects */ removeComponents: function removeComponents(objects) { for(var i=0; i < objects.length; i++) { var id = false; if(!(id = objects.item(i).getAttribute("id"))) { alert("O servidor retornou uma responsta inválida"); Base.raise("", new Error("Missing id for removed object.")); return; } Base.removeComponent(id); } }, /** * @param {event} evt */ getEventMessage: function ClientViewState_getEventMessage(evt) { if(!evt) { Base.raise("", new Error("Event object is required to build event messages.")); return null; } var eventName = evt.type; var argumentsXml = ""; if(evt.srcElement) { // IE evt.currentTarget = evt.srcElement; while(evt.currentTarget && evt.currentTarget['runat'] == undefined) evt.currentTarget = evt.currentTarget.parentElement; if(!evt.currentTarget) throw new Exception("This event is not handled by any component at server"); } var target = evt.currentTarget; for(var v in evt) { // ignoro o nome (j??? foi pego), propriedades em CAIXA ALTA (s?o constantes), fun??????es e objetos (n???o s???o usados) if(v != "type" && !v.isUpperCased() && typeof evt[v] != 'function' && typeof evt[v] != 'object' ) { argumentsXml += '\n\t\t' + '' + v + '' + '' + evt[v] + '' + ''; } } // pega o form como target no caso do evento ser um submit if (this.eventName == 'submit') { var targetElem = evt.currentTarget; while (targetElem !== null && targetElem.tagName != 'form') { targetElem = targetElem.parentNode; } if (targetElem !== null) { target = targetElem; } } else { // pega o componente que possui esse elemento caso o elem atual n?o seja um componente while(target.parentNode && target.parentNode.id && target.attributes.phpclass === null) { target = evt.target.parentNode; } } return '' + '' + '' + eventName + '' + '' + target.id + '' + '' + argumentsXml + '' + '' + ''; }, getSyncMessage: function ClientViewState_getSyncMessage() { var objArr = null; var msg = '' + ''; var somethingToSend = false; // NEW objects msg += ''; var neoArr = _cache.neo.values; if(neoArr.length) somethingToSend = true; for(var i=0; i < neoArr.length; i++) { msg += neoArr[i].getXML(); } msg += ''; // MODIFIED objects msg += ''; var modArr = _cache.modified.values; for(i=0; i < modArr.length; i++) { if(modArr[i].changes.values.length > 0) { somethingToSend = true; msg += ''; msg += ''; for(var j=0; j < modArr[i].changes.values.length; j++) { msg += modArr[i].changes.values[j].getXML(); } msg += ''; msg += ''; } } msg += ''; // DELETED objects msg += ''; var delArr = _cache.deleted.values; if(delArr.length) somethingToSend = true; for(i=0; i < delArr.length; i++) { msg += ''; } msg += ''; msg += '' + ''; if(somethingToSend) return msg; else return ""; }, objectChanged: function ClientViewState_objectChanged(obj, args) { var chg = null; if(!obj) { Base.raise("", new Error("Object argument missing.")); return; } if(!args) { Base.raise("", new Error("ObjectChanged function expects to receive 2 arguments. One given.")); return null; } switch(args.changeType) { case ChangeType.PROPERTY_CHANGED : chg = new Change(ChangeType.PROPERTY_CHANGED, {propertyName : args.propertyName, oldValue : args.oldValue, newValue : obj.get(args.propertyName)}); break; case ChangeType.CHILD_ADDED : chg = new Change(ChangeType.CHILD_ADDED, {child : args.child}); break; case ChangeType.CHILD_REMOVED : chg = new Change(ChangeType.CHILD_REMOVED, {child : args.child}); break; default : Base.raise("", new Error("Change type '" + args.changeType + "' is not supported")); return null; } var chgObj = null; if(!_cache.modified.get(obj.getId())) { _cache.modified.add(obj.getId(), { realObject : obj, changes : new Collection() }); chgObj = _cache.modified.get(obj.getId()); } else { chgObj = _cache.modified.get(obj.getId()); } // verifica se existe um conflito de alterações var change_ = chgObj.changes.get(chg.getId()); if(change_ != null) { // Existe um conflito! // verifica se alteração atual anula uma alteração anterior if(change_.isMirror(chg)) { // neste caso deleta a alteração anterior chgObj.changes.remove(chg.getId()); } else { // senão faz um merge das alterações change_.mergeWith(chg); } } else { // adiciona a alteração chgObj.changes.add(chg.getId(), chg); } }, setSynchronized: function ClientViewState_setSynchronized() { _cache.neo.removeAll(); _cache.modified.removeAll(); _cache.deleted.removeAll(); } } })(); if(typeof Base != "undefined") { Base.provide("system.Environment"); } /** * @alias BrowserInfo * @author Saulo Vallory * @classDescription A função Browser info provê informações * sobre o browser do cliente * @version 0.9 * @return {Object} */ var getBrowserInfo = function getBrowserInfo() { function trim(str) { return str.replace(/^\s+|\s+$/gi, "").replace(/\s{2,}/gi, " "); } function detectRenderEngine() { var presto = window.opera; var gecko = navigator.product == 'Gecko'; var mariner = document.layers && navigator.mimeTypes['*']; var khtml = navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ); var icab = window.ScriptEngine && ScriptEngine().indexOf('InScript') + 1; var trident = window.ActiveXObject; if (presto) {this.renderEngine = "Presto";} // Opera, Dreamweaver MX, Nintendo DS, Nintendo Wii else if (gecko) {this.renderEngine = "Gecko";} // Netscape 6+, Firefox, Galeon/Epiphany else if (mariner) {this.renderEngine = "Mariner";} // Netscape Communicator else if (khtml) {this.renderEngine = "KHTML";} // Konqueror, Safari, OmniWeb else if (icab) {this.renderEngine = "iCab";} // iCab else if (trident) {this.renderEngine = "Trident";} // Internet Explorer } function detectNameAndVersion() { var ua = navigator.userAgent; var uaLen = ua.length; var i, j, ind; // ##### Split into stuff before parens and in/after parens var preparens = ""; var parenthesized = ""; var postparens = ""; ind = ua.indexOf("("); if (ind >= 0) { preparens = trim(ua.substring(0,ind)); parenthesized = ua.substring(ind+1, uaLen); j = parenthesized.indexOf(")"); if (j >= 0) { postparens = trim((parenthesized.substring(j+1, uaLen)).replace(' ', ';')); parenthesized = parenthesized.substring(0, j)+'; '+postparens; } } else { preparens = ua; } // ##### First assume browser and version are in preparens // ##### override later if we find them in the parenthesized stuff var browVer = preparens; var tokens = parenthesized.split(";"); var token = ""; // # Now go through parenthesized tokens for (i=0; i < tokens.length; i++) { token = trim(tokens[i]); //## compatible - might want to reset from Netscape if (token == "compatible") { //## One might want to reset browVer to a null string //## here, but instead, we'll assume that if we don't //## find out otherwise, then it really is Mozilla //## (or whatever showed up before the parens). //## browser - try for Opera or IE } else if (token.indexOf("MSIE") >= 0 || token.indexOf("Gecko") >= 0 || token.indexOf("Opera") >= 0 || token.indexOf("AppleWebKit") >= 0 || token.indexOf("Konqueror") >= 0 || token.indexOf("Safari") >= 0 || token.indexOf("OmniWeb") >= 0 || token.indexOf("Netscape") >= 0 || token.indexOf("SeaMonkey") >= 0 || token.indexOf("Firefox") >= 0) { browVer = token; } //'## platform - try for X11, SunOS, Win, Mac, PPC if ((token.indexOf("X11") >= 0) || (token.indexOf("SunOS") >= 0) || (token.indexOf("Linux") >= 0)) { this.platform = "Unix"; } else if (token.indexOf("Win") >= 0) { this.platform = token; } else if ((token.indexOf("Mac") >= 0) || (token.indexOf("PPC") >= 0)) { this.platform = token; } } var msieIndex = browVer.indexOf("MSIE"); if (msieIndex >= 0) { browVer = browVer.substring(msieIndex, browVer.length); } var leftover = ""; if (browVer.substring(0, "Mozilla".length) == "Mozilla") { this.name = "Netscape"; leftover = browVer.substring("Mozilla".length+1, browVer.length); } else if (browVer.substring(0, "Lynx".length) == "Lynx") { this.name = "Lynx"; leftover = browVer.substring("Lynx".length+1, browVer.length); } else if (browVer.substring(0, "MSIE".length) == "MSIE") { this.name = "IE"; leftover = browVer.substring("MSIE".length+1, browVer.length); } else if (browVer.substring(0, "Microsoft Internet Explorer".length) == "Microsoft Internet Explorer") { this.name = "IE"; leftover = browVer.substring("Microsoft Internet Explorer".length+1, browVer.length); } else if (browVer.substring(0, "Opera".length) == "Opera") { this.name = "Opera"; leftover = browVer.substring("Opera".length+1, browVer.length); } else if (navigator.userAgent.indexOf("Firefox") >= 0) { this.name = "Firefox"; leftover = browVer.substring("Firefox".length+1, browVer.length); } else if (browVer.substring(0, "SeaMonkey".length) == "SeaMonkey") { this.name = "SeaMonkey"; leftover = browVer.substring("SeaMonkey".length+1, browVer.length); } else if (browVer.substring(0, "Netscape".length) == "Netscape") { this.name = "Netscape6+"; leftover = browVer.substring("Netscape".length+1, browVer.length); } else if (browVer.substring(0, "AppleWebKit".length) == "AppleWebKit") { this.name = "(Safari-based)"; leftover = browVer.substring("AppleWebKit".length+1, browVer.length); } else if (browVer.substring(0, "Safari".length) == "Safari") { this.name = "Safari"; leftover = browVer.substring("Safari".length+1, browVer.length); } else if (browVer.substring(0, "Konqueror".length) == "Konqueror") { this.name = "Konqueror"; leftover = browVer.substring("Konqueror".length+1, browVer.length); } else if (browVer.substring(0, "OmniWeb".length) == "OmniWeb") { this.name = "OmniWeb"; leftover = browVer.substring("OmniWeb".length+1, browVer.length); } else if (browVer.substring(0, "Gecko".length) == "Gecko") { this.name = "(Gecko-based)"; leftover = browVer.substring("Gecko".length+1, browVer.length); } leftover = trim(leftover); // # Try to get version info out of leftover stuff ind = leftover.indexOf(" "); if (i >= 0) { this.version = trim(leftover.substring(0, i)); } else { this.version = trim(leftover); } j = this.version.indexOf("."); if (j >= 0) { this.majorver = this.version.substring(0,j); this.minorver = this.version.substring(j+1, this.version.length); } else { this.majorver = this.version; } } var info = { name: null, platform: null, renderEngine: null, version: null, majorver: null, minorver: null }; detectNameAndVersion.apply(info); detectRenderEngine.apply(info); return info; }; Environment = function Environment() { /* * Getting screen.innerHeight/Width */ var myWidth = 0, myHeight = 0; if( typeof( window.innerWidth ) == 'number' ) { //Non-IE this.screen.getInnerWidth = function() { return window.innerWidth; }; this.screen.getInnerHeight = function() { return window.innerHeight; }; } else if( typeof document.documentElement.clientWidth != 'undefined' ) { //IE7 and IE 6+ in 'standards compliant mode' this.screen.getInnerWidth = function() { return document.documentElement.clientWidth; }; this.screen.getInnerHeight = function() { return document.documentElement.clientHeight; }; } else if( typeof document.body.clientWidth != 'undefined' ) { //IE 4 compatible this.screen.getInnerWidth = function() { return document.body.clientWidth; }; this.screen.getInnerHeight = function() { return document.body.clientHeight; }; } /* ------- Getting screen.innerHeight/Width End ------- */ /* * Getting body.scrollTop/Left */ var scrOfX = 0, scrOfY = 0; if( typeof( window.pageYOffset ) == 'number' ) { //Netscape compliant this.body.getScrollTop = function () { return window.pageYOffset; }; this.body.getScrollLeft = function () { return window.pageXOffset; }; } else if( typeof document.body.scrollLeft != 'undefined' ) { //DOM compliant this.body.getScrollTop = function () { return document.body.scrollTop; }; this.body.getScrollLeft = function () { return document.body.scrollLeft; }; } else if( typeof document.documentElement.scrollLeft != 'undefined' ) { //IE6 standards compliant mode this.body.getScrollTop = function () { return document.documentElement.scrollTop; }; this.body.getScrollLeft = function () { return document.documentElement.scrollLeft; }; } /* ------- Getting body.scrollTop/Left End ------- */ }; Object.extend(Environment.prototype, { browser : getBrowserInfo(), screen : {/* innerWidth : null, innerHeight : null */}, body : { /* scrollTop : null, scrollLeft : null */} }); if(typeof Base != "undefined") { Base.provide("system.Postback"); Base.require("system.viewState.ClientViewState"); Base.require("system.Event"); } /** * @class Postbak * @alias Postback * @classDescription A classe Postback é responsável por montar a * mensagem que é enviada ao servidor e interpretar a resposta. * As requisições são enviadas utilizando a classe Ajax da * biblioteca Prototype. Na montagem da mensagem de sincronização * as alterações da interface são obtidas da classe ClientViewState. * * @requires system.ClientViewState * * @constructor * @param {Object} url * @param {Object} urlArgs * @param {Object} method */ Postback = function Postback(url, urlArgs, method) { this.url = url; this.urlArgs = urlArgs; this.method = method; // ocorre após o envio da mensagem this.onSendMessage = new Base.Event(); // ocorre antes da validação da mensagem this.onReceiveMessage = new Base.Event(); // ocorre depois da validação da mensagem e antes do processamento this.onBeforeProcessMessage = new Base.Event(); // ocorre após o processamento da mensagem this.onAfterProcessMessage = new Base.Event(); }; Object.extend(Postback.prototype, { /** * @type {Enum} */ commands: { BeforeCreateObjects : [], BeforeModifyObjects : [], BeforeDeleteObjects : [], OnMessageEnd : [] }, /** * Function receiveServerMessage * * O xml da volta nao pode ter comentario * * @param XMLHTTPRequest xhr * @param Object xjson * @return boolean */ receiveServerMessage: function receiveServerMessage(/* XMLHTTPRequest */ xhr, /* Object */ xjson) { this.onReceiveMessage.raise(); var xmlDoc = xhr.responseXML; if(xmlDoc === null || xmlDoc.firstChild == null) { alert("Ops! Ocorreu um erro no servidor. Por favor atualize a p\341gina e tente novamente."); if(xhr.responseText) { Base.raise("falha no postback", new Error("AJAX request error"), {error : /*ErrorType.POSTBACK*/1, message : xhr.responseText}); // logging console.group("Response"); console.log(xhr.responseText); console.groupEnd(); console.groupEnd(); } return false; } else if(xmlDoc.firstChild != null && xmlDoc.firstChild.tagName == "parsererror") { Base.raise("falha no postback", new Error(), {error : /*ErrorType.PARSER_ERROR*/2, message : xmlDoc.firstChild.firstChild.nodeValue}); // logging console.group("Response"); console.log(xhr.responseText); console.groupEnd(); console.groupEnd(); return false; } // logging console.group("Response"); console.log(xhr.responseText); console.groupEnd(); console.groupEnd(); return this.processServerMessage(xmlDoc); }, processServerMessage: function processServerMessage(xmlDoc) { // Disparando o evento onBeforeProcessMessage this.onBeforeProcessMessage.raise(); // carregando os commandos this.loadCommands(xmlDoc); // Atualizando os componentes this.processMessage(xmlDoc); ClientViewState.setSynchronized(); this.onAfterProcessMessage.raise(); this.commands.BeforeCreateObjects = []; this.commands.BeforeModifyObjects = []; this.commands.BeforeDeleteObjects = []; this.commands.OnMessageEnd = []; return true; }, /** * * @param {Document} xmlDoc */ loadCommands: function loadCommands(xmlDoc) { // Executando comandos na mensagem commands = xmlDoc.getElementsByTagName('command'); for (i = 0; i < commands.length; i++) { var act = commands[i].getAttribute("name"); var executeOn = commands[i].getAttribute("executeon"); var parmsNodes = commands[i].getElementsByTagName('param'); var parms = []; for (j = 0; j < parmsNodes.length; j++) { var param = parmsNodes[j].getAttribute('name'); var value = parmsNodes[j].textContent || parmsNodes[j].text; parms.push(value); } var cmd = Base.getCommand(act); var commCall = cmd.prepare(parms); switch(Number(executeOn)) { case Postback.MessageParsePhase.BeforeCreateObjects : this.commands.BeforeCreateObjects.push(commCall); break; case Postback.MessageParsePhase.BeforeModifyObjects : this.commands.BeforeModifyObjects.push(commCall); break; case Postback.MessageParsePhase.BeforeDeleteObjects : this.commands.BeforeDeleteObjects.push(commCall); break; case Postback.MessageParsePhase.OnMessageEnd : this.commands.OnMessageEnd.push(commCall); break; } } }, /** * * @param {Document} xmlDoc */ processMessage: function processMessage(xmlDoc) { for(var i=0; i < this.commands.BeforeDeleteObjects.length; i++) this.commands.BeforeDeleteObjects[i].run(); /* * Get removed objects NodeList */ objectsGroup = xmlDoc.getElementsByTagName("removedObjects"); if(objectsGroup.length > 0) { objects = objectsGroup.item(0).getElementsByTagName("object"); ClientViewState.removeComponents(objects); } for(var i=0; i < this.commands.BeforeCreateObjects.length; i++) { this.commands.BeforeCreateObjects[i].run(); } /* * Get new objects nodeList */ var objectsGroup = xmlDoc.getElementsByTagName("newObjects"); if(objectsGroup.length > 0) { var objects = objectsGroup.item(0).getElementsByTagName("object"); ClientViewState.createComponents(objects); } // =========================================== for(var i=0; i < this.commands.BeforeModifyObjects.length; i++) this.commands.BeforeModifyObjects[i].run(); /* * Get modified objects nodeList */ objectsGroup = xmlDoc.getElementsByTagName("modifiedObjects"); if(objectsGroup.length > 0) { objects = objectsGroup.item(0).getElementsByTagName("object"); ClientViewState.updateComponents(objects); } // =========================================== for(var i=0; i < this.commands.OnMessageEnd.length; i++) this.commands.OnMessageEnd[i].run(); }, /** * @method send * @memberOf {PostBack} * @alias PostBack.PostbackEventType * @type {Enum} */ send : function send(message) { while( message.indexOf("&") != -1 ) { message = message.replace("&", "__andSymbol"); } this.myAjax = new Ajax.Request(this.url, { //method: this.method, postBody: "_PAGE_ID=" + PAGE_ID + "&__clientMessage=" + encodeURI(message) + (this.urlArgs ? "&" + this.urlArgs : ""), requestHeaders: ["Content-Type", "application/x-www-form-urlencoded"], onException : function (xhr, ex) { Base.raise("Postback exception", ex, {xhr:xhr}); }, onComplete: this.receiveServerMessage.bind(this) }); console.group("NeoBase postback"); console.group("Post"); console.log(message); console.groupEnd(); this.onSendMessage.raise(); } }); /** * @memberOf {PostBack} * @alias PostBack.PostbackEventType * @type {Enum} */ Postback.PostbackEventType = { OnSendMessage : 500, OnReceiveMessage : 501, OnBeforeProcessMessage : 502, OnAfterProcessMessage : 503 }; /** * @memberOf {PostBack} * @alias PostBack.MessageParsePhase * @type {Enum} */ Postback.MessageParsePhase = { BeforeCreateObjects : 701, BeforeModifyObjects : 702, BeforeDeleteObjects : 703, OnMessageEnd : 704 }; if(typeof Base != "undefined") { Base.provide("system.util"); } wait = function wait(millis) { date = new Date(); do { var curDate = new Date(); } while(curDate - date < millis); }; uid = function uid(prefix) { var id; if(!prefix) prefix = ""; do { id = prefix + Math.round(Math.random()*10000000000).toString(); } while($(id) != null) return id; }; if(typeof Base != "undefined") { Base.provide("system.commands.Command"); // Assumir que já está incluído // Base.require("system.jext"); } /** * @class PreparedCommand * @alias PreparedCommand * @classDescription Esta classe implementa uma interface para * criar e manipular commandos * * @constructor * @param {Command} cmd * @param {Array} args */ var PreparedCommand = function PreparedCommand(cmd, args) { this.command = cmd; if(typeof args !== 'undefined') this.arguments = args; }; Object.extend(PreparedCommand.prototype, { /** * @type {Command} */ command: null, /** * @type {Array} */ arguments: [], /** * @method run * Executa o comando que gerou esse PreparedCommand passando os * argumentos utilizados na construção deste objeto */ run: function run() { if(this.arguments) { this.command.run(this.arguments); } else { this.command.run(); } } }); /** * Checks if the object type matchs the type passed in type argument. * If the type argument is a string, the test is made using the typeof argument. * If the type argument is an object, the test is made using the instanceof argument. * If the type argument is an array, the test is made using the above rules for each member in the * array. The function will return true if the object type matches at least one of the types in the array. * * @param {Object} obj * @param {Object, array, string} type */ function checkType(obj, type) { // se type é um array, a função deve retornar true caso pelo menos uma das checagens seja válida if(typeof type == "object" && is_array(type)) { for(var i=0; i < type.length; i++) { if(checkType(obj, type[i])) { return true; } } return false; } if(typeof type == "string") return (typeof obj == type); if(typeof type == "object") return (obj instanceof type); } /** * @class Command * @alias Command * @namespace Base * * @constructor * @param {Object} options Objeto com as propriedades que devem ser definidas pelo construtor */ Base.Command = function Command(options){ this.checkArgumentTypes = true; for(var v in options) this[v] = options[v]; }; Object.extend(Base.Command.prototype, { /** * @type {Function} The function that acttualy executes the command action */ action : null, /** * @type {Array} */ argumentTypes : [], /** * @type {boolean} */ checkArgumentTypes : true, /** * @type {Postback.MessageParsePhase} */ executeOn : null, /** * @type {string} * @private */ id : null, /** * @type {string} */ name : null, getId : function() { return this.id; }, run: function Command_run(args) { if(this.checkArgumentTypes) { var len = this.argumentTypes.length; for(var i=0; i < len; i++) { if(!checkType(args[i],this.argumentTypes[i])) { Base.raise("Erro executando commando " + this.id + '. ', new Error("Argument "+i+" should be "+(typeof this.argumentTypes[i])+", "+(typeof arguments[i])+'('+arguments[i]+') given.' )); return; } } } return this.action.apply(this,args); }, /** * Cria um PreparedCommand para este commando com os argumentos * passados * * @method prepare * @param {Array} args */ prepare: function prepare(args) { if(this.checkArgumentTypes) { var len = this.argumentTypes.length; for(var i=0; i < len; i++) { if(!checkType(args[i],this.argumentTypes[i])) { Base.raise("Erro executando commando " + this.id + '. ', new Error("Argument "+i+" should be "+(typeof this.argumentTypes[i])+", "+(typeof arguments[i])+'('+arguments[i]+') given.' )); return; } } } return new PreparedCommand(this, args); } }); if(typeof Base !== 'undefined') { Base.provide("system.commands.common"); Base.require("system.commands.Command"); } /** * @author Saulo Vallory * @package system.commands * @version 0.9 */ Base.CommandType = { Redirect : "Redirect", CallJSFunction : "CallFunction", EmptyCommand: "EmptyCommand" }; // Criando e registrando o commando Redirect Base.registerCommand(new Base.Command( { id : Base.CommandType.Redirect, name : Base.CommandType.Redirect, action : function Redirect(url) { window.location.href = url; }, argumentTypes : ["string"] })); // Criando e registrando o commando CallJSFunction Base.registerCommand(new Base.Command( { id : Base.CommandType.CallJSFunction, name : Base.CommandType.CallJSFunction, action : function (name, args) { eval(name+'('+args+')'); }, argumentTypes : ["string", "string"] })); // Criando e registrando um commando vazio que não recebe nada e não faz nada Base.registerCommand(new Base.Command( { id : Base.CommandType.EmptyCommand, name : Base.CommandType.EmptyCommand, action : function () {}, argumentTypes : [], checkArgumentTypes : false })); if(typeof Base != "undefined") { Base.provide("web.Style"); // Assumindo que o jext está sempre lá! // Base.require("system.jext"); } /** * @class Style * @alias Style * @namespace Base * @author Saulo Vallory * @version 0.9 * * @param {Object} style */ Style = function Style(style) { this.realObject = style; }; Object.extend(Style.prototype, { realObject : null, _owner : null, /** * @method get * @param {String} prop */ get : function get(prop) { return this.realObject[prop]; }, /** * @method set * @param {String} name * @param {Object} value */ set : function set(name, value) { if(typeof this.realObject[name] != "undefined") var oldValue = this.realObject[name]; else var oldValue = undefined; if(value != oldValue) { this.realObject[name] = value; if(this._owner) { var oldCss = this.realElement.style.cssText; this._owner.onPropertyChange.raise(this, { changeType : ChangeType.PROPERTY_CHANGED, propertyName : "style", oldValue : oldCss}); } } }, /** * @method setOwner * @param {Component} comp * @return {boolean} */ setOwner : function setOwner(comp) { if(!Base.isComponent(comp)) { Base.raise("Parâmetro incorreto", new Error("A função Style.setOwner espera um Component como parâmetro mas recebeu um " + (typeof comp))); return false; } this._owner = comp; return true; }, /** * @method getOwner * @return {Component} comp */ getOwner : function getOwner() { return this._owner; } }); if(typeof Base != "undefined") { Base.provide("web.Component"); Base.require("system.Event"); Base.require("system.util"); Base.require("web.Style"); // Assumir que já está incluído // Base.require("system.jext"); } /** * @class Component * @alias Component * @namespace Base * @author Saulo Vallory * * @requires system.jext * @requires system.Event * @requires system.util * @requires web.Style * * @constructor */ Component = function Component() { this.isComponent = true; this.onPropertyChange = new Base.Event(); this.id = uid("cmp_"); }; Object.extend(Component.prototype, { id : "", onPropertyChange : null, style : null, realElement : null, phpClass : "", initialize : function Component_initialize(elem) { this.id = elem.id; this.style = new Style(elem.style); }, get : function Component_get(name) { if(typeof this["get"+name.capitalize()] == "function") { return this["get"+name.capitalize()](); } else { if(this[name]) return this[name]; if(this["realElement"] == null || typeof this["realElement"] == "undefined") { return this[name]; } return this.realElement[name]; } }, getHTML : function Component_getHTML() { if(this.realElement.nodeType == DOCUMENT_FRAGMENT_NODE) { var temp = document.createElement("div"); temp.appendChild(this.realElement); var html = temp.innerHTML; delete temp; return html; } else return this.realElement.outerHTML; }, /** * @memberOf {Component} * @alias getXML */ getXML : function Component_getXML() { var node = this.realElement; xml = ''; if(node != null && node.attributes) { for(var i=0; i < node.attributes.length; i++) { var att = node.attributes[i]; if(att.nodeValue && !is_function(att.nodeValue)) { xml += ''; xml += ''; xml += ''; } } } xml += ''; return xml; }, getId : function Component_getId() { return this.id; }, set : function Component_set(name, value) { // só é necessário fazer o tracking para elementos na página if(this["realElement"] == null || typeof this["realElement"] == "undefined") { this[name] = value; return; } var oldValue = this.get(name); if(value != oldValue) { if(typeof this["set"+name.capitalize()] == "function") return this["set"+name.capitalize()](value); else { if(name.substr(0,2) == 'on') this.realElement[name] = value; else if(this.realElement.setAttribute instanceof Function) this.realElement.setAttribute(name, value); else this.realElement[name] = value; } this.onPropertyChange.raise(this, { changeType : ChangeType.PROPERTY_CHANGED, propertyName : name, oldValue : oldValue}); } }, /** * @memberOf Component * @param {string} id */ setId : function Component_setId(id){ this.id = id; if(this.realElement) { this.realElement["id"] = id; } }, getStyle : function Component_getStyle() { return this.realElement.style.cssText; }, /** * Nota para desenvolvedores do framewor: Essa função NÃO deve utilizar a função set do objeto style. * A função Style.set já checa a existência do Componente que a contém e comunica a alteração * @memberOf {Component} * @method setStyle * @param {string} txt */ setStyle : function setStyle(prop, value) { if(value == null) this.realElement.style.cssText = prop; else { var oldValue = this.realElement.style[prop]; if(value != oldValue) { var oldCss = this.realElement.style.cssText; this.realElement.style[prop] = value; this.onPropertyChange.raise(this, { changeType : ChangeType.PROPERTY_CHANGED, propertyName : "style", oldValue : oldCss}); } } }, setClassName : function Component_setClassName(value) { this.realElement.className = value; }, getClassName : function Component_getClassName() { return this.realElement.className; }, getDocument : function Component_getDocument() { if(typeof this.realElement != 'undefined') return this.realElement.ownerDocument; else return null; }, getContainer : function Component_getContainer() { return this.container; }, setContainer : function Component_setContainer(cont) { if(typeof cont == 'string') return false; //cont = $C(cont); if(cont == null) return false; var elem = this.realElement; var contDoc = cont.getDocument(); if(contDoc != null && elem.ownerDocument !== contDoc) if(typeof contDoc.importNode != 'undefined') elem = contDoc.importNode(elem, true); //Adicionando Elemento HTML if (elem.parentNode !== cont.realElement) cont.realElement.appendChild(elem); return true; }, removeRealElement : function Component_removeRealElement() { if(this.realElement != null && this.realElement.parentNode != null) this.realElement.parentNode.removeChild(this.realElement); } }); /** * * @param {String} phpClass * @param {HTMLElement} node * @return {Component} */ Component.factory = function factory(phpClass, node) { if(phpClass.toLowerCase() == "image") phpClass = "Picture"; var validClasses = ["body", "button", "dropdownlist", "datepicker", "icon", "menu", "style", "page", "checkbox", "form", "hiddenfield", "hyperlink", "formbutton", "formimage", "htmlfragment", "htmltag", "image", "inputfile", "label", "listbox", "listitem", "literal", "optionitem", "panel", "password", "radio", "radiobutton", "radiogroup", "reset", "slider", "span", "submit", "textarea", "textbox", "uidig", "picture", "ulist"]; if(validClasses.indexOf(phpClass.toLowerCase()) != -1) { var __comp = null; var classExists = false; var __constructor = null; eval('classExists = (typeof ' + phpClass + ' == "function");'); if(!classExists) { Base.raise("constructor for component " + phpClass + " not found. (Component.factory)", new Error()); return null; } eval('__constructor = ' + phpClass + ';'); __comp = new __constructor(node); return __comp; } else { alert ('O componente ' + phpClass + ' não existe!'); return null; } }; if(typeof Base != "undefined") { Base.provide("web.VisualComponent"); Base.require("web.Component"); } /** * @class VisualComponent * @alias VisualComponent * @namespace Base * @classDescription A classe VisualComponent define métodos * inerentes a qualquer componente visível como show, hide e toogle * @author Saulo Vallory * @version 0.9 * * @requires Component * * @constructor */ VisualComponent = function VisualComponent() { this.isVisualComponent = true; // chamando o construtor da classe Component (Component.bind(this))(); }; Object.extend(VisualComponent.prototype, Component.prototype); Object.extend(VisualComponent.prototype, { show : function () { this.style.set('display',''); }, hide : function () { this.style.set('display','none'); }, toogle : function () { this[this.isVisible() ? 'hide' : 'show'](); }, isVisible: function() { return this.realElement.style.display != 'none'; } }); if(typeof Base !== "undefined") { Base.provide("web.Container"); Base.require("web.Component"); Base.require("system.commands.Command"); } /** * @class Container * @alias Container * @namespace Base * @author Saulo Vallory * @version 0.9 * * @requires Component * @requires Command * * @constructor */ Container = function Container() { this.isContainer = true; (Component.bind(this))(); this.onChildAdd = new Base.Event(); this.onChildRemove = new Base.Event(); this.children = new Collection(); }; Object.extend(Container.prototype, Component); Object.extend(Container.prototype, { /** * @type {Collection} */ children : null, /** * @type {Base.Event} */ onChildAdd : null, /** * @type {Base.Event} */ onChildRemove : null, /** * * @param {mixed} obj * @param {Object} noRaise */ addChild : function Container_addChild(obj, noRaise) { /* Ainda não tá implementado if(obj instanceof HTMLElement) { if(document != document.body.ownerDocument) document.importNode(obj, true); if(obj.hasAttribute("phpClass")) { var comp = Component.factory(obj.getAttribute("phpClass"), obj); } else { var phpClass = Component.guessType(obj); } } */ if(Base.isComponent(obj)) { try { Base.addComponent(obj); //Adicionando Objeto if(obj.setContainer(this)) this.children.add(obj.getId(),obj); } catch(e) { Base.raise("Não foi possível adicionar o componente " + obj.getId() + " ao container " + this.id + " ", e); return; } if (noRaise != true) { this.onChildAdd.raise(this,{ changeType : ChangeType.CHILD_ADDED, child : obj}); } } else if (typeof obj == "string" || typeof obj == "number") { var lit = new Literal(obj); //Adicionando Objeto this.children.add(lit.getId(), lit); Base.addComponent(lit); //Adicionando Elemento HTML this.realElement.appendChild(lit.realElement); if (noRaise != true) { this.onChildAdd.raise(this,{ changeType : ChangeType.CHILD_ADDED, child: lit }); } } }, /** * @param {Component} obj * @param {boolean} noRaise */ removeChild : function Panel_removeChild(obj, noRaise) { if(typeof obj == "string") obj = $C(obj); if(obj == null || !(typeof obj == "object" && Base.isComponent(obj))) return; if(this.children.get(obj.get("id")) == null) return false; if(obj.constructor === Literal) { this.children.remove(obj.get("id")); for(var i=0; i < obj.childNodes.length; i++) { this.realElement.removeChild(obj.childNodes[i]); } if (noRaise != true) this.onChildRemove.raise(this,{ changeType : ChangeType.CHILD_REMOVED, child: obj }); return true; } else { this.children.remove(obj.get("id")); this.realElement.removeChild(obj.realElement); if (noRaise != true) this.onChildRemove.raise(this,{ changeType : ChangeType.CHILD_REMOVED, child: obj }); return true; } return false; }, /** * @param {HTMLElement} i * @param {boolean} noRaise */ removeChildByIndex : function Panel_removeChildByIndex (i, noRaise) { if (i >= 0 && i < this.children.length) { var aux = this.children[i]; var auxId = aux.get("id"); this.children.splice(i,i+1); aux.realElement = aux.realElement.parentNode.removeChild(aux.realElement); if (noRaise != true) { this.onChildRemove.raise(this, {changeType : ChangeType.CHILD_REMOVED, child : aux} ); } return true; } return false; }, removeChildren : function (noRaise) { var oldChildren = this.children.removeAll(); for(var i=0; i < oldChildren.length; i++) { if(Base.isContainer(oldChildren[i])) { //console.group('removing children from ' + this.id); oldChildren[i].removeChildren(); //console.groupEnd(); } //console.log('removing ' + this.id); Base.removeComponent(oldChildren[i].get('id')); } this.realElement.innerHTML = ''; } }); // Creating commands Container.CommandEnum = { RemoveChildren : 'RemoveContainerChildren' }; Base.registerCommand(new Base.Command( { id : Container.CommandEnum.RemoveChildren, name : "RemoveContainerChildren", /** * * @param {Container} cont */ action : function (cont) { var comp = null; if(typeof cont == "string") { comp = $C(cont); } else comp = cont; if(!(typeof comp == "object" && Base.isContainer(comp))) { Base.raise("Erro removendo filhos de um container, container ("+cont+") não encontrado.", new Error("Container with id "+cont+" couldn't be found.")); } comp.removeChildren(true); }, checkArgumentTypes : false //argumentTypes : [Object,"string"] })); /** * @author saulo * @version */ if(typeof Base != "undefined") { Base.provide("web.Body"); Base.require("web.VisualComponent"); Base.require("web.Container"); } /** * @class Body * @alias Body * @namespace Base * @author Saulo Vallory * @version 0.9 * * @requires Base.web.VisualComponent * @requires Base.web.Container * * @param {HTMLElement} elem */ Body = function Body(elem) { (VisualComponent.bind(this))(); (Container.bind(this))(); if (typeof elem == "undefined" || elem == null) { var elem = document.createElement('div'); } this.initialize(elem); }; Object.extend(Body.prototype, VisualComponent.prototype); Object.extend(Body.prototype, Container.prototype); Object.extend(Body.prototype, { parent : VisualComponent, parentObject : null, phpClass : "Body", /** * @param {HTMLElement}elem */ initialize : function initialize (elem) { (Component.prototype.initialize.bind(this, elem))(); if (typeof elem == "undefined" || elem == null) { Base.raise("Não é possível criar um componente Body sem um Body! O parâmetro recebido foi " + (typeof elem)); } this.realElement = elem; } }); if(typeof Base != "undefined") { Base.provide("web.HTMLTag"); Base.require("web.VisualComponent"); Base.require("web.Container"); } /** * Class HTMLTag * * @author Saulo * @version 0.1 * * @param {HTMLElement} elem */ HTMLTag = function HTMLTag(elem, tagName) { (VisualComponent.bind(this))(); (Container.bind(this))(); if((typeof elem == "undefined" || elem == null) && tagName != null) { elem = document.createElement(String(tagName)); } this.initialize(elem); }; Object.extend(HTMLTag.prototype, VisualComponent.prototype); Object.extend(HTMLTag.prototype, Container.prototype); Object.extend(HTMLTag.prototype, { parentObject : null, phpClass : "HTMLTag", tagName : '', /** * * @param {HTMLElement} elem */ initialize : function HtmlTag_initialize(elem, tagName) { (Component.prototype.initialize.bind(this, elem))(); if((typeof elem == "undefined" || elem == null) && tagName != null) { var elem = document.createElement(String(tagName)); } this.tagName = elem.localName; this.realElement = elem; }, /** * Transforma este elemento no elemento da tag passada * * ATENÇÃO: Essa função cria um novo elemento e sobrescreve * o elemento original. Todos os atributos serão perdidos * * @param {String} tag */ setTagName : function HTMLTag_setTagName(tag) { var elem = document.createElement(tag); elem.attributes = this.realElement.attributes; while(this.realElement.childNodes[0]) { elem.appendChild(this.realElement.childNodes[0]); } if(this.realElement != null) this.realElement.parent.replaceChild(elem, this.realElement); (Container.initialize.bind(this, elem))(); this.initialize(elem); }, getTagName : function HTMLTag_setTagName() { return this.tagName; } }); if(typeof Base !== "undefined") { Base.provide("web.Hyperlink"); Base.require("web.VisualComponent"); Base.require("web.Container"); } /** * @class Hyperlink * @alias Hyperlink * @namespace Base * @author Saulo Vallory * @version 0.9 * * @param {HTMLElement} elem */ Hyperlink = function Hyperlink(elem) { (VisualComponent.bind(this))(); (Container.bind(this))(); if (typeof elem == "undefined" || elem == null) { var elem = document.createElement('a'); } this.initialize(elem); }; Object.extend(Hyperlink.prototype, VisualComponent.prototype); Object.extend(Hyperlink.prototype, Container.prototype); Object.extend(Hyperlink.prototype, { parent : VisualComponent, phpClass : "Hyperlink", /** * @param {HTMLElement} elem */ initialize : function Hyperlink_initialize(elem) { (Component.prototype.initialize.bind(this, elem))(); if (typeof elem == 'undefined') { Base.raise("Erro criando Hyperlink", new Error("Param elem is not defined in Hyperlink_initialize")); } else { this.realElement = elem; } } }); if(typeof Base !== "undefined") { Base.provide("web.ListItem"); Base.require("web.VisualComponent"); Base.require("web.Container"); } /** * @class ListItem * @alias ListItem * @namespace Base * @author Saulo Vallory * @version 0.9 */ ListItem = function ListItem(elem) { (VisualComponent.bind(this))(); (Container.bind(this))(); if (typeof elem == "undefined" || elem == null) { var elem = document.createElement('li'); } this.initialize(elem); }; Object.extend(ListItem.prototype, VisualComponent.prototype); Object.extend(ListItem.prototype, Container.prototype); Object.extend(ListItem.prototype, { parent : VisualComponent, parentObject : null, phpClass : "ListItem", /** * @param {HTMLElement} elem * * @return boolean */ initialize : function ListItem_initialize (elem) { (Component.prototype.initialize.bind(this, elem))(); if (typeof elem == "undefined" || elem == null) { var elem = document.createElement('li'); } this.realElement = elem; }, /** * @return {UList} */ getParentObject : function ListItem_getParentObject () { return this.parentObject; }, /** * @param {UList} uList * @return boolean */ setParentObject : function ListItem_setParentObject (uList) { if (uList.realElement.tagName.toLowerCase() == 'ul' || uList.realElement.tagName.toLowerCase() == 'ol') { this.parentObject = uList; return true; } return false; } }); if(typeof Base != "undefined") { Base.provide("web.Literal"); Base.require("web.Component"); } /** * @class Literal * @alias Literal * @namespace Base * @author Saulo Vallory * @version 0.9 * * @param {String} html */ Literal = function Literal(html) { (Component.bind(this))(); if (typeof html == "undefined") html = ''; this.realElement = document.createTextNode(html); }; Object.extend(Literal.prototype, Component.prototype); Object.extend(Literal.prototype, { childNodes : [], value : null, phpClass : "Literal", getId : function Literal_getId() { return this.id; }, getValue : function Literal_getValue() { if(typeof(this.realElement.text) != 'undefined') return this.realElement.text; return this.realElement.textContent; }, get : function Literal_get(name) { switch(name.toLowerCase()) { case "value" : return this.getValue(); break; case "id" : return this.getId(); break; default : if(this["realElement"] != null && typeof this["realElement"] != "undefined") { if(typeof this.realElement[name] != "undefined" && this.realElement[name] != null) return this.realElement[name]; } return this[name]; } }, set : function Literal_set(name, value) { var oldValue = this.get(name); if(value == oldValue) return; switch(name.toLowerCase()) { case "value" : this.setValue(value); break; case "id" : this.setId(value); break; default : if(this.realElement[name] == null || typeof this.realElement[name] == "undefined") this[name] = value; else this.realElement[name] = value; } if(this.get(name) != oldValue) { this.onPropertyChange.raise(this, { changeType : ChangeType.PROPERTY_CHANGED, propertyName : name, oldValue : oldValue}); } }, setId : function Literal_setId(id) { this.id = id; }, setValue : function Literal_setValue(val) { if(typeof(this.realElement.text) != 'undefined') this.realElement.text = val; this.realElement.textContent = val; /* this.realElement = this.parseHtml(val); this.childNodes = []; for(var i=0; i < this.realElement.childNodes.length; i++) { this.childNodes[i] = this.realElement.childNodes[i]; } */ }, /** * * @param {String} html * @return DocumentFragment */ parseHtml : function Literal_parseHtml(html) { var tempEl = document.createElement("div"); tempEl.innerHTML = html; Base._findServerObjects(tempEl, Base._serverObjs); var doc = document.createDocumentFragment(); while(tempEl.hasChildNodes()) { doc.appendChild(tempEl.childNodes[0]); } return doc; } }); if(typeof Base != "undefined") { Base.provide("web.Panel"); Base.require("web.VisualComponent"); Base.require("web.Container"); } /** * @class Style * @alias Style * @namespace Base * @author Saulo Vallory * @version 0.9 * * @param {HTMLElement} elem */ Panel = function Panel(elem) { (VisualComponent.bind(this))(); (Container.bind(this))(); if (typeof elem == "undefined" || elem == null) { var elem = document.createElement('div'); } this.initialize(elem); }; Object.extend(Panel.prototype, VisualComponent.prototype); Object.extend(Panel.prototype, Container.prototype); Object.extend(Panel.prototype, { parent : VisualComponent, parentObject : null, phpClass : "Panel", /** * @param {HTMLElement}elem */ initialize : function initialize (elem) { (Component.prototype.initialize.bind(this, elem))(); if (typeof elem == "undefined" || elem == null) { var elem = document.createElement('panel'); } this.realElement = elem; } }); if(typeof Base != "undefined") { Base.provide("web.Span"); Base.require("web.VisualComponent"); Base.require("web.Container"); } /** * @class Span * @alias Span * @namespace Base * @author Saulo Vallory * @version 0.9 * @param {HTMLElement} elem */ Span = function Span(elem) { (VisualComponent.bind(this))(); (Container.bind(this))(); if (typeof elem == "undefined" || elem == null) { var elem = document.createElement('span'); } this.initialize(elem); }; Object.extend(Span.prototype, VisualComponent.prototype); Object.extend(Span.prototype, Container.prototype); Object.extend(Span.prototype, { parent : VisualComponent, parentObject : null, phpClass : "Span", /** * @param {HTMLElement}elem */ initialize : function Span_initialize(elem) { (Component.prototype.initialize.bind(this, elem))(); if (typeof elem == "undefined" || elem == null) { var elem = document.createElement('span'); } this.realElement = elem; } }); if(typeof Base !== "undefined") { Base.provide("web.UList"); Base.require("web.ListItem"); Base.require("web.VisualComponent"); Base.require("web.Container"); } /** * @class UList * @alias UList * @namespace Base * @author Saulo Vallory * @version 0.9 * * @param {HTMLElement} elem */ UList = function UList(elem) { (VisualComponent.bind(this))(); (Container.bind(this))(); if (typeof elem == "undefined") { var elem = document.createElement('ul'); } this.initialize(elem); }; Object.extend(UList.prototype, VisualComponent.prototype); Object.extend(UList.prototype, Container.prototype); Object.extend(UList.prototype, { parent : VisualComponent, parentObject : null, listItems : null, phpClass : "UList", /** * @param {HTMLElement} elem */ initialize : function UList_initialize(elem) { if (elem.tagName.toLowerCase() == 'ul') { (Component.prototype.initialize.bind(this, elem))(); this.realElement = elem; this.listItems = []; var numChildren = elem.childNodes.length; for (var i=0; i < numChildren; i++) { if (typeof elem.childNodes[i] == "object") { if (elem.childNodes[i].nodeName.toLowerCase() == 'li') { var listItem = Base.getComponentById(elem.childNodes[i].id); if (typeof listItem == "undefined" || listItem == null) { listItem = new ListItem(elem.childNodes[i]); Base.addComponent(listItem); } this.listItems[this.listItems.length] = listItem; this.addChild(listItem, true); listItem.setParentObject(this); } } } return true; } return false; }, /** * @classDescription Criando e adicionando um ListItem recebendo um HTMLElement * @param {HTMLElement} elem * @return boolean */ addItem : function UList_addItem(elem, noRaise) { if (elem.tagName.toLowerCase() == "li") { var myListItem = new ListItem(elem); this.addListItem(myListItem, noRaise); return true; } return false; }, /** * @param {ListItem} listItem */ addListItem : function UList_addListItem(listItem, noRaise) { if (listItem.get("tagName").toLowerCase() == "li") { //Adicionando Objeto this.listItems[this.listItems.length] = listItem; //Adicionando Elemento HTML this.realElement.add(listItem.realElement, null); //Adjustando propriedade "parentObject" listItem.setParentObject(this); if (noRaise == undefined || noRaise == false) { this.onChildAdd.raise(this, {changeType : ChangeType.CHILD_ADDED, child : listItem}); } return true; } return false; }, /** * @param {HTMLElement} elem * @return int */ getListItemIndex : function UList_getListItemIndex(elem) { var numItems = this.listItems.length; var j = -1; for (var i = 0; i < numItems && (j == -1); i++) { if (this.listItems[i].get('id') == elem.id) { j = i; } } return j; }, /** * @classDescription Removendo, por índice, um ListItem do array "listItems" * @param {int} i */ removeListItemByIndex : function UList_removeListItemByIndex(i, noRaise) { if ( 0 <= i && i " + sliderthumbID); this.realElement = YAHOO.widget.Slider.getHorizSlider(sliderbgID, sliderthumbID, this.leftUp, this.rightDown, this.tick); this.realElement.setValue(this.oldXValue); if (this.locked == 1) { this.realElement.subscribe("change", this.setLock.bind(this)); this.realElement.setValue(this.oldXValue); } this.realElement.subscribe("change", this.raiseChange.bind(this)); }, raiseChange : function Slider_raiseChange(offSet) { alert ("raiseChange"); this.onPropertyChange.raise(this, {changeType : ChangeType.PROPERTY_CHANGED, propertyName : "xvalue", oldValue : this.oldXValue}); this.oldXValue = offSet; }, /** * @param {int} offSet */ setLock : function Slider_setLock(offSet) { this.oldXValue = offSet; this.realElement.lock(); } }); if(typeof Base != 'undefined') { Base.provide("web.image.Image"); Base.require("web.Component"); } /** * @class Picture * @alias Picture * @namespace Base * @author Saulo Vallory * @version 0.9 * * @param {HTMLElement} elem */ Picture = function Picture(elem) { (VisualComponent.bind(this))(); if (typeof elem == "undefined" || elem == null) { var elem = document.createElement('img'); } this.initialize(elem); }; Object.extend(Picture.prototype, VisualComponent.prototype); Object.extend(Picture.prototype, { parent : VisualComponent, parentObject : null, phpClass : "Image", /** * @param {HTMLElement}elem */ initialize : function Image_initialize(elem) { (Component.prototype.initialize.bind(this, elem))(); if (typeof elem == "undefined" || elem == null) { var elem = document.createElement('img'); } this.realElement = elem; } }); if(typeof Base != "undefined") { Base.provide("web.form.FormField"); } FormField = function(){}; Object.extend(FormField.prototype, { checkChanges : function FormField_checkChanges() { // this function should be overwrited in child class }, setDisabled : function FormField_setDisabled(value) { if(this.realElement.setAttribute instanceof Function) { if(true === value) this.realElement.setAttribute('disabled', value); else this.realElement.removeAttribute('disabled'); } this.realElement['disabled'] = value; } }); if(typeof Base !== "undefined") { Base.provide("web.form.CheckBox"); Base.require("web.VisualComponent"); Base.require("web.form.FormField"); } /** * @class CheckBox * @alias CheckBox * @namespace Base.web.form * @author Saulo Vallory * @version 0.9 * * @requires Base.web.VisualComponent * @requires Base.web.form.FormField * * @param {HTMLElement} elem */ CheckBox = function CheckBox(elem) { (VisualComponent.bind(this))(); (FormField.bind(this))(); if (typeof elem == 'undefined' || elem == null) { var elem = document.createElement("input"); elem.type = "checkbox"; } this.initialize(elem); }; Object.extend(CheckBox.prototype, VisualComponent.prototype); Object.extend(CheckBox.prototype, FormField.prototype); Object.extend(CheckBox.prototype, { parent : VisualComponent, phpClass : "CheckBox", /** * @private * @type {Boolean} elem */ _oldCheckedValue : null, /** * @param {HTMLElement} elem */ initialize : function CheckBox_initialize (elem) { (Component.prototype.initialize.bind(this, elem))(); this.realElement = elem; this._oldCheckedValue = elem.checked; elem.onclick = this._raiseChange.bind(this); }, /** * @method _raiseChange * @private * @param {Event} e */ _raiseChange: function CheckBox_raiseChange(e) { this.onPropertyChange.raise(this, {event:e, changeType : ChangeType.PROPERTY_CHANGED, propertyName : "checked", oldValue : this._oldCheckedValue}); this._oldCheckedValue = this.actualCheckedValue; }, /** * @method setChecked * @public * @param {Boolean} value */ setChecked: function CheckBox_setChecked(value) { if(this.realElement.checked != Boolean(value)) { this.realElement.checked = Boolean(value); this._raiseChange(); } } }); if(typeof Base !== "undefined") { Base.provide("web.form.FieldSet"); Base.require("web.VisualComponent"); Base.require("web.form.FormField"); } /** * @class FieldSet * @alias FieldSet * @namespace Base.web.form * @author Saulo Vallory * @version 0.9 * * @requires Base.web.VisualComponent * @requires Base.web.form.FormField * * @param {HTMLElement} elem */ FieldSet = function FieldSet(elem) { (VisualComponent.bind(this))(); (FormField.bind(this))(); if (typeof elem == 'undefined' || elem == null) { var elem = document.createElement('fieldset'); } this.initialize(elem); }; Object.extend(FieldSet.prototype, VisualComponent.prototype); Object.extend(FieldSet.prototype, FormField.prototype); Object.extend(FieldSet.prototype, { parent : VisualComponent, legend : null, items : null, phpClass : "FieldSet", /** * @param {HTMLElement} elem */ initialize : function FieldSet_initialize (elem) { (Component.prototype.initialize.bind(this, elem))(); this.realElement = elem; //Por padrão, a propriedade "id" do elemento LEGEND é o id do elemento FIELDSET mais uma constante string "Legend" this.legend = document.getElementById(elem.id + "Legend" ); this.items = []; }, /** * @param {Object} obj */ addItem : function FieldSet_addItem (obj, noRaise) { //Adicionando Objeto this.items[this.items.length] = obj; //Adicionando Elemento HTML this.realElement.appendChild(obj.realElement); if (noRaise == undefined) this.onChildAdd.raise(this,{changeType : ChangeType.CHILD_ADDED, child : obj}); }, /** * @param {Object} obj * @param {boolean} noRaise */ removeItem : function FieldSet_removeItem (obj, noRaise) { j = false; for (var i = 0; i0 && i<(this.items.length - 1)) { var aux = this.items[i]; var auxId = aux.get("id"); //Removendo Objeto this.items.splice(i,i+1); //Removendo Elemento HTML this.realElement.removeChild(aux.realElement); if ( noRaise == undefined || noRaise == false) this.onChildRemove.raise( this, {changeType : ChangeType.CHILD_REMOVED, child : aux} ); return true; } return false; }, /** * @return {boolean} */ removeLegend : function FieldSet_removeLegend() { if (this.legend !== null) { this.legend.parentNode.removeChild(this.legend); this.legend = null; return true; } return false; }, /** * @param {HTMLElement} legend */ setLegend : function FieldSet_setLegend(legend) { if (typeof(legend) == "object") { this.legend = legend; } else if (typeof(legend) == "string") { legend = document.getElementById(legend); } this.realElement.appendChild(legend); } }); if(typeof Base !== "undefined") { Base.provide("web.form.Form"); Base.require("web.VisualComponent"); Base.require("web.Container"); Base.require("web.form.FormField"); } /** * @class Style * @alias Style * @namespace Base.web.form * @author Saulo Vallory * @version 0.9 * * @requires Base.web.VisualComponent * @requires Base.web.form.FormField * * @param {HTMLElement} elem */ Form =function Form(elem) { (VisualComponent.bind(this))(); (FormField.bind(this))(); (Container.bind(this))(); this.items = []; this.modifiedItems = []; if (typeof elem == 'undefined' || elem == null) { var elem = document.createElement('form'); } this.initialize(elem); }; Object.extend(Form.prototype, VisualComponent.prototype); Object.extend(Form.prototype, Container.prototype); Object.extend(Form.prototype, FormField.prototype); Object.extend(Form.prototype, { parent : VisualComponent, items : null, modifiedItems : null, phpClass : "Form", /** * @param {HTMLElement} elem */ initialize : function Form_initialize (elem) { if (elem.tagName.toLowerCase() == 'form') { (Component.prototype.initialize.bind(this, elem))(); this.realElement = elem; if (window.attachEvent) // IE { var oldSubmit = this.realElement.onsubmit; // estranhamente, se jogar direto pra this.onChangeListeners não funciona no IE this.realElement.onsubmit = null; // no IE o último evento adicionado USANDO attachEvent é o primeiro // a ser executado. Eventos adicionados pelo html são executados // antes dos eventos adicionados por attachEvent this.realElement.attachEvent('onsubmit', oldSubmit); this.realElement.attachEvent('onsubmit', this.checkFields.bind(this)); } return true; } return false; }, /** * Check fields for modifications */ checkFields : function Form_recheckFields() { var fields = this.realElement.elements; for(var i=0; i < fields.length; i++) { var comp = $C(fields[i].id); if(comp != null) comp.checkChanges(); } }, /** * @param {Object} item */ addItem : function Form_addItem (item, noRaise) { //Adicionando Objeto this.items[this.optionItems.length] = item; //Adicionando Element HTML this.realElement.appendChild(item.realElement); if (noRaise == undefined || noRaise == false) this.onChildAdd.raise(this, {changeType : ChangeType.CHILD_ADDED, child : item } ); }, /** * @param {Object} item * @return boolean */ removeItem : function Form_removeItem (objectItem, noRaise) { var j = false; for (var i = 0; i0 && i<(this.items.length - 1)) { var aux = this.items[i]; var auxId = aux.get("id"); //Removendo Objeto this.items.splice(i,i+1); //Removendo Elemento HTML aux.realElement.parentNode.removeChild(aux.realElement); if ( noRaise == undefined || noRaise == false ) this.onChildRemove.raise( this, {changeType : ChangeType.CHILD_REMOVED, child : aux} ); return true; } return false; }, /** * @private * @param {Event} e */ _raiseChange : function _raiseChange(e) { this.onPropertyChange.raise(this, {event:e, propertyName : "value", oldValue : this.oldValue}); this.oldValue = this.realElement.value; } }); /** * @author Luciano */ if(typeof Base !== "undefined") { Base.provide("web.form.FormButton"); Base.require("web.VisualComponent"); Base.require("web.form.FormField"); } /** * @class FormButton * @alias FormButton * @namespace Base.web.form * @author Saulo Vallory * @version 0.9 * * @requires Base.web.VisualComponent * @requires Base.web.form.FormField * * @param {HTMLElement} elem */ FormButton = function FormButton(elem) { (VisualComponent.bind(this))(); (FormField.bind(this))(); if (typeof elem == 'undefined' || elem == null) { var elem = document.createElement('input'); elem.type = 'button'; } this.initialize(elem); }; Object.extend(FormButton.prototype, VisualComponent.prototype); Object.extend(FormButton.prototype, FormField.prototype); Object.extend(FormButton.prototype, { parent : VisualComponent, /** * @param {HTMLElement} elem */ initialize : function FormButton_initialize (elem) { if (elem.tagName.toLowerCase() == "input" && elem.type.toLowerCase() == "button") { (Component.prototype.initialize.bind(this, elem))(); this.realElement = elem; } else { alert ("Element " + elem.id + " not a FormButtom Type!"); } } }); if(typeof Base !== "undefined") { Base.provide("web.form.FormImage"); Base.require("web.VisualComponent"); Base.require("web.form.FormField"); } /** * @class FormImage * @alias FormImage * @namespace Base.web.form * @author Saulo Vallory * @version 0.9 * * @requires Base.web.VisualComponent * @requires Base.web.form.FormField * * @param {HTMLElement} elem */ FormImage = function FormImage(elem) { (VisualComponent.bind(this))(); (FormField.bind(this))(); if (typeof elem == "undefined" || elem == null) { var elem = document.createElement('input'); elem.type = 'image'; } this.initialize(elem); }; Object.extend(FormImage.prototype, VisualComponent.prototype); Object.extend(FormImage.prototype, FormField.prototype); Object.extend(FormImage.prototype, { parent : VisualComponent, phpClass : "FormImage", /** * @param {HTMLElement} elem */ initialize : function FormImage_initialize (elem) { (Component.prototype.initialize.bind(this, elem))(); if (typeof elem == 'undefined') { Base.raise("Erro criando Hyperlink", new Error("Param elem is not defined in Hyperlink_initialize")); } else { this.realElement = elem; } } }); if(typeof Base !== "undefined") { Base.provide("web.form.HiddenField"); Base.require("web.VisualComponent"); Base.require("web.form.FormField"); } /** * @class HiddenField * @alias HiddenField * @namespace Base.web.form * @author Saulo Vallory * @version 0.9 * * @requires Base.web.VisualComponent * @requires Base.web.form.FormField * * @param {HTMLElement} elem */ HiddenField = function HiddenField(elem) { (VisualComponent.bind(this))(); (FormField.bind(this))(); if (typeof elem == 'undefined' || elem == null) { var elem = document.createElement('input'); elem.type = 'hidden'; } this.initialize(elem); }; Object.extend(HiddenField.prototype, VisualComponent.prototype); Object.extend(HiddenField.prototype, FormField.prototype); Object.extend(HiddenField.prototype, { parent : VisualComponent, oldValue : "", phpClass : "HiddenField", /** * @param {HTMLElement}elem */ initialize : function HiddenField_initialize (elem) { if (elem.type.toLowerCase() == "hidden") { (Component.prototype.initialize.bind(this, elem))(); this.oldValue = elem.value; this.realElement = elem; Event.observe(elem, "change", this._raiseChange.bind(this)); return true; } return false; }, /** * @param {Event} e */ _raiseChange : function _raiseChange(e) { this.onPropertyChange.raise(this, {event:e, changeType : ChangeType.PROPERTY_CHANGED, propertyName : "value", oldValue : this.oldValue}); this.oldValue = this.realElement.value; } }); /** * @author Luciano */ if(typeof Base !== "undefined") { Base.provide("web.form.InputFile"); Base.require("web.VisualComponent"); Base.require("web.form.FormField"); } /** * @class InputFile * @alias InputFile * @namespace Base.web.form * @author Saulo Vallory * @version 0.9 * * @requires Base.web.VisualComponent * @requires Base.web.form.FormField * * @param {HTMLElement} elem */ InputFile = function InputFile(elem) { (VisualComponent.bind(this))(); (FormField.bind(this))(); if (typeof elem == 'undefined') { var elem = document.createElement('input'); elem.type = 'file'; } this.initialize(elem); }; Object.extend(InputFile.prototype, VisualComponent.prototype); Object.extend(InputFile.prototype, FormField.prototype); Object.extend(InputFile.prototype, { phpClass : "FileUpload", /** * * @param {HTMLElement} elem */ initialize : function InputFile_initialize (elem) { (Component.prototype.initialize.bind(this, elem))(); this.realElement = elem; } }); if(typeof Base !== "undefined") { Base.provide("web.form.Label"); Base.require("web.VisualComponent"); Base.require("web.Container"); Base.require("web.form.FormField"); } Label = function Label(elem) { (FormField.bind(this))(); (VisualComponent.bind(this))(); (Container.bind(this))(); if (typeof elem == "undefined") { var elem = document.createElement('label'); } this.initialize(elem); }; Object.extend(Label.prototype, VisualComponent.prototype); Object.extend(Label.prototype, Container.prototype); Object.extend(Label.prototype, FormField.prototype); Object.extend(Label.prototype, { parent : VisualComponent, phpClass : "Label", /** * @param {HTMLElement} elem */ initialize : function Label_initialize (elem) { (Component.prototype.initialize.bind(this, elem))(); if (typeof elem == "undefined" || elem == null) { Base.raise("Error in initialize Label component.", new Error("Param elem is not defined in Label__initialize.")); } else { this.realElement = elem; } } }); if(typeof Base !== "undefined") { Base.provide("web.form.OptionItem"); Base.require("web.VisualComponent"); Base.require("web.Container"); Base.require("web.form.FormField"); } /** * @class OptionItem * @alias OptionItem * @namespace Base.web.form * @author Saulo Vallory * @version 0.9 * * @requires Base.web.VisualComponent * @requires Base.web.form.FormField * * @param {HTMLElement} elem */ OptionItem = function OptionItem(elem) { (VisualComponent.bind(this))(); (FormField.bind(this))(); (Container.bind(this))(); if (typeof elem == "undefined" || elem == null) { var elem = document.createElement('option'); } this.initialize(elem); }; Object.extend(OptionItem.prototype, VisualComponent.prototype); Object.extend(OptionItem.prototype, Container.prototype); Object.extend(OptionItem.prototype, FormField.prototype); Object.extend(OptionItem.prototype, { parent : VisualComponent, parentObject : null, phpClass : "OptionItem", oldSelectedValue : null, /** * @param {HTMLElement} elem */ initialize : function OptionItem_initialize(elem) { (Component.prototype.initialize.bind(this, elem))(); if (typeof elem == "undefined" || elem == null) { var elem = document.createElement('option'); } this.realElement = elem; this.oldSelectedValue = this.realElement.selected; elem.onchange = this._raiseChange.bind(this); }, getParentObject : function OptionItem_getParentObject() { return this.parentObject; }, /** * @param {Object} obj */ setParentObject : function OptionItem_setParentObject(obj) { this.parentObject = obj; }, /** * @return boolean */ isSelected : function OptionItem_isSelected() { return (this.realElement.selected === true); }, /** * @param {Boolean} trueOrFalse * setSelected : function OptionItem_setSelected(trueOrFalse, noRaise) { this.realElement.selected = trueOrFalse; this.set('selected',trueOrFalse); },*/ /** * @param string */ setText : function OptionItem_setText(textValue) { this.removeChildren(); this.addChild(textValue, true); this.realElement.innerHTML = textValue; }, /** * @param {Event} e */ _raiseChange: function _raiseChange(e) { this.onPropertyChange.raise(this, {event:e, changeType : ChangeType.PROPERTY_CHANGED, propertyName : "selected", oldValue : this.oldSelectedValue}); this.oldSelectedValue = this.realElement.selected; } }); if(typeof Base !== "undefined") { Base.provide("web.form.DropDownList"); Base.require("web.form.OptionItem"); Base.require("web.VisualComponent"); Base.require("web.Container"); Base.require("web.form.FormField"); } /** * @class DropDownList * @alias DropDownList * @namespace Base.web.form * @author Saulo Vallory * @version 0.9 * * @requires Base.web.Container * @requires Base.web.VisualComponent * @requires Base.web.form.FormField * @requires Base.web.form.OptionItem * * @param {HTMLElement} elem */ DropDownList = function DropDownList(elem) { (VisualComponent.bind(this))(); (Container.bind(this))(); (FormField.bind(this))(); if (typeof elem == "undefined") elem = document.createElement("select"); this.initialize(elem); this.options = this.children; }; Object.extend(DropDownList.prototype, VisualComponent.prototype); Object.extend(DropDownList.prototype, FormField.prototype); Object.extend(DropDownList.prototype, Container.prototype); Object.extend(DropDownList.prototype, { parent : VisualComponent, options : null, oldSelectedIndex : null, phpClass : "DropDownList", /** * @param {HTMLElement} elem */ initialize : function DropDownList_initialize(elem) { if(typeof elem["tagName"] == "undefined" || elem.tagName.toLowerCase() != 'select') { console.error("DropDownList::addOption :> First parameter should be an HTMLSelectElement"); return false; } (Component.prototype.initialize.bind(this, elem))(); this.realElement = elem; // carregando os filhos for(var i=0; i < elem.options.length; i++) { var op = Base.getComponentById(elem.options[i].id); if (op == null) { op = new OptionItem(elem.options[i]); Base.addComponent(op); } this.addChild(op, true); op.setParentObject(this); } //definindo valores iniciais this.oldSelectedIndex = elem.selectedIndex; var oldOnChange = this.realElement.onchange; // estranhamente, se jogar direto pra this.onChangeListeners não funciona no IE this.realElement.onchange = null; if (window.addEventListener) // Mozilla like { if(oldOnChange) this.onChangeListeners = oldOnChange; this.realElement.addEventListener('change', this._raiseChange.bind(this),false); } else if (window.attachEvent) // IE { if(oldOnChange) this.onChangeListeners = oldOnChange; this.realElement.attachEvent('onchange', this._raiseChange.bind(this)); } return true; }, /** * @param {OptionItem, HTMLElement} opt * @return boolean */ addOption : function DropDownList_addOptionItem (opt, noRaise) { if(!opt || typeof opt != "object" || (Base.isComponent(opt) && opt.get("phpClass") != "OptionItem")) { console.error("DropDownList::addOption :> First parameter should be an HTMLOptionElement or an OptionItem"); return false; } if(typeof opt["tagName"] != "undefined") { if(opt.tagName.toLowerCase() != "option") { console.error("DropDownList::addOption :> First parameter should be an HTMLOptionElement or an OptionItem"); return false; } if(!opt.id) { console.error("DropDownList::select :> It's impossible to find the component for an element without id"); return false; } var comp = Base.getComponentById(opt.id); if(!comp) { console.warn("DropDownList::select :> Component for the element " + opt.id + " could not be found. Creating a new one."); opt = new OptionItem(opt); } else opt = comp; } //Adicionando Objeto this.options.add(this.options.count(),opt); //Adicionando Elemento HTML if(Base.environment.browser.name == "IE") this.realElement.add(opt.realElement); else this.realElement.add(opt.realElement, null); //Adjustando propriedade "parentObject" opt.setParentObject(this); if (noRaise == undefined || noRaise == false) { this.onChildAdd.raise(this, {changeType : ChangeType.CHILD_ADDED, child : opt}); } return true; }, /** * @param {int} i */ getOption : function DropDownList_getOption(i) { return this.options.get(i); }, getSelectedOption : function DropDownList_getSelectedOption() { var index = this.realElement.selectedIndex; if(index < 0) return null; return this.options.get(this.realElement.selectedIndex); }, /** * Remove uma opcão por índice, pelo Elemento HTML ou pelo próprio objeto * @param {int,HTMLElement,OptionItem} obj * @return OptionItem */ removeOption : function DropDownList_removeOption(elem, noRaise) { var index = -1; if(typeof elem == "number") { index = elem; } else if(typeof obj == "object" && Base.isComponent(obj)) { index = elem.get("index"); } else if(typeof elem.tagName == "undefined" && elem.tagName.toLowerCase() == 'option') { index = elem.index; } if(index < 0 || index > this.options.count()) return null; this.realElement.remove(index); var opt = this.options.remove(index); if (noRaise == undefined || noRaise == false) { this.onChildRemove.raise(this, {changeType : ChangeType.CHILD_REMOVED, child : opt} ); } return opt; }, /** * @param {OptionItem,int} opt * @return {boolean} */ select : function DropDownList_select(opt) { if(typeof opt == "number") { if(opt < 0) { console.warn("DropDownList::select :> The index should positive"); return false; } if(opt > this.options.count()) { console.warn("DropDownList::select :> Index out of bounds"); return false; } opt = this.options.get(opt); } else if(typeof opt != "object") { return false; } else if(typeof opt["tagName"] != "undefined" && opt.tagName.toLowerCase() == "option") { if(!opt.id) { console.error("DropDownList::select :> It's impossible to find the component for an element without id"); return false; } var comp = Base.getComponentById(opt.id); if(!comp) { console.warn("DropDownList::select :> Component for the element " + opt.id + " could not be found. Creating a new one."); opt = new OptionItem(opt); } else opt = comp; } this.oldSelectedIndex = this.realElement.selectedIndex; this.realElement.selectedIndex = opt.get("index"); this.onPropertyChange.raise(this, {changeType : ChangeType.PROPERTY_CHANGED, propertyName : "selectedIndex", oldValue : this.oldSelectedIndex} ); return true; }, /** * @param {Event} e * @private */ _raiseChange: function _raiseChange(e) { this.onPropertyChange.raise(this, {event:e, changeType : ChangeType.PROPERTY_CHANGED, propertyName : "selectedIndex", oldValue : this.oldSelectedIndex} ); this.oldSelectedIndex = this.realElement.selectedIndex; if(this.onChangeListeners) this.onChangeListeners(e); } }); if(typeof Base !== "undefined") { Base.provide("web.form.ListBox"); Base.require("web.form.OptionItem"); Base.require("web.VisualComponent"); Base.require("web.Container"); Base.require("web.form.FormField"); } /** * @class ListBox * @alias ListBox * @namespace Base.web.form * @author Saulo Vallory * @version 0.9 * * @requires Base.web.VisualComponent * @requires Base.web.form.FormField * * @param {HTMLElement} elem */ ListBox = function ListBox(elem) { (VisualComponent.bind(this))(); (Container.bind(this))(); (FormField.bind(this))(); if ( (typeof elem == "undefined") || elem == null) { var elem = document.createElement('select'); } this.initialize(elem); }; Object.extend(ListBox.prototype, VisualComponent.prototype); Object.extend(ListBox.prototype, FormField.prototype); Object.extend(ListBox.prototype, Container.prototype); Object.extend(ListBox.prototype, { parent : VisualComponent, isMultiple : null, optionItems : [], oldSelectedOptionItems : [], selectedOptionItems : null, oldSelectedIndex : null, selectedIndex : null, phpClass : "ListBox", /** * @param {HTMLElement} elem */ initialize : function ListBox_initialize (elem) { if ( (elem != null) && elem.tagName.toUpperCase() == 'SELECT') { // construtor da classe pai (Component.prototype.initialize.bind(this, elem))(); this.realElement = elem; // instanciando arrays de opções e índices this.optionItems = []; if( elem.multiple ) { this.oldSelectedOptionItems = []; this.selectedOptionItems = []; this.oldSelectedIndex = []; this.selectedIndex = []; } else { this.oldSelectedOptionItems = null; this.selectedOptionItems = elem.selectedIndex > -1 ? elem.options[elem.selectedIndex] : null; this.oldSelectedIndex = null; this.selectedIndex = elem.selectedIndex; } this.isMultiple = elem.multiple; // instanciando as opções do select for (var i=0; i < elem.options.length; i++) { // verifica se o componente já foi instanciado var op = base.getComponentById(elem.options[i].id); // se não foi, cria e adiciona if (typeof op == "undefined" || op == null) { op = new OptionItem(elem.options[i]); base.addComponent(op); } // adiciono o filho e a referencia para o pai this.optionItems[this.optionItems.length] = op; op.setParentObject(this); // pegando o array de itens selecionados, caso o valor seja "multiple" if (this.isMultiple) { if (op.realElement.selected == true) { this.selectedIndex.push(i); this.selectedOptionItems.push(elem.options[i]); } } } /* if ((this.selectedOptionItems == null || this.selectedOptionItems.length == 0) && this.optionItems.length > 0 ) { this.setSelectedOption(this.optionItems[0]); } */ var oldOnChange = this.realElement.onchange; // estranhamente, se jogar direto pra this.onChangeListeners não funciona no IE this.realElement.onchange = null; if (window.addEventListener) // Mozilla like { if(oldOnChange) this.onChangeListeners = oldOnChange; this.realElement.addEventListener('change', this._raiseChange.bind(this),false); } else if (window.attachEvent) // IE { if(oldOnChange) this.onChangeListeners = oldOnChange; this.realElement.attachEvent('onchange', this._raiseChange.bind(this)); } return true; } return false; }, /** * @param {HTMLElement} elem * @param {boolean} noRaise * * @return {boolean} */ addOption : function ListBox_addOption (elem, noRaise) { if (elem.tagName.toLowerCase() == "option") { var op = new OptionItem(elem); return this.addOptionItem(op, noRaise); } return false; }, /** * @classDescription Adicionando um novo OptionItem * @param {OptionItem} op * @param {boolean} noRaise */ addOptionItem : function ListBox_addOptionItem (op, noRaise) { if (op.get("tagName") == "OPTION") { if (op.get("selected")) this.setSelectedOption(op); //Adicionando Objeto this.optionItems[this.optionItems.length] = op; //Adicionando Elemento HTML this.realElement.add(op.realElement, null); //Setando propriedade "parentObject" op.setParentObject(this); if (typeof(noRaise) == "undefined" || noRaise == false) this.onChildAdd.raise(this, {changeType : Change.CHILD_ADDED, child : op} ); return true; } return false; }, changeSelected : function ListBox_changeSelected () { if(!this.isMultiple) { this.oldSelectedIndex = this.selectedIndex; this.selectedIndex = this.realElement.selectedIndex; if(this.selectedIndex != -1) { this.oldSelectedOptionItems = this.selectedOptionItems; this.selectedOptionItems = this.realElement.options[this.selectedIndex]; } } else { var newSelected = []; var newSelectedIndex = []; for (var i = 0; i < this.realElement.options.length; i++) { if (this.realElement.options[i].selected == true) { newSelected.push(this.optionItems[i]); newSelectedIndex.push(i); } } this.oldSelectedIndex = this.selectedIndex; this.selectedIndex = newSelectedIndex; this.oldSelectedOptionItems = this.selectedOptionItems; this.selectedOptionItems = newSelected; } }, /** * @return {[int] | [array]} */ getOldValue : function ListBox_getOldValue () { if (this.isMultiple == false) { return this.oldSelectedIndex; } var arraySelInd = []; for (var i = 0; i < this.oldSelectedOptionItems.length; i++) { arraySelInd[i] = this.oldSelectedOptionItems[i].get("index"); } return arraySelInd; }, getSelectedIndex : function ListBox_getSelectedIndex() { return this.realElement.selectedIndex; }, /** * @param {OptionItem} op * @return {boolean} */ isChild : function ListBox_isChild (op) { var found = false; for (var i = 0; (i < this.optionItems.length) && found == false; i++) { if (this.optionItems[i].get("id") == op.get("id")) found = true; } return found; }, /** * @classDescription Se o objeto estiver selecionado então retorna o seu indice no array de elementos selecionados * @param {OptionItem} op * @return {boolean} */ isSelected : function ListBox_isSelected (op) { var indexSelected = -1; if (this.isMultiple) { for (var i=0; (i < this.selectedOptionItems.length) && (indexSelected == -1); i++) { if (this.selectedOptionItems[i].get("id") == op.get("id")) indexSelected = i; } } else { if (this.isChild(op) && this.selectedIndex == op.get("index")) indexSelected = op.get("index"); } return indexSelected; }, /** * @classDescription Removendo, por índice, um OptionItem do array "optionItems" * @param {int} i * @return {boolean} */ removeOptionByIndex : function ListBox_removeOptionByIndex (i, noRaise) { if (0<=i && i toCompareValue) { result = true; } break; case this._LESS_OR_EQUAL: if(fieldValue <= toCompareValue) { result = true; } break; case this._GREATER_OR_EQUAL: if(fieldValue >= toCompareValue) { result = true; } break; default: if(fieldValue === toCompareValue) { result = true; } } return result; } }); if(typeof Base != "undefined") { Base.provide("web.form.validator.CustomValidator"); Base.require("web.form.validator.BaseValidator"); } /** * @class CustomValidator * @alias CustomValidator * @namespace Base * @author Saulo Vallory * @version 0.9 */ CustomValidator = function CustomValidator(){ // chamando o construtor da classe pai (BaseValidator.bind(this))(); }; // extends Component Object.extend(CustomValidator.prototype, BaseValidator.prototype); // definição de métodos e propriedades Object.extend(CustomValidator.prototype, { jsFunction: null, validateFunction: null, setJSFunction: function CustomValidator_setJSFunction(jsFunction) { this.jsFunction = jsFunction; this.setLastValidationField(3, false); }, getJSFunction: function CustomValidator_getJSFunction() { return this.jsFunction; }, doValidation: function RegExValidator_doValidation() { var fieldValue = this.getFieldToValidate.get(1); var validTest = this.getLastValidationField(3); if(validTest === true) { var lastValue = this.getLastValidationField(1); if(lastValue === fieldValue) { var result1 = this.getLastValidationField(2); if((typeof result1) === 'boolean') { return result1; } } } var result; eval("result = " + this.jsFunction + "('" + fieldValue + "');"); this.setLastValidationField(1, fieldValue); this.setLastValidationField(2, result); this.setLastValidationField(3, true); return result; } }); if(typeof Base != "undefined") { Base.provide("web.form.validator.RangeValidator"); Base.require("web.form.validator.BaseValidator"); } /** * @class RangeValidator * @alias RangeValidator * @namespace Base * @author Saulo Vallory * @version 0.9 */ RangeValidator = function RangeValidator(){ // chamando o construtor da classe pai (BaseValidator.bind(this))(); }; // extends Component Object.extend(RangeValidator.prototype, BaseValidator.prototype); // definição de métodos e propriedades Object.extend(RangeValidator.prototype, { minValue: 0, maxValue: -1, strictComparison: false, setMinValue: function RangeValidator_setMinValue(minValue) { if(((typeof minValue) === 'number') && (minValue !== this.minValue)) { this.minValue = minValue; this.setLastValidationField(3, false); } }, getMinValue: function RangeValidator_getMinValue() { return this.minValue; }, setMaxValue: function RangeValidator_setMaxValue(maxValue) { if(((typeof maxValue) === 'number') && (maxValue !== this.maxValue)) { this.maxValue = maxValue; this.setLastValidationField(3, false); } }, getMaxValue: function RangeValidator_getMaxValue() { return this.maxValue; }, setStrictComparison: function RangeValidator_setStrictComparison(strictComparison) { if(((typeof strictComparison) === 'boolean') && (this.strictComparison !== strictComparison)) { this.strictComparison = strictComparison; this.setLastValidationField(3, false); } }, getStrictComparison: function RangeValidator_getStrictComparison() { return this.strictComparison; }, doValidation: function RangeValidator_doValidation() { var fieldValue = this.getFieldToValidate.get(1); var validTest = this.getLastValidationField(3); if(validTest === true) { var lastValue = this.getLastValidationField(1); if(lastValue === fieldValue) { var result1 = this.getLastValidationField(2); if((typeof result1) === 'boolean') { return result1; } } } this.setLastValidationField(1, fieldValue); this.setLastValidationField(3, true); var result = false; if(this.strictComparison) { if(this.minValue >= 0) { if(fieldValue.length > this.minValue) { if(this.maxValue > this.minValue) { if(fieldValue.length < this.maxValue) { result = true; } } else { result = true; } } } else { if(this.maxValue > 0) { if(tamValue < this.maxValue) { result = true; } } else { result = true; } } } else { if(this.minValue >= 0) { if(fieldValue.length >= this.minValue) { if(this.maxValue >= this.minValue) { if(fieldValue.length <= this.maxValue) { result = true; } } else { result = true; } } } else { if(this.maxValue >= 0) { if(fieldValue.length <= this.maxValue) { result = true; } } else { result = true; } } } this.setLastValidationField(2, result); return result; } }); if(typeof Base != "undefined") { Base.provide("web.form.validator.RegExValidator"); // informa que esse arquivo foi carregado Base.require("web.form.validator.BaseValidator"); // require normal, é tipo o import do Base } /** * @class RegExValidator * @alias RegExValidator * @namespace Base * @author Saulo Vallory * @version 0.9 */ RegExValidator = function() { // chamando o construtor da classe pai (BaseValidator.bind(this))(); }; // extends Component Object.extend(RegExValidator.prototype, BaseValidator.prototype); // definição de métodos e propriedades Object.extend(RegExValidator.prototype, { expression: '', setExpression: function RegExValidator_setExpression(newExpression) { this.expression = newExpression.toString(); this.setLastValidationField(3, false); }, getExpression: function RegExValidator_getExpression() { return this.expression; }, doValidation: function RegExValidator_doValidation() { var fieldValue = this.getFieldToValidate.get(1); var validTest = this.getLastValidationField(3); if(validTest === true) { var lastValue = this.getLastValidationField(1); if(lastValue === fieldValue) { var result1 = this.getLastValidationField(2); if((typeof result1) === 'boolean') { return result1; } } } this.setLastValidationField(1, fieldValue); this.setLastValidationField(3, true); var result = false; var re = new RegExp(this.expression); if(fieldValue.match(re)) { result = true; } this.setLastValidationField(2, result); return result; } }); RegExValidator.CommonExp = { Date : /(0[1-9]|[12][0-9]|3[01])([- \/.])(0[1-9]|1[012])\2(19|20)\d\d$/, Time : /^(\d{1,2})\:(\d{1,2})\:(\d{1,2})$/, Alpha : /^[a-zA-Z\.\-]*$/, AlphaNum : /^\w+$/, UnsignedInt : /^\d+$/, Integer : /^[\+\-]?\d*$/, Real : /^[\+\-]?\d*\.?\d*$/, UnsignedReal : /^\d*\.?\d*$/, Email : /^[\w-\.]+\@[\w\.-]+\.[a-z]{2,6}$/, Phone : /^[\d\.\s\-]+$/ }; if(typeof Base != "undefined") { Base.provide("web.form.validator.RequiredFieldValidator"); Base.require("web.form.validator.BaseValidator"); } /** * @class Style * @alias Style * @namespace Base * @author Saulo Vallory * @version 0.9 */ RequiredFieldValidator = function RequiredFieldValidator(){ // chamando o construtor da classe pai (BaseValidator.bind(this))(); }; // extends Component Object.extend(RequiredFieldValidator.prototype, BaseValidator.prototype); // definição de métodos e propriedades Object.extend(RequiredFieldValidator.prototype, { doValidation : function RequiredFieldValidator_doValidation() { fieldValue = this.getFieldToValidate.get('value'); fieldValue = fieldValue.toString(); result = false; if(fieldValue.length > 0) { result = true; } return result; } }); if(typeof Base !== "undefined") { Base.provide("web.Button"); Base.require("web.VisualComponent"); } /** * @class Button * @alias Button * @namespace Base.web * @author Saulo Vallory * @version 0.9 * * @requires VisualComponent * * @constructor */ Button = function Button(elem) { (Container.bind(this))(); (VisualComponent.bind(this))(); (FormField.bind(this))(); if (typeof elem == "undefined") { var elem = document.createElement('button'); if (elem.type != 'button') { try { elem.type = 'button'; } catch(e){} } } this.initialize(elem); }; Object.extend(Button.prototype, Container.prototype); Object.extend(Button.prototype, VisualComponent.prototype); Object.extend(Button.prototype, FormField.prototype); Object.extend(Button.prototype, { items : null, phpClass : "Button", /** * @param {HTMLElement} elem */ initialize : function Button_initialize (elem) { (Component.prototype.initialize.bind(this, elem))(); this.realElement = elem; this.items = []; }, /** * @param {Object} item */ addItem : function Button_addItem(item, noRaise) { if (typeof(item) == "object" && item.getAttribute("phpclass") == "Image") { //Adicionando Objeto this.items[this.items.length] = item; //Adicionando Elemento HTML this.realElement.appendChild(item.realElement); if (typeof(noRaise) !== "undefined" || noRaise == false) { this.onChildAdd.raise(this,{ changeType : ChangeType.CHILD_ADDED, child : item}); } } else if (typeof(item) == "string") { this.items[this.items.length] = item; if (typeof(noRaise) !== "undefined" || noRaise == false) { this.onChildAdd.raise(this,{ changeType : ChangeType.CHILD_ADDED, child: item }); } } }, /** * @param {Object} item * @param {boolean} noRaise */ removeItem : function Button_removeItem(item, noRaise) { var found = false; for (var i = 0; (i < this.items.length) && found == false; i++) { if (this.items[i] == item) found == true; } if (found == true) { return this.removeItemByIndex(i, noRaise); } return false; }, /** * @param {HTMLElement} i * @param {boolean} noRaise */ removeItemByIndex : function Button_removeItemByIndex (i, noRaise) { if (0<=i && i