/************************************************* * BaLHau LIB * Esta biblioteca foi desenvolvida por Vítor Hugo Fernandes, a.k.a BaLHau * @author Balhau */ /** * Método que devolve os elementos que contém uma determinada className * @param cls {@link String} nome da class * @return {@link Array} contendo os elementos de uma determinada class */ var getByClassName=function(cls){ var el=document.getElementsByTagName('*'); var out=[]; for(var i=0;i=10?vmin:"0"+vmin; var hora=vhor>=10?vhor:"0"+vhor; var seg=(totseg%60)>=10?totseg%60:"0"+totseg%60; var rt=""; rt=(hora>0)?hora+":":""; rt+=min+":"+seg; return rt; }; /** * Método que devolve os valores representados numa string URL no formato GET * @return {Object} Variaveis e seus respectivos valores */ String.prototype.getVarsFromUrl=function(){ var aux=this.split("?"); if(aux.length==0) return {}; var vars=aux[1].split("&"); var out={}; var par=""; for(var i=0;i"; document.body.appendChild(dcont); var frm=$(id); if(callbackobject){ if(typeof(callbackobject.onComplete)=="function") frm.onComplete=callbackobject.onComplete; } return id; } BLauLib.AIM.form=function(formE,name){ formE.setAttribute('target',name); } BLauLib.AIM.submit=function(formE,callbackobject){ BLauLib.AIM.form(formE, BLauLib.AIM.criaFrame(callbackobject)); if(callbackobject){ if(typeof(callbackobject.onStart)=="function") return callbackobject.onStart(); return true; }else{ return true; } } BLauLib.AIM.onLoaded=function(id){ var el=$(id); if(el.contentDocument){ var doc=el.contentDocument; } else if(el.contentWindow){ var doc=el.contentWindow.document; } else{ var doc=window.frames[id].document; } if(doc.location.href=="about:blank"){ return; } if(typeof(el.onComplete)=='function'){ el.onComplete(doc.body.innerHTML); } } /** * Método que efectua uma ligação assíncrona ao servidor * @param {String} metodo Tipo de ligação POST/GET * @param {String} urlAja Endereço da ligação */ BLauLib.Ajax.prototype.open=function(metodo,urlAja) { //Copia das estruturas devido à  não visibilidade do operador "this" dentro do método "onreadystatechange" var onLoading=this.onLoading; var onLoaded=this.onLoaded; var onError=this.onError; var ajax=this.xmlHttp; var estado=this.xmlHttp.readyState; var pthis=this; var ready=function() { if(ajax.readyState==4) { if(typeof(onLoaded)=="function"){ pthis.text=ajax.responseText; pthis.html=ajax.responseXML; onLoaded(); } } if(ajax.readyState==2){ if(typeof(onLoading)=="function"){ onLoading(); } } if(ajax.readyState==3){ if(typeof(onError)=="function"){ onError(); } } }; this.xmlHttp.onreadystatechange=ready; this.xmlHttp.open(metodo,urlAja); if(metodo=="POST"|| metodo=="post"){ this.xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); } }; /** * Método que envia uma mensagem para o servidor * @param {String} conteúdo para o servidor */ BLauLib.Ajax.prototype.send=function(conteudo) { this.xmlHttp.send(conteudo); }; /** * Devolve o dia da semana para um determinado mes de um determinado ano * @param mes Mes * @param ano Ano * @return Índice do dia da semana */ Date.getFirstDayMonth=function(mes,ano){ var d=new Date(ano,mes); d.setDate(1); return d.getDay(); }; /** * Método que devolve o número de dias de um mês * @param mes Mes que se pretende saber o numero de dias * @param ano Ano que se pretende saber o numero de dias * @return Dias 28-31 dias do mes */ Date.getNumDaysMonth=function(mes,ano){ return 32-new Date(ano,mes,32).getDate(); } BLauLib.UI={}; /** * Painel que apresenta os dados no ecran sob a forma paginada * @param {String} Id do elemento contentor * @param {Array} Array com os cabeçalhos * @param {Array} Array com os dados tabelados * @param {Number} Number com o número de elementos por página */ BLauLib.UI.NPaged=function(iddiv,aheaders,adata,nppag,css){ this.headers=aheaders; this.data=adata; this.nppage=nppag; this.divp=$(iddiv); this.tblcon=null; this.idpr=this.divp.id; this.pagenumber=1; if(typeof(css)=="undefined") this.css="npage"; else this.css=css; this.build(); }; /** * Objecto que representa um objecto calendário */ BLauLib.UI.DatePicker=function(id){ this.id=id; this.dinput=$$('input'); this.dbox=BLauLib.UI.DatePicker.buildDataBox(dinput); this.dinput.id="data_"+this.id; this.dbox.id="dataBox_"+this.id; }; /** * Método que efectua a construção do div de dados */ BLauLib.UI.DatePicker.buildDateBox=function(inputobj){ var i_obj=$(inputobj); var divbox=$$('div'); }; /** * Método que efectua a criação da tabela contentora das datas * @param {obj} Elemento associado ao calendário */ BLauLib.UI.DatePicker._createTableDate=function(obj,id){ var DS=7; var id=id; var tbody=$$('table'); //Criação do elemento table que servirá de contentor do calendário var linhas=$$('tr',DS+1); //Numero de linhas da tabela var cells=$$('td',46); //Numero de células 46, inclui dias do mes, semana, cabeçalho e rodapé tbody.className="dpTB"; tbody.id="dpTB_"+id; //Configuração do cabeçalho var btleft=$$('input'); var btright=$$('input'); var title=$$('div'); title.id="dpHeader_"+id; btleft.type="button"; btright.type="button"; btright.value=">"; btleft.value="<"; cells[1].colSpan=DS-2; cells[1].className="dpTTD"; cells[0].add(btleft); cells[1].add(title); cells[2].add(btleft); linhas[0].add(cells[0],cells[1],cells[2]); //Configuração dos dias da semana var dsem=cells.select(3,2+DS); var dsm=["Do","Se","Te","Qu","Qu","Se","Sa"]; for(var i=0;i=this.data.length) //caso o valor de n esteja fora do intervalo de dados return; if(n>=posmin && n1){ for(var i=0;i"+this+""; }; /** * Efectua a remoção de caracteres vazios à direita da string * @return {String} String sem espaços brancos à direita */ String.prototype.rtrim=function(){ var i=this.length-1; while(i>=0 && this.charAt(i)==' '){ i--; } return this.substring(0,i+1); } /** * Verifica se uma string é vazia * @return {Boolean} Valor verdadeiro caso a string seja vazia, falso caso contrário */ String.prototype.empty=function(){ return (this.trim()==''); } String.prototype.trim=function(){ return this.ltrim().rtrim(); } /** * Método que devolve um array de elementos que devolvem valor true quando passados para a função callback * @param {Function} callback Função callback que avalia o elemento * @return {Array} Array com os elementos que retornam valor true na avaliação pela função callback */ Array.prototype.where=function(callback){ var out=[]; for(var i=0;i=0;i--){ stou+=this.charAt(i); } return stou; }; /** * Método que transforma uma String num array com a sua codificação UNicode * @param {String} car Caracter separador * @return {String} Codificação Unicode separada através do caracter car */ String.prototype.toUnicodeArray=function(car){ var sb=new StringBuilder(''); for(var i=0;i b.l ? a.l <= b.r : b.l <= a.r)) && (a.t == b.t || (a.t > b.t ? a.t <= b.b : b.t <= a.b)) && (r[r.length] = l[i])); return j ? !!r.length : r; }; /** * Método que efectua a duplicação em profundidade de um determinado Elemento HTML. Quando invocado este método * cria um elemento idêntico ao elemento instanciado assim como os Elementos filhos num processo recursivo. * Os identificadores são diferentes de cópia para cópia para evitar colisões em posteriores invocações de objectos * a partir de javascript partindo do seu ID; * @param {Booleano} Variável boleana indicando o tipo de clonagem. Caso este parãmetro não seja inserido * ou seja verdadeiro a cópia é feita em profundidade, caso o valor seja falso temos unicament a cópia do elemento * sem efectuar profundidade. * @return {HElement} Devolve um objecto do tipo HElement que consiste no presente objecto duplicado */ HElement.prototype.clone = function(prof){ if(typeof(this.clones)=='undefined' || this.clones==null) this.clones=0; if(typeof(prof)=='undefined'){ prof=true; } var cln = document.createElement(this.tagName); for (i = 0; i < this.attributes.length; i++) { if (this.attributes[i].name == "id") { cln.setAttribute(this.attributes[i].name, this.attributes[i].nodeValue + "_clone_" + this.clones); } else { //cln.attributes[i]=document.createAttribute(el.attributes[i].name); cln.setAttribute(this.attributes[i].nodeName,this.attributes[i].nodeValue); if(typeof(this.innerText)!='undefined') cln.innerText=this.innerText; } } if (prof) { var filhos = this.childNodes; for (i = 0; i < filhos.length; i++) { //Elementos do tipo TEXTO if (filhos[i].nodeType == 3) { cln.appendChild(filhos[i]); } else { elF = HElement.get(filhos[i]); cln.appendChild(HElement.get(elF.clone(prof))); } } } else cln.innerHTML = this.innerHTML; return cln; }; /** * Método que coloca um elemento no centro da janela */ HElement.prototype.putAtCenter=function(){ var wd=BLauLib.Window.width(); var he=BLauLib.Window.height(); var sx=BLauLib.Window.scrX(); var sy=BLauLib.Window.scrY(); var x=wd/2+sx-this.offsetWidth/2; var y=he/2+sy-this.offsetHeight/2; this.style.position="absolute"; this.style.left=isNaN(x)?(wd/2+"px"):(x+"px"); this.style.top=isNaN(y)?(he/2+"px"):(y+"px"); } /** * Método que aplica uma função de callback aos elementos em profundidade * @param {Function} callback */ HElement.prototype.traverse=function(callback){ callback(this); for(var i=0;iminx) this.style.width=xdiff+"px"; if(ydiff>miny) this.style.height=ydiff+"px"; } /*** * Objecto que representa uma contentor janela * @classDescription Este objecto representa um contentor janela. O propósito consiste em simular um ambiente desktop * a partir de construção de um conjunto de elementos e alguns métodos associados * @param {String} nel Nome do elemento * @param {String} titulo Titulo da janela * @param {String} bdcontent Conteudo do contentor * @param {Number} dimx Dimensão em X * @param {Number} dimy Dimensão em Y */ BLauLib.Window=function(nel,titulo,bdcontent,dimx,dimy){ var nel=nel; this.dx=null; this.drag=false; this.dy=null; if(dimx && dimy){ dx=Math.max(dimx,BLauLib.Window.MIN_WIDTH); dy=Math.max(dimy,BLauLib.Window.MIN_HEIGHT); } else{ dx=300; dy=100; } this.titulo=titulo; if(!nel){ nel=BLauLib.Window.COUNT; BLauLib.Window.COUNT++; } //contentor this.contentor=$$("div"); //topbar this.tbbar=$$("div"); imgclose=$$("img"); //tabelatop var tbartable=$$("table"); tbartable.className="tbwindow"; //tbartable.setWidth(dx); //titulo this.divT=$$("div"); this.divT.innerHTML=this.titulo; this.divT.className="titleheader"; //divImgClose var divImgClose=$$("div"); divImgClose.className="imgclose"; //corpo this.bd=$$("div"); this.bd.className="wcontent"; this.contentor.className="wmain"; this.contentor.id="wd_"+nel; this.contentor.setWidth(dx); var obj=this.contentor; var tbb=this.tbbar; //top bar this.tbbar.className="wheader"; this.tbbar.id="tpbar_"+nel; //this.tbbar.setHeight(BLauLib.Window.TBAR_HEIGHT); imgclose.id="imgclose_"+nel; imgclose.src=BLauLib.Window.IMGCLOSE; var evimgclose=function(ev){ var el=HElement.get(obj); var onimgclose=function(){ el.parentNode.removeChild(el); } el.desvanece(0.2,onimgclose); } this.bd.className="wcontent"; this.bd.id="bd_"+nel; this.bd.style.minHeight=dy+"px"; this.bd.innerHTML=bdcontent; //adiciona os elementos ao top bar this.tbbar.appendChild(this.divT); divImgClose.appendChild(imgclose); this.tbbar.appendChild(divImgClose); //eventos var isto=this; this.tbbar.onmousedown=function(e){ e=e?e:window.event; isto.drag=true; var elH=HElement.get(obj); var hD=HElement.get(tbb); var pnt=elH.startDrag(e.clientX,e.clientY,null); } this.tbbar.onmouseup=function(){ document.onmousemove=null; isto.drag=false; } imgclose.onmouseup=evimgclose; this.contentor.appendChild(this.tbbar); this.contentor.appendChild(this.bd); } /** * Método que devolve o div contentor da janela */ BLauLib.Window.prototype.getContentor=function(){ return this.contentor; } /** * Método que atribui uma determinada transparência à janela * @param {Number} val Transparência, valor entre 0 e 100 */ BLauLib.Window.prototype.setAlpha=function(val){ this.contentor.setAlpha(val); } /** * Método que permite especificar o conteúdo do contentor da janela * @param {String} val String contendo o HTML que irá ficar interno ao contentor da janela */ BLauLib.Window.prototype.setBodyContent=function(val){ this.bd.innerHTML=val; } /** * Método que permite especificar o conteúdo da barra de título da janela * @param {String} titulo HTML com o conteúdo a passar para a janela de título */ BLauLib.Window.prototype.setTitle=function(titulo){ this.divT.innerHTML=titulo; } /** * Objecto Canvas que encapsular um conjunto de funcionalidades a operar sobre o objecto canvas * @classDescription Neste objecto pretende-se encapsular um conjunto de funcionalidades que irão operar sob * a tag canvas. Este objecto consiste numa pequena API para automatizar algumas ferramentas e funcionalidades de * computação visual que se pode efectuar recorrendo à especificação HTML5 * @param {String} id identificador do objecto canvas */ BLauLib.Canvas=function(id){ this.canvas=$(id); if(this.canvas && this.canvas.getContext){ this.c=this.canvas.getContext("2d"); } else throw "O browser não suporta o objecto canvas"; } /** * Método que especifica a função que será executada quando se efectua um varrimento da imagem pixel por pixel. * A função enviada para o método será invocada para todos os valores de pixel. * @see #inverte * @see #noiseImage * @see #blackWhiteNoise * @see #Threshold * @param {Function} func Função callback * @param {Object} args Argumentos adicionais para a função callback */ BLauLib.Canvas.prototype._ppixelCallback=function(func,args){ var imgd=this.c.getImageData(0,0,this.canvas.width,this.canvas.height); var pixs=imgd.data; var n=pixs.length; var sm=0; for(var i=0;i0.5) return [255,255,255,100]; return [0,0,0,100] },null) } /*** * Aplica threshold na imagem * @param {Number} treshold Limite de threshold */ BLauLib.Canvas.prototype.Threshold=function(tresh){ this._ppixelCallback(function(px1,px2,px3,alpha,tr){ var arr=[]; sm=(px1+px2+px3)/3; if(sm xmax) { sfac = xmax / img.width; img.width = img.width * sfac; img.height = img.height * sfac; } this.canvas.width = img.width; this.canvas.height = img.height; this.c.drawImage(img,0,0,img.width,img.height); this.c.scale(sfac,sfac); } /** * Método que carrega uma imagem para o objecto canvas efectuando um redimensionamento * a partir da sua altura máxima * @param {String} src Endereço da imagem * @param {Number} xmax Altura máxima da imagem */ BLauLib.Canvas.prototype.loadScaledYImage=function(src,ymax){ var img=new Image(); var sfac=1; img.src=src; if (xmax && img.width > ymax) { sfac = ymax / img.height; img.width = img.width * sfac; img.height = img.height * sfac; } this.canvas.width = img.width; this.canvas.height = img.height; this.c.drawImage(img,0,0,img.width,img.height); this.c.scale(sfac,sfac); } var HOSTNAME=""; var DIR_IMAGENS=""; BLauLib.Window.COUNT=0; BLauLib.Window.TBAR_HEIGHT=25; BLauLib.Window.BBAR_HEIGHT=25; BLauLib.Window.MIN_HEIGHT=100; BLauLib.Window.MIN_WIDTH=100; BLauLib.Window.IMGCLOSE=HOSTNAME+DIR_IMAGENS+"close16.png"; BLauLib.Window.IMGRESIZE=HOSTNAME+DIR_IMAGENS+"resze.png"; BLauLib.Window.width=function(){ return $('$html')[0].clientWidth; } BLauLib.Window.height=function(){ return $('$html')[0].clientHeight; } BLauLib.Window.scrX=function(){ return $('$html')[0].scrollLeft; } BLauLib.Window.scrY=function(){ return $('$html')[0].scrollTop; } BLauLib.MsgBox=function(tipoMsg,msg,titulo){ BLauLib.Window.apply(this, ["msg"+BLauLib.Window.COUNT,titulo,400,100]); this.bd.innerHTML=msg; return this.contentor; } /** * Método que efectua a transicao entre dois niveis de transparencia * @param {Number} alphaIni Percentagem de opacidade inicial * @param {Number} alphaFin Percentagem de opacidade final * @param {Number} seg Numero em segundos de duracao da transicao * @see #desvanece * @see #aparece * @see #getAlpha * @see #setAlpha */ HElement.prototype.transicaoAlpha=function(alphaIni,alphaFin,seg,callback){ if(!this.ontransition){ this.ontransition=true; var cresc=true; var transita=true; if(alphaIni>alphaFin) cresc=false; var passo=(alphaFin-alphaIni)/(seg*24); var alphaAct=alphaIni; var obj=this; var act=function(){ if ((cresc === true && alphaAct > alphaFin) || (cresc === false && alphaAct < alphaFin)) { transita=false; if(alphaAct>100){ obj.setAlpha(100) } if(alphaAct<0){ obj.setAlpha(0); } obj.ontransition=false; clearInterval(i); if(callback!=null){ callback(); } } else{ alphaAct+=passo; obj.setAlpha(alphaAct); } } if(transita) var i=setInterval(act,1000/30); } }; /** * Método que remove um elemento filho a partir do seu identificador * @param {String} id Identificador do elemento a remover */ HElement.prototype.removeChildById=function(id){ var cnt=this.childElementCount; var filho=null; for(var i=0;i 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } /** * Método que descodifica uma string do formato UTF-8 * @return {String} String descodificada */ String.prototype.decodeUTF8=function(){ var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < this.length ) { c = this.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = this.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = this.charCodeAt(i+1); c3 = this.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } var Priberam=function(){ this.descricao=""; this.NDIV=32; this.onLoaded=null; } var DragHandler = { // private property. _oElem : null, // public method. Attach drag handler to an element. attach : function(oElem,dgEl) { oElem.onmousedown = DragHandler._dragBegin; _dgEl=dgEl; // callbacks oElem.dragBegin = new Function(); oElem.drag = new Function(); oElem.dragEnd = new Function(); return oElem; }, // private method. Begin drag process. _dragBegin : function(e) { var oElem = DragHandler._oElem = this; if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; } if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; } var x = parseInt(oElem.style.left); var y = parseInt(oElem.style.top); e = e ? e : window.event; oElem.mouseX = e.clientX; oElem.mouseY = e.clientY; oElem.dragBegin(oElem, x, y); document.onmousemove = DragHandler._drag; document.onmouseup = DragHandler._dragEnd; return false; }, // private method. Drag (move) element. _drag : function(e) { var oElem = DragHandler._oElem; var x = parseInt(oElem.style.left); var y = parseInt(oElem.style.top); e = e ? e : window.event; oElem.style.left = x + (e.clientX - oElem.mouseX) + 'px'; oElem.style.top = y + (e.clientY - oElem.mouseY) + 'px'; oElem.mouseX = e.clientX; oElem.mouseY = e.clientY; oElem.drag(oElem, x, y); return false; }, // private method. Stop drag process. _dragEnd : function() { var oElem = DragHandler._oElem; var x = parseInt(oElem.style.left); var y = parseInt(oElem.style.top); oElem.dragEnd(oElem, x, y); document.onmousemove = null; document.onmouseup = null; DragHandler._oElem = null; alert("END"); } } Priberam.prototype.get=function(pal){ var aj=new BLauLib.Ajax(); var dc; var obj=this; aj.addVar("url","http://www.priberam.pt/dlpo/default.aspx?pal="+encodeURI(pal)); aj.onLoaded=function(){ var eltmp=document.createElement('hidden'); eltmp.innerHTML=aj.text; var dvs=eltmp.getElementsByTagName("div"); obj.descricao=dvs[obj.NDIV].innerHTML.decodeUTF8(); obj.onLoaded(); }; aj.open("POST","http://localhost/wbservices/wb_loadurl"); aj.send(aj.encPostVars()); }; /** * Método que contém um conjunto de funcionalidades para o processamento de captchas * @classDescription Este objecto pretende fornecer um conjunto de funcionalidades de manipulação de imagens gerados pelo * sistema RECaptcha * @param {String} pubkey Chave pública * @param {String} privkey Chave privada * @author Balhau */ var RECaptcha=function(pubkey,privkey){ this.publickey=pubkey; this.privatekey=privkey; this.challenge=""; this.challengeURL=RECaptcha.ServerName+"challenge?k="+this.publickey; } /** * Método que utiliza um script de servidor para guardar imagens geradas pelo serviço RECaptcha * @param {String} imgname Nome da imagem que pretendemos guardar */ RECaptcha.prototype.saveImage=function(imgname){ var aj=new BLauLib.Ajax(); var obj=this; aj.onLoaded = function(){ var resp = aj.text; resp=resp.split(";")[0]; resp=resp.split(","); resp=resp[1].split(":"); resp=resp[1].replace(/'/gi,""); obj.challenge=resp; var naj=new BLauLib.Ajax(); var urlImg=RECaptcha.ServerName+"image?c="+resp.trim(); naj.addVar("url",urlImg); naj.addVar("imgname",imgname); naj.onLoaded=function(){ } naj.callPost(RECaptcha.PHPCallbackFile); } aj.open("GET",RECaptcha.PHPRedirectFile+"?url="+this.challengeURL); aj.send(null); } /** * Nome do ficheiro que efectua o processamento das imagens geradas pelo mecanismo RECaptcha */ RECaptcha.PHPCallbackFile="save.php"; /** * Nome do ficheiro que funciona como proxy para endereços externos. */ RECaptcha.PHPRedirectFile="redirect.php"; /** * Endereço do serviço RECaptcha */ RECaptcha.ServerName="http://www.google.com/recaptcha/api/";