
var debug=false;

function log(str) {    
    //firebug running
    if('object' == typeof console) {
        console.log(str)
    }
}    

function autoDebug() {
    if($("#guest").attr('value') =='False' )
        debug=true;
}

/******************************************/
var staticWidth = 0;
var clientInfo = new Object;
var xmlInfo = new Object;

$(document).ready(function() {
    
    //~ initialize keyboard shortcuts 
    //~ if($(document).shortkeys) {
        //~ except zoom Tab in admin or qs mode, cf. initAnnotationsLayer /
        //~ if( !( $(".request#tab").attr('value') == 'zoom' && $(".session#guest").attr('value') =='False') ) 
            //~ connectShortkeys();
    //~ } 
    //~ connectHotkeys();
    
    autoDebug();
    
    // (--1--) get ClientInfo from xml
    xmlInfo.wWidth = $(".session#windowwidth").attr('value');
    xmlInfo.clientWidth = $(".session#clientwidth").attr('value');
    xmlInfo.wHeight = $(".session#windowheight").attr('value');
    xmlInfo.fullScreen = $(".session#fullScreen").attr('value');
    
    // (--2--) switch Fulscreen Mode
    if(xmlInfo.fullScreen=="true") {
        try {
            goFullScreen();
        } 
        catch(e){}
    }
    // (--3--) get actual ClientWindow-Dimensions 
    clientInfo.wWidth=getWindowsize('wWidth');
    clientInfo.wHeight=getWindowsize('wHeight');
    clientInfo.clientWidth=getWindowsize('clientWidth');
    
    if(debug) log(getWindowsize('wWidth'))
    
    //compare and store if changed
    if( (xmlInfo.wWidth != clientInfo.wWidth) || (xmlInfo.wHeight != clientInfo.wHeight) ) {
        sendClientInfo()
        //make a second request on img src with the actual dimensions
        if($(".request#tab").attr('value') =='pageview') {
            adjustSinglePageImage()
        }
    }
    //~ discard loader when image is loaded
    $('#singlePageImage').load(function() {
        $(this).css('background','transparent none');
    });
    if($(".request#tab").attr('value') =='pageview' && $("#sessionSearchData").length > 0 ) {
        //~ check selected offset
        var id = $(".request#id").attr('value');
        if($("#sessionSearchData a#"+id).closest('div.pageHits').length > 0) {
            $("#sessionSearchData a#"+id).closest('div.pageHits').show();
        } 
        else { //~ fall back to first offset
                $('div#n0').show();
        }
        //~ this works if the non-page-hit-page is part of a struct which is given in the pagehITS
        //~ else {
            //~ struct = $("form.navDropdowns#0 option[selected]").val();
            //~ if($("#sessionSearchData li#"+struct).closest('div.pageHits').length > 0) {
                //~ $("#sessionSearchData li#"+struct).closest('div.pageHits').show();
            //~ }
        //~ }
        $("#sessionSearchData a.nav").click(function() {
            $("#sessionSearchData > div").hide();
            $("#sessionSearchData div#n"+this.id).show();
        });
        
    }

    $(window).resize(function() {
        
        refreshClientInfo(); // write to clientInfo-Object
        sendClientInfo();
        setAdminTableWidth();
    });
    
    setAdminTableWidth();
    //~ admin tables zebra style
    $(".vlsTable tr:nth-child(odd), .vlsTable50 tr:nth-child(odd)").addClass("odd");
    
    // submit form on change of select 
    $("select.change").change(function() {
		this.parentNode.submit();
    });
    
    $("a.showbox").click(function() {
        $("#sbox").show()
    });
    $("a.hidebox").click(function() {
        $("#sbox").hide()
    });
    
    
    //~ @toggleFulltextHits if true on searchResult-part
    $("a.toggle").click(function() {
        $(this).next('ul').toggle();
        $(' .showHits', this).toggle();
        $(' .hideHits', this).toggle();
        $(this).closest('li').toggleClass('toggled');
        
        // send toggleInfo to server
        var pID = $("vlparam[id='dc.fulltext']").attr('value') ? $("vlparam[id='dc.fulltext']").attr('value') : $("vlparam#query").attr('value');
        if($(this).next('ul').css('display')=='none') {
            $.get('/client/setToggleState?tree&id=id'+pID+'&idx='+this.id+'&uncheck')
        } else {
            $.get('/client/setToggleState?tree&id=id'+pID+'&idx='+this.id+'&check')
        }
    });
    //~ fetch previously toggled elements from server
    if( $("a.toggle").length > 0 ) {
        var pID = $("vlparam[id='dc.fulltext']").attr('value') ? $("vlparam[id='dc.fulltext']").attr('value') : $("vlparam#query").attr('value');
        $.ajax({
            type:       "GET",
            url:        "/client/getToggleState",
            cache:      false,
            data:       "tree&id=id" + pID,
            success:    function(data) {
                $("actions item",data).each(function() {
                    toggledItems=$(this).attr('value')
                });
                try {
                    items=eval(toggledItems);
                    for( x=0; x < items.length; x++ ) {
                        //set/remove class for treefolder icon and toggle the indentation list below
                        $elem = $('a.toggle#'+items[x]);
                        $elem.next('ul').toggle();
                        $elem.children('.showHits').toggle();
                        $elem.children('.hideHits').toggle();
                        $elem.closest('li').toggleClass('toggled');
                    }
                } catch(e) {  }
            }
        });
    }
    
    $("a.toggleStructure").click(function() {
        var pID = $(".request#id").attr('value');
        //set/remove class for treefolder icon and toggle the indentation list below
        $(this).parent().toggleClass('toggleLi');
        $('ul.'+this.id).toggle();
        //~ $(this).parent().next().toggle();
        // and send toggleInfo to server
        if($(this).parent().hasClass('toggleLi')) {
            $.get('/client/setToggleState?tree&id=id'+pID+'&idx='+this.id+'&check')
        } else {
            $.get('/client/setToggleState?tree&id=id'+pID+'&idx='+this.id+'&uncheck')
        }
    });
    
    //fetch previously toggled elements from server
    if( $("a.toggleStructure").length > 0 ) {
        pID = $(".request#id").attr('value');
        $.ajax({
            type:       "GET",
            url:        "/client/getToggleState",
            cache:      false,
            data:       "tree&id=id" + pID,
            success:    function(data) {
                $("actions item",data).each(function() {
                    toggledItems=$(this).attr('value')
                });
                try {
                    items=eval(toggledItems);
                    for( x=0; x < items.length; x++ ) {
                        //set/remove class for treefolder icon and toggle the indentation list below
                        $('a.toggleStructure#'+items[x]).parent().toggleClass('toggleLi');
                        $('ul.'+ items[x]).toggle();
                    }
                } catch(e) { }
            }
        });
    }
    
    //for lack of ie css2 support
    $("input[type='text']").addClass('text');
    
});

