/*
 * (c) Ambientia Ltd.
 * dhtml menu 6.6
 *
 * recent additions:
 * -muilla kuin ns4 luodaan vain max syvyyden verran layereitä
 * -tyhjät valikot = itemejä
 * -lisätty syvyys funktio addItemWithDepth
 * -rakenne muutettu proto-muotoon (eräs muisti-optimointi)
 * -hiding of "bully" elements (select, flash ...)
 * -item styles
 * -onfocus open
 *
 * Netcape 4+, Internet Explorer 4+
 * Mozilla 5,  Opera 5+
 *
 * required: dhtmlib.js
 *
 * @author J Löf
 */
var jMenuS = new Array();     //menu stack
var jmenuTimeout = null;      //timeout pointer
/* ------ Preferences ----- */
var prefs =
{
  UP:0,RIGHT:1,DOWN:2,LEFT:3,
  EMPTY_MENUTEXT         : '- no items -',   //if set, emptymenus alway contain atleast this text
  LAYER_PREFIX           : 'menu',     //string div id prefix
  MENU_TIMEOUT           : 1000,       //milliseconds to hide
  HIDE_ALL               : 1,          //boolean hide rootlevel on mouseout
  OVERRIDE_COORDS        : 0,          //boolean always override given coordinates
  MOUSE_POSITION         : 0,          //boolean always use mouse positioning
  ROOT_DIRECTION         : 2,          //direction to open root
  FIRSTCHILD_DIRECTION   : 1,          //direction to open firstchild
  DEFAULT_CSS            : 'valikko',  //default class name
  TABLE_PADDING          : 2,          //layout table padding
  DEFAULT_WIDTH          : 250,        //default width, if dynamic check fails (isNS4)
  DEFAULT_HEIGHT         : 20,         //default height, if dynamic check fails (isNS4)
  AVERAGE_FONT_WIDTH     : 4,          //for approximating menu sizes when can't read element size (isNS4)
  ITEM_MARKER            : '<img src="/pics/dhtml-nuoli.gif" alt="" height="12" width="4"  border="0" align="right">'
};
/* ------ /Preferences ----- */
function JValikko( _xset, _yset, _width, _height, _css, _open )
{ 
    this._xset = _xset || null;
    this._yset = _yset || null;
    this._xoffset = 0;
    this._yoffset = 0;
    this._width = _width || 0;
    this._height = _height || 0;
    this._x = 0;       //internal calls only
    this._y = 0;       //internal calls only
    this._css = _css || prefs.DEFAULT_CSS; 
    this._open = false; 
    this._parent = false;
	if ( DHTMLBase.browser.isNS4 )
		this._layer = prefs.LAYER_PREFIX + jMenuS.length;
	else
		this._layer = prefs.LAYER_PREFIX + "1";
    
	this.self = "jMenuS[" + jMenuS.length + "]";
    this._id = "jM"+jMenuS.length;
    jMenuS.push(this);
    this.itemS = new Array();
    this.subMenuS = new Array();
	this.hiddenElements = new Array();
}

