﻿function closeMenu() {
  if (_GrupoOver == false && _ItensOver == false) {
    nClose = 0;
    var divItens = getById("_divItens_nemu");
    divItens.style.display = "none";
    divItens.innerHTML = "";

    if (_LastGrupo != null)
      _LastGrupo.updateStyleOut();

    _LastGrupo = null;
  }
  else if (nClose < 10) {
    nClose++;
    setTimeout("closeMenu();", 1000);
  }
}

//funções auxiliares de DOM
function getById(id) {
  return document.getElementById(id);
}
//Cria um novo elemento
//Obs.: Não funciona no IE p/ elementos de tabela como td, tr e etc.
//Utilizar insertCell ou insertRow que é o método padrão do elemento.
function addElement(tipo, id) {
  obj = document.createElement(tipo);
  if (id != "") obj.id = id;
  return obj;
}
function getWidthUl(ul) {
  var w = 0;
  //ul li ul
  if (ul.childNodes.length > 0 && ul.childNodes[0].childNodes.length > 1) {
    w += getWidthUl(ul.childNodes[0].childNodes[1]);
    return w + ul.offsetWidth;
  }
  else
    return ul.offsetWidth;
}


// Itentifica o navegador
var version = 0
if (navigator.appVersion.indexOf("MSIE") != -1) {
  temp = navigator.appVersion.split("MSIE")
  version = parseFloat(temp[1])
}
var msie = document.all
var ie6 = typeof dropmenuiframe == 'undefined' ? 0 : 1
var ns6 = document.getElementById && !document.all
var netscape = navigator.vendor == "Netscape";
var safari = (navigator.userAgent.indexOf('Safari') != -1) ? true : false;

//Retorna a posição absoluta de um elemento
//what - É o elemento
//offsettype - É o tipo de posição: top, left...
function getposOffset(what, offsettype) {
  var totaloffset = (offsettype == "left") ? what.offsetLeft : what.offsetTop;
  var parentEl = what.offsetParent;
  while (parentEl != null) {
    if (msie) {
      totaloffset = (offsettype == "left") ? totaloffset + parentEl.offsetLeft : totaloffset + parentEl.offsetTop;
    }
    else {
      totaloffset = (offsettype == "left") ? totaloffset + parentEl.offsetLeft : totaloffset + parentEl.offsetTop;
    }
    (offsettype == "left") ? leftOffset = parentEl.offsetLeft : topOffset = parentEl.offsetTop;
    parentEl = parentEl.offsetParent;
  }
  if (ie6) {
    if (offsettype == "left") totaloffset -= leftOffset;
  }
  if (msie) {
    if (offsettype == "left") totaloffset += 1;
  }
  return totaloffset;
}

//Variáveis de controle do menu
var _id_topmenu = "MenuConteiner";
var _GrupoOver = false;
var _ItensOver = false;
var _LastGrupo = null;
var nClose = 0;

// MenuItem - Inicio
function MenuItem(texto, link) {
  this.Link = link;
  this.Texto = texto;
}
MenuItem.prototype.draw = function(ul) {
  var li = addElement("li", "");
  var link = addElement("a", "");

  link.innerHTML = this.Texto;
  link.href = this.Link;

  link.rel = this;
  //link.onmouseover = this.LinkMouseOver;
  //link.onmouseout = this.LinkMouseOut; 

  ul.appendChild(li);
  li.appendChild(link);
}
MenuItem.prototype.LinkMouseOut = function() {
  var a = this;
  var Item = this.rel;

}

MenuItem.prototype.LinkMouseOver = function() {
  var a = this;
  var Item = this.rel;

}
//MenuItem - Fim


