﻿/// <reference path="jquery.js" />

var globalPageName = 'home';
var globalNewRenameValue = '';
var globalTextPageTree = 'page tree';
var globalCurrentSection = -1;
var globalHandler = 'PageWikiHandler.aspx';
var globalNewsTeaserAr = null;

var globalIndexEditSaveFileId;

var debug = false;
function handleError(E)
// not very well named, should be something like "logError"
{
    if (debug) {
        alert(E.name + ' : ' + E.message);
    }

}

function sendGet(para, funcPointer) {
    alert("sendGet has been replaced by Fetch/FetchJson/FetchHtml");
}

function loadPage(pageName) {
    globalPageName = pageName;

    var para = globalHandler + '?' +
        'mode=' + 'loadPage' + '&' +
        'pageName=' + encodeURIComponent(globalPageName);

    FetchJson(para, handleResponseGetLoadPage);

    setToShowSpan();
}

function loadLastPage() {

    var para = 'PageWikiHandler.aspx?' +
        'mode=' + 'getLastPage';

    FetchJson(para, handleResponseGetLoadPage);

    setToShowSpan();

}

function clickOnNewsIsRead(newsId) {
    globalNewsId = newsId;

    var cb = document.getElementById("newsCb" + newsId);

    globalNewsChecked = cb.checked;

    var para = 'PageUmlaufHandler.aspx' + '?' +
        'mode=' + 'switchReadState' + '&' +
        'newsId=' + newsId + '&' +
        'value=' + cb.checked;

    FetchJson(para, handleResponseClickOnNewsIsRead);
}

function handleResponseClickOnNewsIsRead(jsonObject) {

    var data = jsonObject.data;
    setSpan('status' + globalNewsId, data);
    // openSectionsLoad();

    var ele = document.getElementById("newsLine" + globalNewsId);

    if (globalNewsChecked) {
        ele.className = "read";
    } else {
        ele.className = "notread";
    }

}

function clickOnWikiIsRead(wikiId) {
    globalWikiId = wikiId;

    var cb = document.getElementById("wikiCb" + wikiId);

    globalWikiChecked = cb.checked;

    var para = 'PageWikiHandler.aspx' + '?' +
        'mode=' + 'switchReadState' + '&' +
        'pageId=' + wikiId + '&' +
        'value=' + cb.checked;

    FetchJson(para, handleResponseClickOnWikiIsRead);
}

function handleResponseClickOnWikiIsRead(jsonObject) {
    setSpan('status' + globalWikiId, jsonObject.data);

    var ele = document.getElementById("newsLine" + globalWikiId);

    if (globalWikiChecked)
        ele.className = "read";
    else
        ele.className = "notread";

}

if (document.ids) x = 'nc4';
else if (document.all && !document.getElementById) x = 'ie4';
else if (window.opera && !document.createElement) x = 'op5';
else if (window.opera && window.getComputedStyle) {
    if (document.createRange) x = 'op8';
    else if (window.navigate) x = 'op7.5';
    else x = 'op7.2';
}
else if (window.opera && document.compatMode) x = 'op7';
else if (window.opera && document.releaseEvents) x = 'op6';
else if (document.contains && !window.opera) x = 'kq3';
else if (window.pkcs11 && window.XML) x = 'f15';
else if (window.getSelection && window.atob) x = 'nn7';
else if (window.getSelection && !document.compatMode) x = 'nn6';
else if (window.clipboardData && document.compatMode) x = 'ie6';
else if (window.clipboardData) {
    x = 'ie5';
    if (!document.createDocumentFragment) x += '.5';
    if (document.doctype && !window.print) x += 'm';
}
else if (document.getElementById && !document.all) x = 'op4';
else if (document.images && !document.all) x = 'nn3';
else if (document.clientWidth && !window.RegExp) x = 'kq2';
else x = '???';

var brOP = x.substr(0, 2) == 'op';
var brIE = x.substr(0, 2) == 'ie';
var brNN = x.substr(0, 2) == 'nn';

var lastFadeIn = null; // last fade in object
var isFading = false; // currently fading
var firstFade = true; // fading is in initial state

function fadeInit() {
    var ar = document.getElementsByTagName("table");
    var name = "magictable";

    for (var n = 0; n < ar.length; n++) {
        try {
            var ele = ar[n];

            if (ele.id.substring(0, name.length) == name) {
                fadeSetBounds(ele.id);
            }
        }
        catch (e) {
        }
    }
}

