var sites;

document.addEventListener('DOMContentLoaded', function() {
	document.removeEventListener('DOMContentLoaded', arguments.callee, false);
	init();
}, false );

function init() {	
	var siteDiv = document.getElementById('sites');
	// var siteList = siteDiv.getElementsByTagName('div')[0];

	chrome.storage.sync.get('sites', function(items) {
		sites = items['sites'];

		document.addEventListener("DOMNodeInserted", layout, false);

		if (sites.length == 0) {
			alert("Oh noez!");
		}

		for (var i = 0; i < sites.length; i++) {
			(function() {
				var site = sites[i];

				var link = createSite(site.abbreviation, site.url);

				var color = site.color;

				if (color) {
					link.style.background = 'rgba(' + color.red +', ' + color.green + ', ' + color.blue + ', ' + 1 +')';
					console.log(site.url, link.style.color);
				}
				
				link.setAttribute("href", site.url);

				siteDiv.appendChild(link);
			})();
		}
	});

	document.onkeypress = function(e) {
		var character = String.fromCharCode(e.charCode);
		var value = parseInt(character);
		if (value != NaN) {
			document.location = sites[value].url;
		}
	}

	var optionsLink = document.createElement("a");
	optionsLink.setAttribute("class", "settings btn");
	optionsLink.onclick = function() {
		chrome.tabs.create({
			url: "options/options.html"
		});
	}

	optionsLink.innerHTML = "Options";
	document.body.appendChild(optionsLink);

	window.onresize = function() {
		layout();
	};
}

function layout() {
	document.removeEventListener("DOMNodeInserted", layout);
	
	var sitesElement = document.getElementById("sites");

	var rowHeight = 224;
	var colWidth = 224;
	var cols = Math.ceil(sites.length / 3);
	var shouldWidth = cols * colWidth;
	sitesElement.style.width = shouldWidth + "px";
	var scale = window.innerWidth / (shouldWidth + 20);
	if (rowHeight * 3 * scale > window.innerHeight) {
		scale = window.innerHeight / (rowHeight * 3);
	}
	sitesElement.style.webkitTransform = "scale(" + scale + ", " + scale + ")";
	sitesElement.style.marginLeft = -shouldWidth / 2 + "px";
}

function createSite(abbreviation, url) {
	var site = document.createElement('a');

	site.innerHTML = abbreviation + '<span class="url">' + getHostname(url) + '</span>';

	return site;
}
@@ -1594,50 +1594,143 @@
 ;%0A%0A%09
-var rowHeight = 224;%0A%09var col
+const ROW_HEIGHT = 224;%0A%09const COL_WIDTH = 224;%0A%09const MAX_HEIGHT = window.innerHeight - 4;%0A%09const MAX_WIDTH = window.inner
 Width 
-= 22
+- 
 4;%0A
+%0A
 %09var
@@ -1796,16 +1796,17 @@
 s * 
-colWidth
+COL_WIDTH
 ;%0A%09s
@@ -1851,16 +1851,17 @@
 + %22px%22;%0A
+%0A
 %09var sca
@@ -1865,33 +1865,25 @@
 scale = 
-window.innerWidth
+MAX_WIDTH
  / (shou
@@ -1902,25 +1902,26 @@
 );%0A%09if (
-rowHeight
+ROW_HEIGHT
  * 3 * s
@@ -1931,71 +1931,56 @@
 e %3E 
-window.innerHeight) %7B%0A%09%09scale = window.innerHeight / (rowHeight
+MAX_HEIGHT) %7B%0A%09%09scale = MAX_HEIGHT / (ROW_HEIGHT
  * 3

Clean up layout function. Fix padding on sides of viewport.