
var clientInfo = new Object;
var xmlInfo = new Object;

$(document).ready(function() {
    
    //ClientInfo from xml
    xmlInfo.wWidth = $("param#windowwidth").val();
    xmlInfo.wHeight = $("param#windowheight").val();
    xmlInfo.fullScreen = $("param#fullScreen").val();

    if(xmlInfo.fullScreen=="true") {
        try {
            goFullScreen();
        } 
        catch(e){}
    }
    //actual ClientWindow-Dimensions 
    clientInfo.wWidth=getWindowsize('wWidth');
    clientInfo.wHeight=getWindowsize('wHeight');
    
    $(window).resize(function() {
        refreshClientInfo();
        sendClientInfo()
    });
    
    if(xmlInfo.wWidth != clientInfo.wWidth || xmlInfo.wHeight != clientInfo.wHeight) {        
        sendClientInfo()
        if($("param#tab").val() =='pageview') {
            adjustSinglePageImage()
        }
    }
    
    //initialize keyboard shortcuts 
    if($(document).shortkeys) {
        connectShortkeys();
    }

    // submit form on change of select 
    $("select.change").change(function() {
		this.parentNode.submit();
    });
    
    $("#purnLink").click(function() {
        $("#copyPurn").show()
    });
    $("#copyPurnHide").click(function() {
        $("#copyPurn").hide()
    });
    
    $("a.toggleFulltextHits").click(function() {
        var id=this.id
        $('ul.fulltext#'+this.id).toggle();
        $('ul.fulltext#'+this.id).css('display')!='none' ? $('img#cInfo').attr('src','/clientInformation?openedIndex='+id) : 0;
        $('a.toggleFulltextHits#'+this.id + '> span.showFulltextHits').toggle();
        $('a.toggleFulltextHits#'+this.id + '> span.hideFulltextHits').toggle();
    });


    //Dirk: setup the position of the adminbox
    setupAdminBox()
    
    //Dirk: 
    dialogCloseChecker()
});


//refresh actual ClientWindow-Dimensions
function refreshClientInfo() {
    clientInfo.wWidth=getWindowsize('wWidth');
    clientInfo.wHeight=getWindowsize('wHeight');
}
//send Window-Dimensions via /clientInformation?
function sendClientInfo(args) {
    $('img#cInfo').attr('src','/clientInformation?'+addParams(clientInfo,args));
}
//rewrite Window-Dimensions on Image-Src Request
function adjustSinglePageImage() {
    newImgSource = replaceParams($('img#singlePageImage').attr('src'),clientInfo);
    $('img#singlePageImage').attr("src",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/
    $("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)
    });
    jsonStr += '})'; 
    $(document).shortkeys(eval(jsonStr));
}

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;
    
    axis=='wWidth' ? z = $(window).width() - getXSpace() : axis=='wHeight' ? z = $(window).vlsHeight() - getYSpace() :  0;
    return z;
}

