Jump to content

User:Bradv/Scripts/Menubook.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// MENUBOOK
// Created by Bradv
// Version 0.9 - April 17, 2010

// MENUBAR OBJECT
menubar = {
    initialized: false,
    element: null,
    menus: [],
    currentMenu: null,    
    topzindex: 10,
    stylesheet: null,
    
    init: function () {
        if (!menubar.initialized) {
            menubar.IMenu.init();
            menubar.IMenuItem.init();
            menubar.initialized=true;
        }
    },
    styles: {
        setRules: function (visible) {
            var rules = [
                '#menubar {position: fixed;top: 0px;left: 0px;width: 100%;padding: 0 1em;margin: 0;line-height: 2em;max-height: 2em;font-size: 1.2em;background-color: #f0f0f0;border-bottom: 1px solid darkblue;z-index: 10;white-space: nowrap;}',
                'body {margin-top: 2.5em;background-position: 0 2.5em;}',
                '#p-cactions, #p-personal, #p-logo, #sprint {margin-top: 2em;}',
                '.menu {position: relative;display: inline;}',
                '.menu .pBody {position: fixed;border: 1px solid darkblue;background-color: #f0f0f0;overflow: auto;min-width: 15em;min-height: 1em;padding: .5em !important;margin: 0 !important;}',
                '.menu h5 {padding:.4em .5em .4em;margin-bottom: -2px;text-transform: none;font-weight: bold;color: darkblue;cursor: default;display: inline;}',
                '.menu .highlight, .menu li.highlight, .menu li.highlight {background-color: darkblue !important; color: #f0f0f0 !important;}',
                '.menu ul {list-style: none;margin: 0 !important;padding: 0 !important;}',
                '.menu li {list-style: none;margin: 0 !important;padding-left: 1.5em !important;padding-right: 1.5em !important;background: none;line-height: 1.8em;height: 1.8em;color: darkblue;}',
                '.menu li a:link, .menu li a:visited {color: inherit;background-color: inherit;}',
                '.menu li.break {border-bottom: 1px solid darkblue;}',
                '.menu li .submenu_arrow {position: absolute;right: 0.3em;}',
                '.menu li .submenu {position: absolute;}',
                '#menubar_clock {position: fixed;right: 0em;top: 0em;padding: 0 .5em;display: block;font-size:larger;font-weight:bolder}'];
            for (i=0; i<rules.length; i++) {
                if (visible) {
                    menubar.styles.addRule(rules[i]);
                } else {
                    menubar.styles.removeRule(rules[i]);
                }
            }
        },    
        addRule: function (rule) {
            if (!menubar.stylesheet) {
                var nod = document.createElement('style');
                nod.type = 'text/css';
                nod.rel = 'stylesheet';
                nod.media = 'screen';
                nod.title = 'menubar';
                document.getElementsByTagName('head')[0].appendChild(nod);
                
                for (var i=0; i<document.styleSheets.length; i++) {
                    if (document.styleSheets[i].title == 'menubar') {
                        menubar.stylesheet = document.styleSheets[i];
                        break;
                    }
                }
            }
            var found=false;
            for (var i=0; i<menubar.stylesheet.cssRules.length; i++) {
                var r = menubar.stylesheet.cssRules[i];                    
                if (r.selectorText==rule.substring(0,rule.indexOf('{')-1)) {
                    found=true;
                    break;
                }
            }
            if (!found) menubar.stylesheet.insertRule(rule, menubar.stylesheet.cssRules.length);
        },
        removeRule: function (rule) {
            if (menubar.stylesheet) {
                for (var i=menubar.stylesheet.cssRules.length-1; i>=0; i--) {
                    var r = menubar.stylesheet.cssRules[i];                    
                    if (r.selectorText==rule.substring(0,rule.indexOf('{')-1)) {
                        menubar.stylesheet.deleteRule(i);
                        return true;
                    }
                }
            }
        }
    },
    show: function () {
        menubar.init();
        menubar.styles.setRules(true);
        if (!menubar.element) {
            menubar.element = document.createElement('div');
            menubar.element.id = 'menubar';
            menubar.element.object = menubar;
            menubar.element.addEventListener('mousedown', function (event) {
                if (this.style.zIndex < this.object.topzindex) {
                    this.style.zIndex += this.object.topzindex;
                }
            }, false);
            document.body.appendChild(menubar.element);
        } else {
            menubar.element.style.display='';
        }
    },
    hide: function () {
        if (menubar.element) menubar.element.style.display='none';
        menubar.styles.setRules(false);
    },    
    getMenu: function (id) {
        for (var i=0;i<menubar.menus.length;i++) {
            if (menubar.menus[i].element.id == id) {
                return menubar.menus[i];
            }
        }
        return null;
    },
    addMenu: function (id, title, populateCallback, populateArgs) {
        var div = document.createElement('div');
        div.id = id;
        div.className = 'menu';
        var header = document.createElement('h5');
        header.appendChild(document.createTextNode(title));
        div.appendChild(header);
        var pBody = document.createElement('div');
        pBody.className = 'pBody';
        div.appendChild(pBody);
        var ul = document.createElement('ul');
        pBody.appendChild(ul);
        
        var m = new menubar.Menu(this, div, populateCallback, populateArgs);
        this.menus[this.menus.length] = m;
        return m;
    },
    addMenuFromPortlet: function (portlet, newid, populateCallback, populateArgs) {
        if (newid) portlet.id = newid;
        portlet.className = 'menu';
        
        var m = new menubar.Menu(this, portlet, populateCallback, populateArgs);
        this.menus[this.menus.length] = m;
        return m;
    },
    showMenu: function (menu) {
        menubar.hideMenu();
        
        menubar.currentMenu = menu;
        menu.header.className = 'highlight';
        menu.pBody.style.display = '';
        menu.pBody.style.left = menu.element.offsetLeft + 'px';
        menu.pBody.style.top = menu.header.offsetHeight + 'px';
        window.addEventListener('mousedown', function (event) {
            if (menubar.currentMenu) {
                if (!menubar.utils.isAncestor(event.target, menubar.currentMenu.element)) {
                    menubar.hideMenu();
                }
            }
        }, false);        
        menu.pBody.addEventListener('mouseup', function (event) {
            if (event.target.tagName=='A' && event.which==1) {
                menubar.hideMenu();
            }
        }, false);
        if (menu.populateCallback) {
            menu.populateCallback(menu, menu.populateArgs);
        }
    },
    hideMenu: function () {
        if (menubar.currentMenu) {
            var menu = menubar.currentMenu;
            menu.header.className = '';
            menu.pBody.style.display = 'none';
            menubar.currentMenu=null;
            for (var i=0; i<menu.menuItems.length; i++) {
                var mi = menu.menuItems[i];
                if (mi.submenu) {
                    mi.submenu.hide();
                }
            }
        }
    },
    Menu: function(parentObject, element, populateCallback, populateArgs) { //extends IMenu
        this.menuItems = [];
        this.parentObject = parentObject;
        this.element = element;
        this.populateCallback = populateCallback;
        this.populateArgs = populateArgs;
        
        this.element.object = this;
        this.header = menubar.utils.getSingleNode(this.element, 'h5');
        this.pBody = menubar.utils.getSingleNode(this.element, 'div[@class="pBody"]');
        this.ul = menubar.utils.getSingleNode(this.element, 'div[@class="pBody"]/ul');
        if (this.ul && this.ul.hasChildNodes) {
            var lis = this.ul.childNodes;
            for (var i=0; i<lis.length; i++) {
                if (lis[i].nodeName == 'LI') {
                    this.addMenuItem(lis[i]);
                }
            }
        }      
        
        this.parentObject.element.appendChild(this.element);

        this.pBody.style.display = 'none';
        
        with (this.header) {
            addEventListener('mouseover', function (event) {
                if (!menubar.currentMenu) {
                    this.className = 'highlight';
                } else {
                    menubar.showMenu(this.parentNode.object);
                }
            }, false);
            addEventListener('mouseout', function (event) {
                if (!menubar.currentMenu) {
                    this.className = '';
                }
            }, false);
            addEventListener('click', function (event) {
                if (menubar.currentMenu == this.parentNode.object) {
                    menubar.hideMenu();
                } else {
                    menubar.showMenu(this.parentNode.object);
                }
            }, false);
        }
    },    
    Submenu: function (parentObject, populateCallback, populateArgs) { // extends IMenu
        this.menuItems = [];
        this.parentObject = parentObject;
        this.populateCallback = populateCallback;
        this.populateArgs = populateArgs;
        
        this.arrow = document.createElement('span');
        this.arrow.className = 'submenu_arrow';
        this.arrow.appendChild(document.createTextNode('\u25BA'));
        this.parentObject.element.appendChild(this.arrow);
        
        this.element = document.createElement('div');
        this.element.object = this;
        this.element.className='pBody';
        this.element.style.display='none';
        this.ul = document.createElement('ul');
        this.element.appendChild(this.ul);
        this.parentObject.element.appendChild(this.element);
        
        tmp = this.addMenuItem();
        tmp.element.textContent = 'Loading...';
        
        this.visible = false;
        this.showTimeout = null;
        
        this.show = function () {
            var items = this.parentObject.parentObject.menuItems;
            for (var i=0; i<items.length; i++) {
                if (items[i].submenu && (items[i] != this.parentObject)) {
                    items[i].submenu.hide();
                }
            }
            if (this.populateCallback) {
                this.populateCallback(this, this.populateArgs);
            }
            this.visible=true;
            this.showTimeout=null;                
            this.element.style.display='';
            this.setLocation();
        }
        this.setLocation = function () {
            if (this.visible && this.parentObject.element.offsetParent) {
                var li = this.parentObject.element;
                var top = li.offsetTop + li.offsetParent.offsetTop;
                var left = li.offsetParent.offsetLeft + li.offsetParent.offsetWidth;
                this.element.style.top = top + 'px';
                this.element.style.left = left + 'px';

                if (top + this.element.offsetHeight > window.innerHeight) {
                    top = window.innerHeight - this.element.offsetHeight;
                }
                if (left + this.element.offsetWidth > window.innerWidth) {
                    left = li.offsetParent.offsetLeft - this.element.offsetWidth;
                }
                this.element.style.top = top + 'px';
                this.element.style.left = left + 'px';
            } else {
                this.hide();
            }
        }
        this.hide = function () {            
            this.element.style.display='none';
            this.visible = false;
            window.clearTimeout(this.showTimeout);
            this.showTimeout=null;
            for (var i=0; i<this.menuItems.length; i++) {
                var mi = this.menuItems[i];
                if (mi.submenu) {
                    mi.submenu.hide();
                }
            }
            this.parentObject.element.className = this.parentObject.element.className.replace('highlight', '');
        }

        with (this.parentObject.element) {
            addEventListener('mouseover', function (event) {
                var submenu = this.object.submenu;
                if (submenu && !submenu.visible) {                
                    submenu.showTimeout = window.setTimeout(function () {
                        submenu.show();
                    }, 250);
                }
            }, false);
            
            addEventListener('mouseout', function (event) {
                window.clearTimeout(this.object.submenu.showTimeout);
            }, false);
        }
    },
    IMenu: {
        init: function () {
            menubar.Menu.prototype.addMenuItem = menubar.IMenu.addMenuItem;
            menubar.Menu.prototype.removeMenuItem = menubar.IMenu.removeMenuItem;
            menubar.Menu.prototype.clearMenuItems = menubar.IMenu.clearMenuItems;
            
            menubar.Submenu.prototype.addMenuItem = menubar.IMenu.addMenuItem;
            menubar.Submenu.prototype.removeMenuItem = menubar.IMenu.removeMenuItem;
            menubar.Submenu.prototype.clearMenuItems = menubar.IMenu.clearMenuItems;
        },
        addMenuItem: function (li) {
            var m = new menubar.MenuItem(this, li);
            this.menuItems[this.menuItems.length] = m;
            return m;
        },
        removeMenuItem: function (menuItem) {
            for (var i=0; i<this.menuItems.length; i++) {
                if (this.menuItems[i] == menuItem) {
                    this.ul.removeChild(menuItem.element);
                    this.menuItems.splice(i, 1);
                    return;
                }
            }
        },
        clearMenuItems: function () {
            for (var i=this.menuItems.length-1; i>=0; i--) {
                this.ul.removeChild(this.menuItems[i].element);
            }
            this.menuItems = [];
        }
    },
    MenuItem: function (parentObject, li) { //extends IMenuItem
        this.parentObject = parentObject;
        this.element = li || document.createElement('li');
        this.element.object = this;
        this.submenu = null;        
        if (this.element.parentNode != this.parentObject.ul) {
            this.parentObject.ul.appendChild(this.element);
        }
        with (this.element) {
            addEventListener('mouseover', function (event) {
                if (this.className.indexOf('highlight')==-1) {
                    this.className += ' highlight';
                }
            }, false);
            
            addEventListener('mouseout', function (event) {
                //if (!this.object.submenu || !this.object.submenu.visible) {
                    this.className = this.className.replace('highlight', '');
                //}
            }, false);
        }
    },
    IMenuItem: {
        init: function () {
            menubar.MenuItem.prototype.createSubMenu = menubar.IMenuItem.createSubMenu;
        },
        createSubMenu: function(populateCallback, populateArgs) {
            this.submenu = new menubar.Submenu(this, populateCallback, populateArgs);
            return this.submenu;            
        }
    },
    utils: {
        readCookie: function(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') { c = c.substring(1,c.length); }
                if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); }
            }
            return null;
        },
        getSingleNode: function (context, expression) {
            var result = document.evaluate(expression, context, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
            return result.singleNodeValue;
        },
        isAncestor: function (node, ofNode) {
            while(node.parentNode) {
                if (node.parentNode == ofNode) {
                    return true;
                }
                node = node.parentNode;
            }
            return false;
        }
    }
}