//~ set admin tables width in pixels
function setAdminTableWidth() {
    if ($.browser.msie)  {
        $('.vlsTable').each(function(){
            //~ expecting something like "vlsTable 30"
            classNames = $(this).attr('class').split(' ');
            if(classNames.length > 1) {
                factor = 100 / classNames[1];
                cols = $(this).closest('tr').children('td').length;
                $(this).css('width', getWindowsize('wWidth') / factor - (cols * 5));
            } else {
                width = $(this).css('width')
                $(this).css('width', getWindowsize('wWidth') - 2)
                //~ alert(width + ' ' + getWindowsize('wWidth') );
            }
        });
    }
}

/*
function calculateBarPercentage() {
    $('.vlsTable tr .bar').each(function(){
        cols = $(this).closest('tr').find('td').length;
        if(debug) log(cols)
        $(this).closest('tr').find('.bar').each(function(){
            value = $(this).attr('vls:width')
            if(debug) log('GG'+value)
            $(this).css('width',parseInt(value/(cols))+'%')
        });
    });
}
*/
//refresh actual ClientWindow-Dimensions
function refreshClientInfo() {
    clientInfo.wWidth=getWindowsize('wWidth');
    clientInfo.wHeight=getWindowsize('wHeight');
    clientInfo.clientWidth=getWindowsize('clientWidth');
}
//send Window-Dimensions via /clientInformation?
function sendClientInfo(args) {
    $('img#cInfo').attr('src','/clientInformation?'+addParams(clientInfo,args));
    if(debug) {
        log(addParams(clientInfo,args))
        log(hasCol('left') == true)
    }
}
//rewrite Window-Dimensions on Image-Src Request
function adjustSinglePageImage() {
    newImgSource = replaceParams($('img#singlePageImage').attr('src'), clientInfo);
    $('img#singlePageImage').attr("src", newImgSource);
    if(debug) log(newImgSource)
}

