// Made by MobGen
var rollon = null;
var startcarousel = null;

var blockWidth = 245;
var blockHeight = 245;
var columnsPerRow = parseInt(parseInt($(window).width())/blockWidth); //width of page, needs to become variable

if (columnsPerRow < 3) { columnsPerRow = 3; }
var firstTime = true;
var grid = {0: []};
var clickedBlock = 0;
var scrollToRow = false;
var scrolltoblock;
var prevpos = -10;
			 
$(document).ready(function() {
	$(window).resize(function() {
		$(".slider").stop();
		var newColumnsPerRow = parseInt(parseInt($(window).width())/blockWidth);
		if (newColumnsPerRow < 3) { newColumnsPerRow = 3; }
		if(newColumnsPerRow != columnsPerRow){
			columnsPerRow = newColumnsPerRow; //width of page, needs to become variable			
			initGrid();
			redrawBoard();
		}		
	});
	$(".toggleblock").live("click",function(e){		
		$(".slider").stop();
		// toggles the block. opens a closed block, and closes an opened one!
		blockId = $(this).closest(".block").attr("id").substr(6);
		
		// we are opening a block. let's remember which one, so we can scroll to it
		clickedBlock = blockId;		
		
		blocks[blockId]['status'] = ((blocks[blockId]['status'] == 'closed') ? 'open' : 'closed');
		redrawBoard();
		updateBoodschappen();		
	});
	updateBoodschappen();
});
//big image viewer on home page
function findCarousels() {	
	if (rollon != null) clearTimeout(rollon);
	var i = 1;
	$(".carousel").each(function(i) {
		$(this).attr("id","111"+i);
		cid = $(this).attr("id");
		var iw  = parseInt($("#" + cid + " .slideritem").width());
		var sliderwidth = ($("#" + cid + " .slider .slideritem").length)*iw;
		if (sliderwidth > iw) {
			$("#" + cid + "").mouseenter(function() { clearTimeout(rollon);$("#" + cid + " .next").fadeTo("fast",1);$("#" + cid + " .previous").fadeTo("fast",1); });
			$("#" + cid + "").mouseleave(function() { rollon = setTimeout("rollCarousel('"+cid+"')",1333);$("#" + cid + " .next").fadeTo("fast",0.1);$("#" + cid + " .previous").fadeTo("fast",0.1); });
			$("#" + cid + " .next").fadeTo("fast",0.1).click(function() {
				if ($("#" + cid + " .slider:animated").length == 0) {
					var lpos = parseInt($("#" + cid + " .slider").css("left"));
					if (lpos <= 0 && lpos > (-sliderwidth+iw)) { $("#" + cid + " .slider").animate({"left": "-="+iw+"px"}, "slow",function() { $(this).stop(); }); } 
					else { $("#" + cid + " .slider").animate({"left": "+="+(sliderwidth-iw)+"px"}, "slow",function() { $(this).stop(); }); }
				}
			});	
			$("#" + cid + " .previous").fadeTo("fast",0.1).click(function() {
				if ($("#" + cid + " .slider:animated").length == 0) {
					var lpos = parseInt($("#" + cid + " .slider").css("left"));
					if (lpos < 0 && lpos >= (-sliderwidth)) { $("#" + cid + " .slider").animate({"left": "+="+iw+"px"}, "slow",function() { $(this).stop(); }); } 
					else { $("#" + cid + " .slider").animate({"left": "+="+(-sliderwidth+iw)+"px"}, "slow",function() { $(this).stop(); }); }
				}
			});			
			var timelag = i * 1555;
			rollon = setTimeout("rollCarousel('"+cid+"')",timelag);			
		}
		i++;
	});
}
function rollCarousel(tid) {
	clearTimeout(rollon);
	var nid = tid;
	var iw  = parseInt($("#" + nid + " .slideritem").width());
	var sliderwidth = ($("#" + nid + " .slider .slideritem").length)*iw;
	var lpos = parseInt($("#" + nid + " .slider").css("left"));	
	if (lpos <= 0 && lpos > (-sliderwidth+iw)) { $("#" + nid + " .slider").animate({"left": "-="+iw+"px"}, "slow");rollon = setTimeout("rollCarousel('"+nid+"')",6000); } 
	else { $("#" + nid + " .slider").animate({"left": "+="+(sliderwidth-iw)+"px"}, "slow");rollon = setTimeout("rollCarousel('"+nid+"')",7000); }
}
function initSite() {
	//first time
	initGrid();
	checkBlocks();
}
var header = null;
function changeHeader(){
	if(header != null) {
		$("#header").html(header);
	}
}
function initGrid(){
	grid = {0: []};
	for(var i=0; i<columnsPerRow; i++){
		// initialize the grid
		grid[0][i] = 0;
	}
}
function checkBlocks() {
	blockLoop:
	for (var blockId in blocks) {
		if(blocks[blockId]['status'] == 'open'){
			blocks[blockId]['width'] = blocks[blockId]['width_open'];
			blocks[blockId]['height'] = blocks[blockId]['height_open'];
			blocks[blockId]['content'] = blocks[blockId]['content_open'];
		} else{
			blocks[blockId]['width'] = blocks[blockId]['width_closed'];
			blocks[blockId]['height'] = blocks[blockId]['height_closed'];
			blocks[blockId]['content'] = blocks[blockId]['content_closed'];
		}
		// For every block we want to place
		if(blocks[blockId]["placed"]){
			// this block already has a position
			continue blockLoop;
		}
		
		rowLoop:
		for (var row in grid){
			columnLoop:
			for (var column in grid[row]){
				// Find the first empty spot in our grid
				var filled = grid[row][column]; // 0 = empty, above 0 = blockId
				if(filled == 0){
					var blockFits = true;
					nextColumnLoop:
					for (var j=0;j<=blocks[blockId]['width']-1;j++) {
						// If our block is wider than 1, check if the spot(s) on the right is empty
						var nextColumn = parseInt(column)+parseInt(j);
						if(grid[row][nextColumn] != 0){
							// spot on the right is not empty. moving on
							blockFits = false;
							continue;
						}
						nextRowLoop:
						for (var k=0;k<=blocks[blockId]['height']-1;k++) {
							// If our block is higher than 1, check if the spot(s) below are empty
							var nextRow = parseInt(row)+parseInt(k);
							if(grid[nextRow] == undefined){
								// We reached the bottom of the page, and we're out of rows. create one!
								grid[nextRow] = [];
								for(var i=0; i<columnsPerRow; i++){
									grid[nextRow][i] = 0;
								}
								// grid has changed, so we need to start again
								checkBlocks();
								return false;
							}
							if(grid[nextRow][nextColumn] != 0){
								// spot below is not empty. moving on
								blockFits = false;
								continue;
							}
						}
					}


					if(blockFits){
						// If the block fits, put it in the grid
						for (var j=0;j<=blocks[blockId]['width']-1;j++) {
							var nextColumn2 = parseInt(column)+parseInt(j);
							grid[row][nextColumn2] = blockId;
							
							for (var k=0;k<=blocks[blockId]['height']-1;k++) {
								var nextRow2 = parseInt(row)+parseInt(k);
								grid[nextRow2][nextColumn2] = blockId;
							}
						}
						blocks[blockId]["placed"] = 1;
						continue blockLoop;
					}
				}
			}
		}
		// Still no place to put my block? better create a new row
		nextRow = parseInt(row)+1;
		grid[nextRow] = [];
		for(var i=0; i<columnsPerRow; i++){
			grid[nextRow][i] = 0;
		}
		// grid has changed, so we need to start again
		checkBlocks();
		return false;
	}
	reDraw();
}

