var fb = typeof(console) == 'undefined' ? {
    log: function(){},
    error: function(){}
} : console;


var Menu = Class.create({
    initialize: function()
    {
        // blocks|unblocks submenu hide|show
        this.canHide = false;
        // currently .active tab
        this.currentTab = -1;
        // indicates whether submenu is shown
        // contains tab indexes and true|false values
        this.states = {};
        this.sRef = $('header').select('.drop-down-menu');
    },
    
    // handle tabs hover
    hover_it: function()
    {
        $('header').down('.h-menu').observe('mouseover', function(evt)
        {   
	    try{ 
            var li = null;
            var elm = evt.element();
            elm.hasClassName('top-level') ? li = elm : li = elm.up('.top-level');

            var position = li.getAttribute('for');
            if(this.currentTab == position)
                return -1;
            else
                this.states[this.currentTab] = false;

            var needed = this.sRef[position];
         
            if(this.states[position] === false || typeof(this.states[position]) == 'undefined')
            {                
                this.canHide = false;
                this.states[position] = true;
                
                this.currentTab = position;
                $('header').select('.selected').invoke('removeClassName', 'selected');
                li.addClassName('selected');
                this.sRef.invoke('addClassName', 'hidden');
                // appear
                needed.hide().removeClassName('hidden');
               
                new Effect.Appear(needed, {
                    duration: 0.8,
                    afterFinish: function(){
                        this.canHide = true;
                    }.bind(this)
                });
            }
	 }catch(e){}
        }.bind(this));
    },

    //
    // Mouse out from h-menus
    exit_it: function()
    {
        $('header').down('.h-menu').observe('mouseout', function(evt)    
        {
            var elm = evt.relatedTarget;
            // Ie6 measures
            // in case no correct element was transmitted
            if(elm == null || typeof(elm) == 'undefined')
                return -1;
            // if show|hide is blocked
            if(!this.canHide)
                return -1;
            // if hovered element is related with hovered elm
            if($(elm).hasClassName('inner-link')
                || $(elm).hasClassName('top-level')
                    || $(elm).hasClassName('sub-menu-item')
                        || $(elm).hasClassName('inner-link')
                            || $(elm).hasClassName('sub-menu-link')
                                || $(elm).hasClassName('drop-down-menu'))
                return -1;

            //
            // hide submenu
            //

            var needed = this.sRef[this.currentTab];

            if(this.states[this.currentTab])
            {
                this.states[this.currentTab] = false;
                this.currentTab = -1;
                $('header').select('.selected').invoke('removeClassName', 'selected');
                needed.hide();
            }
        }.bind(this));
    },

    //
    // mouse out from submenus
    drop_down_exit: function()
    {
       $$('.drop-down-menu').each(function(ul)
        {       
            ul.observe('mouseout', function(evt)
            {
                var elm = evt.relatedTarget;

                // ie6 bottleneck
                try{
                    // if hovered elm has nothing to do wight submenu
                    if($(elm).hasClassName('sub-menu-link') 
                            || $(elm).hasClassName('sub-menu-item')
                                || $(elm).hasClassName('inner-link')
                                    || $(elm).hasClassName('top-level')
                                        || $(elm).hasClassName('drop-down-menu'))
                        return -1;
                }catch(e){return -1;}

                // hide submenu
                this.states[this.currentTab ]= false;
                this.currentTab = -1;
                ul.hide();
            }.bind(this));
        }.bind(this));
    },
    
    start: function()
    {
        this.hover_it();
        this.exit_it();
        this.drop_down_exit();
    }
});

function fixPng()
{
    Element.addMethods({
        pngHack: function(el){
            var el = $(el);
            if (!Prototype.Browser.IE) return el;
            var gif = 'images/s.gif';
            if ((el.match('img')) && (el.src.include('png'))){
                var alphaImgSrc  = el.src;
                var sizingMethod = 'scale';
                el.src = gif;
            } else if (el.getStyle('backgroundImage').include('png')){
                var bgc = el.getStyle('backgroundColor') || '';
                var alphaImgSrc = el.getStyle('backgroundImage').gsub(/url\(|\)|'|"/, '');
                var sizingMethod = 'crop';
                el.setStyle({
                    background: [bgc, ' url(', gif, ') no-repeat'].join('')
                });
            } else {
                return el;
            }
            el.runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="#{al}",sizingMethod="#{sz}")'.interpolate({
                al: alphaImgSrc,
                sz: sizingMethod
            });
            return el;
        }
    });

    $$('.drop-down-menu').each(function(li){
        li.pngHack();
    });
}

function process_ddm(ddm)
{
    ddm.select('a, span').invoke('addClassName', 'sub-menu-link');
    ddm.select('li').invoke('addClassName', 'sub-menu-item');
}

document.observe('dom:loaded', function()
{
   
    //$('header').select('.drop-down-menu').invoke('addClassName', 'hidden');
    
    // todo: need better place for it
    // png fix 
    //Prototype.Browser.IE ? fixPng() : -1;

    // identifying. Temporary measures
    $('header').select('.h-menu li').each(function(li, index)
    {
        li.setAttribute('for', index);
    });
    $('header').select('.h-menu a').each(function(li, index)
    {
        li.addClassName('inner-link');
    });
    $$('.drop-down-menu').each(function(ddm)
    {
        process_ddm(ddm);
    });

    $('header').down('.h-menu').select('li').invoke('addClassName', 'top-level');
    
    new Menu().start();
});
