function FontResizer(buttons, afterResizeCallback) {
	this.textContainers = new Array();
	this.currentSize = FontResizer.DEFAULT_SIZE;
	this.cookieManager = new CookieManager();
	this.afterResizeCallback = afterResizeCallback;
	
	this.init(buttons);
}

FontResizer.DEFAULT_SIZE = 0;
FontResizer.COOKIE_NAME = "currentFontSize";

FontResizer.prototype = {
		
		init				:	function(buttons) {
			var that = this;
			buttons.each(function(i, button) {
				$(button).click(function() {
					that.changeFontSize(i);
				});
			});
			
			var lastFontSize = this.cookieManager.readCookie(FontResizer.COOKIE_NAME);
			if (lastFontSize != null) {
				this.changeFontSize(parseInt(lastFontSize, 10));
			}
		},
		
		changeFontSize		:	function(size) {
			var that = this;
			var containers = this.getTextContainers();
			var diff = (size - this.currentSize) * this.DELTA;
			
			if (diff == 0) {
				return;
			}
			
			$.each(containers, function(i, container) {
				var fontSize = that.getFontSize(container) + diff;
				
				if (fontSize > diff) {
					container.css("font-size", fontSize);
				}
			});
			
			this.currentSize = size;
			this.cookieManager.createCookie(FontResizer.COOKIE_NAME, this.currentSize, 1);
			
			if (this.afterResizeCallback) {
				this.afterResizeCallback.call(this, {"diff" : diff});
			}
		},
		
		getTextContainers	:	function() {
			if (this.textContainers.length == 0) {
				var that = this;
				var containerTags = ["div", "span", "p", "em", "h1", "h2", "h3", "h4", "li", "td", "th", "label"];
				$.each(containerTags, function(i, value) {
					$(value).each(function(j, container) {
						that.textContainers.push($(container));
					});
				});
			}
			return this.textContainers;
		},
		
		getFontSize			:	function(elem) {
			
			var rawSize = elem.css("font-size");
			var fontSize = parseFloat(rawSize, 10);
			if (!isNaN(fontSize)) {
				return fontSize;
			}
			fontSize = this.FONT_MAP[rawSize];
			
			
			return fontSize == undefined ? 0 : fontSize;
		},
		
		FONT_MAP			:	{
			"xx-small"	:	9,
			"x-small"	:	10,
			"small"		:	13,
			"medium"	:	16,
			"large"		:	18,
			"x-large"	:	24,
			"xx-large"	:	32
		},
		
		DELTA				:	2

};


function CookieManager() {}

CookieManager.prototype = {
		
		createCookie	:	function(name, value, days) {
			var expires = "";
			
			if (days) {
				var date = new Date();
				date.setTime(date.getTime() + days * 24 * 60 * 60);
				expires = "; expires=" + date.toUTCString();
			}
			
			document.cookie = name + "=" + value + expires + "; path=/";
		},
		
		readCookie		:	function(name) {
			var regex = name + "=(.*?)(;|$)";
		    var results = document.cookie.match(regex);

		    if (results) {
		    	return unescape(results[1]);
		    }

		    return null;
		}
		
};
