// (sk) 14.05.2008
// (c) 2008 klickTel AG. All rights reserved.

// Encapsulated as class-like construct to keep the global namespace clean
var ktMenuClass = Class.create({

    isMaps:0,
    eventListenersCreated:false,
    loginStatus:false,
    prototypeVersion:0,
    isInitialized: false,
    iframeEl:null,
    isMSIE6:false,
    
    initialize:function()
    {
        // Easy: check if in maps mode!
        var isMaps = 0;
        if(typeof mapUtils != 'undefined') {
            isMaps = 1;
        }
        this.isMaps = isMaps;
        this.eventListenersCreated = false;
        this.loginStatus = 0;

        this.prototypeVersion = parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1]);

        // Detect IE < 7
        if(navigator.userAgent.indexOf("Opera")==-1){
            if (navigator.appVersion.indexOf("MSIE")!=-1){
                    var temp=navigator.appVersion.split("MSIE");
                    var version=parseFloat(temp[1]);
                    this.isMSIE = true;
                    this.isMSIE6=(version < 7);
            }
        }
    },
    
    
    /*****************/
    /*** MOUSEOVER ***/
    /*****************/
    mouseOver:function(e) {
        // console.log('menu.js: mouseover');
        if(window.ktMenuCloseTimer != null) window.clearTimeout(window.ktMenuCloseTimer);
        var el = Event.element(e);
        if(el.tagName.toLowerCase() != 'ul') {
            var layerUL = el.up('li').down('ul');
        } else {
            var layerUL = el;
        }
        if(layerUL != null) {
        	if(this.isMSIE6) {
        		layerUL.style.display = "block";
        	} else {
            	layerUL.show();
        	}
            //layerUL.style.display = "block";
            //alert("menu.js: mouseover "+layerUL.style);
            if($('menu_iframe') != null) {
                $('menu_iframe').show();
            }
        }
    },
    

    /*****************/
    /*** CLOSEMENU ***/
    /*****************/
    closeMenu:function(e)
    {
        // Get a handle to the "Meine Adressen" tab
        if(this.prototypeVersion < 1.6) {
            var tab = $$('#nav_main ul li')[6];
        } else {
            var tab = $('nav_main').select('ul li')[6];
        }
        var layerUL = tab.down('ul');
        if(layerUL != null) {
            // Delay because there is some space between the nav li and the ul containing the entries
            window.ktMenuCloseTimer = window.setTimeout(function() {
                layerUL.hide();
                if($('menu_iframe') != null) {
                    $('menu_iframe').hide();
                }
            }, 200);
        }
    },


    /****************/
    /*** MOUSEOUT ***/
    /****************/
    mouseOut:function(e) {
        this.closeMenu();
    },

    
    /******************/
    /*** REPOSITION ***/
    /******************/
    reposition:function() {
        if($('ktMenuUserLoginData') != null) {
            var mainUL = $('ktMenuUserLoginData').up('ul');
            var diff = mainUL.getWidth() - mainUL.up('li').getWidth() + 2;
        } else {
            var diff = 0;
        }
        if(this.prototypeVersion < 1.6) {
            mainUL.style.marginLeft='-'+diff+'px';
            if($('menu_iframe') != null) {
                //$('menu_iframe').style.marginLeft='-'+diff+'px';
            }
        } else {
            mainUL.setStyle({
                marginLeft:'-'+diff+'px'
            });
            if($('menu_iframe') != null) {
            /*
                $('menu_iframe').setStyle({
                  //  marginLeft:'-'+diff+'px'
                });
             */
            $('menu_iframe').clonePosition(mainUL);
            $('menu_iframe').setStyle({
                position:'absolute'
            });
           // alert($('menu_iframe').inspect());
            }
        }
    },
    
    
    /*********************/
    /*** HANDLE LOGOUT ***/
    /*********************/
    handleLogout:function(e, noLoginDialogExec) {
        //console.log('menu.js: handleLogout 0');
        if(typeof mapUtils != 'undefined') {
            mapUtils.logOut();
        }
        this.closeMenu();
        $('ktMenuUserLoginData').hide();
        this.mouseOut(e);
        if(e != null) Event.stop(e);
        this.reposition();
        //console.log('menu.js: handleLogout 1');
        if(!noLoginDialogExec) {
            //loginDialog.onLogout(true);
            loginDialog.forceLogout();
        }
        //console.log('menu.js: handleLogout 2');
    },
    
    
    /**************/
    /*** UPDATE ***/
    /**************/
    update:function(action) {
        if(action == null) action = '';
        //console.info(action);

        // Get a handle to the "Meine Adressen" tab
        if(this.prototypeVersion < 1.6) {
            var tab = $$('#nav_main ul li')[6];
        } else {
            var tab = $('nav_main').select('ul li')[6];
        }

        // Easy: check if in maps mode!
        var isMaps = 0;
        if(typeof mapUtils != 'undefined') { // && mapUtils != null) {
            isMaps = 1;
        }
		
		if (!this.isInitialized) {
		
			// If in maps mode modify link
			if (isMaps) {
				tab.observe('click', function(e){
					this.closeMenu();
					if (Event.element(e).id != 'ktMenu_MYDE_Link') {
						Event.stop(e);
						mapUtils.switchToAddressbook();
					}
				}
.bindAsEventListener(this));
				tab.down('a').href = '#';
			}
		}

        // UPDATE UL
        new Ajax.Request('/global/ajax/menu.php', 
        {
            parameters:
            {
                src:top.location.href,
                maps:isMaps,
                sid:this.getParam('sid')
            },
            
            onSuccess:function(req) {
                tab.down('ul').update(req.responseText);
                this.reposition();

                if(!isMaps) {
                    tab.down('a').href=$("ktMenu_MYDE_Link").href;
                }

                if(!ktMenu.eventListenersCreated) {
                    tab.observe('mouseover', this.mouseOver.bindAsEventListener(this));
                    tab.observe('mouseout', this.mouseOut.bindAsEventListener(this));
                    //tab.down('ul').observe('mouseout', ktMenu.mouseOut);
                    this.eventListenersCreated = true;
                }

                 // Maps Mode -> modify link
                if($('ktMenuLogoutLink') != null) {
                    $('ktMenuLogoutLink').observe('click', this.handleLogout.bindAsEventListener(this));
                }
            }.bind(this)
        });
    },

    getParam:function(name)
    {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
            return "";
        else
            return results[1];
    },


    /************/
    /*** INIT ***/
    /************/
    init:function() {
        if (this.isInitialized) {
                return;
        }
	
        if(typeof Prototype != 'undefined' && Prototype != null) {            
            if($('nav_main') != null) {
                // Easy: check if in maps mode!
                if(typeof mapUtils != 'undefined') {
                    mapUtils.listenEvent('login', function() {
                        this.update('login');
                    }.bindAsEventListener(this));
                    mapUtils.listenEvent('logout', function() {
                        this.update('logout');
                    }.bindAsEventListener(this));
                }
                this.update();
		this.isInitialized = true;

                // IF IE < 7 add an iframe to overlay SELECT boxes
                if(0 && this.isMSIE6) {
                    var iframe = new Element('iframe', { id:'menu_iframe' });
                    $(document.body).appendChild(iframe);
                    iframe.setStyle({
                        display:'none',
                        position:'absolute',
                        top:0,
                        left:0,
                        zIndex:99999998
                    });
                    this.iframeEl = iframe;
                }


            }
        } else {
            console.error('Prototype.js V1.6 or later is required for menu.js');
        }
    }
});

var ktMenu = null;

Event.observe(window, 'load', function() {
    if(typeof mapUtils == 'undefined') {
        ktMenu = new ktMenuClass();
        ktMenu.init();
    }
});
