//    por diego nunes - dnunes[em]gmail.com
//  (cc) Conteúdo sob licença Creative Commons
//http://creativecommons.org/licenses/by-sa/2.0/

function gE(tI) { var d=document, r, n, i;
  if (tI instanceof Array) {
    for (n=tI.length, i=0; i<n; i++) r[r.length]=gE[tI[i]]; return r;
  } else { return (d.getElementById) ? d.getElementById(tI) : (d.all) ? d.all[tI] : false; }
}
function gFETN(tTn, tFs, isER, pE, deep) {
  //getFilteredElements[by]TagName: <str TagName> [, str/arr theFilters [, bool isERFilter [, object parentElement]]]
  //Se o quarto parâmetro for enviado, a função só retornará elementos descendentes do que foi passado.
  var tEs, i, n, ii, nn, tF, tER, tR=new Array(); if (deep===undefined) deep=1;
  if (deep || !pE) { tEs=(pE || document).getElementsByTagName(tTn); } else { tEs=childsOfType(pE, tTn); }
  if (!tFs) { return (tEs.length) ? tEs : false; } if (typeof(tFs) == 'string') { tFs=[tFs]; }
  for (n=tEs.length, i=0; i<n; i++) { passed=1;
    for (nn=tFs.length, ii=0; ii<nn; ii++) { tF=tFs[ii].split('=');
      if (isER) { tER=new RegExp(tF[1], 'g'); if (!tER.test(tEs[i][tF[0]])) { passed=0; } }
      else { if (tEs[i][tF[0]] != tF[1]) passed=0; }
    } if (passed) { tR[tR.length]=tEs[i]; /* compatível com IE5.1 */ }
  }
  return (tR.length) ? tR : false;
}
function cE(tN, tPs, tC) { // createElement 3.0 -- <str tagName> [, str/arr tProperties] [, str/obj conteúdo]
  //Essa função, se chamada com 2 parâmetros, os assumirá como "tN" e "tC", e não "tN" e "tPs".
  if (!document.createElement) return false; var nE, tER, i, n, tP; nE=document.createElement(tN);
  if (arguments.length > 1) { if (arguments.length == 2) { tC=tPs; tPs=[]; }
    if (typeof(tPs) == 'string') { tPs=[tPs]; }
    for (n=tPs.length, i=0; i<n; i++) { tP=tPs[i].split('='); nE[tP.shift()]=tP.join('='); }
    if (tC) { i=0;
      if (tC instanceof Array) { for (n=tC.length; i<n; i++) { nE.appendChild( (typeof(tC[i])=='string')?cTN(tC[i]):tC[i] ); } }
      else { nE.appendChild( (typeof(tC)=='string')?cTN(tC):tC ); }
    }
  } return nE;
}
function cTN(tV) { return (tV && document.createTextNode) ? document.createTextNode(tV) : false; }
function rEs(tO) { var i, n; //removeElements. Recebe um objeto ou uma coleção deles, para remover do documento
  if (!tO) { return false; } if (!tO.nodeName) { if (tO.length) for (n=tO.length; n--;) rEs(tO[n]); }
  else tO.parentNode.removeChild(tO);
}