// JValikon alimetodit

		JValikko.prototype.lisaaItem = function (_name, _url, _target, _onmouseover, _onmouseout, _css)
    {
        var p =
        {
          _name        : _name,
          _url         : _url,
          _id          : this._id + 'i' + this.itemS.length,
          _mouseover   : this.self + ".hideChildren()",
          _target      : _target,
          _onmouseover : _onmouseover,
          _onmouseout  : _onmouseout,
          _css         : _css
        }
        this.itemS.push(p);
        return p;
    }
    
	var max_depth = 0;

    JValikko.prototype.addItemWithDepth = function (_depth, _name, _url)
    {
      if (_depth > max_depth)
      {
		  max_depth = _depth;
      }


      //init branch tracker
      if (!this.currentBranch)
      {
        this.currentBranch = this; //is root
        this.currentBranch._depth = 0;
      }
      //track
		  if (_depth == this.currentBranch._depth)
		  {
			  var parent = this.currentBranch._parent;
		  }
		  else if (_depth > this.currentBranch._depth)
		  {
			  var parent = this.currentBranch;
		  }
		  else if (_depth < this.currentBranch._depth)
		  {
			  var parent = this.currentBranch;
			  while (parent._depth >= _depth)
			  {
				  parent = parent._parent;
			  }
      }
	
      this.currentBranch = parent.lisaaMenu(_name, _url);
      this.currentBranch._depth = _depth;
	  if (!DHTMLBase.browser.isNS4)
		this.currentBranch._layer = prefs.LAYER_PREFIX + this.currentBranch._depth;

    }
    
    JValikko.prototype.lisaaMenu = function (_name, _url, _target, _onmouseover, _onmouseout, _css)
    {   
        var t = new JValikko(null, null, this._width, this._height, this._css, false);
        t._parent = this;
        var p = this.lisaaItem(_name, _url, _target, _onmouseover+";"+t.self+".swz(this);", _onmouseout+";"+t.self+".swz(this);", _css);
        p._submenu = t;  
        this.subMenuS.push(t);
        return t;
    }
    
    JValikko.prototype._look = function (n)
    {
        if (this._customlook) return this._customlook(n);
        
        var html = "";
        
       /* if (!this.itemS.length && prefs.EMPTY_MENUTEXT)
          this.lisaaItem(prefs.EMPTY_MENUTEXT)
         */
        if (this.itemS && this.itemS.length )
        {
          if (DHTMLBase.browser.isNS4) html += '<table cellpadding="1" cellspacing="0" border="0"><tr><td bgcolor="#000000">';
          html += '<table class="'+this._css+'" cellpadding="'+prefs.TABLE_PADDING+'" cellspacing="0" border="0"';
          if (!DHTMLBase.browser.isNS4 && this._width) html += ' width="'+this._width+'"';
          if (DHTMLBase.browser.isNS4) html += ' width="100%"';
          html += '>';
          for (var i = 0; i < this.itemS.length; i++)
          {
            html += '<tr class="'+this._css+'"><td class="'+(this.itemS[i]._css||this._css)+'" onmouseover="DHTMLBase.hoverIn(this)" onmouseout="DHTMLBase.hoverOut(this)"><nobr>';
            if (this.itemS[i]._submenu && this.itemS[i]._submenu.itemS.length) html += prefs.ITEM_MARKER;
            if (this.itemS[i]._url)
            {
              html += '<a';
              if (this.itemS[i]._url)       html += ' href="'+this.itemS[i]._url+'"';
              if (this.itemS[i]._target)    html += ' target="'+this.itemS[i]._target+'"';
              html += ' onmouseover="'+this.itemS[i]._onmouseover+'"';
              html += ' onfocus="'+this.itemS[i]._onmouseover+'"';
              html += ' onmouseout="'+this.itemS[i]._onmouseout+'"';
              html += ' class="'+this._css+'">';
            }
            html += this.itemS[i]._name;
            if (this.itemS[i]._url)         html += '</a>';
            html += '</nobr></td></tr>';
          }
          html += '</table>';
          if (DHTMLBase.browser.isNS4) html += '</td></tr></table>';
        }
        return html;
    }
    
    JValikko.prototype.create = function ()
    {
		DHTMLBase.createLayer( this._layer, this._look(), this._xset, this._yset, this._open );
    }
    
    JValikko.prototype.show = function (_fromAnchor )
    {
        if ( this._open ) return; //on jo näkyvillä
     
	   
        // Piirretään ensin layer jos muu kuin ns4
		if(!DHTMLBase.browser.isNS4)
			DHTMLBase.writeToLayer( this._layer, this._look());


        if ( prefs.MOUSE_POSITION || !_fromAnchor )
        {
           /*paikannus hiiren koordinaattiin */
          this._x = window.event.x;
          this._y = window.event.y;
          if (this._parent && DHTMLBase.browser.isNS4)
          {
            this._x += this._parent._x;
            this._y += this._parent._y;       
          }
        } //end else if
        else           
        {
            /*paikannus parent-elementin koordinaatin perusteella */
            if (this._parent) //alitason valikolle
            {
                if (_fromAnchor.parentNode && _fromAnchor.parentNode.parentNode)
                {
					var a = DHTMLBase.getGeometry(_fromAnchor.parentNode.parentNode);
				}
                else
                  var a = DHTMLBase.getGeometry(_fromAnchor);
                
                this._x = a.x;
                this._y = a.y;     
                if (DHTMLBase.browser.isNS4) //netscape 4
                {
                    var xl = 0;
                    for (var i = 0; i < this._parent.itemS.length; i++)
                      if (this._parent.itemS[i]._name.length > xl) xl = this._parent.itemS[i]._name.length;
                   this._x += parseInt(this._parent._x) + parseInt(xl * prefs.AVERAGE_FONT_WIDTH);
                   this._y += parseInt(this._parent._y);            
                   var height = this.itemS.length * prefs.DEFAULT_HEIGHT; //guess height          
                   if ( (this._y + height) > DHTMLBase.bodyHeight() )
                      this._y = (DHTMLBase.bodyHeight() - height);
                   if (this._y < 0)
                    this._y = 0;
                }
                else //paremmat selaimet
                {  
                  var own = DHTMLBase.getGeometry(DHTMLBase.getLayer(this._layer));
                  if (prefs.FIRSTCHILD_DIRECTION==prefs.RIGHT || this._parent._parent)
                  {     

                    if ((a.x + a.width + own.width) > DHTMLBase.bodyWidth())
                    {
                      this._x -= own.width;
                      if (this._x < 0) this._x = 0;
                    }
                    else
                        this._x += a.width;
                  }    
                  
                  if ( (this._y + own.height) > DHTMLBase.bodyHeight() )
                      this._y = (DHTMLBase.bodyHeight() - own.height);
                  if (this._y < 0) this._y = 0;
                  
                  if (prefs.FIRSTCHILD_DIRECTION==prefs.DOWN && !this._parent._parent)this._y += a.height;
                }
            } //end if
            else if (!this._parent) //juuritason valikoille
            {
                var a = DHTMLBase.getGeometry(_fromAnchor);
                this._x = a.x;
                this._y = a.y;
                if (prefs.ROOT_DIRECTION == prefs.RIGHT)
                    this._x += a.width;
                else
                    this._y += a.height;
                var own = DHTMLBase.getGeometry(DHTMLBase.getLayer(this._layer));
                if (own.width < a.width)
                {
                    var l = DHTMLBase.getLayer(this._layer);
                    l.style.width = a.width;
                    l.firstChild.style.width = a.width;   
                } //endif
                
                own = DHTMLBase.getGeometry(DHTMLBase.getLayer(this._layer));
                                      
                if (DHTMLBase.browser.isNS4) //netscape 4
                {
                    var xl = 0;
                    for (var i = 0; i < this.itemS.length; i++)
                      if (this.itemS[i]._name.length > xl) xl = this.itemS[i]._name.length;
                    own.width = (xl * prefs.AVERAGE_FONT_WIDTH);
                    
                    own.height = this.itemS.length * prefs.DEFAULT_HEIGHT; //guess height          
                }
                
                if ((this._x + own.width) > DHTMLBase.bodyWidth())
                  this._x = DHTMLBase.bodyWidth()-own.width;
            
                if ( (this._y + own.height) > DHTMLBase.bodyHeight() )
                  this._y = (DHTMLBase.bodyHeight() - own.height);
            
            } //endif
        } //endif
        
        if ( this._xset && !prefs.OVERRIDE_COORDS) this._x = this._xset;
        if ( this._yset && !prefs.OVERRIDE_COORDS) this._y = this._yset;
        
        DHTMLBase.setLayerPosition( this._layer, (parseInt(this._x) + parseInt(this._xoffset)), (parseInt(this._y) + parseInt(this._yoffset)), this._align);
        
        DHTMLBase.visibility( this._layer, true);
        /* piilota alle jäävät selectboxit ym. elementit */
        this.hideElements();
        
        this._open = true;
    }
    
    JValikko.prototype.hide = function ()
    {
        if (!this._open) return;
        DHTMLBase.visibility( this._layer, 0);
		if (!DHTMLBase.browser.isNS4)
		{
			DHTMLBase.getLayer( this._layer).style.width = 0;
			DHTMLBase.writeToLayer( this._layer, "");
		}
        
        /* restore hidden elements */
        this.restoreHiddenElements()
        
        for( var s = 0; s < this.subMenuS.length; s++ )
            if (this.subMenuS[s]._open)
                this.subMenuS[s].hide();
        this._open = false;
    }
    
    JValikko.prototype.hideChildren = function ()
    {
        for (var c = 0; c < this.subMenuS.length; c++)
          this.subMenuS[c].hide();
    }
    
    JValikko.prototype.findRoot = function()
    {
        var thisRoot = false;
        var level = this;
        while (!thisRoot)
        {
            if (level._parent) level = level._parent;
            else thisRoot  = level.self;
        }
        return thisRoot;
    }
    
    JValikko.prototype.swz = function ( _fromAnchor )
    {
        if (!this.itemS.length)
        {
          if (this._parent)
            for( var u = 0; u < this._parent.subMenuS.length; u++ )
                this._parent.subMenuS[u].hide();
          return;
        }
        for( var a = 0; a < jMenuS.length; a++ )
            if ( !jMenuS[a]._parent && ( jMenuS[a].self != this.findRoot() ) )
                jMenuS[a].hide();
        if (this._parent)
            for( var u = 0; u < this._parent.subMenuS.length; u++ )
                this._parent.subMenuS[u].hide();
        this.show(_fromAnchor);
    }
       
    
    JValikko.prototype.hideElements = function ()
    {
      this.restoreHiddenElements();
      var layGeo = DHTMLBase.getGeometry(DHTMLBase.getLayer(this._layer));
      
      for (var i = 0; i < DHTMLBase.hideTheseArray.length; i++)
  	  {
        var sel = DHTMLBase.hideTheseArray[i];
               
  		  if ( (sel.geo.top >= layGeo.top && sel.geo.top <= layGeo.bottom) || (sel.geo.bottom >= layGeo.top && sel.geo.bottom <= layGeo.bottom) )
  			  if ( ( sel.geo.left <= layGeo.right && sel.geo.left >= layGeo.left ) || (sel.geo.right >= layGeo.left && sel.geo.right <= layGeo.right ) || (sel.geo.left <= layGeo.left && sel.geo.right >= layGeo.right) )
          {
  				  this.hiddenElements.push(sel);
  				  sel.style.visibility = 'hidden';
  			  }
  	    
      }
    }
    
    JValikko.prototype.restoreHiddenElements = function()
    {
	    while (this.hiddenElements.length)
		    this.hiddenElements.pop().style.visibility = 'visible';
    }