// cf. thirdparty/jquery.shortkeys.js
function connectShortkeys() {
        
    var jsonStr = '({'; // cf. http://rayfd.wordpress.com/2007/03/28/why-wont-eval-eval-my-json-or-json-object-object-literal/
    // fetch key-definitions from the name attribute on the navPort-links
    $("div#navPort a[name]").each( function(i) {
        jsonStr += "'"+this.name+"': function() { location.href='"+this.href+"'}";
        if(i < $("div#navPort a[name]").length - 1) jsonStr += ",\n"; // IE doesn't permit empty param (last comma)
    });
    if(debug) {
    for(key in link) {
        $(document).bind('keydown', 
        {combi:key, disableInInput: true}, 
        function(evt){
            //~ log(key+link[key]);
            location.href = link[key];
        });
    }
    }
}
function countObj(obj) {
         var i=0; for (var k in obj) {i+=1}
         return i;
}

function addParams(clientInfo,args) {
    var strReturn='';
    var k=0; 
    for ( var j in clientInfo) {
        strReturn += j +'='+clientInfo[j];
        k++; if(k < countObj(clientInfo)) strReturn += '&';
    }
    for ( var j in args) {
        strReturn += '&'+ j +'='+args[j];
    }
    return strReturn;
}

function replaceParams(strReq,clientInfo) {
    var aNewParams = new Array;
    var strNewParams='';
    var strReturn;
    var ctWParams = countObj(clientInfo);
    //~ no params yet: add new Params / the case with the anchor on the overview tab
    if(!strReq) {
        strReturn = "?";
        var k=0; 
        for ( var j in clientInfo) {
            k+=1;
            strReturn += j +'='+clientInfo[j];
            if(k < ctWParams) strReturn += '&';
        }
    } 
    //~ url params exist: replace respective Params / the case with the img src request and zoom buttons
    else {
        strReturn = strReq.substr(0,strReq.lastIndexOf('?')+1) // baseRequestUrl
        var strQueryString = strReq.substr(strReq.indexOf("?")+1);
        var aQueryString = strQueryString.split("&");
        for ( var i = 0; i < aQueryString.length; i++ ) {
            var aParam = aQueryString[i].split("=");
            if(!aNewParams[i]) { // -> add existing param value
                    aNewParams[i] = aParam[0] + '='+ aParam[1];
                    for ( var j in clientInfo) { // for keys of clientInfo add new param value
                    if ( aParam[0].indexOf(j) > -1 ) { 
                        aNewParams[i] = aParam[0] + '='+clientInfo[j]; 
                    } 
                } 
            }
        }
        for ( var i = 0; i < aNewParams.length; i++ ) {
            strNewParams += aNewParams[i];
            if(i < aNewParams.length-1) 
                strNewParams += '&';
        }
        strReturn += strNewParams;
        
        //~ check if keys of clientInfo exist and add params if not / the case with fulltextsearch-links
        var k=0; 
        for ( var j in clientInfo) {
            if(strReturn.indexOf(j) <= -1) {
                if(k < ctWParams) strReturn += '&';
                strReturn += j +'='+clientInfo[j];
                k++;
            }
        }
    }
    return strReturn;
}

