//Requires jquery.cookie plugin (http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/)

var FontSize = function() {
	return {
		fontSizeDelta: 0,
		classes: ['#text p'],
		SIZE_MAX: 48,
		SIZE_MIN: 10,

		init: function(fontClasses) {
			//Normalise the font configuration
			this.config = [];
			for(var i=0; i<fontClasses.length; i++) {
				if (typeof(fontClasses[i]) == 'string') {
					this.config.push({'selectors': fontClasses[i]});
				} else if (typeof(fontClasses[i]) == 'object') {
					var group = {'selectors': []};
					for (var f=0; f<fontClasses[i].length; f++) {
						group.selectors.push(fontClasses[i][f]);
					}
					this.config.push(group);
				}
			}
			
			//Fetch the default sizes for each group and selector
			for (var f=0; f<this.config.length; f++) {
				for (var s=0; s<this.config[f].selectors.length; s++) {
					var currentFontSize = this.getFontSize(this.config[f].selectors[s]);
					if (isNaN(currentFontSize) == false) {
						this.config[f].defaultSize = currentFontSize;
						break;
					}
				}
			}
			
			//Fetch the font delta
			this.fontSizeDelta = $.cookie('fontDelta');  
			this.fontSizeDelta = parseFloat(this.fontSizeDelta, 12);
			if (isNaN(this.fontSizeDelta)) {
				this.fontSizeDelta = 0;
			} else {
				//Update to the currently specified font size
				this.update();
			}
		},
		
		getFontSize: function(selector) {
			var currentFontSize = $(selector).css('font-size');  
			return parseFloat(currentFontSize, 10);
		},
		
		larger: function() {
			this.update(+1);
		},
		smaller: function() {
			this.update(-1);
		},
		
		
		update: function(delta) {
			//Set font delta to zero if not passed
			if (typeof(delta) == 'undefined') {
				delta = 0;
			}			
			
			var fontsChanged = false;
			for(var f=0; f<this.config.length; f++) {
				//Fetch the size of the reference tag
				if (this.config[f].defaultSize) {
					var newFontSize = this.config[f].defaultSize + this.fontSizeDelta + delta
					if ((newFontSize > this.SIZE_MIN) && (newFontSize < this.SIZE_MAX)) {
						fontsChanged = true;
						//Change each specified selector
						for(var s=0; s<this.config[f].selectors.length; s++) {
							$(this.config[f].selectors[s]).css({fontSize: newFontSize}).fadeIn("slow");
						}
					}
				}
			}
			
			//Fonts have changed - store new delta permanently
			if (fontsChanged)
				this.fontSizeDelta += delta;
			
		},
		
		onWindowBeforeUnload: function() {
			//Store the text size cookie
			$.cookie('fontDelta', FontSize.fontSizeDelta, {path: '/'});
		}
	};
}();

window.onbeforeunload = FontSize.onWindowBeforeUnload;