// (eof) JValikon alimetodit
		
		
function jValikkoSuljeKaikki() { jMenuHideAll(); }

function jMenuHideAll()
{
    for (var n = 0; n < jMenuS.length; n++)
    {
        if (prefs.HIDE_ALL) jMenuS[n].hide();
        else jMenuS[n].hideChildren();
    }
}

function JValikkoAlusta()
{   


	if (DHTMLBase.browser.isNS4)
    {
		for (var h = 0; h < jMenuS.length; h ++ )
		{
			jMenuS[h].create();
		}
	}
	else
	{
		for (var h = 1; h <= max_depth; h ++ )
		{
		DHTMLBase.createLayer( prefs.LAYER_PREFIX + h, '', 0, 0, 0);  
		}
	}
    /* scan for elements to be hidden selectboxes etc. */
    DHTMLBase.hideTheseScan(document.body);
}

/* ------------------------ EVENT HANDLERS ------------------------------------------------------------- */  
if (DHTMLBase.browser.isNS4)
  window.document.captureEvents( Event.MOUSEOUT | Event.MOUSEOVER | Event.MOUSEDOWN |  Event.MOUSEMOVE );

document.onmouseout = function (e)
{
    DHTMLBase.setupEventObject(e)
    if ( (element = DHTMLBase.findProp(window.event.srcElement, "id")) != null )
       if ( element.id.match && element.id.match(prefs.LAYER_PREFIX) )
       {
           clearTimeout(jmenuTimeout);
           jmenuTimeout = setTimeout( "jMenuHideAll()", prefs.MENU_TIMEOUT );
       }
}
document.onmouseover = function (e)
{
    DHTMLBase.setupEventObject(e)
    if ( (element = DHTMLBase.findProp(window.event.srcElement, "id")) != null )
       if ( element.id.match && element.id.match(prefs.LAYER_PREFIX) )
        clearTimeout(jmenuTimeout);
}
document.onmousedown = function (e)
{
    DHTMLBase.setupEventObject(e)
    if ( DHTMLBase.findProp(window.event.srcElement, "href") == null )
        jMenuHideAll();
}