function getXSpace() {
    // margins of these
    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($("#layoutColleft").val() == 'true') {
        cols.push('td.colleft');
        layoutElems.push('td.colleft');
    }
    if($("#layoutColright").val() == '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 = $("param#client").val();
    var val=0;
    if(client=='browser') {
        if($("div#navPort").length>0) {
            nPortHeight = getNum($("div#navPort").height());
            !$.browser.msie ? nPortHeight+=getNum($("div#navPort").css('padding-bottom')) : 0;
            val+=nPortHeight;
            colmainPaddingTop = getNum($("td.colmain").css('padding-top'));
            val+=colmainPaddingTop;
            colmainPaddingBottom = getNum($("td.colmain").css('padding-bottom'));
            val+=colmainPaddingBottom;
        }
        
        if($("#topContent").css('display')!='none') {
            if($("#topContent").length>0) {
                tcHeight = getNum($("#topContent").height()); 
                val+=tcHeight;
            }
            //~ #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) {
    if(!input) {
        alert("Bitte mindestens einen Suchbegriff eingeben.");
        return false;
    }
}

/*
 * modded snippet of dimensions plugin for jquery - for VisualLibraryServer
 * height property doesn't work for mozilla in the dimensons-version that is implemented in jquery-version 1.2
 * for mozilla use innerHeight instead of clientHeight - if( $.browser.opera ...) -> if( $.browser.mozilla || $.browser.opera ...)
 
 * Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 */

(function($){

// store a copy of the core height and width methods
var vlsHeight = $.fn.vlsHeight

$.fn.extend({
    vlsHeight: function() {
		if ( !this[0] ) error();
		if ( this[0] == window )
			if ( $.browser.mozilla || $.browser.opera || ($.browser.safari && getNum($.browser.version) > 520) )
				// we do not expect horizontal scrollbars in VLS # return self.innerHeight - (($(document).height() > self.innerHeight) ? getScrollbarWidth() : 0);
                return self.innerHeight;  
			else if ( $.browser.safari )
				return self.innerHeight;
			else {
                return $.boxModel && document.documentElement.clientHeight || document.body.clientHeight;
            }
		if ( this[0] == document ) {
			// we do not expect horizontal scrollbars in VLS # return Math.max( ($.boxModel && document.documentElement.scrollHeight || document.body.scrollHeight), document.body.offsetHeight );
            return Math.max( ($.boxModel && document.documentElement.offsetHeight || document.body.offsetHeight), document.body.offsetHeight );
		}
		return vlsHeight.apply(this, arguments);
	}
});

/*
var scrollbarWidth = 0;
var getScrollbarWidth = function() {
	if (!scrollbarWidth) {
		var testEl = $('<div>')
				.css({
					width: 100,
					height: 100,
					overflow: 'auto',
					position: 'absolute',
					top: -1000,
					left: -1000
				})
				.appendTo('body');
		scrollbarWidth = 100 - testEl
			.append('<div>')
			.find('div')
				.css({
					width: '100%',
					height: 200
				})
				.width();
		testEl.remove();
	}
	return scrollbarWidth;
};
*/
})(jQuery);


function bookmark() {
    if ($.browser.msie) 
        window.external.AddFavorite(location.href, document.title);
    else if (window.sidebar) 
        window.sidebar.addPanel(document.title, location.href, "");
}


jQuery.timer = function (interval, callback)
/* *	jQuery Timer plugin v0.1
 *		Matt Schmidt [http://www.mattptr.net]
 *
 *	Licensed under the BSD License:
 *		http://mattptr.net/license/license.txt*/
{
 var interval = interval || 100;

	if (!callback)
		return false;
	
	_timer = function (interval, callback) {
		this.stop = function () {
			clearInterval(self.id);
		};
		
		this.internalCallback = function () {
			callback(self);
		};
		
		this.reset = function (val) {
			if (self.id)
				clearInterval(self.id);
			
			var val = val || 100;
			this.id = setInterval(this.internalCallback, val);
		};
		
		this.interval = interval;
		this.id = setInterval(this.internalCallback, this.interval);
		
		var self = this;
	};
	
	return new _timer(interval, callback);
 };
 
function setupAdminBox(){
    //Dirk: handle the admin box stuff - the code is pretty ugly
    
    $('div.adminBox').css('margin-top',0);
    
    //center the box
    leftMove = 100
    if ($(window).width() < 1200){
        leftMove = leftMove + 100;
    }
    $('div.adminBox').css('margin-left',getNum($(window).width() / 2)-200)
    
        
    $('div.submenu').each(function(){
        submenu = $(this)
        submenubox = $('div.submenubox#'+ submenu.attr('id'))
        
        submenu.hover(
            function(){
                $(this).attr('entered','true')
                submenubox.css('margin-left',$(this).offset().left+$(this).width()-9)
                submenubox.css('margin-top',$(this).offset().top-1)
                submenubox.show()
            },
            function(){
                $(this).attr('entered','false')
                $('div.adminBox').attr('noclose','true')
                $.timer(800, 
                    function (timer){
                        if (submenubox.attr('entered') != 'true'){
                            submenubox.hide()
                            //$('div#popupcontainer').hide()
                            $('div.adminBox').attr('noclose','false')
                        }
                        timer.stop()
                    }
                )           
            }
        )
        submenubox.hover(
            function(){
                $(this).attr('entered','true')
            },
            function(){
                submenubox = $(this)
                submenubox.attr('entered','false')
                
                $.timer(800, 
                    function (timer){
                        if (submenubox.attr('entered') != 'true'){
                            if (submenu.attr('entered') != 'true')
                                submenubox.hide()
                            if ($('div.adminBox').attr('entered') != 'true')
                                $('div#popupcontainer').hide()
                        }
                        timer.stop()
                    }
                )
            }
        )
    });

    $('div.adminBox').hover(
        function () {
            $('div#popupcontainer').show()
            $('div.adminBox').attr('entered','true')
        }, 
        function () {
            $('div.adminBox').attr('entered','false')
            $.timer(900, function (timer){
                if ($('div.adminBox').attr('noclose') != 'true' && $('div.adminBox').attr('entered') != 'true'){
                    $('div#popupcontainer').hide()
                }
                $('div.adminBox').attr('noclose','false')
                timer.stop()
            })
        }
    );
   
}

var reloadDelay = 0
function dialogCloseChecker(){
    //periodically check if reloadDelay is > 0 - then reload the current page
    //Use Case: a Thickbox with IFrame content does a POST and CLOSE concurrently
    //          a imediate refresh of the self.parent frame would come _before_ the POST
    //          so we delay the reload
    $.timer(200,
        function (timer){
            if (reloadDelay > 0){
                reloadDelay = 0
                timer.stop()
                $.timer(reloadDelay,function(timer){window.location.reload(false);timer.stop()})
            }
        }
    )
}