﻿/// <reference path="../jquery.js" />

var globalPageName = 'home';
var globalNewRenameValue = '';
var globalTextPageTree = 'page tree';
var globalCurrentSection = -1;
var globalHandler = 'PageWikiHandler.aspx';
var globalNewsTeaserAr = null;
var globalHandler = 'PageWikiHandler.aspx';

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 magicTabShowLine(mySelf, lineNr, speed) {

    var master = $(mySelf).parents('.magicTabDiv');

    var divs = master.find('div.fadeDiv'); //  $(mySelf).parents('.magicTabDiv').find('table.magictable');

    // divs.stop(true, true);

    if (typeof (master.attr('myLastId')) == "undefined") {
        master.attr('myLastId', 0);
    }
    var last = parseInt(master.attr('myLastId'));

    if (lineNr == last) return;
    divs.find('div:nth-child(' + (last + 1) + ')').fadeOut(speed);
    divs.find('div:nth-child(' + (lineNr + 1) + ')').fadeIn(speed);

    master.attr('myLastId', lineNr);

    //$('#test1').fadeOut(2000);

    //mt.find('tr:nth-child(' + (lineNr + 1) + ')').css('display', '');
    //    mt.find('tr').fadeOut(speed);
    //    mt.find('tr:nth-child(' + (lineNr + 1) + ')').fadeIn(speed);
}

function fadeInit3() {

    $('.magicTable3').each(function () {

        var tab = $(this);

        fadeInit3_prepareMagicTab(tab);

    });


    $('.magicTable3').each(function () {

        var tab = $(this);

        fadeInit3_prepareMagicTab(tab);

    });
}

function fadeInit3_prepareMagicTab(tab) {

    var buttonHeight = 22;
    var trs = tab.children('tBody').children('tr');

    var maxHeight = 0;

    trs.each(function () {
        if ($(this).height() > maxHeight) {
            maxHeight = $(this).height();
        }
    });
    maxHeight += buttonHeight;

    var buttons = new Array;

    var myFadeTime = tab.attr('myFadeTime');
    var myFullHeight = tab.attr('myFullHeight');
    var myFullWidth = tab.attr('myFullWidth');
    var myCss = tab.attr('myCss');
    var myPhotoBut = tab.attr('myPhotoBut');

    trs.each(function (index, element) {

        var bu = $(element).children().first();
        var css2 = index == 0 ? " selected" : "";

        buttons.push(
                '<td class="bu ' + css2 + '">' +
                    '<a ' +
                        'onclick="magicTable3ShowLine(this, ' + index + ', ' + myFadeTime + ')" ' +
                        'href="#" ' +
                    '>' +
                        bu.html() +
                    '</a>' +
               '</td>');

        bu.hide();
    });

    var cssWidth = '';
    if (myFullHeight != '0') maxHeight = myFullHeight;
    if (myFullWidth != '0') cssWidth = ';width:' + myFullWidth + 'px';

    tab.after('<div class="magicTable3Container ' + myCss + '" style="height:' + maxHeight + 'px ' + cssWidth + '" />');

    var masterDiv = tab.next();

    var divTab;

    if (myPhotoBut != 'top') {
        masterDiv.append('<div class="table3" style=\"height:' + (maxHeight) + 'px" />');
        divTab = masterDiv.children().first();
    }

    masterDiv.append(
                '<div class="buttons">' +
                    '<table>' +
                        '<tr>' +
                            buttons.join(' ') +
                        '</tr>' +
                    '</table>' +
                '</div>'
        );

    if (myPhotoBut == 'top') {
        masterDiv.append('<div class="table3" />');
        divTab = masterDiv.children().next();
    }

    trs.each(function (index) {
        //$(this).show();
        var doShow = index == 0 ? '' : ' display:none';
        var cssH = ''; // ' ;height:' + (maxHeight) + 'px';
        divTab.append(
                '<div class="divRow" style="' + doShow + cssWidth + cssH + '">' +
                    '<table cellpadding=0 cellspacing=0>' + $(this).html() + '</table>' +
                '</div>');
    });

    tab.detach();
}

