/******************************************************************************
 *                                                                            *
 * LIBRARIA DE FUNÇÕES E CLASSES DINÂMICAS UTILIZADAS PARA PROCEDIMENTOS AJAX *
 * VERSÃO: 0.51                                                                *
 * AUTOR: Patrick S. de Palma                                                 *
 *                                                                            *
 ******************************************************************************/

if (typeof addEvent == "undefined")
  var addEvent = function( obj, type, fn ) {
    if ( obj.attachEvent ) {
      obj['e'+type+fn] = fn;
      obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
      obj.attachEvent( 'on'+type, obj[type+fn] );
    } else
      obj.addEventListener( type, fn, false );
  }


/*
** Limpa o conteudo do select
*/
function clearSelect(obj) {
  obj.options.length = 0;
  obj.innerHTML = "";
}

/*
** Cria um objeto select
** O formato da variável data pode ser:
** Texto: "chave:valor"
*/
function createSelect(ObjParent, name) {
  var s = document.createElement("select");
  if (typeof name != "undefined") s.name = name;
  return ObjParent.appendChild(s);
}

/*
** Adiciona um elemento ao select
*/
function addSelectOption(obj, value, text) {
  var option = document.createElement("OPTION");
  option.value = value;
  option.text = text;
  obj.options.add(option, -1);
  return option;
}

/*
** Alias para a função acima
*/
function addOption(obj, value, text) { return addSelectOption(obj, value, text)}

/*
** Remove elemento de select por índice
*/
function delOptionByIndex(obj, index) { obj.remove(index) }

/*
** Remove elemento de select por valor
*/
function delOptionByValue(obj, value) {
  for (var i=0;i<obj.options.length;i++)
    if (obj.options[i].value == value) obj.remove(i);
}

/*
** Remove elemento de select por texto
*/
function delOptionByText(obj, text) {
  for (var i=0;i<obj.options.length;i++)
    if (obj.options[i].text == text) obj.remove(i);
}

/*
** Retorna o elemento selecionado de um select
*/
function getSelectedOption(obj) {
  if (typeof obj == "string") obj = document.getElementById(obj) || document.getElementsByName(obj)[0];
  return (obj.selectedIndex>=0) ? obj.options[obj.selectedIndex].value : null;
}

/*
** ALIAS DE getSelectedOption(obj)
*/
function getOption(obj) {
  return getSelectedOption(obj);
}

/*
** Seleciona um item do select pelo seu valor
*/
function selectByVal(node, val) {
  if (typeof node == "string") node = document.getElementById(node) || document.getElementsByName(node)[0];
  for (var i=0,c=node.options.length; i<c; i++) {
    if (node.options[i].value == val) {
      node.options[i].selected = true;
      return true;
    }
  }
  return false;
}

/*
** Seleciona um item do select pelo texto
*/
function selectByText(node, text) {
  if (typeof node == "string") node = document.getElementById(node) || document.getElementsByName(node)[0];
  for (var i=0,c=node.options.length; i<c; i++) {
    if (node.options[i].text == text) {
      node.options[i].selected = true;
      return true;
    }
  }
  return false;
}

/*
** Cria tabela
*/
function createTable(parentNode) {
  var t = parentNode.appendChild(document.createElement("TABLE"));
  t.appendChild(document.createElement("TBODY"));
  return t;
}

/*
** Mostra mensagens no meio da tela
*/
function Display() {
  this.width    	= 223;
  this.height     = 22;
  this.padding    = 2;
  this.border     = 2;
  this.bgColor    = "#F2F2F2";
  this.intervalID = null;

  this.screenWidth  = function() { return window.innerWidth == null ? document.body.offsetWidth : window.innerWidth };
  this.screenHeight = function() { return window.innerHeight == null ? document.body.offsetHeight : window.innerHeight };
  this.offsetTop    = function() { return window.pageYOffset == null ? document.body.scrollTop : window.pageYOffset };

  this.left = function() { return (this.screenWidth() - this.width) / 2 }; // X
  this.top  = function() { return (this.screenHeight() - this.height) / 2 + this.offsetTop() }; // Y
  
  this.getWidth   = function() { return document.all ? this.width  : (this.width - ((this.padding * 2) + (this.border * 2))) };
  this.getHeight  = function() { return document.all ? this.height : (this.height - ((this.padding * 2) + (this.border * 2))) };
  this.createEvent = function() {
    // Meio gambiarra más ficou limpo!!! :)
    window.objDisplay = this;
    addEvent(window, "resize", this.refresh);
    addEvent(window, "scroll", this.refresh);
  }
  
  this.destroyEvent = function() {
    removeEvent(window, "resize", this.refresh);
    removeEvent(window, "scroll", this.refresh);
    window.objDisplay = null; // Destroi objeto
  }      
    
  this.show = function(text) {
    this.div.style.display = "block";
    this.div.innerHTML = text||"";
    this.refresh();
    this.createEvent();
  }
  
  this.text = function(text) { this.div.innerHTML = text };
  
  this.refresh = function(e) {
    var self = this.objDisplay ? this.objDisplay : this;
    var s    = self.div.style;
    
    s.backgroundColor = self.bgColor;
    s.width           = self.getWidth()   + "px";
    s.height          = self.getHeight()  + "px";
    s.left            = self.left()       + "px";
    s.top             = self.top()        + "px";
    s.border          = self.border       + "px ridge";    
    s.padding         = self.padding      + "px";
  }
  
  this.hide = function() { 
    this.div.style.display = "none";
    this.destroyEvent();
  }
  
  this.destroy = this.hide;
  
  // Cria objeto div
  var div = document.createElement("div");

  // STYLE
  div.style.position  = "absolute";
  div.style.textAlign = "center";
  div.style.display   = "none";
  this.div            = document.body.appendChild(div);
  this.handleEvent    = this.refresh;
}