// IMPLEMENTATION - MENUBOOK
menubook = {
    settings: {        
        enabled:     true,
        clock:       true,
        menulimit:   32,
        load: function () {
            for (var name in menubook.settings) {
                if (typeof menubook.settings[name] != 'function') {
                    var val = menubar.utils.readCookie('menubook_' + name);
                    if (val) {
                        switch (typeof menubook.settings[name]) {
                            case 'boolean':
                                menubook.settings[name] = (val == 'true');
                                break;
                            case 'number':
                                menubook.settings[name] = parseInt(val);
                                break;
                            default:
                                menubook.settings[name] = val.toString();
                        }
                    }
                }
            }
        },
        save: function () {
            var cend = "; expires=Tue, 31-Dec-2030 23:59:59 GMT; path=/";
            
            for (var name in menubook.settings) {
                if (typeof menubook.settings[name] != 'function') {
                    document.cookie = 'menubook_' + name + '=' + menubook.settings[name].toString() + cend;
                }
            }            
        }       
    },    
    init: function () {
        menubook.settings.load();
        if (menubook.settings.enabled) {        
            menubar.init();
            menubar.styles.setRules(true);
            menubook.setPortletStyles();
        }
    },
    loadMenubar: function () {
        // rename new print/export toolbox to get rid of the hyphen in the name
        var obj = document.getElementById('p-coll-print_export');
        if (obj) {
            obj.id = 'p-print_export';
        }

        menubook.settings.load();
        if (menubook.settings.enabled) {
            menubar.show();
            menubook.setPortletStyles();
            menubook.loadClock();
            menubook.loadConfigMenu();
            menubook.loadPortlets();
            menubook.loadExtensions();
        } else {            
            addOnloadHook(function () {
                mw.util.addPortletLink('p-personal', '#', 'Enable Menubook', 'enableMenubook', null, null, document.getElementById("pt-logout"));
                with (document.getElementById('enableMenubook')) {
                    style.fontWeight = 'bold';
                    onclick = function () {
                        menubook.settings.enabled = true;
                        menubook.settings.save();
                        this.parentNode.removeChild(this);
                        menubook.loadMenubar();
                    }
                }
            });
            if (menubar.element) {
                menubar.hide();
                menubook.setPortletStyles();
                menubook.loadPortlets();
            }
        }
    },
    loadClock: function () {
        if (menubook.settings.clock) {
            if (!menubook.loadClock.element) {
                menubook.loadClock.element = document.createElement('a');
                with (menubook.loadClock.element) {
                    id = 'menubar_clock';
                    href = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/index.php?title=' + encodeURIComponent(mw.config.get('wgPageName')) + '&action=purge';
                }
                menubar.element.appendChild(menubook.loadClock.element);
                
                function updateClock()
                {
                    if (menubook.loadClock.element) {
                        var now = new Date();
                        var hh = now.getUTCHours();
                        var mm = now.getUTCMinutes();
                        var ss = now.getUTCSeconds();
                        var time = ( hh < 10 ? '0' + hh : hh ) + ':' + ( mm < 10 ? '0' + mm : mm ) + ':' + ( ss < 10 ? '0' + ss : ss );
                        menubook.loadClock.element.textContent = time;
                        menubook.loadClock.timeout = window.setTimeout(updateClock, 1000);
                    }
                }
                
                updateClock();
            }
        } else if (menubook.loadClock.element) {
            window.clearTimeout(menubook.loadClock.timeout);
            menubar.element.removeChild(menubook.loadClock.element);
            menubook.loadClock.element = null;
        }
    },
    loadConfigMenu: function () {
        var menu = menubar.getMenu('m-main');
        if (menu) {
            if (menubook.settings.enabled) {
                menu.element.style.display='';
            } else {
                menu.element.style.display='none';
            }
        } else if (menubook.settings.enabled) {
            menubar.addMenu('m-main', '\u25BC', function mainCallback (menu) {
                menu.clearMenuItems();
                
                function addCheckbox (name, caption, indentlevel) {
                    with (menu.addMenuItem()) {
                        var label = document.createElement('label');

                        var input = document.createElement('input');
                        input.type = 'checkbox';
                        input.value = name;
                        input.checked = menubook.settings[name];
                        input.style.marginLeft = (indentlevel ? (indentlevel * 0.5) : 0) + 'em';
                        label.appendChild(input);                
                        
                        label.appendChild(document.createTextNode(caption));
                        element.appendChild(label);
                        
                        input.addEventListener('click', function (event) {
                            menubook.settings[event.target.value] = event.target.checked ? true : false;
                            menubook.settings.save();
                            menubook.loadMenubar();
                        }, false);
                    }
                    return element;
                }
                
                addCheckbox('enabled', 'Enable Menubook');
                addCheckbox('clock', 'Show clock');
                with (menu.addMenuItem()) {
                    var nod = document.createElement('span');
                    nod.style.fontWeight='bold';
                    nod.textContent = 'Wikipedia portlets:';
                    element.appendChild(nod);
                }
                for (var ptl in menubook.portlets) {
                    addCheckbox('p_' + ptl, menubook.portlets[ptl].title, 1);
                }
                
                with (menu.addMenuItem()) {
                    var nod = document.createElement('span');
                    nod.style.fontWeight='bold';
                    nod.textContent = 'Menubook extensions:';
                    element.appendChild(nod);
                }
                for (var ext in menubook.extensions) {
                    addCheckbox('ext_' + ext, menubook.extensions[ext].title, 1);
                }

                with (menu.addMenuItem()) {
                    var a = document.createElement('a');
                    a.href = '#';
                    a.onclick = function () { window.location.reload() };
                    a.textContent = 'Refresh';
                    a.style.fontWeight='bold';
                    element.appendChild(a);
                }
            });
        }
    },
    setPortletStyles: function () {
        for (var name in menubook.portlets) {
            menubook.settings['p_' + name] = true; 
        }
        with (menubook.settings) {
            load();
            var rules = {
                content: '#content {margin-top: 2.8em;margin-left: 2em;margin-right: 2em;border: 1px solid #bbb;}',
                logo: '#p-logo {display: none;}',
                cactions: '#p-cactions {left: 3em;}',
                utcdate: '#utcdate {display: none;}',
                search: '#searchBody {padding: 1em !important;}'
            }                
            
            if (enabled && p_navigation && p_search && p_interaction && p_tb && (p_print_export || !document.getElementById('p-print_export')) && (p_lang || !document.getElementById('p-lang'))) {
                menubar.styles.addRule(rules.content);
                menubar.styles.addRule(rules.logo);
                menubar.styles.addRule(rules.cactions);
            } else {
                menubar.styles.removeRule(rules.content);
                menubar.styles.removeRule(rules.logo);
                menubar.styles.removeRule(rules.cactions);
            }
            if (enabled && p_personal) {
                menubar.styles.addRule(rules.utcdate);
            } else {
                menubar.styles.removeRule(rules.utcdate);
            }
            if (enabled && p_search) {
                menubar.styles.addRule(rules.search);
            } else {
                menubar.styles.removeRule(rules.search);
            }
        }
    },
    loadPortlets: function () {
        for (var name in menubook.portlets) {
              
            var portlet = document.getElementById('p-' + name);
            if (portlet) {
                var menu = menubar.getMenu('m-'+name);
                if (!menu && menubook.settings.enabled) {
                    var m = portlet.cloneNode(true);
                    menu = menubar.addMenuFromPortlet(m, 'm-' + name);                    
                }
                if (menubook.settings.enabled && menubook.settings['p_' + name]) {
                    menu.element.style.display='';
                    portlet.style.display='none';
                    if (menubook.portlets[name].enable) menubook.portlets[name].enable();
                } else {                    
                    if (menu) menu.element.style.display='none';                        
                    portlet.style.display='';
                    if (menubook.portlets[name].disable) menubook.portlets[name].disable();
                }                
            }
        }
    },
    portlets: {
        personal: {
            title: 'Personal tools',
            enable: function () {
            },
            disable: function () {
            }
        },
        navigation: {
            title: 'Navigation'
        },
        search: {
            title: 'Search',
            enable: function () {
                var search = menubar.getMenu('m-search');                
                search.populateCallback = function () {
                    var f = document.searchform;
                    if (f) f.search.focus()
                }
            }
        },
        interaction: {
            title: 'Interaction'
        },
        tb: {
            title: 'Toolbox'
        },
        print_export: {
            title: 'Print/Export'
        },
        lang: {
            title: 'Languages'
        },
        cactions: {
            title: 'Views',
            enable: function () {
                var cactions = document.getElementById('p-cactions');
                if (cactions) cactions.style.display='';
            }
        }
    },
    loadExtensions: function () {
        // add extensions
        for (var name in menubook.extensions) {
            menubook.settings['ext_' + name] = true;
        }
        menubook.settings.load();
        
        var extensionCallback = function (menu, args) {
            var head, tmp;
            if (!menu.menuItems.length) {
                head = menu.addMenuItem();
                var a = document.createElement('a');
                a.style.fontWeight='bold';
                a.href = args.ext.title_href;
                a.title = args.ext.title;
                a.textContent = args.ext.title;
                head.element.className='break';
                head.element.appendChild(a);

                tmp = menu.addMenuItem();
                tmp.element.textContent = 'Loading...';
            }                                    
            var url = args.ext.ajax_url;
            menubook.getUrl(url, true, function (response) {
                for (var i=menu.menuItems.length-1;i>0;i--) {
                    menu.removeMenuItem(menu.menuItems[i]);
                }
                args.ext.ajax_callback(response, menu);
            });
        }

        for (var name in menubook.extensions) {
            var menu = menubar.getMenu('m-ext-' + name);
            if (!menu && menubook.settings.enabled) {
                var ext = menubook.extensions[name];                    
                menu = menubar.addMenu('m-ext-' + name, ext.title, extensionCallback, {name: name, ext: ext});
            }
            if (menubook.settings.enabled && menubook.settings['ext_' + name]) {
                menu.element.style.display='';
            } else {
                if (menu) menu.element.style.display='none';
            }
        }
    },
    getUrl: function (url, returnxml, callback) {
        var now = new Date();
        var elapsed = (now.getTime() - menubook.getUrlTimer.getTime());
        if (elapsed < 1000) {
            window.setTimeout(function () {menubook.getUrl(url, returnxml, callback)}, 250);
            return;
        }
        
        menubook.getUrlTimer = now;
        
        var aj = sajax_init_object();
        aj.onreadystatechange = function () {
            if (aj.readyState == 4 && aj.status == 200) {
                if (returnxml) {
                    callback(aj.responseXML);
                } else {
                    callback(aj.responseText);
                }
            }
        }
        aj.open('GET', url, true);
        aj.send(null);
    },
    getUrlTimer: new Date(),
    extensions: {}
}