Function.prototype.bind=function(obj, args) { var metodo=this; return function() { return metodo.apply(obj, args); } }
Function.prototype.bindAsEventListener=function(obj) { var metodo=this; return function(e) { return metodo.call(obj, e); } }
function adEvento(tO, tE, tF, tPs) { //3.1 - <str/arr tObject(s)>, <str/arr tEvent(s)>, <func tFunction> [, arr tParams]
  if (tO instanceof Array || tE instanceof Array) { if (!(tO instanceof Array)) tO=[tO]; if (!(tE instanceof Array)) tE=[tE]; }
  if (tO instanceof Array) { for (n=tO.length; (n--)>0; n) { for (nn=tE.length; (nn--)>0; ) {
      if (!adEvento(tO[n], tE[nn], tF, tPs)) return false;
  } } return true; }
  var tnF=(tPs) ? function(e) { tF.apply(tO, Array(e).concat(tPs)); } : tF;
  /* Iniciar arrays, caso não existam */ if (!tO.eventos) { tO.eventos=[]; } if (!tO.eventos[tE]) { tO.eventos[tE]=[]; }
  tO.eventos[tE][tO.eventos[tE].length]={tE: tE,   tF: tF,   tPs: tPs };
  if (tO.addEventListener) { tO.addEventListener(tE, tnF, true); return true; }
  if (tO.attachEvent) { tO.attachEvent('on'+tE, tnF); return true; }
  /* alert('Erro!'); */ return false;
}
function remEventos(tO, tE, tF, tPs) {
  //Recebendo apenas objeto e nome do evento
  if (arguments.length == 2) { if (!tO.eventos) return false;
    var tCEv; if (!(tE instanceof Array)) tE=[tE];
    for (n=tE.length, i=0; i<n; i++) { tCEv=tE[i]; tCEvs=tO.eventos[tCEv];
      for (nn=tCEvs.length, ii=0; ii<nn; ii++) {
        remEventos(tO, tCEvs[ii]['tE'], tCEvs[ii]['tF'], tCEvs[ii]['tPs'] );
      } tO.eventos[tCEv]=[];
    } return true;
  }
  //Recebendo informações sobre o evento
  var tnF=(tPs) ? function(e) { tF.apply(tO, Array(e).concat(tPs)); } : tF;
  if (document.detachEvent) { tO.detachEvent('on'+ tE, tnF, true); return true; }
  if (tO.removeEventListener) { tO.removeEventListener(tE, tnF, true); return true; }
  tO["on"+ tE] = null;
}
function getSrc(e) { /* event */ return (e.target) ? e.target : (window.event && event.srcElement) ? event.srcElement : false; }
function getKeyCode(e) { /* event */ return (e.which) ? e.which : (window.event && event.keyCode) ? event.keyCode : false; }
function getMouseButton(e) { if (!e) e = window.event; var keymap=Array();
  if (e.which != undefined) { keymap[1]='left'; keymap[2]='middle'; keymap[3]='right'; }
  else if (e.button != undefined) { keymap[1]='left'; keymap[4]='middle'; keymap[2]='right'; }
	return keymap[(e.which) ? e.which : e.button];
}
function poin(e) { try { e.preventDefault(); } catch(e) { event.returnValue=false; } return false; }
function valorValido(tV) { /* theValue */ return new RegExp('[a-z0-9]','gi').test(tV); }
function RETest(tER, tV, tF) { /* tRegularExpression, tValue, tFlags */ return new RegExp(tER, (tF)?tF:'').test(tV); }
function insertBefore(tN, nN) { /* tNode, newNode */ return tN.parentNode.insertBefore(nN, tN); }
function insertAfter(tN, nN) { /* tNode, newNode */ var tP=tN.parentNode;
  while ((tN=tN.nextSibling) && tN.nodeType != 1) { /* dã! */ }
  if (tN) { tP.insertBefore(nN, tN); } else { tP.appendChild(nN); } return tP.childNodes.length;
}
function childsOfType(tO, tT) { /* tParentObject, <string/arr tTag(s)> */ var i, n, tCs, tR=[];
  tT=new RegExp( (tT instanceof Array)?tT.join('|') : tT , 'i');
  for (i=0, n=(tCs=tO.childNodes).length; i<n; i++) {
    if (tCs[i].nodeType==1 && tT.test(tCs[i].nodeName.toLowerCase())) tR[tR.length]=tCs[i];
  } return (tR.length) ? tR : false;
}
function firstParentOfType(tO, tT) { /* <node tObject>, <string/arr tTag(s)> */
  tT=new RegExp( (tT instanceof Array)?tT.join('|') : tT , 'i');
  while (tO && (tO.nodeType != 1 || !tT.test(tO.nodeName.toLowerCase()))) { tO=tO.parentNode; }
  return (tO) ? tO : false;
}
function isDescendantOf(tO, tT) { while (tO=tO.parentNode) { if (tO == tT) { return true; } } return false; }