// clientWindow Params 
function getWindowsize(axis) {
    var z;
    // sites with fixed width - wWidth is fetched from body css instead of from clientWidth
    if (axis == 'clientWidth') {
        return $(window).width();
    }
    else if(staticWidth && axis == 'wWidth') {
        z = getNum($('body').css('width'));
    } else {
        axis=='wWidth' ? z = $(window).width() - getXSpace() : axis=='wHeight' ? z = $(window).height() - getYSpace() :  0;
    }
    return z;
}

function hasCol(side) {
    var tabs = $(".layout#col"+side).attr('value').split(',');    
    
    for (var i in tabs) {
        if ( tabs[i] == $(".request#tab").attr('value') ) 
            return true;
    }
}
function getXSpace() {
    
    var layoutElems = ['body','td.colmain'];
    var margins = ['padding','margin','border'];
    var sides = ['left','right'];
    // widths and margins of these if they are part of the layout
    var cols=[];
    if( hasCol('left') == true ) {
        cols.push('td.colleft');
        layoutElems.push('td.colleft');
    }
    if( hasCol('right') == true ) {
        cols.push('td.colright');
        layoutElems.push('td.colright');
    }
    // subtract widths and margins
    var space=0;
    for(i = 0; i < cols.length; i++) {
        space+=getNum($(cols[i]).width());
    }
    for( x = 0; x < layoutElems.length; x++) {
        if( $(layoutElems[x]).length > 0 ) {
            for( y = 0; y < margins.length; y++ ) {
                for( z=0; z < sides.length; z++ ) {
                    space+=getNum($(layoutElems[x]).css(margins[y]+"-"+sides[z]));
                }
            }
        }
    }    
    // Browser-wackiness / scrollbars/ comfort 
    space += 20;
    return space;
}

function getYSpace() {
    var client = $("#client").attr('value');
    var val=0;
    if(client=='browser') {
        if($("div#navPort").length>0) { 
            nPortHeight = getNum($("div#navPort").height())+
                getNum($("div#navPort").css('padding-bottom'))+
                getNum($("div#navPort").css('margin-top'))+
                getNum($("div#navPort").css('margin-bottom'));
            val+=nPortHeight;
            colmainPadding = getNum($("td.colmain").css('padding-top')) + getNum($("td.colmain").css('padding-bottom'));
            val+=colmainPadding;
        }
        
        if($("#topContent").css('display')!='none') {
            if($("#topContent").length>0) {
                val += getNum($("#topContent").height());                 
            }
            if($("div#topmenu").length>0) {
                val += getNum($("div#topmenu").height()); 
            }
            //~ #pageView is renamed in fullScreen to #fpView in order to loose the padding-top
            if($("#pageView").length>0) {
                nPathHeight=20; //~ we must assume this value, because nPath is not Part of, f.e. titleInfo
                val+=nPathHeight;
                pwPaddingTop = getNum($("#pageView").css('padding-top')); 
                val+=pwPaddingTop;
            }
        } 
    }
        footerHeight = getNum($("#footer").height())+getNum($("#footer").css('border-top-width'))+getNum($("#footer").css('padding-top'))*2;
        val+=footerHeight;
        return val;
}

//avoid NaN
function getNum(val) {
    val = parseInt(val);
    isNaN(val) ? val=0 : false;
    return val;
}

// on quicksearch-input 
function alertIfEmpty(input, message) {
    if(!input || input.length <= 1) {
        if(!message) {
            alert("Bitte mindestens einen Suchbegriff eingeben.");
        } else { alert(message);
        }
        return false;
    }
}

//~ add to favs
function bookmark() {
    if ($.browser.msie) 
        window.external.AddFavorite(location.href, document.title);
    else if (window.sidebar) 
        window.sidebar.addPanel(document.title, location.href, "");
}