//GrupoItem - Inicio
function GrupoItem() {
  this.Itens = [];
  this.CssLink = "";
  this.Css = "";
  this.CssItens = "";
  this.Link = "";
  this.Div = null;
  this.ImgSepar = "";
  this.Selecionado = false;
}
GrupoItem.prototype.AddItem = function(item) {
  if (!(item instanceof MenuItem)) return false;

  item.parent = this;
  this.Itens[this.Itens.length] = item;

  return true;
}
GrupoItem.prototype.Render = function() {
  var divMenu = getById(_id_topmenu);
  var tr = getById("_tr_menu");

  var td = tr.insertCell(tr.childNodes.length);
  var div = addElement("div", "");
  var link = addElement("a", "");

  td.appendChild(div);

  link.innerHTML = "&nbsp;";
  if (this.Link != "")
    link.href = this.Link;

  div.appendChild(link);
  div.rel = this;
  this.Div = div;

  this.updateStyleOut();

  div.onmouseover = this.mouseover;
  div.onmouseout = this.mouseout;
}
GrupoItem.prototype.updateStyleOut = function() {
  var div = this.Div;
  var grupo = this;
  var tb = div.parentNode;
  var css2 = "";

  if (grupo.Selecionado) {
    grupo.updateStyleOver();
    return;
  }

  css2 = this.Css;
  if (css2 == "")
    css2 = this.parent.CssMenuGrupoItens;

  tb.className = this.CssLink + " " + css2;
}
GrupoItem.prototype.updateStyleOver = function() {
  var div = this.Div;
  var grupo = this;
  var tb = div.parentNode;
  var css2 = "";

  css2 = this.Css;
  if (css2 == "")
    css2 = this.parent.CssMenuGrupoItens;

  tb.className = this.CssLink + "hover  " + css2 + "hover";
}
GrupoItem.prototype.ItensOver = function() {
  _ItensOver = true;
}
GrupoItem.prototype.ItensOut = function() {
  _ItensOver = false;

  setTimeout("closeMenu();", 500);
}

//Cria os itens dentro da div dinamicamente.
//Ele leva em consideração e tamanho da tela
GrupoItem.prototype.mouseover = function()
{
  _GrupoOver = true;

  var grupo = this.rel;
  var divItens = getById("_divItens_nemu");
  var div = this;

  divItens.innerHTML = "";
  divItens.className = grupo.CssItens + " " + grupo.parent.CssItens;
  divItens.style.display = "block";
  if (_LastGrupo != null)
    _LastGrupo.updateStyleOut();

  grupo.updateStyleOver();
  _LastGrupo = grupo;

  divItens.onmouseover = grupo.ItensOver;
  divItens.onmouseout = grupo.ItensOut;


  //Posicionar a div de itens
  var y = null;
  var x = null;

  var TamItensH = null;
  var TamDisponivelH = document.documentElement.clientHeight;
  var TamDisponivelW = document.documentElement.clientWidth;

  var ul = addElement("ul", "");
  divItens.appendChild(ul);
  var topLi = null;
  var limiteBalanceamento = null;
  var b = 0; //Indice de Balanceamento de colunas
  for (var i = 0; grupo.Itens.length > i; i++, b++) {
    grupo.Itens[i].draw(ul);
    if (topLi == null)
      topLi = ul.childNodes[0];

    if (limiteBalanceamento != null && b == limiteBalanceamento) {
      ul = addElement("ul", "");
      topLi.appendChild(ul);
      topLi = null;
      b = 0;
      continue;
    }
    else if (limiteBalanceamento != null)
      continue;

    y = getposOffset(divItens, "top");
    TamItensH = ul.offsetHeight + y;

    //Pergunter de coube se não couber
    //cria um nível a mais
    if (TamDisponivelH <= TamItensH) {
      //Resolução muito baixa. Mecanismo p/ evitar loop infinito
      if (ul.childNodes.length <= 3) {
        if (ul.childNodes.length <= 2)
          limiteBalanceamento = -1; //Desconsiderar balancemento
        else
          limiteBalanceamento = ul.childNodes.length;

        continue;
      }
      //Balanceamento 
      if (limiteBalanceamento == null) {
        var limite = i;
        var col = 2;

        while (true) {
          var resto = grupo.Itens.length % col;
          if (resto == 0)
            limiteBalanceamento = grupo.Itens.length / col;
          else
            limiteBalanceamento = (grupo.Itens.length - resto) / col;


          if (limite < limiteBalanceamento)
            col++;
          else {
            if (resto > 0 && (limiteBalanceamento + resto) <= limite)
              limiteBalanceamento += resto;
            break;
          }
        }

        b = 0;
        for (; i >= limiteBalanceamento; i--) {
          var li = ul.childNodes[i];
          ul.removeChild(li);
        }
      }
      else {
        var li = ul.childNodes[ul.childNodes.length - 1];
        ul.removeChild(li); //Remove o ultimo
        i--;
      }

      ul = addElement("ul", "");
      topLi.appendChild(ul);

      topLi = null;
    }
  }

  x = getposOffset(div, "left");
  ul = divItens.childNodes[0];

  var w = 0;
  w = getWidthUl(ul);
  var difX = TamDisponivelW - w;

  if (difX <= 0)
    divItens.style.left = "0px";
  else if (x <= difX)
    divItens.style.left = x + "px";
  else
    divItens.style.left = difX + "px";

  if (grupo.Itens.length == 0) {
    _ItensOver = false;
    divItens.style.display = "none";
  }
}

