// ========================================
// Copyright (c) 2007, 2008 by Wolfgang Fischer
// ========================================

var body, header, main, page_area, content_area, sidebar, splitbar, footer, is_ltr;

var dragged, old_ondrag, old_onselect;
var MIN_SIDEBAR_WIDTH = 20; // in pixel
var DEFAULT_SIDEBAR_WIDTH = '20em';
var SPLIT_BAR_DRAG_OFFSET;

var agt=navigator.userAgent.toLowerCase();
var IS_IE = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var IE_VER = IS_IE ? parseInt(agt.substring(agt.indexOf("msie") + 5)) : 0;
var LEFT_BUTTON = IS_IE ? 1 : 0;


function explorer_init() {
    page_area = document.getElementById("page_area");
    content_area = document.getElementById("content_area");
    sidebar = document.getElementById("sidebar");
    splitbar = document.getElementById("splitbar");
    footer = document.getElementById("footer");
    init_cookies();
    main = document.getElementById("main");
    if (main != null) {
        body = document.body;
        is_ltr = (body.dir == "ltr");

        SPLIT_BAR_DRAG_OFFSET = (splitbar.offsetWidth / 2) + main.offsetLeft;

        if (sidebar.offsetWidth < MIN_SIDEBAR_WIDTH) set_sidebar_width("0px");
        size_areas_to_sidebar();

        sidebar_scroll_left = get_cookie("explorer_sidebar_scroll_left");
        if (sidebar_scroll_left != "") sidebar.scrollLeft = sidebar_scroll_left;
        sidebar_scroll_top = get_cookie("explorer_sidebar_scroll_top");
        if (sidebar_scroll_top != "") sidebar.scrollTop = sidebar_scroll_top;

        window.onresize = size_areas_to_window;
        addBeforeUnloadEvent(save_tree_state);
        splitbar.ondblclick = toggle_display_sidebar;
        splitbar.onmousedown = drag_init;
        // if (! IS_IE) {
            // Scroll selected tree node (current page) into view
        //    selected = document.getElementById('node_selected');
        //    if (selected != null) selected.scrollIntoView(true);
        //}
    }
}


function toggle_comments(element) {
    parent_item = element.parentNode
    is_show_comments = (parent_item.className == "ib_selected")
    parent_item.className = is_show_comments ? "" : "ib_selected"
    toggleComments();
}


function save_tree_state() {
    // This function is called on the "onunload" event of the window
    set_cookie("explorer_sidebar_scroll_left", sidebar.scrollLeft);
    set_cookie("explorer_sidebar_scroll_top", sidebar.scrollTop);

    // Create cookie for each expanded node
    descendants = sidebar.getElementsByTagName('ul');
    for (i = 0; i < descendants.length; i++) {
        id = descendants[i].parentNode.firstChild.id;
        if (id) set_cookie(id, descendants[i].style.display == "none" ? "" : 1);
    }
}



// ===================================
// Split bar event handling
// ===================================
function toggle_display_sidebar(e) {
    var evt = e || window.event;
    consume_event(evt);
    if (sidebar.offsetWidth < MIN_SIDEBAR_WIDTH) { // Show sidebar
        sidebar_width = get_cookie("explorer_sidebar_width");
        if (sidebar_width != "") {
            set_sidebar_width(sidebar_width);
            if (sidebar.offsetWidth < MIN_SIDEBAR_WIDTH) {
                set_cookie("explorer_sidebar_width", DEFAULT_SIDEBAR_WIDTH);
                set_sidebar_width(DEFAULT_SIDEBAR_WIDTH);
            }
        } else {
            set_cookie("explorer_sidebar_width", DEFAULT_SIDEBAR_WIDTH);
            set_sidebar_width(DEFAULT_SIDEBAR_WIDTH);
        }
        set_cookie("explorer_hide_sidebar", "");
    } else { // Hide sidebar
        set_cookie("explorer_sidebar_width", sidebar.offsetWidth + "px");
        set_cookie("explorer_hide_sidebar", 1);
        set_sidebar_width("0px");
    }
    size_areas_to_sidebar();
}


function consume_event(evt) {
    if (evt.stopPropagation) {
        evt.stopPropagation();
        evt.preventDefault();
    } else {
        evt.cancelBubble = true;
        evt.returnValue = false;
    }
}


function drag_init(e) {
    var evt = e || window.event;
    if (evt.button == LEFT_BUTTON) {
        dragged = false;
        document.onmousemove = drag;
        document.onmouseup = drop;
        if (IS_IE) {
            // prevent IE text selection while dragging
            old_ondrag = document.body.ondrag;
            old_onselectstart = document.body.onselectstart;
            document.body.ondrag = function () { return false; };
            document.body.onselectstart = function () { return false; };
        }
    }
    return false;
}


function drag(e) {
    var evt = e || window.event;
    dragged = true;
    width = calc_sidebar_width(evt.clientX) + 'px';
    set_sidebar_width(width);
}


function drop(e) {
    var evt = e || window.event;
    document.onmouseup = null;
    document.onmousemove = null;
    if (IS_IE) {
        // enables IE text selection while dragging
        document.body.ondrag = old_ondrag;
        document.body.onselectstart = old_onselectstart;
    }
    if (dragged) {
        width = calc_sidebar_width(evt.clientX);
        if (width > 0) {
            set_cookie("explorer_sidebar_width", width + 'px');
            set_cookie("explorer_hide_sidebar", "");
        } else {
            set_cookie("explorer_hide_sidebar", 1);
        }
    }
}

