
var debug=false;
var layout = null;

var hoveredEls = []
Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}

if (typeof Function.prototype.bind == 'undefined') {
  Function.prototype.bind = function() {
    var __method = this, args = Array.prototype.slice.call(arguments), object = args.shift();
    return function() {
      var local_args = args.concat(Array.prototype.slice.call(arguments));
      if (this !== window) local_args.push(this);
      return __method.apply(object, local_args);
    }
  }
}

function log(str) {    
    //firebug running
    if('object' == typeof console) {
        console.log(str)
    }
}    

function autoDebug() {
    if($("#guest").attr('value') =='False' )
        debug=true;
}
    

/******************************************/

//vls layout namespace
var VLSLayout = function(){ 
    
    function Layout(){
		this.wWidth = $(".session#windowwidth").attr('value');
        this.clientWidth = $(".session#clientwidth").attr('value');
        this.wHeight = $(".session#windowheight").attr('value');
        this.leftColWidth = $(".session#leftcolwidth").attr('value');
        this.rightColWidth = $(".session#rightcolwidth").attr('value');
        this.bodyWidth = $(".session#bodywidth").attr('value');
        
        this.fullScreen = $(".session#fullScreen").attr('value') == 'true';
        this.parentOfNavPort = null;
        
        if( $("#fullScr").length > 0 && this.fullScreen) {
            this.goFullScreen();
        }
        
        $("#fullScr").click(this.toggleFullScreen.bind(this, this));
        
        layoutInfo = this.getLayoutInfo()
        if( (this.clientWidth != layoutInfo.clientWidth) || (this.wHeight != layoutInfo.wHeight) ) {
            sendClientInfo(layoutInfo)
        }
        
        $(window).resize(this.onResize.bind(this, this));

        this.setAdminTableWidth();

    }
    
    Layout.prototype.onResize = function(layout, event) {
        sendClientInfo(layout.getLayoutInfo());
        layout.setAdminTableWidth();
    }
    
    //~ set admin tables width in pixels for IE
    Layout.prototype.setAdminTableWidth = function() {
        if ($.browser.msie)  {
            layoutInfo = this.getLayoutInfo();
            
            $('.vlsTable').each(function() {
                //~ expecting something like "vlsTable 30"
                classNames = $(this).attr('class').split(' ');
                //~ the first className denotes the width in percentage
                if(classNames.length > 1) {
                    percent = classNames[1];
                } else {
                    percent = 100;
                }
                factor = 100 / percent;
                tableWidth = layoutInfo.bodyWidth / factor - 40;
                $(this).css('width', tableWidth);
            });
        }
    }

    
    Layout.prototype.getLayoutInfo = function() {
        var layoutInfo = {};
        // update actual ClientWindow-Dimensions 

        layoutInfo.wHeight = $(window).height() - this.getYSpace()
        layoutInfo.clientWidth = $(window).width();
        layoutInfo.bodyWidth = $('body').width();
        
        leftColWidth = $('td.colleft').outerWidth(true);
        if (leftColWidth) {
            layoutInfo.leftColWidth = leftColWidth;
        }
        
        rightColWidth = $('td.colright').outerWidth(true);
        if (rightColWidth) {
            layoutInfo.rightColWidth = rightColWidth;
        }
        
        layoutInfo.wWidth = $('td.colmain').width();
        
        return layoutInfo
    }
    
    Layout.prototype.goFullScreen = function() {
        parentOfNavPort = $("#navPort").parent().attr('id');
        $("tr#rowBottom").hide();
        $("#topContent").hide();
        $("#fsCenter").hide();
        $("#fhCenter").show();
        $("tr#navParts").length>0 ? 0: $("table#cont td:first").append($("#navPort"));
        //~ $("#navPath").hide();    $("#navPath + br").hide();    $("#pageView").attr('id','fpView');
        this.fullscreen = true;
    }
    
    Layout.prototype.leaveFullScreen = function() {
        $("tr#rowBottom").show();
        $("#topContent").show();
        $("tr#navParts").length>0 ? 0 : $('#'+parentOfNavPort).append($("#navPort"));
        $("#fhCenter").hide();
        $("#fsCenter").show();
        //~ $("#navPath").show();    $("#navPath + br").show();    $("#fpView").attr('id','pageView');
        this.fullscreen = false;
    }
    
    Layout.prototype.toggleFullScreen = function(layout, event) {
        if (layout.fullscreen == true) 
            layout.leaveFullScreen();
        else 
            layout.goFullScreen();
        var params = layout.getLayoutInfo()
        params.fullScreen = layout.fullscreen
        sendClientInfo(params);
    }
    
    Layout.prototype.getYSpace = function() {
        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;
    }
	
    //publish
    return {
		Layout:Layout
	}
}();

