var doOverlap = function (b1,b2) {
	var m = 10;
	var b1x1 = $(b1).offset().left - m;
	var b1y1 = $(b1).offset().top - m;
	var b1x2 = b1x1 + $(b1).width() + 3*m;
	var b1y2 = b1y1 + $(b1).height() + m;
	var b2x1 = $(b2).offset().left - m;
	var b2y1 = $(b2).offset().top - m;
	var b2x2 = b2x1 + $(b2).width() + 3*m;
	var b2y2 = b2y1 + $(b2).height() + m;
	var result =  ((b1x2 >= b2x1) && (b1y2 >= b2y1) && (b1x1 <= b2x2) && (b1y1 <= b2y2));
	var check = b1x1 + "," + b1y1 + "," + b1x2 + "," + b1y2 + " " + $(b1).find('h1').text() + "\n"
			  + b2x1 + "," + b2y1 + "," + b2x2 + "," + b2y2 + " " + $(b2).find('h1').text() + "\n";
	// console.log(result + "\n" + check);
	return result;
}

var anyOverlap = function (b,bs) {
	var result = false;
	$.each(bs,function() {
		if (doOverlap(b,this)) {
			result = true;
		};
	});
	return result;
}

var launch = function(){

	// remove news block if there's no news in it
	if ($(".news .item").size() < 1) {
		$(".news").hide();
	}

	var blocks = [];

	// position blocks randomly
	$(".block").each(function (i,e) {
		
		// make them draggable
		$(this).draggable();
		
		// 1. compute bounding box (origin + ranges)
		var m = 20;
		var bx = parseInt($("img.animage").css("width").substring(0,3));
		bx += m;
		console.log(bx);
		var by = m;
		var bxr = $(window).width()  - bx - $(this).width()  - 2*m;
		var byr = $(window).height() - by - $(this).height() - 2*m;
		
		var x = bx + Math.floor(Math.random()*bxr);
		var y = by + Math.floor(Math.random()*byr);
		$(this).css("left", x).css("top", y);
		
		var count = 0;
		$(this).css("display", "none");
		
		while (anyOverlap(this,blocks) && count < 100) {
			x = bx + Math.floor(Math.random()*bxr);
			y = by + Math.floor(Math.random()*byr);
			$(this).css("left", x).css("top", y);
			count = count + 1;
		}
		
		$(this).css("display", "block");
		blocks.push(this);
	});
	
	// check if they overlap

	// force links to target blank page
	$("a").each(function() {
		if ($(this).attr('class') !== 'top') {
			this.target = '_blank';
		}
	});

	// load sIFR
	if(typeof sIFR == "function"){
		sIFR.replaceElement(named({
			sSelector:"body h1", 
			sFlashSrc:"interface/sifr/sifr-davidg-medium.swf", 
			sColor:"#444444", 
			sLinkColor:"#000000", 
			sBgColor:"#FFFFFF", 
			sHoverColor:"#CCCCCC", 
			nPaddingTop:20, 
			nPaddingBottom:20, 
			sFlashVars:"textalign=left&offsetTop=0"
		}));
	};

}