function magicTable3ShowLine(mySelf, lineNr, speed) {

    var master = $(mySelf).parents('.magicTable3Container').first();

    var tab = master.find('div.table3'); //  $(mySelf).parents('.magicTabDiv').find('table.magictable');

    if (typeof (master.attr('myLastId')) == "undefined") {
        master.attr('myLastId', 0);
    }
    var last = parseInt(master.attr('myLastId'));

    var buttons = master.find('div.buttons');
    buttons.first().find('td:nth-child(' + (last + 1) + ')').removeClass('selected');
    buttons.first().find('td:nth-child(' + (lineNr + 1) + ')').addClass('selected');

    if (lineNr == last) return;
    tab.find('div.divRow:nth-child(' + (last + 1) + ')').first().fadeOut(speed); //.css("display", "none");//.fadeOut(speed);
    tab.find('div.divRow:nth-child(' + (lineNr + 1) + ')').first().fadeIn(speed); //.css("display", ""); //.fadeIn(speed);

    //    t1.fadeOut(speed); //.hide();
    //    t2.fadeIn(speed); // show();



    master.attr('myLastId', lineNr);

    //$('#test1').fadeOut(2000);

    //mt.find('tr:nth-child(' + (lineNr + 1) + ')').css('display', '');
    //    mt.find('tr').fadeOut(speed);
    //    mt.find('tr:nth-child(' + (lineNr + 1) + ')').fadeIn(speed);
}

function fadeInit2() {

    $('.magicTabDiv.fade2').each(function () {

        var master = $('.magicTabDiv');

        if (master.find('div.fadeDiv').length != 0) return;

        var tab = master.find('table.magictable');
        tab.find('td.hide').detach();
        tab.hide();

        tab.after('<div class="fadeDivContainer"><div class="fadeDiv" /></div>');

        var div = master.find('div.fadeDiv');

        tab.find('tr').each(function () {
            $(this).show();
            div.append('<div class="divRow"><table cellpadding=0 cellspacing=0>' + $(this).html() + "</table></div>");
        });

        var divs = div.find('div.divRow');
        divs.hide();
        div.find(':first-child').show();

        var maxHeight = 480;

        divs.find('img').each(function () {
            var h = $(this).height();
            maxHeight = Math.max($(this).height(), maxHeight)
        });
        master.find('div.fadeDivContainer').height(maxHeight + 5);


    });





    // special function for jörn genkel website alike entry effect

    $('.fadeContainer .fade3').hover(
        function () {
            $('.fadeContainer .fade2').fadeOut(1000);
        },
        function () {
            $('.fadeContainer .fade2').fadeIn(1000);
        }
    );
}

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);
    neuAufbauWiki();
    wikiTimeLineInit();
    checkNextDirList(0);
    checkNextTreeList(0);
    fadeInit();
    fadeInit2();
    fadeInit3();
    imageWipeInit();
}


function imageWipeInit() {

    $('#imagegallery').cycle({
        fx: 'scrollHorz',
        timeout: 0,
        next: '#next1',
        prev: '#prev1'
    });
    $("#imagegallery").touchwipe({
        wipeLeft: function () {
            $("#imagegallery").cycle("next");
        },
        wipeRight: function () {
            $("#imagegallery").cycle("prev");
        }
    });
}


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);
}

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);
}

function setGreenListMode(obj, listMode, xspanId) {

    var me = $(obj);

    var top = me.parents('.wikiGreenTop');
    var rootId = top.attr('myRootId');
    var spanId = top.attr('mySpanId');
    top.attr('myListMode', listMode);

    fileGetTreeGreen(obj, rootId, spanId, listMode);
}

function swapWikiGreenList(myself) {

    var me = $(myself);

    var top = me.parents('.wikiGreenListDiv');

    top.find('.content').toggle();

    var img = top.find('img.plusMinus');

    if (img.attr('src') == 'app_themes/poolar/images/singlePlus3.gif')
        img.attr('src', 'app_themes/poolar/images/singleMinus3.gif');
    else
        img.attr('src', 'app_themes/poolar/images/singlePlus3.gif');
}