function fadeSetBounds(name) {
    var table = null;
    var div = null;
    var ar = null;
    var maxOffsetHeight = 0;

    try {
        table = document.getElementById(name);
        div = document.getElementById(name + "-div");

        if (!div || typeof (div) != 'object')
            return;

        ar = table.firstChild.childNodes;
    }
    catch (e) {
        return;
    }

    for (var n = 0; n < ar.length; n++) {
        try {
            var ele = ar[n];
            var ele2 = null;

            var ele2 = ele.childNodes[1];
            ele2.style.display = "block";

            var offsetWidth = ele.offsetWidth;
            var offsetHeight = ele.offsetHeight;

            if (offsetHeight > maxOffsetHeight)
                maxOffsetHeight = offsetHeight;

            try {
                var table2 = document.getElementById(ele.id + "-split");
                table2.style.width = offsetWidth + "px";
                table2.style.height = offsetHeight + "px";
            }
            catch (e) {
            }

            if (n > 0)
                ele2.style.display = "none";
        }
        catch (e) {
        }
    }

    div.style.height = maxOffsetHeight + "px";
}

function swap(name, fadeSpeed, swapFade) {
    var disp;
    disp = 'table-row';
    if (brOP) disp = 'table-row';
    if (brNN) disp = 'table-row';
    if (brIE) disp = 'block';

    var ele = document.getElementById(name);

    if (fadeSpeed > 0) {
        try {
            var ele2 = ele.childNodes[1];
            var select = $(ele2);

            if (isFading) return;

            if (lastFadeIn == ele) {
                select.stop();
            }
            else if (ele2.style.display != "none") {
                select.fadeOut(fadeSpeed);
            }
            else {
                lastFadeIn = ele;
                isFading = true;
                select.fadeIn(fadeSpeed, function () { isFading = false });
            }
        }
        catch (e) {
        }
    } else if (swapFade == 2) {
        try {
            var ele2 = ele.childNodes[1];
            if (ele2.style.display != "none") {
                ele2.style.display = 'none';
            } else {
                ele2.style.display = disp;
            }
        }
        catch (e) {
        }
    } else {
        if (ele.style.display != "none") {
            ele.style.display = 'none';
        } else {
            ele.style.display = disp;
        }
    }
}

function swapCloseAll(name, fadeSpeed, swapFade) {
    var ar = document.getElementsByTagName("tr");

    for (var n = 0; n < ar.length; n++) {
        var ele = ar[n];

        if (ele.id.substring(0, name.length) != name) {
            continue;
        }

        if (fadeSpeed > 0) {
            if (firstFade) {
                firstFade = false;
                lastFadeIn = ele;
            }

            try {
                var ele2 = ele.childNodes[1];
                var select = $(ele2);

                if (isFading) return;

                if (ele2.style.display != 'none') {
                    select.fadeOut(fadeSpeed);
                }
            }
            catch (e) {
            }
        } else if (swapFade == 2) {
            try {
                var ele2 = ele.childNodes[1];
                if (ele2.style.display != 'none') {
                    ele2.style.display = 'none';
                }
            }
            catch (e) {
            }
        } else {
            if (ele.style.display != 'none') {
                ele.style.display = 'none';
            }
        }
    }
}

function handleResponseGetLoadPage(jsonObject) {

    globalNewsTeaserAr = jsonObject.teaserAr;

    setSpan('SpanWiki', jsonObject.data);
    toggle_all_tables("collapse");

    if (globalCurrentSection != -1) {
        reopenOpenSections();
        globalCurrentSection = -1;
    }
    magiclist_globalInit(null);
    neuAufbau();
    wikiTimeLineInit();
    checkNextDirList(0);
    checkNextTreeList(0);
    fadeInit();

}

function historyCopyVersion(id) {
    globalPageName = pageName;

    var para = 'PageWikiHandler.aspx?' +
        'mode=' + 'historyCopyVersion' + '&' +
        'pageId=' + id;

    FetchJson(para, handleResponseGethistoryCopyVersion);

    setToShowSpan();
}

function handleResponseGethistoryCopyVersion(jsonObject) {
    loadPage(jsonObject.data);
}