function reDraw(){
	var html = "";
	var html2 = "";
	for (var row1 in grid){
		for (var column1 in grid[row1]){
			blockId = grid[row1][column1];
			html += "["+grid[row1][column1]+"]";
			if(blockId == 0){
				// empty space!
				continue;
			}
			if( ! blocks[blockId]['drawn']){
				// we draw every block only once
				var className = " bw"+blocks[blockId]['width']+" bh"+((blocks[blockId]['height'] > 3) ? "a" : blocks[blockId]['height']);
				/*if(blocks[blockId]['width'] > 1){
					className += " bw"+blocks[blockId]['width'];
				}
				if(blocks[blockId]['height'] > 1){
					className += " bh"+((blocks[blockId]['height'] > 3) ? "a" : blocks[blockId]['height']);
				}*/
				var contentclass = 'sc';
				if(blocks[blockId]['status'] == 'open'){ contentclass ='lc'; }
				html2 += '<div class="block'+className+'" style="left:'+column1*blockWidth+'px;top:'+row1*blockHeight+'px;" id="block_'+blockId+'">'+
						'<div class="t clr"><div class="tl"></div><div class="tr"></div></div>'+
						'<div class="'+contentclass+' r"><div class="l">'+
						blocks[blockId]['content']+
						'</div></div><div class="f clr"><div class="fl"></div><div class="fr"></div></div></div>';
				blocks[blockId]['drawn'] = true;
				if(clickedBlock > 0 && clickedBlock == blockId){
					scrollToRow = (row1*blockHeight)+140;
					clickedBlock = 0;
				}
			}
		}
		html += "<br/>";
	}
	$("#content").html(html2);
	// did we just open a block that we want to scroll to?
	if(scrollToRow > 0){
		//console.log(scrollToRow);
		scrolltoblock = setInterval("scrollDown();",1);
	}
	
	firstTime = false;
	// initialize carousel(s)
	rollon = null;
	if (startcarousel != null) clearTimeout(startcarousel);
	startcarousel = setTimeout("findCarousels();",5000);
	// debug list, shows how grid has been built up
	//$("#content").append("<br/><br/>"+html);
}
function scrollDown() {
	var curpos = $(window).scrollTop();
	if (curpos == prevpos) { clearInterval(scrolltoblock);scrollToRow = false;prevpos=-10;return; }
	prevpos = curpos;
	curpos = curpos+10;
	if (curpos <= scrollToRow) { window.scrollTo(0,curpos); }
	else { clearInterval(scrolltoblock);scrollToRow = false;prevpos=-10; }	
}
function redrawBoard(){
	// reset the blocks
	for (var blockId in blocks) {
		blocks[blockId]["drawn"] = false;
		blocks[blockId]["placed"] = false;
	}
	// reset the grid
	for (var row in grid){
		for (var column in grid[row]){
			grid[row][column] = 0;
		}
	}
	// reset the html
	$("#content").html('');
	// do the magic
	checkBlocks();	
}

