function onDocReady() {
	var user = "jakub";
	var domain = "jakubdolejs";
	$("#contact").prepend('<p><a href="mailto:'+user+'@'+domain+'.com">'+user+'@'+domain+'.com</a></p>');
	$("a.email").click(function(e){pageTracker._trackPageview('/send_email');});
	if (typeof(geoip_country_code) != "undefined") {
		$("#contact ~ p").remove();
		if (geoip_country_code() == "GB") {
			$("#contact").after('<p>London <a class="tel" href="tel:+447735030342">0773 503 0342</a></p><p>Canada <a class="tel" href="tel:+14166043688">+1 416 604 3688</a></p>');
			//$("a.image").each(setImperialUnits);
		} else if (geoip_country_code() == "CA" || geoip_country_code() == "US") {
			$("#contact").after('<p>Toronto <a class="tel" href="tel:+14166043688">416 604 3688</a></p><p>UK <a class="tel" href="tel:+447735030342">+44 773 503 0342</a></p>');
			$("p.agent a.tel").each(function(index){
				$(this).text($(this).text().substr(1));
			});
		}
	}
	$("a.org").attr("target","_blank");
	$("a").click(function(e){
		e.stopPropagation();
		return true;
	});
	$("a.image").css("position","absolute");
	$(window).resize(onResize);
	onResize();
}
function setImperialUnits(index) {
	$(this).attr("title",images[index].imperial);
}
function onResize() {	
	gridWidth = $("#thumbnails").width();
	thumbsAcross = Math.floor(gridWidth/thumbWidth);
	if (thumbsAcross < 2) thumbsAcross = 2;
	totalPositions = $("a.image").length + $("a.image img.emphasized").length*3;
	rows = [];
	for (var i=0; i<totalPositions; i++) {
		var rowIndex = Math.floor(i/thumbsAcross);
		if (rowIndex >= rows.length) {
			rows[rowIndex] = [];
		}
		rows[rowIndex].push(new Position());
	}
	$("a.image").each(orderThumbs);
	$("#thumbnails").height(rows.length*thumbWidth);
}
function Position() {
	this.reserved = false;
}
function orderThumbs(index) {
	var j=0;
	var i=0;
	if (!$(this).find("> img").hasClass("emphasized")) {
		while (i<rows.length) {
			if (!rows[i][j].reserved) {
				rows[i][j].reserved = true;
				$(this).css("left",(j*thumbWidth)+"px").css("top",(i*thumbWidth)+"px");
				return;
			}
			j++;
			if (j >= rows[i].length) {
				j=0;
				i++;
			}
		}
	} else {
		while (i<rows.length) {
			if (!rows[i][j].reserved && j+1 < rows[i].length && !rows[i][j+1].reserved) {
				if (i+1 == rows.length) {
					rows[i+1] = [];
				}
				while (rows[i+1].length <= j+1) {
					rows[i+1].push(new Position());
				}
				if (!rows[i+1][j].reserved && !rows[i+1][j+1].reserved) {
					rows[i][j].reserved = true;
					rows[i][j+1].reserved = true;
					rows[i+1][j].reserved = true;
					rows[i+1][j+1].reserved = true;
					$(this).css("left",(j*thumbWidth)+"px").css("top",(i*thumbWidth)+"px");
					return;
				}
			}
			j++;
			if (j >= rows[i].length) {
				j=0;
				i++;
			}
		}		
	}
}
var gridWidth = 100;
var thumbWidth = 145;
var thumbLeft = 0;
var thumbTop = 0;
var thumbsAcross = 1;
var rows = [];
var totalPositions = 0;
$(document).ready(onDocReady);