function checkNextDirList(num) {
    var bt = document.getElementById("ListImageSmall" + num);
    if (bt != null) {
        try {
            eval(bt.getAttribute('href'));
        } catch (E) { handleError(E); }

        window.setTimeout("checkNextDirList(" + (num + 1) + ")", 50);
    }

}

// OK so here: CheckNextTreeList is called from PageWiki_Onload (or somesuch loading routine)
// with a num of 0. 

function checkNextTreeList(num)
// @num     the index of the Tree on the Page
// initializes each tree by call the onclick method
// of a hidden element in the treelist (which is responsible for 
// actually building up the tree)
// 
{

    var bt = document.getElementById("treeInit" + num);
    if (bt != null) {


        window.setTimeout("initTheTree(" + num + ")", 500);
        window.setTimeout("initTheTree(" + num + ")", 2000);

        try {
            eval(bt.getAttribute('href'));
        } catch (E) { handleError(E); }

        // this is actually a call to FileGetTree()
        window.setTimeout("checkNextTreeList(" + (num + 1) + ")", 50);
    }

}

function initTheTree(num) {

    var bt = document.getElementById("FileList" + num + "Init");
    if (bt != null) {

        try {
            eval(bt.getAttribute('href'));
        } catch (E) { handleError(E); }
    }
}


function checkForDirLists() {
    var cont = true;

    for (var n = 0; cont; n++) {
        var bt = document.getElementById("ListImageSmall" + n);
        if (bt == null) {
            cont = false;
        }
        else {
            try {
                eval(bt.getAttribute('href'));
            } catch (E) { handleError(E); }
            window.setTimeout("Nix()", 1000);
        }
    }
}

function fileGetTree(rootId, spanId, spanDirId, filterDir, filterFiles, defaultBranch) {
    globalLastSpanId = spanId;

    var para = 'PageDownloadHandler.aspx?' +
        'mode=getTree&' +
        'value=' + rootId + '&' +
        'spanDirId=' + spanDirId + '&' +
    //'viewMode=' + 'readonly' + '&' +
        'filterDir=' + encodeURIComponent(filterDir) + '&' +
        'filterFiles=' + encodeURIComponent(filterFiles) + '&' +
        'defaultBranch=' + encodeURIComponent(defaultBranch);

    FetchJson(para, handleResponseFileGetTree);
}

function handleResponseFileGetTree(jsonObject) {
    setSpan(globalLastSpanId, jsonObject.data);
}

function fileGetTreeDir(rootId, spanId, filterFiles) {
    globalLastSpanTreeId = spanId;

    var para = 'PageDownloadHandler.aspx?' +
        'mode=getTreeDir&' +
        'value=' + rootId + '&' +
        'spanId=' + spanId + '&' +
        'filterFiles=' + encodeURIComponent(filterFiles);
    //'viewMode=' + 'readonly' + '&' +
    //'viewFilter=' + encodeURIComponent(filter) + '&' +
    //'search=&' +

    FetchJson(para, handleResponseFileGetTreeDir);
}

function handleResponseFileGetTreeDir(jsonObject) {
    setSpan(globalLastSpanTreeId, jsonObject.data);
}

function fileListMode(mode, value, num, filter) {
    globalLastNum = num;

    var para = 'PageDownloadHandler.aspx?' +
        'mode=getList&' +
        'value=' + value + '&' +
        'listMode=' + mode + '&' +
    //'viewMode=' + 'readonly' + '&' +
        'viewFilter=' + encodeURIComponent(filter) + '&' +
        'search=';

    FetchJson(para, handleResponsefileListMode);
}

function handleResponsefileListMode(jsonObject) {
    setSpan("fileList" + globalLastNum, jsonObject.data);
}

function commentEdit(fileId) {

    var spanRef = document.getElementById('commentRef' + fileId);
    var spanHidden = document.getElementById('commentHidden' + fileId);
    var value = spanHidden.innerHTML;

    value = value.replace(/<BR>/g, "\n");

    if (value.substring(0, 5).toLowerCase() == '<span') value = '';
    spanRef.style.display = 'none';
    var spanArea = document.getElementById('commentArea' + fileId);

    spanArea.innerHTML = '<textarea id="commentText' + fileId + '" cols="40" rows="5">' +
        value + '</textarea><br />' +
        '<a href="javascript:commentEditSave(' + fileId + ')">save</a> ' +
        '<a href="javascript:commentEditCancel(' + fileId + ')">cancel</a> ';

}