function calc_sidebar_width(posX) {
    width = posX - SPLIT_BAR_DRAG_OFFSET;
    if (! is_ltr) width = main.offsetWidth - width;
    if (width < MIN_SIDEBAR_WIDTH) width = 0;
    return width;
}



// ===================================
// Resizing of areas
// ===================================
function set_sidebar_width(posX) {
    sidebar.style.width = posX;
    sidebar.style.display = (posX == "0px") ? "none" : "block"
    size_areas_to_sidebar();
}


function size_areas_to_sidebar() {
    posX = sidebar.offsetWidth + "px";
    // This changes settings like "20em" for the sidebar width
    // to the corresponding pixel value
    sidebar.style.width = posX;
    if (is_ltr) {
        splitbar.style.left = posX;
        page_area.style.left = posX;
    } else {
        splitbar.style.right = posX;
        page_area.style.right = posX;
    }
    size_areas_to_window()
}


function size_areas_to_window() {
    if ( IS_IE && IE_VER < 7) {
        content_width = Math.max(document.documentElement.clientWidth - 2 * main.offsetLeft - page_area.offsetLeft, 0);
        page_area.style.width = content_width + "px";
        content_area.style.width = content_width + "px";
        main_height = Math.max(document.documentElement.clientHeight - footer.offsetHeight - main.offsetLeft - main.offsetTop, 0);
        sidebar.style.height = main_height + "px";
        splitbar.style.height = main_height + "px";
        content_area.style.height = Math.max(main_height - content_area.offsetTop, 0) + "px";
    } else {
        main_height = Math.max(footer.offsetTop - main.offsetTop - 2, 0);
        main.style.height = main_height + "px";
        content_area_height = Math.max(main_height - content_area.offsetTop - 1, 0);
        content_area.style.height = content_area_height + "px";
        set_cookie("explorer_main_height", main.offsetHeight);
        set_cookie("explorer_content_area_height", content_area.offsetHeight);
    }
}



// ===================================
// Handle toggle button click events
// ===================================
function toggle_node(e) {
    var evt = e || window.event;
    toggle_button = IS_IE ? evt.srcElement : evt.target;
    expand = toggle_button.src.slice(-5, -4) == '1';

    set_node_expansion(toggle_button, expand, evt.shiftKey);
}


function set_node_expansion(toggle_button, expand, recurse) {
    subtree = toggle_button.parentNode.lastChild;
    if (subtree.nodeType == 3) {  // Text node
        subtree = subtree.previousSibling
    }
    if (recurse) {
        if (expand) {
            set_cookie('expand_subtree', toggle_button.id);
            // Reload the document to show the missing element
            window.location.href = unescape(window.location.pathname)
        } else {
            collapse_node(toggle_button, subtree);
            // Collapse
            descendants = subtree.getElementsByTagName('ul');
            for (var i=0; i < descendants.length; i++) {
                sub_subtree = descendants[i]
                collapse_node(sub_subtree.parentNode.firstChild, sub_subtree);
            }
        }
    } else {
        if (expand) {
            if (subtree.className == 'wiki_tree') {
                expand_node(toggle_button, subtree);
            } else {
                set_cookie(toggle_button.id, 1);
                // Reload the document to show the missing element
                window.location.href = unescape(window.location.pathname)
            }
        } else {
            collapse_node(toggle_button, subtree);
        }
    }
}

function expand_node(toggle_button, subtree) {
    toggle_button.src = toggle_button.src.slice(0, -5) + '0.png';
    subtree.style.display = "block";
}


function collapse_node(toggle_button, subtree) {
    toggle_button.src = toggle_button.src.slice(0, -5) + '1.png';
    subtree.style.display = "none";
}


// ===================================
// Cookie handling library
// ===================================
var cookies = new Object();


function init_cookies() {
    var saved_cookies = document.cookie.split(';');
    var cookie;
    for (var i=0; i < saved_cookies.length; i++) {
        cookie = saved_cookies[i].replace(/^\s+/,"");
        if (cookie.indexOf("=") != 0) {
            cookies[cookie.substring(0, cookie.indexOf("="))]
                = cookie.substring(cookie.indexOf("=")+1, cookie.length);
        }
    }
    set_cookie('expand_subtree', '');
}


function set_cookie(name, value, days) {
    var expires;
    if (value == "") days = -1;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+days*24*60*60*1000);
        expires = "; expires="+date.toGMTString();
    } else expires = "";
    document.cookie = name+"="+value+expires+"; path=";
    cookies[name] = value;
}


function get_cookie(name) {
    value = cookies[name];
    if (value == null) return "";
    else return value;
}


// ===================================
// Initialize after loading the page
// ===================================
// use this instead of assigning to window.onload directly:
function addBeforeUnloadEvent(func) {
    var oldonbeforeunload = window.onbeforeunload;
    if (typeof window.onbeforeunload != 'function') {
        window.onbeforeunload = func;
    } else {
        window.onbeforeunload = function() {
                oldonbeforeunload();
                func();
            }
    }
}

addLoadEvent(explorer_init)