$(function () {
    mw.util.addPortletLink('p-personal', '#', 'view css', 'viewcss', null, null, document.getElementById("pt-logout"));
    with (document.getElementById('viewcss')) {
        onclick = function () {
            if (menubar && menubar.stylesheet) {
                var s = '';
                for (var i=0; i<menubar.stylesheet.cssRules.length; i++) {
                    s += menubar.stylesheet.cssRules[i].cssText + '\n';
                }
                alert(s);
            }
        }
    }
});
menubook.init();
$(menubook.loadMenubar);

//MENUBOOK EXTENSIONS
$(function () {
    importStylesheetURI('/skins-1.5/common/diff.css');
    menubar.styles.addRule('.submenu-diff {padding:0px !important;max-height:40em;max-width:40em;white-space:normal}');
    menubar.styles.addRule('.submenu-diff a:link {color: blue}');
    menubar.styles.addRule('.submenu-diff a:visited {color: purple}');
});
// create history submenu - used by other extensions
menubook.historyCallback = function (menu, args) {
    var url = '/w/api.php?format=xml&action=query&prop=revisions&rvlimit=10&titles=' + args.title;
    menubook.getUrl(url, true, function (response) {
        menu.clearMenuItems();
        
        var subItems = response.documentElement.getElementsByTagName('rev');
        for (var j=0; j<subItems.length; j++) {
            with (menu.addMenuItem()) {
                var title = args.title;
                var revid = subItems[j].getAttribute('revid');
                var a = document.createElement('a');
                a.href = mw.config.get('wgScript') + '?title=' + args.title.replace(' ', '_', "g").replace('&', '%26', "g") + '&diff=prev&oldid=' + revid;
                a.appendChild(document.createTextNode(subItems[j].getAttribute('timestamp') + ' ' + subItems[j].getAttribute('user')));
                a.title = subItems[j].getAttribute('comment');
                element.appendChild(a);
                createSubMenu(menubook.diffPreview, {url: a.href + '&diffonly=true&action=render'});
            }
        }
        
        menu.setLocation();
    });
}
menubook.diffPreview = function (menu, args) {
    menubook.getUrl(args.url, false, function (response) {
        menu.element.className += ' submenu-diff';
        menu.element.innerHTML = response;
        menu.setLocation();
    });
} 
menubook.extensions.watchlist = {
    title: 'My Watchlist',
    title_href: mw.config.get('wgArticlePath').replace('$1', 'Special:Watchlist'),
    ajax_url: '/w/api.php?format=xml&action=query&list=watchlist&wlprop=ids|title|timestamp|user|comment&wllimit=' + menubook.settings.menulimit,
    ajax_callback: function (responseXML, menu) {    
        var items = responseXML.documentElement.getElementsByTagName('item');
        for (var i=0; i<items.length; i++) {
            with (menu.addMenuItem()) {
                var title = items[i].getAttribute('title');
                var a = document.createElement('a');                
                a.href = mw.config.get('wgScript') + '?title=' + title.replace(' ', '_', "g").replace('&', '%26', "g") + '&oldid=' + items[i].getAttribute('revid');
                a.textContent = title;
                if (items[i].getAttribute('user')==mw.config.get('wgUserName')) a.style.fontStyle='italic';
                element.appendChild(a);
                createSubMenu(menubook.historyCallback, {title: title});
            }
        }
    }
}
menubook.extensions.npp = {
    title: 'New Pages',
    title_href: mw.config.get('wgArticlePath').replace('$1', 'Special:NewPages'),
    ajax_url: '/w/api.php?action=query&format=xml&list=recentchanges&rcshow=!bot|!redirect&rctype=new&rcnamespace=0&rcprop=title|timestamp|ids|patrolled&rclimit='+menubook.settings.menulimit,
    ajax_callback: function (responseXML, menu) {    
        var items = responseXML.documentElement.getElementsByTagName('rc');
        for (var i=0; i<items.length; i++) {
            with (menu.addMenuItem()) {
                var title = items[i].getAttribute('title');
                var rcid = items[i].getAttribute('rcid');
                var a = document.createElement('a');
                a.href = mw.config.get('wgScript') + '?title=' + title.replace(' ', '_', "g").replace('&', '%26', "g") + '&rcid=' + rcid;
                a.textContent = title;
                if (items[i].getAttribute('patrolled')==null) a.style.fontWeight='bold';
                element.appendChild(a);
                createSubMenu(menubook.historyCallback, {title: title});
            }
        }
    }
}
menubook.extensions.oldnpp = {
    title: 'Unpatrolled',
    title_href: '/w/index.php?title=Special:NewPages&dir=prev&hidepatrolled=1&hidebots=1',
    ajax_url: '/w/api.php?action=query&format=xml&list=recentchanges&rcshow=!bot|!redirect|!patrolled&rctype=new&rcnamespace=0&rcprop=title|timestamp|ids|patrolled&rcdir=newer&rclimit='+menubook.settings.menulimit,
    ajax_callback: function (responseXML, menu) {    
        var items = responseXML.documentElement.getElementsByTagName('rc');
        for (var i=0; i<items.length; i++) {
            with (menu.addMenuItem()) {
                var title = items[i].getAttribute('title');
                var rcid = items[i].getAttribute('rcid');
                var a = document.createElement('a');
                a.href = mw.config.get('wgScript') + '?title=' + title.replace(' ', '_', "g").replace('&', '%26', "g") + '&rcid=' + rcid;
                a.textContent = title;
                if (items[i].getAttribute('patrolled')==null) a.style.fontWeight='bold';
                element.appendChild(a);
                createSubMenu(menubook.historyCallback, {title: title});
            }
        }
    }
}
menubook.extensions.rc = {
    title: 'Recent changes',
    title_href: mw.config.get('wgArticlePath').replace('$1', 'Special:RecentChanges'),
    ajax_url: '/w/api.php?format=xml&action=query&list=recentchanges&rclimit='+menubook.settings.menulimit,
    ajax_callback: function (responseXML, menu) {    
        var items = responseXML.documentElement.getElementsByTagName('rc');
        for (var i=0; i<items.length; i++) {
            with (menu.addMenuItem()) {
                var title = items[i].getAttribute('title');
                var revid = items[i].getAttribute('revid');
                var a = document.createElement('a');
                a.href = mw.config.get('wgScript') + '?title=' + title.replace(' ', '_', "g").replace('&', '%26', "g") + '&diff=prev&oldid=' + revid;
                a.textContent = title;
                element.appendChild(a);
                createSubMenu(menubook.historyCallback, {title: title});
            }
        }
    }
}

