
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(attribs){
        this.baseLayout = attribs.baseLayout; 
        this.defaultTop = attribs.defaultTop;
        this.centerParts = attribs.centerParts; 
        this.leftParts = attribs.leftParts;
        this.rightParts = attribs.rightParts;
        this.bottomParts = attribs.bottomParts; 
        this.middleParts = attribs.middleParts;
    	
		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();
        this.updateHeight();
    }
    
    Layout.prototype.onResize = function(layout, event) {
        sendClientInfo(layout.getLayoutInfo());
        layout.setAdminTableWidth();
        layout.updateHeight()
    };
    
    //~ 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 = {};

        layoutInfo.wHeight = $(window).height() - this.getYSpace();
        layoutInfo.clientWidth = $(window).width();
        layoutInfo.bodyWidth = $('body').width();
        
        leftColWidth = $(this.leftParts[this.baseLayout] ).outerWidth(true);
        if (leftColWidth) {
            layoutInfo.leftColWidth = leftColWidth;
        }
        
        rightColWidth = $(this.rightParts[this.baseLayout] ).outerWidth(true);
        if (rightColWidth) {
            layoutInfo.rightColWidth = rightColWidth;
        }
        
        layoutInfo.wWidth = $(this.centerParts[this.baseLayout] ).width();
        
        return layoutInfo;
    };
    
    Layout.prototype.goFullScreen = function() {
        
        parentOfNavPort = $("#navPort").parent().attr('id');
        $(this.bottomParts[this.baseLayout]).hide();
        $(this.defaultTop[this.baseLayout]).hide();
        $("#fsCenter").hide();
        $("#fhCenter").show();
        $("table#cont td:first").append($("#navPort"));
        this.fullscreen = true;
    };
    
    Layout.prototype.leaveFullScreen = function() {
        $(this.bottomParts[this.baseLayout]).show();
        $(this.defaultTop[this.baseLayout]).show();
        $('#'+parentOfNavPort).append($("#navPort"));
        $("#fhCenter").hide();
        $("#fsCenter").show();
        this.fullscreen = false;
    };
    
    Layout.prototype.toggleFullScreen = function(layout, event) {
        if (layout.fullscreen == true) {
            layout.leaveFullScreen();
            layout.updateHeight();
        } else {
            layout.goFullScreen();
            layout.updateHeight();
        }
        var params = layout.getLayoutInfo();
        params.fullScreen = layout.fullscreen;
        sendClientInfo(params);
    };
    
    Layout.prototype.updateHeight = function() {    
        if($('#pages').length > 0) {
            l = this.getLayoutInfo();
            var bottomPart = $(this.bottomParts[this.baseLayout]).length > 0;
            var bottomPartHidden = $(this.bottomParts[this.baseLayout]).filter(":hidden").length > 0;
            var bottomHeight = $(this.bottomParts[this.baseLayout]).outerHeight();
            var bottom = bottomPartHidden ? 0 : bottomHeight;
            var height = bottomPartHidden ? l.wHeight+bottomHeight : l.wHeight;
            $('#pages').css({
                'width': l.wWidth + 15,
                'height': height + 'px',
                'bottom': bottom + 'px',
                //~ 'left':l.leftColWidth + 'px',
                'right':'0px'
            }); 
        }
    };
    Layout.prototype.getYSpace = function() {
        var client = $("#client").attr('value');
        var val=0;
        
        if($("div#navPort").length > 0) { 
            val += $("div#navPort").outerHeight();
        }
        log(val)
        if(!this.fullscreen) {
        val += $(this.defaultTop[this.baseLayout] ).outerHeight() ;
        } 
        log(val)
        if($("#pageView").length>0) {
            val += $('#navPath .navDropdowns').outerHeight();
            //~ add pageview paddings
            val += $('#pageView').outerHeight() - $('#pageView').height();
        }
        //~ if(!this.fullscreen) {
            val += $(this.bottomParts[this.baseLayout] ).outerHeight();
        //~ } 
        log(val)
        log('---')
        return val;
    };

    //publish
    return {
		Layout:Layout
	};
}();

$(document).ready(function() {
    
    
    var layoutSymbolizer = {
    		//~ mainBase-Layout 
    		'baseLayout': $("#layout-useLayout").attr('value'), // cssLayout, tableLayout, 
    		//~ map baseLayout html/css-identifiers
    		'defaultTop': {'cssLayout':'#defaultTop', 'tableLayout':'.topContent' }, 
    		'centerParts': {'cssLayout':'#centerParts', 'tableLayout':'.colmain' }, 
    		'leftParts': {'cssLayout':'#leftParts', 'tableLayout':'.colleft' }, 
    		'rightParts': {'cssLayout':'#leftParts', 'tableLayout':'.colright' }, 
    		'bottomParts': {'cssLayout':'#bottomParts', 'tableLayout':'.footerContent' }, 
    		'middleParts': {'cssLayout':'#centerParts', 'tableLayout':'.rowMiddle td' }
    };
    layout = new VLSLayout.Layout(layoutSymbolizer);
    autoDebug();
    if($("#pageView").length>0) {
        $("#pageLoader").height(layoutInfo.wHeight);
        $("#pageLoader").width($('#pageView').outerWidth());
    }
    
    //~ 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();
});


$(window).load(function() {
    if($("#pageView").length>0) {
        $("#pageLoader").hide();
    }
});    

//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 _determineColumn(tableCell){
		var $tableCell = $(tableCell);
		var index = $("td", $tableCell.closest("tr")).index($tableCell) + 1;
		return $("tr td:nth-child("+index+")", $tableCell.closest("table"));
	}
	$('.hoverActiveColumn tr td').hover(function (){
		_determineColumn(this).addClass('hovered');
	}, function() {
		_determineColumn(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);
};