function fileGetTreeGreen(obj, rootId, spanId, xlistMode) {

    var top = $(obj).parents('.wikiGreenTop');
    top.attr('myRootId', rootId);
    var listMode = top.attr('myListMode');

    globalLastSpanTreeId = top.find('.contentSpan').attr('id');

    var para = 'pageWikiHandler.aspx?' +
        'mode=getGreenList&' +
        'value=' + rootId + '&' +
        'spanId=' + spanId + '&' +
        'listMode=' + listMode + '&' +
        'search=';

    FetchJson(para, handleResponseFileGetTreeDir2);
}

function handleResponseFileGetTreeDir2(jsonObject) {
    setSpan(globalLastSpanTreeId, jsonObject.data);
}

function openFileSystemImage(filePathId) {

    var para = "pageTree3Handler.aspx" + '?' +
                    'instance=0&' +
                    'mode=' + 'openFileSystemImage' + '&' +
                    'index=' + filePathId + '&' +
                    'masterId=0'
                    + '&pageIndex=0';

    var win = helpers.openWindow(para, null, 'width=960px,height=700px,status=yes,scrollbars=yes,resizable=yes,toolbar=no', 'true');

    helpers.focusIfSet(win);
}

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);
}

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")).show();
}


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=' + encodeURIComponent(globalPageName), null, 'menubar=yes,toolbar=yes,width=860px,height=650px,status=yes,scrollbars=yes,resizable=yes', 'true');
//    helpers.focusIfSet(win);
//}

function exportToLocationHref(exportFormat) {

    var para = 'PageWikiHandler.aspx?' +
        'mode=exportToLocationHref&' +
        'pageName=' + encodeURIComponent(globalPageName) + '&' +
        'exportFormat=' + exportFormat + '&' +
        getCacheBreak();

    helpers.relocate(para, false, true);


}