// CLICK HACK
HTMLElement.prototype.click = function() {
    var evt = this.ownerDocument.createEvent('MouseEvents');
    evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
    this.dispatchEvent(evt);
}

// OUTERHTML HACK - for debugging purposes only
/*
try {
    if(!document.documentElement.outerHTML){
	Node.prototype.getAttributes = function(){
		var attStr = "";
		if(this && this.attributes.length > 0){
			for(a = 0; a < this.attributes.length; a ++){
				attStr += " " + this.attributes.item(a).nodeName + "=\"";
				attStr += this.attributes.item(a).nodeValue + "\"";
			}
		}
		return attStr;
	}

	Node.prototype.getInsideNodes = function(){
		if(this){
			var cNodesStr = "", i = 0;
			var iEmpty = /^(img|embed|input|br|hr)$/i;
			var cNodes = this.childNodes;
			for(i = 0; i < cNodes.length; i ++){
				switch(cNodes.item(i).nodeType){
					case 1 :
						cNodesStr += "<" + cNodes.item(i).nodeName.toLowerCase();
						if(cNodes.item(i).attributes.length > 0){
							cNodesStr += cNodes.item(i).getAttributes();
						}
						cNodesStr += (cNodes.item(i).nodeName.match(iEmpty))? "" : ">";
						if(cNodes.item(i).childNodes.length > 0){
							cNodesStr += cNodes.item(i).getInsideNodes();
						}
						if(cNodes.item(i).nodeName.match(iEmpty)){
							cNodesStr += " />";
						} else {
							cNodesStr += "</" + cNodes.item(i).nodeName.toLowerCase() + ">";
						}
						break;
					case 3 :
						cNodesStr += cNodes.item(i).nodeValue;
						break;
					case 8 :
						cNodesStr += "<!--" + cNodes.item(i).nodeValue + "-->";
						break;
				}
			}
			return cNodesStr;
		}
	}

	HTMLElement.prototype.outerHTML getter = function(){
		var strOuter = "";
		var iEmpty = /^(img|embed|input|br|hr)$/i;
		switch(this.nodeType){
			case 1 :
				strOuter += "<" + this.nodeName.toLowerCase();
				strOuter += this.getAttributes();
				if(this.nodeName.match(iEmpty)){
					strOuter += " />";
				} else {
					strOuter += ">" + this.getInsideNodes();
					strOuter += "</" + this.nodeName.toLowerCase() + ">";
				}
				break;
			case 3 :
				strOuter += this.nodeValue;
				break;
			case 8 :
				cNodesStr += "<!--" + this.nodeValue + "-->";
				break;
		}
		return strOuter;
	}

	HTMLElement.prototype.outerHTML setter = function(str){
		var iRange = document.createRange();

		iRange.setStartBefore(this);

		var strFragment = iRange.createContextualFragment(str);
		var sRangeNode = iRange.startContainer;

		iRange.insertNode(strFragment);
		sRangeNode.removeChild(this);
	}
    }
}
catch (e) {
}
*/