function commentEditCancel(fileId) {
    var spanRef = document.getElementById('commentRef' + fileId);
    spanRef.style.display = '';
    var spanArea = document.getElementById('commentArea' + fileId);
    spanArea.innerHTML = '';
}

function commentEditSave(fileId) {
    var spanRef = document.getElementById('commentRef' + fileId);
    spanRef.style.display = '';
    var spanText = document.getElementById('commentText' + fileId);
    var value = removeHtmlTag(spanText.value);
    var spanArea = document.getElementById('commentArea' + fileId);
    spanArea.innerHTML = '';
    var spanHidden = document.getElementById('commentHidden' + fileId);
    spanHidden.innerHTML = value;

    globalCommentEditSaveFileId = fileId;

    var url = 'PageDownloadHandler.aspx?' +
        'mode=commentSave&' +
        'fileId=' + fileId + '&' +
        'value=' + encodeURIComponent(value);

    FetchHtml(url, handleResponseCommentEditSave);
}




function handleResponseCommentEditSave(responseText) {
    setSpan('commentRef' + globalCommentEditSaveFileId, responseText);
}

function setToShowSpan() {
    document.getElementById("trShow").style.display = '';
    document.getElementById("trEdit").style.display = 'none';
}


function doWikiShow() {
    loadPage(globalPageName);
}



function buttonBackClicked() {
    //history.back();

    var v = document.getElementById("buttonBack");
    if (v == null) return;

    var para = 'PageWikiHandler.aspx?' +
        'mode=' + 'getLastPageName';

    FetchJson(para, handleResponseButtonBack);
}

function handleResponseButtonBack(jsonObject) {
    loadPage(jsonObject.data);
}

function buttonPrintClicked() {
    var win = helpers.openWindow('pageWikiViewPrint.aspx?name=' + globalPageName, null, 'menubar=yes,toolbar=yes,width=860px,height=650px,status=yes,scrollbars=yes,resizable=yes', 'true');
    win.focus();
}

function exportToLocationHref(exportFormat) {

    var para = 'PageWikiHandler.aspx?' +
        'mode=exportToLocationHref&' +
        'pageName=' + globalPageName + '&' +
        'exportFormat=' + exportFormat + '&' +
        getCacheBreak();

    helpers.relocate(para, false, true);


}

function exportToWindow(exportFormat) {

    var para = 'PageWikiHandler.aspx?' +
        'mode=exportToWindow&' +
        'pageName=' + globalPageName + '&' +
        'exportFormat=' + exportFormat + '&' +
        getCacheBreak();

    var win = helpers.openWindow(para, '_blank', 'width=600,height=400,menubar=yes,toolbar=yes,scrollbars=yes,resizable=yes', 'true', true);

}


function viewWiki(id) {
    // alert(id);
    var win = helpers.openWindow('pageWikiViewHistory.aspx?id=' + id, '_blank', 'width=900,height=700,resizable=yes', 'true');
}

function viewFileId() {
    var win = helpers.openWindow('pageViewWikiFile.aspx', '_blank', 'width=600,height=400,scrollbars=yes,resizable=yes', 'true');
}

function viewWikiPages() {
    var win = helpers.openWindow('pageViewWikiPages.aspx', '_blank', 'width=600,height=400,scrollbars=yes,resizable=yes', 'true');
}


function doCancelWiki() {
    swap('trShow');
    swap('trEdit');
    loadPage(globalPageName);
    return false;
}


function Fensterhoehe() {
    if (window.innerHeight) {
        return window.innerHeight;
    } else if (document.body && document.body.offsetHeight) {
        return document.body.offsetHeight;
    } else {
        return 0;
    }
}

function doRename(textfield) {
    globalNewRenameValue = document.getElementById(textfield).value;

    var para = 'PageWikiHandler.aspx?' +
        'mode=' + 'doRename' + '&' +
        'pageName=' + encodeURIComponent(globalPageName) + '&' +
        'newPageName=' + encodeURIComponent(globalNewRenameValue);

    FetchJson(para, handleResponseDoRename);

    return false;
}

function handleResponseDoRename() {
    loadPage(globalNewRenameValue);
}

function getRename() {
    var para = 'PageWikiHandler.aspx?' +
        'mode=' + 'getRename' + '&' +
        'pageName=' + encodeURIComponent(globalPageName);

    FetchJson(para, handleResponseGetPageTree);
    return false;
}