$(document).ready(function() {
    layout = new VLSLayout.Layout();
    
    autoDebug();
    
    //~ discard loader when image is loaded // this causes heavy cpu load in firefox, it seems to be 'virtually' tiling an animated .gif ...
    $('#singlePageImage').load(function() {
        $(this).css('background','transparent none');
    });
      
    //~ admin tables zebra style
    $(".vlsTable tr:visible:odd, .vlsTable50 tr:visible:odd)").addClass("odd");
    
    // change domain on change of select 
    $("select#selectDomain").change(function() {
        location.href = $("#selectDomain option:selected").val();
    });
    // 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() {
        var a = $(this);
        a.next('ul').toggle();
        if($('.showHits').length > 0) { $(' .showHits', this).toggle();}
        if($('.hideHits').length > 0) { $(' .hideHits', this).toggle();}
        
        a.closest('li').toggleClass('toggled');
        
        // send toggleInfo to server
        var pID = $("var#query").attr('value');
        if(a.next('ul').css('display')=='none') {
            $.get('/client/setToggleState?tree&id=id'+pID+'&idx='+a.attr('id')+'&uncheck')
        } else {
            try {loadFulltexts(a);} catch(e) {/*catch error if fulltext.js not loaded  */}
            $.get('/client/setToggleState?tree&id=id'+pID+'&idx='+a.attr('id')+'&check')
        }
    });
    //~ autotoggle single results
    if( $("a.toggle").length == 1 ) {
        if($("a.toggle").closest('li').hasClass('toggled')== false ) {
            $("a.toggle").click();
        }
    }
    //~ fetch previously toggled elements from server
    if( $("a.toggle").length == 1 && $('.metadataTable').length == 1) {
        var pID = $("var#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++ ) {
                        a = $('a.toggle#'+items[x]);
                        // load texts
                        try {loadFulltexts(a);} catch(e) {/*catch error if fulltext.js not loaded  */}
                        //set/remove class for treefolder icon and toggle the indentation list below
                        a.next('ul').toggle();
                        if(a.children('.showHits').length > 0) { a.children('.showHits').toggle();}
                        if(a.children('.hideHits').length > 0) { a.children('.hideHits').toggle(); }
                        a.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();
        // 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');
    
    setupHoverTables();
});

//send Window-Dimensions via /clientInformation?
function sendClientInfo(args) {
    $('#footerLayoutInfo').css('color', 'red');
    $('#footerLayoutInfo').attr('title', args['wWidth'] + 'x' + args['wHeight'] + ' ' + 
        args['leftColWidth'] + '-' +args['rightColWidth'] + ' ' + args['clientWidth'] + '/' + args['bodyWidth']);
    $('img#cInfo').attr('src','/clientInformation?' + joinQueryString(args));
    //alert($('img#cInfo').attr('src')+args)
}

function countObj(obj) {
         var i=0; for (var k in obj) {i+=1}
         return i;
}


//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, "");
}


function setupHoverTables(){
	$('.hoverActiveRow  tr').hover(function (){
		$(this).addClass('hovered')
	}, function() {
		$(this).removeClass('hovered')
	})
}

function parseQueryString(qs)
{
    return function(a)
        {
            if (a == "") return {};
            var b = {};
            for (var i = 0; i < a.length; ++i)
            {
                var p=a[i].split('=');
                b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
            }
            return b;
       }(qs.split('&'))
}

function joinQueryString(args) {
    var res = '';
    var i = 0;
    for (var j in args) {
        if (i > 0){
            res += '&' + j + '=' + args[j];
        } else {
            res += j + '=' + args[j];
        }
        i += 1
    }
    return res;
}


//a .load function that handles cached images better
//https://gist.github.com/797120/7176db676f1e0e20d7c23933f9fc655c2f120c58
$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length;
      
  elems.bind('load',function(){
      if (--len <= 0){ callback.call(elems,this); }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
        this.src = src;
     }  
  }); 

  return this;
};

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);
};
