function popupContainer() {
  this.popupCurrent=null;               // текущее открытое меню
  this.popupArray=new Array(50);        // список всех меню на странице
  this.pac=0;                           // число меню на странице
  this.popupActive=0;                   // есть ли открытое меню
  this.idPrefix="menu";
};

pu_cont=new popupContainer();
browser=getBrowser();

// Двигает скользящее меню, располагая его относительно позиции курсора мыши.
function moveMenu(e) {
  if (pu_cont.popupCurrent!=null) {
     if (!pu_cont.popupCurrent.isStatic) {
        setLeft(pu_cont.popupCurrent.id, getEventX(e)+5);
        setTop(pu_cont.popupCurrent.id, getEventY(e)+5);
     }
  }
};

// Открывает меню. Левый верхний угол располагается относительно либо элемента с указанным ID, либо позиции курсора мыши.
// Обработчик вешается на произвольное событие в объемлющей странице.
function popupDisplay(evt,popup,ownerId) {
  if (popup.disabled) {
     return true;
  }
  pu_cont.popupActive-=1;
  pu_cont.popupCurrent=popup;
  if (popup != null) {
     var x=getEventX(evt);
     var y=getEventY(evt);
     if (popup.isStatic) {
        if (ownerId == null) {
           x-=6; y-=6;
        }
        else {
           x = getOffsetLeft(ownerId);
           y = getOffsetTop(ownerId) + getHeight(ownerId);
        }
     }
     else {
       x+=5; y+=5;
     }
     // Положение скользящего меню (если оно уже открыто) определяется не здесь, а в функции moveMenu
     if (!(isVisible(popup.id) && popup.isStatic)) {
        setLeft(popup.id,x);
        setTop(popup.id,y);
     }
  }
  hideAll();
  if (popup!=null) {
     setVisible(popup.id,true);
  }
  return true;
};

function popupDisable(popup)
{
 if (popup != null) {
    popupHide(popup);
    popup.disabled = true;
 }
}

function popupEnable(popup)
{
 if (popup != null) {
    popup.disabled = false;
 }
}

// Скрывает меню. Вешается на некоторое событие в объемлющей странице.
function popupHide(popup) {
  if (popup != pu_cont.popupCurrent)
     return true;

  pu_cont.popupActive+=1;
  if (!popup.isStatic) {
     hideAll();
     pu_cont.popupCurrent=null;
  }
  else {
     setTimeout("hideAllIfActive()",100);
  }
  return true;
};

function activate() {
  pu_cont.popupActive-=1;
};

function deactivate() {
  pu_cont.popupActive+=1;
  setTimeout("hideAllIfActive()",1);
};

function hideAllIfActive() {
  if (pu_cont.popupActive==0) {
     hideAll();
  }
};

function hideAll() {
  for (var i=0; i<pu_cont.pac; i++) {
      setVisible(pu_cont.popupArray[i],false);
  }
};

// Конструктор класса
function ROLPopup(width, cellpadding) {
  var index=pu_cont.pac+1;                    // номер этого меню
  this.id=pu_cont.idPrefix+index;             // имя DIV, содержащего меню
                                              // увеличить число меню на странице и сохранить id нового меню
  pu_cont.popupArray[pu_cont.pac++]=pu_cont.idPrefix+index;
  this.disabled = false;
  this.createPopup=createPopup;
  this.addLink=addLink;
  this.addLinkWithTarget=addLinkWithTarget;
  this.addText=addText;
  this.addHeader=addHeader;
  this.css="ROLpopup";
  this.target="_self";
  this.cellpadding=0;
  this.isStatic=false;                        // Меню со ссылками всегда статическое, иначе динамическое
  if (arguments.length>=2) {
     this.cellpadding=cellpadding;
  };
  this.leftpadding=5;
  this.rightpadding=5;
  // Вводная разметка - все меню погружается в таблицу, ширина которой может быть передана в первом параметре конструктора,
  // а ctllpadding - во втором. Поскольку событие onMouseOut повешено на таблицу, то меню закрывается, когда курсор выходит из таблицы.
  this.shtml='<table onmouseover="activate()" onmouseout="deactivate()"  border="0" cellspacing="0" cellpadding="' +
             this.cellpadding+'"';
  if (arguments.length>=1 && arguments[0]!=0) {
     this.shtml += ' width='+width;
  }
  this.shtml += '>';
  this.html='';                         // Здесь формируется само меню
  this.ehtml='</table>';                // Заключительная разметка
};

// Добавляет в меню ссылки без target. Параметры объединены в пары: текст, URL.
function addLink() {
  for (var i=0; i < arguments.length; i+=2) {
      this.html += '<tr><td class="popuplnk" width='+this.leftpadding+'>&nbsp;</td><td class="' +
                   this.css+'lnk"><a class="popuplnk" href="'+arguments[i+1]+'" target="'+this.target+'">'+arguments[i] +
                   '</a></td><td class="popuplnk" width='+this.rightpadding+'>&nbsp;</td></tr>';
  }
  this.isStatic=true;
};

// Добавляет в меню ссылки c target. Параметры объединены в пары: текст, URL.
function addLinkWithTarget() {
  for (var i=0; i<arguments.length; i+=3) {
       this.html+='<tr><td class="popuplnk" width='+this.leftpadding+'>&nbsp;</td><td class="'+this.css +
       'lnk"><a class="popuplnk" href="'+arguments[i+1]+'" target="'+arguments[i+2]+'">'+arguments[i] +
       '</a></td><td class="popuplnk" width='+this.rightpadding+'>&nbsp;</td></tr>';
  }
  this.isStatic=true;
};

// Добавляет текстовые строки без URL
function addText() {
  for (var i=0; i<arguments.length; i++) {
      this.html+='<tr><td class="popuptxt" width='+this.leftpadding+'>&nbsp;</td><td class="'+this.css+'txt">' +
                 arguments[i]+'</td><td class="popuptxt" width='+this.rightpadding+'>&nbsp;</td></tr>';
  }
};

// Добавляет заголовок меню. Вызов метода должен предшествовать вызовам addText и addLink
function addHeader(text) {
  this.html+='<tr><th class="popuphdr" width='+this.leftpadding+' nowrap>&nbsp;</th><th class="'+this.css +
             'hdr">'+text+'</th><th class="popuphdr" width='+this.rightpadding+'>&nbsp;</th></tr>';
};

// При создании нового меню создается скрытый DIV, содержащий таблицу, сформированную при добавлении в меню элементов.
function createPopup() {
  if (browser=="NS4") {
     document.writeln('<layer onmouseover="activate()" onmouseout="deactivate()" id="' +
                      this.id+'" visibility="hide">'+this.shtml+this.html+this.ehtml+'</layer>');
  }
  if (browser=="IE" || browser=="NS6") {
     document.writeln('<div id="'+this.id+'" class="popup">'+this.shtml+this.html+this.ehtml+'</div>');
  }
};

document.onmousemove=moveMenu;

if (browser=="NS4") {
   document.captureEvents(Event.MOUSEMOVE);
}