function initSearch() {

    var para = 'PageWikiHandler.aspx?' +
        'mode=' + 'initSearch';

    FetchJson(para, handleResponseInitSearch);

    return false;
}

function handleResponseInitSearch(jsonObject) {
    setSpan('SpanWiki', jsonObject.data);
}

function doSearch(fieldName) {

    var text = document.getElementById(fieldName).value;
    var para = 'PageWikiHandler.aspx?' +
        'mode=' + 'doSearch' + '&' +
        'text=' + encodeURIComponent(text);

    setSpan('SpanSearchResult',
        '<table width="60%">' +
            '<tr>' +
                '<td align="center">' +
                    '<img src="app_themes/poolar/images/loading5.gif">' +
                '</td>' +
            '</tr>' +
        '</table>'
    );
    FetchJson(para, handleResponseDoSearch);

    return false;
}

function handleResponseDoSearch(jsonObject) {
    setSpan('SpanSearchResult', jsonObject.data);
}


function getHistory() {
    setToShowSpan();
    var para = 'PageWikiHandler.aspx?' +
        'mode=' + 'getHistory' + '&' +
        'pageName=' + globalPageName;

    FetchJson(para, handleResponseGetPageTree);
    return false;
}

function getPageList() {
    var para = 'PageWikiHandler.aspx?' +
        'mode=' + 'getPageList';

    FetchJson(para, handleResponseGetPageList);
}

function handleResponseGetPageList(jsonObject) {
    setSpan('SpanWiki', jsonObject.data);
}


function getPageWebStart() {
    setToShowSpan();
    var para = 'PageWikiHandler.aspx?' +
        'mode=' + 'getWebExportStart' + '&' +
        'pageName=' + globalPageName;

    FetchJson(para, handleResponseGetPageTree);
    return false;
}

function getPageWeb() {

    //setToShowSpan();
    var para = 'PageWikiHandler.aspx?' +
        'mode=' + 'getWebExport' + '&' +
        'pageName=' + globalPageName;

    FetchJson(para, handleResponseGetPageTree);
    return false;
}

function getPageTree() {
    setToShowSpan();
    var para = 'PageWikiHandler.aspx?' +
        'mode=' + 'getPageTree';

    FetchJson(para, handleResponseGetPageTree);

    return false;
}

function handleResponseGetPageTree(jsonObject) {
    setSpan('SpanWiki', jsonObject.data);
}

function swapWiki(level, id) {

    var v = document.getElementById('Span' + level + '-' + id);
    if (v.style.display == 'none')
        v.style.display = '';
    else
        v.style.display = 'none';
}



function rememberOpenSections(selectedSection) {

    var ar = new Array();

    var eles = document.getElementsByTagName("span");

    for (i = 0; i < eles.length; i++) {
        var id = eles[i].id;

        if (id.length > 6 && id.substring(0, 6) == 'SpanH1') {
            var section = id.substring(7);
            if (eles[i].style.display == '' || section == selectedSection) {
                ar.push(section);
            }
        }
    }
    SetCookie("wikiOpenSections", ar.join(","), 60);
}

function reopenOpenSections() {
    var wikiOpenSections = GetCookie("wikiOpenSections");
    if (wikiOpenSections == null || wikiOpenSections == "") return;

    var ar = wikiOpenSections.split(',');

    var eles = document.getElementsByTagName("span");

    for (i = 0; i < eles.length; i++) {
        var id = eles[i].id;

        if (id.length > 6 && id.substring(0, 6) == 'SpanH1') {
            var section = id.substring(7);

            for (n = 0; n < ar.length; n++) {
                if (ar[n] == section) {
                    eles[i].style.display = '';
                    break;
                }
            }
        }
    }
    DeleteCookie("wikiOpenSections");

}

function swapWikiAll(disp) {
    var eles = document.getElementsByTagName("span");

    for (i = 0; i < eles.length; i++) {
        var id = eles[i].id;

        if (id.length > 6 && id.substring(0, 6) == 'SpanH1') {
            eles[i].style.display = disp;
        }
    }
}


function getWindowHeight() {
    var y;
    if (self.innerHeight) // all except Explorer
    {
        y = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight)
    // Explorer 6 Strict Mode
    {
        y = document.documentElement.clientHeight;
    }
    else if (document.body) // other Explorers
    {
        y = document.body.clientHeight;
    }
    return y;
}