//Remove todos os itens de dentro da div
GrupoItem.prototype.mouseout = function() {
  _GrupoOver = false;

  //Posicionar a div de itens
  var grupo = this.rel;
  var div = this;

  setTimeout("closeMenu();", 1000);
}

function Menu() {
  this.GrupoItens = [];
  this.Css = "";
  this.CssMenuGrupoItens = "";
  this.CssItens = "";
  this.ImgSepar = "";
}

Menu.prototype.AddGrupoItem = function(grupo) {
  if (!(grupo instanceof GrupoItem)) return false;

  grupo.parent = this;
  this.GrupoItens[this.GrupoItens.length] = grupo;

  return true;
}

//Monta a Tabela com os GrupoItens
//Obs.: Os itens só serão montado ao passar o mouse encima do GrupoItens
Menu.prototype.Render = function() {
  var divMenu = getById(_id_topmenu);
  var tabela = addElement("table", "_tb_menu");
  var tr = tabela.insertRow(0);
  tr.id = "_tr_menu";
  divMenu.className = this.Css;
  tabela.cellPadding = 0;
  tabela.cellSpacing = 0;

  divMenu.appendChild(tabela);

  var iSepar = null;
  var primeiro = true;
  var ultimo = false;
  var td = null;
  for (var i = 0; this.GrupoItens.length > i; i++) {
    //Primeiro
    if (i != 0)
      primeiro = false;

    //Ultimo
    if ((primeiro && this.GrupoItens.length == 1) ||
      (primeiro == false && this.GrupoItens.length - 1 == i))
      ultimo = true;

    //Frufru no inicio p/ deixar o canto aredondado
    if (primeiro) {
      td = tr.insertCell(tr.childNodes.length);
      td.className = "openmenuAzul";
      td.style.width = "2px";
      td.style.border = "none";
      td.innerHTML = "<label style='visibility: hidden;'>a</label>";
    }

    this.GrupoItens[i].Render();

    //Frufru no fim p/ deixar o canto aredondado
    if (ultimo) {
      td = tr.insertCell(tr.childNodes.length);
      td.className = "closemenuAmarelo";
      td.style.width = "2px";
      td.style.border = "none";
      td.innerHTML = "<label style='visibility: hidden;'>a</label>";
    }

    iSepar = this.GrupoItens[i].ImgSepar;
    if (iSepar == "")
      iSepar = this.ImgSepar;

    //Não pode entrar no ultimo
    if (iSepar != "" && ultimo == false) {
      td = tr.insertCell(tr.childNodes.length);
      td.style.width = "1px";
      if (this.GrupoItens[i].Css == "")
        td.className = this.CssMenuGrupoItens;
      else
        td.className = this.GrupoItens[i].Css;

      var img = addElement("img", "");
      img.src = iSepar;
      td.appendChild(img);
    }
  }

  var divItens = addElement("div", "_divItens_nemu");
  divMenu.appendChild(divItens);
}
