(function($) {
	$(document).ready(function() {
		var persistFont = function (font) {
			// one week
			var duration = 7 * 24 * 3600 * 1000;
			var expires = (new Date((new Date()).getTime() + duration)).toGMTString();
			document.cookie = 'fontsize=' + escape(font) + ';expires=' + expires + ';path=/';
		};

		$.fn.extend({
			'fontsizer': function(targets) {
				var anchor = this;

				if (!targets) {
					targets = 'body';
				}

				targets = $(targets);

				$(this).each(function() {
					// first read font size from cookie
					var cookie = document.cookie;
					var result = cookie.match(/fontsize=([a-z]+)/);
					if (result) {
						targets.addClass('font-' + result[1]);
					}

					$(this).click(function() {
						// font size classes to loop through
						var fonts = ['normal', 'l', 'xl'];

						var newFont;
						for (var i = 0; i < fonts.length; i++) {
							var font = fonts[i];

							targets.each(function() {
								if ($(this).hasClass('font-' + font)) {
									$(this).removeClass('font-' + font);
									newFont = fonts[(i + 1) % fonts.length];
								}
							});
						}
						if (!newFont) {
							newFont = fonts[1];
						}
						targets.addClass('font-' + newFont);
						persistFont(newFont);
					});
				});
			}
		});
	})
})(jQuery);