function getWindowWidth() {
    var x;
    if (self.innerWidth) // all except Explorer
    {
        x = self.innerWidth;
    }
    else if (document.documentElement && document.documentElement.clientWidth)
    // Explorer 6 Strict Mode
    {
        x = document.documentElement.clientWidth;
    }
    else if (document.body) // other Explorers
    {
        x = document.body.clientWidth;
    }
    return x;

}

function showWindowHeight() {
    var x, y;
    if (self.innerHeight) // all except Explorer
    {
        x = self.innerWidth;
        y = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight)
    // Explorer 6 Strict Mode
    {
        x = document.documentElement.clientWidth;
        y = document.documentElement.clientHeight;
    }
    else if (document.body) // other Explorers
    {
        x = document.body.clientWidth;
        y = document.body.clientHeight;
    }

    //        var h = window.innerHeight;
    setSpan('SpanHead', y);
}



function viewFilePreview(fileId) {
    var win = helpers.openWindow('pageViewUpPreview.aspx?fileId=' + fileId, null, 'width=860px,height=650px,status=yes,scrollbars=yes,resizable=yes', 'true');
    win.focus();
}

document.onkeydown = Tastendruck;

function Tastendruck(Evenement) {
    if (!Evenement)
        Evenement = window.event;
    if (Evenement.which) {
        Tastencode = Evenement.which;
    } else if (Evenement.keyCode) {
        Tastencode = Evenement.keyCode;
    }
    taste(Tastencode);
    return Tastencode;
}

function taste(Tastencode) {

    var v = document.getElementById('trEdit');
    if (v != null) {
        if (v.style.display != 'none') return;
    }



    // alert(Tastencode);
    if (Tastencode == 39) {
        var h = document.getElementById("keyright");
        if (h != null) {
           helpers.relocate(h.href);
        }
    }
    if (Tastencode == 37) {
        buttonBackClicked();
        //        var butBack = document.getElementById("buttonBack");
        //        var h = document.getElementById(butBack);
        //       helpers.relocate(h.href);
    }
}

function setSpan(spanName, content) {
    var span = document.getElementById(spanName);
    if (span == null) return;
    span.innerHTML = content;
}

function handleEventSearchKeyPress(E)
// 13 is the keycode for enter
{

    if (Tastendruck(E) == 13) {
        doSearch('textSearch');
        // prevents the default action for this even
        // - the submittal of the ASP form
        //
        // these are all possible ways to can
        // "user pressed enter in searchbox" 
        if (!E) { E = window.event; }

        if (E.stopPropagation) { E.stopPropagation; }
        if (E.preventDefault) { E.preventDefault(); }
        E.returnValue = false;
        E.cancelBubble = true;
        E.cancel = true;
        return false;
    }
}



function RotateThumb(fileID, degrees) {

    // we only do quarter-turns
    switch (degrees) {
        case "90":
        case "270":
            break;

        default:
            return 0;
    }


    if (document.getElementById(fileID).tagName != "IMG") {
        return 0;
    }

    var url = 'PageDownloadHandler.aspx?mode=RotateThumb&fileid=' + fileID + '&degrees=' + degrees;
    FetchHtml(url, handleResponseRotateThumb);

    return 1;
}

function handleResponseRotateThumb(responseText) {
    fileID = responseText;
    if (fileID == "0") {
        return 0;
    } else {

        document.getElementById(fileID).src = document.getElementById(fileID).src + "&" + getCacheBreak();
        return 1;
    }
}