function exportToWindow(exportFormat) {

    var para = 'PageWikiHandler.aspx?' +
        'mode=exportToWindow&' +
        'pageName=' + encodeURIComponent(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() {

    previewClose();

    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/loading7.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=' + encodeURIComponent(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=' + encodeURIComponent(globalPageName);

    FetchJson(para, handleResponseGetPageTree);
    return false;
}

function getPageWeb() {

    //setToShowSpan();
    var para = 'PageWikiHandler.aspx?' +
        'mode=' + 'getWebExport' + '&' +
        'pageName=' + encodeURIComponent(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');
    helpers.focusIfSet(win);
}

function openWikiShowTreeWindow(fileId, mode) {
    var win = helpers.openWindow('pageWikiShowTree.aspx?fileId=' + fileId + '&mode=' + mode, null, 'width=860px,height=650px,status=yes,scrollbars=yes,resizable=yes', 'true');
    helpers.focusIfSet(win);
}

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;
}


function neuAufbauWiki() {

    var height = getWindowHeight();
    var width = getWindowWidth();
    var midTD = document.getElementById("skin1-midTd");
    var scrmv = document.getElementById("screenmove");
    var wiki = document.getElementById("wiki");


    var trEdit = document.getElementById("trEdit");

    midTD.style.height = String(height - 70).concat("px");

    if (scrmv != null) {
        scrmv.style.height = String(height - 120).concat("px");
    }

    $('.screenmove2').each(function () {
        var myFixH = parseInt($(this).attr('myFixH'), 10);
        $(this).height(height - myFixH);

    });
    //    if (wiki != null)
    //        wiki.style.height = String( height - 100 ).concat("px");


}

function neuAufbauWiki2() {

    //Hoehe = Fensterhoehe();
    Hoehe = getWindowHeight();
    //if (Hoehe != Fensterhoehe())
    //setSpan('SpanHead', Hoehe)
    // window.onresize = neuAufbauWiki;
    var v = document.getElementById("skin1-midTd");

    //v.style.top= 100;
    // v.style.backgroundColor = "green";
    v.style.height = String(Hoehe - 70).concat("px");

    //        var w = document.getElementById("divtest");
    //        w.style.height = String(Hoehe - 120).concat("px");
    // setSpan('SpanTest', Hoehe++);
}
function PageWiki_OnLoad() {

    //var allWiki = document.getElementById("allWiki");
    //allWiki.onclick = nodeClicking;

    // showWindowHeight(); 
    xxx = 0;
    Hoehe = 0;
    if (!window.Weite && window.innerWidth) {
        window.onresize = neuAufbauWiki;
    }
    if (!window.Weite && document.body && document.body.offsetWidth) {
        window.onresize = neuAufbauWiki;
    }
    neuAufbauWiki();

    //        var wikiOpenSections = GetCookie("wikiOpenSections");
    //        if (wikiOpenSections != null)
    //            reopenOpenSections(wikiOpenSections);

    var params = top.location.search;
    var pageName = "";
    var editorState = "";
    var editorSection = "";
    if (params > "") {
        params = "&" + params.substr(1, params.length);
        var data = params.split("&");


        for (i = 1; i < data.length; i++) {
            var my_par = data[i].split("=");
            if (my_par[0] == "name") {
                pageName = my_par[1];
            }
            else if (my_par[0] == "editor")
                editorState = my_par[1];
            else if (my_par[0] == "section")
                editorSection = my_par[1];
        }
    }

    pageName = decodeURIComponent(pageName.replace(/\+/g, " "));

    if (pageName == "") pageName = globalEmptyPageName;  //'Home';

    if (editorState == "on") {
        globalPageName = pageName;
        if (editorSection == "") {
            doWikiEdit();
        }
        else {
            globalCurrentSection = editorSection;
            doSectionEdit(editorSection);
        }
    } else {

        loadPage(pageName);
    }


}
function doWikiEdit(wikiPageName) {
    // wikiPageName is required to be properly url encoded

    var w = window.open(helpers.getFinalUrl("PageWikiEditor.aspx?wikiPageName=" + wikiPageName), "_top"); //, helpers.getSomeWindowName(), "");
}

function showHasRead() {

    var para = globalHandler + '?' +
            'mode=' + 'showHasRead' + '&' +
            getCacheBreak() + '&rawmode=true';

    var w = openNewWindow(para);  // helpers.openWindow("", "HasRead", "width=700,height=400,status=yes,scrollbars=yes,resizable=yes", true);
}

function wikiButtonClick(txtPara) {
    var para = globalHandler + '?' +
        'mode=' + 'customButtonClick' + '&' +
        'para=' + txtPara;
    FetchJson(para, handleResponseWikiButtonClick);
}

function buttonTriggerTmkWebExportClick() {
    var para = globalHandler + '?' +
        'mode=' + 'triggerTmkWebExport';
    var that = this;

    FetchJson(para, handleResponseButtonTriggerTmkWebExportClick, that);
}


function handleResponseButtonTriggerTmkWebExportClick(data, ele) {
    alert(util.tr('Export started', 'Export angestoßen', ''));
}


function openNewWindow(destinationUrl, useClassicWindow) {
    ///	<summary>
    ///		Open Window Helper method
    ///		Look for telerik radwindow manager in the page if found show url in radWondow
    ///		Else show the window in classic window
    ///	</summary>
    ///	<returns type="window" />
    ///	<param name="destinationUrl" type="String">
    ///		The url that will be opened.
    ///	</param>
    ///	<param name="useClassicWindow" type="Boolean">
    ///		Use Classic helpers.openWindow() if RadWindowManager is not found. Also if 
    /// Popup blocker is open alert user.
    ///	</param>
    var oManager = null;
    try {
        oManager = GetRadWindowManager();
    }
    catch (err) {
        //Handle errors here
    }

    destinationUrl = helpers.getFinalUrlForSessionHandover(destinationUrl);

    if (typeof (useClassicWindow) == "undefined")
        var useClassicWindow = false;

    if (oManager == null || typeof (oManager) == "undefined" || useClassicWindow == true) {
        var oWin = helpers.openWindow(destinationUrl, null, 'width=700px,height=700px,status=yes,scrollbars=yes,resizable=yes', 'true');
        if (oWin == null || typeof (oWin) == "undefined") {
            alert("System has been blocked by POP-UP BLOCKER.\nPlease disable the POP-UP BLOCKER and try again\nor\nContact your system administrator. ");
        }
        else oWin.focus();
        return oWin;
    }
    else {
        var oWnd = radopen(destinationUrl, destinationUrl);
        oWnd.Center();
        return oWnd;
    }
}
function handleResponseWikiButtonClick(data) {
    var sp = document.getElementById('SpanCustomButtonResponse');

    if (sp != null) {
        setSpan('SpanCustomButtonResponse', data.data);
    }

}

function getPosition(theElement) {
    var positionX = 0;
    var positionY = 0;

    while (theElement != null) {
        positionX += theElement.offsetLeft;
        positionY += theElement.offsetTop;
        theElement = theElement.offsetParent;
    }

    return [positionX, positionY];
}

function menuItemClicked(sender, eventArgs) {

    var item = eventArgs.get_item();

    var value = item.get_value();

    switch (value) {

        case "exportPdf": exportToLocationHref("pdf"); break;

        case "exportExcel": exportToLocationHref("excel"); break;

        case "exportWord": exportToLocationHref("word"); break;

        case "exportWindow": exportToWindow(""); break;

        default: alert("Value '" + value + "' not supported"); break;
    }
}

function onSearchResultClick(eventObject) {

    var target = eventObject.target;

    var offset = $(target).offset();

    var spanWikiWidth = $('#divWikiPageContent').innerWidth();
    var skin1midTdHeight = $('#skin1-midTd').innerHeight();

    var viewPortHeight = $(window).height();

    var previewDiv = $('<div id="previewDiv" />');
    var previewDivHead = $('div#previewDivHead');

    var offSetDistance = 100;

    var cssObj = {
        'background-color': 'white',
        'width': (spanWikiWidth - offSetDistance - 50) + 'px',
        'height': (viewPortHeight * 0.75) + 'px',
        'border-color': 'black',
        'border-width': '1px',
        'border-style': 'solid',
        'position': 'absolute',
        'overflow': 'hidden'
    };


    previewDiv.css(cssObj);

    //previewDiv.offset({ top: offset.top + 10, left: offset.left + offSetDistance });
    previewDiv.offset({ top: $(document).scrollTop() + viewPortHeight * 0.125, left: offset.left + offSetDistance });

    $('#divWikiPageContent').append(previewDiv);

    previewDiv.html("<table width=\"100%\" height=\"100%\"><tr height=\"100%\"><td align=\"center\" style=\"vertical-align:middle;\" height=\"100%\"><img src=\"app_themes/poolar/images/loading7.gif\" /></td></tr></table>");

    previewDiv.show();
}

function onSearchResultSelect(event, selection) {
    var browserEvent = event || window.event;
    var $event = $.event.fix(browserEvent);
    var url = 'PageWikiHandler.aspx?mode=loadPagePreview&pageName=' + selection;
    onSearchResultClick($event);
    FetchJson(url, showWindow);
}

function showWindow(o, ev) {
    var pageHtml = o.data;

    $('#previewDiv').html(pageHtml);

    $('#previewDiv').show();

    var cssObjContent = {
        'padding' : '5px',
        'overflow': 'auto'
    }

    var previewDivContent = $('div#previewDivContent');
    previewDivContent.css(cssObjContent);
    previewDivContent.height($('#previewDiv').innerHeight() - $('#previewDivHead').innerHeight());

    $('.searchResult').click(function (ev) {

    });

    $('#originalPageHref').click(function (ev) {
        ev.stopPropagation();
    });

    // Prevent preview window from closing when clicking into it
    $('#previewDiv').click(function (ev) {
        return false;
    });

    $('#skin1-midTd').bind('click', previewClose);
}

function previewClose() {
    $('#previewDiv').remove();
    $('#skin1-midTd').unbind('click', previewClose);
    return false;
}

document.onkeydown = onKeyDown;

function onKeyDown(e) {

    var be = e || window.event;

    if (be) {

        var je = $.event.fix(be);
        var keyCode = je.keyCode;

        if (je.keyCode == 27) {
            previewClose();
        }
        else {
            return;
        }
    }


}
