/*
 * Copyright (c) 2008 David Crawshaw <david@zentus.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/* Fills the "Menu" and "Footer" elements. */
var menu = function() {
    var name;
    var prefix;
    var editing = window.location.pathname.search(/wixify\/[^\/]+$/) >= 0;

    if (this.wixer && wixer.name)
        name = wixer.name
    else {
        name = window.location.pathname;
        if (name.charAt(name.length - 1) == "/")
            name = name.substring(1) + "index";
        if (name && name.search(/^\/.*\.html$/) != -1)
            name = name.substring(1, name.length - 5);
    }

    /*
     * This prefix thing is messy, but useful. It comes from the generated
     * html in com.zentus.wixer.WiXHTML and tells us where we are relative
     * to the root of the site. E.g. we may be in:
     *     /proxied/my/subdir/hello.html
     * and the edit page may be in:
     *     /proxied/wixify/edit.html?name=my/subdir/hello
     */
    if (window.prefix)
        prefix = window.prefix;
    else
        prefix = editing ? '../' : '/';
    prefix += 'wixify/';

    // display the control menu
    var m = document.getElementById("Menu");
    if (m && name) {
        var view = '<a href="../' + name + '.html">view</a>';
        var edit = '<a href="'+prefix+'edit.html?name='+ name +'">edit</a>';
        var user = menu.getCookie("wixer-user");

        m.innerHTML = 
              '<div id="MenuBar">'
            + '&#171; '
            + (editing ? view : edit)
            + '<ul id="MenuDropdown">'
            + (editing ? ' <li>' + edit + '</li>' : '')
            + ' <li><a href="'+prefix+'history.html?name='+name+'">'
            +       'history</a></li>'
            + ' <li><a href="'+prefix+'recentchanges.html">'
            +       'recent&nbsp;changes</a></li>'
            + ' <li><a href="'+prefix+'upload.html">upload</a></li>'
            + '</ul>'
            + '</div>'
            + '<div id="MenuUser">' + (user ? user : '') + '</div>'
            + '<div id="MenuUserDetails">'
            +   '<a href="'+prefix+'pref.html">preferences</a><br />'
            +   '<a id="MenuUserLogout" href="javascript:;">logout</a>'
            + '</div>';

        var menuBar = document.getElementById("MenuBar");
        var menuUser = document.getElementById("MenuUser");
        var menuUserLogout = document.getElementById("MenuUserLogout");
        var menuUserDetails = document.getElementById("MenuUserDetails");

        menuBar.onmouseover = function() {
            var dropmenu = document.getElementById("MenuDropdown");

            if (dropmenu.style.display == "block") {
                if (dropmenu.timeoutId) {
                    clearTimeout(dropmenu.timeoutId);
                    dropmenu.timeoutId = null;
                }
                return;
            }

            // find button position
            var objtop = 0;
            var objleft = 0;
            for (var obj = menuBar; obj; obj = obj.offsetParent) {
                objleft += obj.offsetLeft;
                objtop += obj.offsetTop;
            }

            // display dropmenu window
            dropmenu.style.display = "block";
            dropmenu.style.left = (objleft - dropmenu.offsetWidth) + "px";
            dropmenu.style.top =
                Math.round(objtop - (menuBar.offsetHeight / 2)) + "px";
        };

        menuBar.onmouseout = function() {
            var dropmenu = document.getElementById("MenuDropdown");
            if (dropmenu.timeoutId)
                return;
            dropmenu.timeoutId = setTimeout(function() {
                dropmenu.style.display = "none";
                dropmenu.timeoutId = null;
            }, 150);
        };

        menuUser.onclick = function() {
            menuUserDetails.style.display = "block";
            menuUserDetails.timeoutId = setTimeout(function() {
                menuUserDetails.style.display = "none";
                menuUserDetails.timeoutId = null;
            }, 3000);
        };

        menuUserLogout.onclick = function() {
            /* TODO: import wixi.js and use a standard interface */
            menuUser.innerHTML = "";
            menuUserDetails.style.display = "none";
            var ex = new Date();
            ex.setTime(ex.getTime() - 1);
            document.cookie = "wixer-key=; expires=" + ex.toGMTString()
                + "; path=/";
            document.cookie = "wixer-user=; expires=" + ex.toGMTString()
                + "; path=/";
        };
    }

    // display the footer
    var f = document.getElementById("Footer");
    if (f)
        f.innerHTML =
              '<span id="Signature">powered by '
            + '<a title="the wixer wiki compiler" '
            + 'href="http://www.zentus.com/wixer/"><span class="inset">W'
            + '<span class="insetLower">i</span>xer</span></a></span>';
};

menu.getCookie = function(name) {
    var cook = document.cookie;
    var pos = cook.indexOf(name + "=");
    if (pos == -1)
        return null;
    else
        pos += name.length + 1;
    var end = cook.indexOf(";", pos);
    if (end == -1)
        end = cook.length;
    return (pos >= end) ? null : cook.substring(pos, end);
};

if (window.addEventListener)
    window.addEventListener("load", menu, false);
else if (window.attachEvent)
    window.attachEvent("onload", menu);