function toggle_row(parent, action) {
    // action can be "toggle","collapse","expand"
    // defaults to "toggle"

    // definition of status:
    // - "collapsed":       a row that has rows after it on a deeper level that aren't displayed
    // - "expanded":        a row that has rows after it on a deeper level that are displayed
    // - "collapsed_hide":  a row that is one of the rows after a "collapsed" row. not displayed
    // - "hide":            a row that is one of the rows after a "collapsed" row, but is on a deeper level by more than one

    //
    // we call each sibling until we reach one of the same level again
    //
    // case 1: parent is "expanded", so we have to collapse the rows after it
    //  - if the sibling is an immediate level below the parent level, we give it the status of "collapsed_hide"
    //  - if the sibling is on a deeper level than the parent level by more than one, we give it a status of "hide"
    //    - if the sibling is on a deeper lavel than the parent by more than one, but the previous row is shallower by more than one
    //      or on the same level as the row, we give it status "collapsed_hide"
    //  - if the sibling is on the same level we quit
    // 
    // case 2: parent is "collapsed" so we have to expand the rows after it
    // - if the sibling is on an immediate level below the parent level, we remove it from status "collapsed_hide"
    // - if the sibling is in a lower level than the parent level by more than one, we remove it from the status "hide"
    // - if the sibling is on the same level we quit

    //

    // the important part is that both "collapsed_hide"  and "hide" apply

    // variable declarations:
    var parent_classes = get_classes(parent);
    var parent_level = 0;

    var sibling;
    var sibling_classes;
    var sibling_level;

    var prevsibling;
    var prevsibling_classes;
    var prevsibling_level;

    var distance = 0;
    var i = 0;


    if (action) {
        switch (action) {
            case "toggle":
            case "collapse":
            case "expand":
                break;
            default:
                action = "toggle";
                break;
        }
    } else {
        action = "toggle";
    }


    //find  parent level first
    parent_level = magic_get_level(parent);

    switch (action) {

        case "toggle":
            if (is_in_class(parent, "expanded")) {
                remove_from_class(parent, "expanded");
                add_to_class(parent, "collapsed");
            }
            else if (is_in_class(parent, "collapsed")) {
                remove_from_class(parent, "collapsed");
                add_to_class(parent, "expanded");
            }
            break;

        case "collapse":
            remove_from_class(parent, "expanded");
            add_to_class(parent, "collapsed");
            break;

        case "expand":
            remove_from_class(parent, "collapsed");
            add_to_class(parent, "expanded");
            break;

    }

    // now loop through all roles until the next sibling is found
    sibling = parent;
    while (sibling = sibling.nextSibling) {

        // first get the sibling level
        sibling_level = magic_get_level(sibling);
        distance = sibling_level - parent_level;

        //if we are at the same level or shallower we're done
        if (distance <= 0) { return 0; }

        // if we are exactly one level deeper
        if (distance == 1) {

            // if it already has class "collapsed_hide" remove it, otherwise add

            switch (action) {
                case "toggle":
                    if (is_in_class(sibling, "collapsed_hide")) {
                        remove_from_class(sibling, "collapsed_hide");
                    } else {
                        add_to_class(sibling, "collapsed_hide");
                    }
                    break;

                case "collapse":
                    add_to_class(sibling, "collapsed_hide");
                    break;

                case "expand":
                    remove_from_class(sibling, "collapsed_hide");
                    break;
            }
        }

        // if we are more than one level deeper
        if (distance > 1) {
            switch (action) {
                case "toggle":
                    if (is_in_class(sibling, "hide")) {
                        remove_from_class(sibling, "hide");
                    } else {
                        add_to_class(sibling, "hide");
                    }
                    break;

                case "collapse":
                    add_to_class(sibling, "hide");
                    break;

                case "expand":
                    remove_from_class(sibling, "hide");
                    break;
            }
        }
    }

    return 1;
}




function toggle_all_rows(tableID, action)
// collapses/expands all rows in a magictable
{

    var table;
    var row;

    if (action) {
        switch (action) {
            case "toggle":
            case "collapse":
            case "expand":
                break;
            default:
                action = "toggle";
                break;
        }
    } else {
        action = "toggle";
    }



    try {
        table = document.getElementById(tableID);
    }

    catch (e) {
        //alert("can't assign table "+ e);
        return 0;
    }



    try {
        row = table.firstChild.firstChild;
    }
    catch (e) {
        //alert("can't assign row "+ e);
        return 0;
    }


    try {

        if (row.tagName == "TR") {
            if (is_in_class(row, "collapsed") || is_in_class(row, "expanded")) {
                toggle_row(row, action);
            }
        }
        while (row = row.nextSibling) {
            if (row.tagName == "TR") {
                if (is_in_class(row, "collapsed") || is_in_class(row, "expanded")) {
                    toggle_row(row, action);
                }
            }

        }
    }

    catch (e) {
        //alert("Other Error: " + e);
        return 0;
    }

    return 1;
}