$(document).ready(function() {
	// make the headline fit inside the top of the page
	headline();	
	// adjust menu for ipad
	smallRes();
	$(window).resize(function() {
		headline();
		smallRes();
	});	
});
function headline() {
	$("h1").each(function(i) {				
		var i = 0;
		var changed = true;		
		while(changed && i <= 71) {
			i++;
			var obj = $(this);
			var tw = parseInt(parseInt($(obj).width())*1.2);			
			var pw = parseInt($(window).width());
			var fs = parseInt(obj.css("fontSize"));	
			//alert(tw+","+pw+","+fs);
			if (tw > pw && fs >= 12) {	obj.css("fontSize",(fs-1)+"px");}
			else if (tw <= pw && fs < 72) {	obj.css("fontSize",(fs+1)+"px");}
			else { changed = false; }
		}
	});
}
function smallRes() {
	if (columnsPerRow <= 3) { $("#nav li a").addClass("smallres"); }
	else { $("#nav li a").removeClass("smallres"); }
}
// vote buttons

// clear input value when clicked first time
function clearDefault(obj) {
	if ($(obj).attr("rel") != 1) { $(obj).attr("rel","1").attr("value",""); }
}
// set active menu
function setMenu() {	
	$("#nav ul li a").removeClass("act");
	var mo = window.location.hash.replace(/_/g,'').replace(/ /g,'');
	var ai = $(mo).attr("class");	
	var aai = $("#"+ai).attr("class");
	if (ai) { $("#"+ai).addClass("act"); }
	if (aai) { $("#"+aai).addClass("act"); }
	$(mo).addClass("act");
	$("#nav").focus();	
}