/*
** FUNÇÃO QUE ORDENA UTILIZANDO O ALGORITMO QUICKSORT (desenvolvido por Charles Antony Richard Hoare)
** @Autor Patrick S. de Palma
** Modo de uso: 
** sortTable(<id_tabela>, <coluna>, <linha_inicio>, <linha_fim>[, decrescente = <1 | 0>])
*/
function sortTable(tableNode, col, start, end, desc) {
  // global variables

  if (typeof desc == "undefined") desc = 0;
  var parent = tableNode;

  if(parent.nodeName != "TBODY")
    parent = parent.getElementsByTagName("TBODY")[0];
  if(parent.nodeName != "TBODY")
    return false;

  var items = parent.rows;

  // quick sort
  quicksort(start, end+1, desc);
    
  function exchange(i, j) {
    if(i == j+1) {
      parent.insertBefore(items[i], items[j]);
    } else if(j == i+1) {
      parent.insertBefore(items[j], items[i]);
    } else {
      var tmpNode = parent.replaceChild(items[i], items[j]);
      if(typeof items[i] == "undefined") {
        parent.appendChild(tmpNode);
      } else {
        parent.insertBefore(tmpNode, items[i]);
      }
    }
  }
  
  function move(a, b) {
    parent.insertBefore(items[a], items[b]);
  }
  
  function get(i) {
    var node = items[i].getElementsByTagName("TD");
    if (node.length==0) 
      return "";
    else 
      node = node[col];
    if(!node.childNodes || node.childNodes.length == 0) return "";

    // assumes firstChild of node is a textNode
    var retval = node.firstChild.nodeValue;
    if(parseInt(retval) == retval) return parseInt(retval);
    return retval;
  }
  
  function compare(val1, val2, desc) { 
    var x = val1;
    var y = val2;
    
    if (String(x).indexOf('%') >= 0) {
      x = x.replace('%','');
      y = y.replace('%','');
    }
    
    var reData = /(^[0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
    var reDec  = /^[\.,0-9]+$/;
    
    if (!isNaN(x)) {
      x = Number(x);
      y = Number(y);
    } else if (reDec.test(x)) {
      // Retira os pontos "."
      x = x.replace(/^[^0-9]+/g, '');
      y = y.replace(/^[^0-9]+/g, '');
      // Converte a número
      x = parseFloat(x);
      y = parseFloat(y);
    } else if (reData.test(x)) {
      x = x.replace(reData, '$3$2$1');
      y = y.replace(reData, '$3$2$1');
    } else {
      x = String(x).toLowerCase();
      y = String(y).toLowerCase();
      
    }
    return desc ? x > y : x < y; 
  }

  function quicksort(m, n, desc) {
    if(n <= m+1) return;

    if((n - m) == 2) {
      if(compare(get(n-1), get(m), desc)) exchange(n-1, m);
      return;
    }

    i = m + 1;
    j = n - 1;

    if(compare(get(m), get(i), desc)) exchange(i, m);
    if(compare(get(j), get(m), desc)) exchange(m, j);
    if(compare(get(m), get(i), desc)) exchange(i, m);

    pivot = get(m);

    while(true) {
      j--;
      while(compare(pivot, get(j), desc)) j--;
      i++;
      while(compare(get(i), pivot, desc)) i++;
      if(j <= i) break;
      exchange(i, j);
    }

    exchange(m, j);

    if((j-m) < (n-j)) {
      quicksort(m, j, desc);
      quicksort(j+1, n, desc);
    } else {
      quicksort(j+1, n, desc);
      quicksort(m, j, desc);
    }
  }
}
function sortOnClick()
{
  var tabela = this.offsetParent;
  var rows = tabela.rows.length - 1;
  if (this.desc == null) this.desc = false;
  else this.desc = !this.desc;
  sortTable(tabela, this.cellIndex, 1, rows, this.desc);
  
  // Reseta todas as celulas
  for (var i=0; i<tabela.rows[0].cells.length; i++)
    tabela.rows[0].cells[i].className = "";
  
  this.className = this.desc ? "orderZA" : "orderAZ";
  
  // Repõe a cor nas linhas da tabela
  for (var i=1;i<tabela.rows.length;i++)
    tabela.rows[i].className = (i % 2) ? "cor1" : "cor2";
}

function initSortable() {
  var tabelas = document.getElementsByTagName("table");
  if (tabelas.length==0) return;
  for (var i=0;i<tabelas.length; i++) {
    if (tabelas[i].className.indexOf('sortable') != -1) {
      var tabela = tabelas[i];
      var cells = tabela.rows[0].cells;
      for (var j=0; j<cells.length; j++) {
        cells[j].onclick = sortOnClick;
        cells[j].onmouseover = function(e) { rowEvent(this, e) };
      }
    }
  }
}
addEvent(window, "load", initSortable);