/**
LK Comunicação & Marketing
2008
@Biblioteca natural de funções JavaScript.
@Modelo 2.0
Revisado por: Pedro Henrique Menez Xudré
Última alteração: 3 de Junho de 2008
Atualizações:
* Criação da classe LAY para a manipulação de camadas e conformidades para o modelo TABLELESS.
* Revisão da classe XML e inclusão de funções de tratamento dos dados recebidos.
* Revisão da classe DOM, tornando a manipulação interna ao objeto e não mais pela classe.
* Revisão na descrição de cada função.
Glossário:
* NI : Não Inicializável, a classe / objeto não precisa ser inicializado para cumprir com suas funções.
* IO : Inicializável Opcional, a classe / objeto pode ser inicializada quando ouver necessidade de personalização.
* SI : Somente Inicializável, a classe / objeto necessita de parâmetros de inicialização, assim como uma possivel associação à um objeto externo.
*/
// Declaração de variáveis locais:
undefined = null;
// Implementação de Classes padrão no JavaScript:
String.prototype.me = function() {
return this;
};
String.prototype.trim = function() {
return this.replace(/^\s{1,}|\s{1,}$/gim, '');
};
/*function OBJ_length(listAll) {
var n=0;
for(i in this)
if(listAll||(typeof(this[i])!="function"&&typeof(this[i])!="undefined"))
n++;
return n;
}
Object.addProperty(length, OBJ_length, null);*/
/*Object.prototype.length = function(listAll) {
var n=0;
for(i in this)
if(listAll||(typeof(this[i])!="function"&&typeof(this[i])!="undefined"))
n++;
return n;
};*/
// Declaração das Classes:
var COOKIE; // (NI) Classe manipuladora de Cookies do Usuário.
var CORE; // (NI) Classe manipuladora do Navegador.
var CSS; // (NI) Classe manipuladora de Folhas de Estilo.
var DOM; // (NI) Classe manipuladora de Objetos.
var FLA; // (SI) Classe manipuladora de SWF.
var JS; // (NI) Classe manipuladora de JavaScript.
var LAY; // (SI) Classe manipuladora de camadas. (TABLELESS)
var NATURE; // (NI) Classe interna de manipulação dos padrões da biblioteca.
var XML; // (IO) Classe de comunicação AJAX.
COOKIE = {
};
CORE = {
agentNatural: function() {
var kind, n;
kind = ['Firefox', 'InternetExplorer 6 and prior', 'Mozilla', 'Opera', 'Safari'];
if(/firefox/i.test(navigator.userAgent)) n=0;
else if(/msie ?(?:5\.0[0-9]*|[6-9])/i.test(navigator.userAgent)) n=1;
else if(/gecko\/200[3456]/i.test(navigator.userAgent)) n=2
else if(/opera/i.test(navigator.userAgent)) n=3;
else if(/safari/i.test(navigator.userAgent)) n=4;
return kind[n];
},
agent: function(n) {
var ok=false;
if(CORE.agentNatural()==n) ok=!ok;
return ok;
},
location: null
};
CSS = {
};
DOM = {
feed: function(who) {
switch(typeof(who)) {
case 'string':
break;
case 'object':
break;
default:
break;
}
},
get: function(id) {
// @Adquire o item pelo ID setado ou, após falha, encontra pela TAG e por último se nada for adquirido faz a tentativa por atributo setado.
if(typeof(id)=="string") {
if(document.all) id = document.all[id];
else if(document.getElementById) id = document.getElementById(id);
}
return typeof(id)=="object" ? id : null;
},
length: function(me) {
if(!me) me = this;
var n=0;
for(i in me)
if(listAll||(typeof(me[i])!="function"&&typeof(me[i])!="undefined"))
n++;
return n;
},
replaceContent: function(on, content) {
if((on=DOM.get(on))!=null) on.innerHTML = content;
},
serialize: function(on) {
// @Transforma objetos em um String única contendo nomes e valores das variáveis.
var _tmp;
switch(typeof(on)) {
case 'object':
_tmp = new Array();
for(att in on)
if(typeof(on[att])=="string"||typeof(on[att])=="number")
_tmp.push(att+"="+on[att]);
_tmp = _tmp.join("&");
break;
case 'array': _tmp = "p[]="+on.join("&p[]="); break;
case 'string': _tmp = on.trim(); break; // /[\x26\x3D]{4,}/i.test(on) ? on : null
default: _tmp = null;
}
return _tmp;
},
token: {
from: ['&', '<', '>'],
to: ['#00#', '#01#', '#02#']
},
tokenize: function(text, rev) {
// Realiza a codificação do conteúdo XML/AJAX.
var __reg, __to, __walk;
// if(rev) text = text^'ahdfls.sdue:9912';
__walk = Math.min(this.token.from.length, this.token.to.length);
for(var i=0; i<__walk; i++) {
__reg = !rev ? new RegExp(this.token.from[i], "gim") : new RegExp(this.token.to[i], "gim") ;
__to = !rev ? this.token.to[i] : this.token.from[i];
text = text.replace(__reg, __to);
}
return text; // !rev ? text^'ahdfls.sdue:9912' : new String(text);
},
untokenize: function(text) {
// Realiza a decodificação do conteúdo XML/AJAX.
return this.tokenize(text, true);
}
};
FLA = function(movie, name) {
// @Inicializa e seta valores para a Classe FLA.
if(typeof(movie)=="string") this.__swf = new String(movie).trim();
else throw new Error("FALHA: Arquivo SWF não definido.");
if(typeof(name)=="string") this.__id = new String(name).trim();
JS.SWF[name] = this;
};
FLA.prototype = {
// @Classe de ações para integração Flash e JavaScript.
_def: {
version: '9,0,0,0',
menu: 'false',
quality: 'best',
loop: 'false',
scale: 'noscale',
wmode: 'transparent',
allowScriptAccess: 'sameDomain',
flashvars: null,
width: '100%',
height: '100%'
},
draw: function(width, height, vars) {
var mod = false;
if((width!=null&&width!=this._def.width)||(height!=null&&height!=this._def.height)||(typeof(vars)=='string'&&vars!=this._def.flashvars)) mod = true;
if(mod||this.__fla==null) document.write(this.init(width, height, vars));
else document.write(this.__fla);
},
__fla: null,
init: function(width, height, vars) {
// @Retorna a estrutura HTML do SWF com as predefinições.
var fla = new String();
var _no = /^(?:id|version|width|height)$|^_/i;
var _attKind = /string|number|boolean/i;
this._def.width = width = width!=null ? width : this._def.width;
this._def.height = height = height!=null ? height : this._def.height;
if(vars) this._def.flashvars = DOM.serialize(vars);
if(CORE.agent(1)) {
fla += '';
} else {
fla += '';
}
return (this.__fla = new String(fla));
},
__id: new String('fla'),
__swf: null
};
JS = {
parse: function(html) {
// @Verifica a existência de códigos JavaScript no conteúdo e os executa.
var _tmp = new String(html);
var _reg = new RegExp("(]{0,}>)(.{1,})(?=<\/script>)<\/script>", "im");
var _cmd = _reg.exec(_tmp);
if(_cmd!=null) {
if(_cmd[2].indexOf('<\/script>')!=-1) {
_cmd[2] = _cmd[2].substr(0, _cmd[2].indexOf('<\/script>'));
_cmd[0] = _cmd[1]+_cmd[2]+'<\/script>';
}
var _regSwf = new RegExp("([a-z0-9_.-]{1,})\.draw\\x28[a-z0-9, -]*\\x29;?", "im");
var _swf = _regSwf.exec(_cmd[2]);
_cmd[2] = _swf ? _cmd[2].replace(_regSwf, '').trim() : _cmd[2];
if(_swf) eval(_cmd[2]);
this.__flow += _cmd[2];
var _fla = _swf ? this.SWF[_swf[1]].init() : '';
_tmp = _tmp.replace(_cmd[0], _fla.trim());
if(_reg.test(_tmp)) _tmp = this.parse(_tmp);
}
return DOM.untokenize(_tmp);
},
process: function() {
// @Faz o pós-processamento dos comandos JavaScript encontrados no conteúdo.
if(this.__flow!='') {
eval(this.__flow);
this.__flow = '';
}
},
SWF: {},
__flow: new String()
};
LAY = function(id, index) {
};
LAY.prototype = {
move: function(top, left) {
},
visible: true,
__check: function() {
}
};
NATURE = {
};
XML = function(path, load_text) {
if(typeof(path)=="string") this.__p = new String(path).trim();
if(typeof(load_text)=="string") this.__lt = new String(load_text).trim();
this.__init();
};
XML.prototype = {
build: function() {
var xml=false;
var foundrie = {
dom: function() { return new XMLHttpRequest(); },
msxml3: function() { return new ActiveXObject('Msxml3.XMLHTTP'); },
msxml2_5: function() { return new ActiveXObject('Msxml2.XMLHTTP.5.0'); },
msxml2_3: function() { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); },
msxml2: function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
msnative: function() { return new ActiveXObject('Microsoft.XMLHTTP'); }
};
for(f in foundrie) { try { xml=foundrie[f](); } catch(e) { continue; } break; }
if(CORE.agent(1)) delete xml.length;
return !xml ? null : xml;
},
__callback: function(on, result) {
var _tmp;
_tmp = JS.parse(DOM.untokenize(result));
DOM.replaceContent(on, _tmp);
JS.process();
},
__init: function() {
this.__xml = new this.build();
if(!this.__xml) { alert("FALHA: Erro na criação do módulo XML."); }
},
load: function(on, vars, method, path, callback, response) {
// @Contacta o arquivo e carrega o conteudo XML. Retorna TRUE para sucesso ou FALSE em caso de falhas.
var _xml, _type, pass = false, _this = this;
if(this.__xml==null) { alert("FALHA: Classe XML não inicializada."); return false; }
if(path==null&&this.__p==null) { alert("FALHA: Caminho para o XML não estabelecido."); return false; }
method = String(method).toLowerCase()!="get" ? "POST" : "GET";
_type = method=="POST" ? "application/x-www-form-urlencoded" : "text/html";
path = path!=null ? new String(path).trim() : _this.__p;
callback = typeof(callback)=="fucntion" ? callback : _this.__callback;
_xml = _this.__xml;
try {
// if(CORE.agent(1)) _xml = new build();
_xml.open(method, path, true);
pass = true;
} catch(e) { alert("FALHA: Não foi possivel inicializar o objeto XML."); return false; }
if(pass) {
_this.loaded = false;
try {
_xml.setRequestHeader("Content-Type", _type+"; charset=iso-8859-1");
_xml.setRequestHeader("Cache-Control", "no-cache; must-revalidate");
if(CORE.agent(1)) _xml.setRequestHeader("Pragma", "no-cache; must-revalidate");
_xml.setRequestHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
} catch(e) { alert("AVISO: Não foi possivel definir cabeçalhos ao XML."); }
_xml.onreadystatechange = function() {
if(_xml.readyState!=4) {
if((on=DOM.get(on))!=null) DOM.replaceContent(on, _this.__lt);
return false;
}
if((on=DOM.get(on))!=null) {
if(_xml.status==200) {
callback(on, _xml.responseText);
_this.response = _xml.responseText;
return (_this.loaded=true);
} else alert("("+_xml.status+") FALHA: o arquivo destino do XML parece estar corrompido.");
}
return false;
};
try {
vars = DOM.serialize(vars);
if(DOM.get(on)!=null) vars += "&inner="+on;
_xml.send(vars);
pass = true;
} catch(e) { alert("FALHA: Não foi possível enviar solicitação."); return false; }
}
return pass;
},
loaded: null,
__lt: new String("Carregando..."),
__on: null,
__p: null,
response: null,
send: function(vars, response, method, path) {
return this.load(null, vars, method, path, null, response);
},
sended: null,
__xml: null
};