/* :::::::::::
GRID 
::::::::::::::*/

	var MIN_KOLUMNEN = 2;
	var COL_BREITE = 212;
	var ABSTAND = 7; 
	
	var offset_x, offset_y, top_y = 0;
	max_y = new Array();
	
	// :::: DOM READY
	$(function() { 
		
	//	console.log($('ul.navmain1 li.rex-active'));
		 $(".box_link[rel!=]").click(function() {
			var r = $(this).attr("rel");
			location.href=r;
		}).css("cursor","pointer"); 
		
		if($('ul.navmain1 li.rex-current').offset()) { var akaofset = $('ul.navmain1 li.rex-current').offset().top + 2; }
		if($('ul.navmain1 li.rex-active').offset()) { var akaofset = $('ul.navmain1 li.rex-active').offset().top + 2; }
		$('#naviright').css('margin-top', akaofset);

		offset_y = $('#contentbox').offset().top;
	    offset_x = $('#contentbox').offset().left;
	    if($('.box')) { getgrid(); }
	    
	});
	
	// :::: RESIZE
	$(window).resize( function() { getgrid(); } );
	
	//
	function getgrid() {
		// Anzahl Kolumnen
		boxflaeche = $(window).width()-250;		
		var kolumnen = Math.max(MIN_KOLUMNEN, parseInt(boxflaeche / (COL_BREITE+ABSTAND)));
		if(kolumnen * (COL_BREITE+ABSTAND+20) > boxflaeche) {kolumnen--;}	
		$('.box').css('width',COL_BREITE  + 'px');
		$('.doppelbox').css('width', COL_BREITE*2 + ABSTAND +28  );
		for (x=0; x < kolumnen; x++) {	max_y[x] = 0; }
		var maxHoehe = 0;
		// lets iterate over all posts
		$('.box').each(function(i) {
			var pos, cursor, w , altura = 0;
			w = (Math.floor($(this).outerWidth() / COL_BREITE));
			cursor = 0;

			if (w>1) {
				for (x=0; x < kolumnen-(w-1); x++) {
					cursor = max_y[x] < max_y[cursor] ? x : cursor;
				}
				pos = cursor;
				
				for (var x=0; x<w; x++) {
					altura = Math.max(altura, max_y[pos+x]);
				}
				for (var x=0; x<w; x++) { 
					max_y[pos+x] = parseInt($(this).outerHeight()) + ABSTAND + altura;
					$(this).css('left', pos*(COL_BREITE+ABSTAND+28) + offset_x).css('top',altura + offset_y);
				}
				if (altura+top_y > maxHoehe) {
					maxHoehe=max_y[pos+w-1];
				}

			} // ENDE if
			else {
				for (x=0; x < kolumnen; x++) {
					cursor = max_y[x] < max_y[cursor] ? x : cursor;
				}
				$(this).css('left', cursor*(COL_BREITE+ABSTAND+28) + offset_x).css('top',max_y[cursor] + offset_y);
				max_y[cursor] += $(this).outerHeight() + ABSTAND;
				if (max_y[cursor] > maxHoehe) {maxHoehe=max_y[cursor];}
			}

		}); // Ende FUNKTION

		$('.test').css('top', maxHoehe);

	} // Ende getgrid-Funktion