function toggle_all_tables(action) {
    var tables;
    var i = 0;

    if (action) {
        switch (action) {
            case "toggle":
            case "collapse":
            case "expand":
                break;
            default:
                action = "toggle";
                break;
        }
    } else {
        action = "toggle";
    }

    tables = document.getElementsByTagName("table");

    for (i = 0; i < tables.length; i++) {
        if (tables[i].id.search("magictable-") == 0) {
            toggle_all_rows(tables[i].id, action);
        }
    }

}



function magic_get_level(element) {
    var element_classes = get_classes(element);
    var element_level;

    if (!element_classes) {
        element_level = 0;
    } else {
        for (i = 0; i < element_classes.length; i++) {
            if (element_classes[i].substr(0, 5) == "level") {
                element_level = parseInt(element_classes[i].substring(5, element_classes[i].length));
                if (isNaN(element_level)) { element_level = 0; }
            }
        }
    }

    return element_level;
}

// Magiclist

// global variables
var magiclists = null;

function magiclist_onClick(evt) {
    var e = evt ? evt : window.event;
    var target = e.target ? e.target : e.srcElement;
    var image = null;
    var imagePath = "App_Themes/poolar/buttons/";

    do {
        if (target.nodeName == "LI") { break; }
    } while (target = target.parentNode)

    if (is_in_class(target, "magiclist_none")) { return true; }

    if (is_in_class(target, "magiclist_hidden")) {
        remove_from_class(target, "magiclist_hidden");
        add_to_class(target, "magiclist_visible");
        //change image from + to -
        image = target.getElementsByTagName("img")[0];
        if (image) { image.setAttribute("src", imagePath + "collapser.png"); }
    } else {

        remove_from_class(target, "magiclist_visible");
        add_to_class(target, "magiclist_hidden");
        //change image from - to +
        image = target.getElementsByTagName("img")[0];
        if (image) { image.setAttribute("src", imagePath + "expander.png"); }
    }

    e.cancelBubble = true;
    if (e.stopPropagation) { e.stopPropagation(); }
    return true;

}



function magiclist_liInit(node) {
    if (node.nodeType != 1) { return true; }
    if (node.nodeName != "LI") { return true; }
    //ok we are a li, //test if we have ul children
    var imagePath = "App_Themes/poolar/buttons/";
    var baseImage = null;
    var image = null;
    baseImage = document.createElement("img");
    baseImage.setAttribute("src", imagePath + "expander.png");
    var liText = null;
    var isOpen = false;

    var nodeListUL = node.getElementsByTagName("ul");

    if (nodeListUL.length > 0) {
        // ok we have children
        // now we need to find out if we should be ::open::
        // it's valid anywhere from here to the next UL
        // that's a nasty way to do it but it gets the job done
        liText = node.innerHTML.substr(0, node.innerHTML.indexOf('<ul>'));
        if (liText == "") {
            liText = node.innerHTML.substr(0, node.innerHTML.indexOf('<UL>'));
        }
        isOpen = (liText.indexOf("::open::") == -1) ? false : true;
        node.innerHTML = node.innerHTML.replace(liText, liText.replace("::open::", ""));


        image = baseImage.cloneNode(false);
        if (isOpen) {
            add_to_class(node, "magiclist_visible");
            image.setAttribute("src", imagePath + "collapser.png");
        } else {
            add_to_class(node, "magiclist_hidden");
        }
        node.insertBefore(image, node.firstChild);

        try {
            if (node.addEventListener) {
                node.addEventListener('click', magiclist_onClick, false);
            } else { node.attachEvent('onclick', magiclist_onClick); }
        }
        catch (E) { }

    } else {
        add_to_class(node, "magiclist_none");
        image = baseImage.cloneNode(false);
        image.setAttribute("src", imagePath + "placeholder.png");
        node.insertBefore(image, node.firstChild);
    }
}

function magiclist_ulInit(node)
//traverse the tree from shallow left, to deep right
{
    var child = null;
    magiclist_liInit(node);
    for (child = node.firstChild; child; child = child.nextSibling) {
        magiclist_ulInit(child);
    }
}

function magiclist_globalInit(evt)
// finds all ul-elements that are in the class "magiclist"
{
    var nodeListUL = null;
    var i = 0;
    magiclists = new Array();

    nodeListUL = document.getElementsByTagName("ul");
    for (i = 0; i < nodeListUL.length; i++) {
        if (is_in_class(nodeListUL[i], "magiclist")) {
            magiclists.push(nodeListUL[i]);
            magiclist_ulInit(nodeListUL[i]);
        }
    }
    return true;
}
