(function($)
{
	$.fn.textReplace = function(options)
	{
		options = $.extend({ }, $.fn.textReplace.defaults, options);
		return this.each(function()
		{
			var $this = $(this);
			$this.html('<div class="text-replace-container">' + $this.text() + '</div>');
			var container = $this.find('.text-replace-container');
			
			// Analyse text styles.
			var parameters =
			{
				text: container.text(),
				width: container.width(),
				height: container.height(),
				size: getPixelCount($this.css('font-size')),
				colour: $this.css('color'),
				transform: getTransform($this.css('text-transform'))
			};
			
			// Construct target URI.
			parameters = $.extend({ }, parameters, options.scriptParameters);
			var imageUri = options.scriptUrl + '?';
			for (var key in parameters)
			{
				imageUri += key + '=' + encodeURIComponent(parameters[key]) + '&';
			}
			
			container.css(
			{
				textIndent: '-10000em',
				backgroundImage: 'url(\'' + imageUri + '\')',
				backgroundRepeat: 'no-repeat'
			});
			
			// Perform an AJAX request to the script to retrieve the height of the image.
			$.get(imageUri + 'sample', function(data)
			{
				var height = parseInt(data, 10);
				var extension = height - container.height();
				if (extension > 0)
				{
					// Extend the container downards to allow the full image to be visible.
					container.css(
					{
						marginBottom: -extension,
						paddingBottom: extension 
					});
				}
			});
		});
	};
	
	$.fn.textReplace.defaults =
	{
		scriptUrl: 'textreplace.php',
		scriptParameters: { }
	};
	
	function getPixelCount(string)
	{
		return parseInt(string.match(/(\d+(\.\d+)?)px/i)[1]);
	}
	
	function getColour(rgb)
	{
		var matches = rgb.match(/rgb\((\d{0,3}), *(\d{0,3}), *(\d{0,3})\)/i);
		
		// Generate hex string.
		alert(rgb);
		var decimal = (parseInt(matches[1], 10) << 16) +
		              (parseInt(matches[2], 10) << 8) +
		              (parseInt(matches[3], 10));
		var hex = decimal.toString(16);
		
		// Pad it out with zeros.
		var startLength = hex.length;
		for (var i = 0; i < 6 - startLength; i++)
		{
			hex = '0' + hex;
		}
		
		return hex;
	}
	
	function getTransform(transform)
	{
		switch (transform)
		{
			case 'uppercase':
			case 'lowercase':
			case 'capitalize':
				return transform;
			default:
				return 'none';
		}
	}
})(jQuery);