function sW(tS, sS) { /* (Bool) startsWith: theString, subString */
  return (tS && sS && tS.substring(0,sS.toString().length) == sS.toString()) ? true : false;
}
function addTok(tokList, tTok, tDiv) { return (((tokList) ? tokList : '') + ((tDiv)?tDiv:' ') + tTok); }
function hasTok(tokList, tTok, tDiv) { var n, i, tToks=tokList.split((tDiv)?tDiv:' ');
  for (n=tToks.length, i=0; i<n; i++) { if (tToks[i]==tTok) { return 1; } } return 0;
}
function remTok(tokList, tTok, tDiv) { if (!tokList) return false; var n, i, tRs=[], tToks=tokList.split((tDiv)?tDiv:' ');
  for (n=tToks.length, i=0; i<n; i++) { if (tToks[i]!=tTok) { tRs[tRs.length]=tToks[i]; } } return tRs.length ? tRs.join((tDiv)?tDiv:' ') : '';
}
function getStyle(tO, tS) { /* tObject, tStylename */
  if (window.getComputedStyle) { return window.getComputedStyle(tO, null).getPropertyValue(tS); }
  else if (tO.currentStyle) { var tER=new RegExp('^([^\-]+)\-([a-z])(.*)$');
    tS=tS.replace(tER, '$1') + tS.replace(tER, '$2').toUpperCase() + tS.replace(tER, '$3');
    return tO.currentStyle[tS];
  }
  return false;
}
function round(tN, n) { tP=Math.pow(10, n); return Math.round(tN * tP) /tP; }
function getScrollPos() { var ret=Array();
  if (self.pageYOffset) { ret['x']=self.pageXOffset; ret['y']=self.pageYOffset; } //all except Explorer
  else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
	  ret['x']=document.documentElement.scrollLeft; ret['y']=document.documentElement.scrollTop; }
  else if (document.body) { ret['x']=document.body.scrollLeft; ret['y']=document.body.scrollTop; } //all other Explorers
  return ret;
}
function setScrollPos(pos, tE) { if (!tE) tE=document;
  if (tE.documentElement && tE.documentElement.scrollTop) { tE=tE.documentElement; }
  else if (tE.body) { tE=tE.body; } else if (!tE.offsetLeft) { tE=0; }
  if (tE) {
    if (typeof(pos['x']) != 'undefined') { tE.scrollLeft=pos['x']; }
    if (typeof(pos['y']) != 'undefined') { tE.scrollTop=pos['y']; }
    return true;
  } else { return false; }
}
function getPageSize() { var ret=Array(); var test1 = document.body.scrollHeight; var test2 = document.body.offsetHeight;
  if (test1 > test2) { ret['x']=document.body.scrollWidth; ret['y']=document.body.scrollHeight; /* all but Explorer Mac */ }
  else { ret['x']=document.body.offsetWidth; ret['y']=document.body.offsetHeight; /* Explorer Mac */ }
  return ret;
}


function XMLHTTPRequest() { var tXHR=0; //Criação de objeto XMLHTTPRequest cross-browser
  if (window.XMLHttpRequest) { tXHR=new XMLHttpRequest(); } //Objeto nativo (FF/Safari/Opera7.6+)
  else {
    try { tXHR=new ActiveXObject("Msxml2.XMLHTTP"); } //activeX (IE5.5+/MSXML2+)
    catch(e) {
      try { tXHR=new ActiveXObject("Microsoft.XMLHTTP"); } //activeX (IE5+/MSXML1)
      catch(e) { /* O navegador não tem suporte */ tXHR=false; }
    }
  }
  return tXHR;
}
//void makeXHRCall : makes a XMLHTTPRequest and configure the callback function with optional parameters
//  object t(XHR)Object, string tURL, string tMethod ("POST" | "GET")
//  [, string tContents(ToSend) [, array tHeaders (array of arrays in pair format: "['name', 'value']")
//  [, function t(Callback)Function [, boolean tReturn(Type) [, array t(aditional)Params(ToCallBack) ]]] ]]
//    - tHeaders: an array containing other arrays with two indexes: 0) Header Name, and 1) Header Value
//    - tReturn(Type): 0 = responseText. 1 = responseXML.
function makeXHRCall(tO, tU, tM, tC, tHs, tF, tR, tPs) { if (!tO || !tU) return false; if (!tHs) tHs=[]; var i, n;
  if (tF) tO.onreadystatechange=XHRStateChanged.bind(tO, [tF, tPs]);
  tO.open(((tM) ? tM : 'GET'), tU, true);
  for (i=0, n=tHs.length; i<n; i++) { tO.setRequestHeader(tHs[i][0], tHs[i][1]); }
  tO.send((tC) ? tC : null);
  return void(null);
}
function XHRStateChanged(tF, tPs, tRT) { //function tFunction [, array Params [, boolean tReturnType]]
  if (this.readyState == 4) { if (this.status == 200) {
    //Definir retorno do XHR como primeiro parâmetro da chamada da função callBack
    tPs=tPs || Array(); tPs.unshift( (this[(tRT) ? 'responseHTML' : 'responseText' ]) ); tF.apply(window, tPs);
  } else { return false; } }
  return true;
}
