// JavaScript Document
(function($){
		  
 	$.fn.fontReplace = function(options) {
		
		var defaults = {
				
			path		: 'jquery/',			//Path to the fontReplace php script. Do not include the file name
			textIndent	: -1000,					//Amount to indent the original text
			fontFile	: 'HUM777L',			//The font to use. Place inside the /fonts subdirectory. Must be .ttf file
			fontSize	: 24,						//The size of the font
			fontColor	: '#000000',				//The color that the font should be. Can only use hex values at present. NB: NO # in argument
			background	: '#ffffff',				//The color of the background in the generated image NG: NO # in argument
			width		: 0,						//If this value is set, fixed width is used
			height		: 0							//If this value is set, fixed height is used
		}
		
		var options = $.extend(defaults, options);


    	return this.each(function() {
		
			obj = $(this);	//Handle to the current object
			
			imageText = obj.text();	//Get the text inside the matched element
			
			//We need to do some calculations in order to set the height and width of the element
			//The element needs to have a fixed height and width for the image to fit in nicely
			
			//First the width calculations
			if(options.width == 0) {
				textLength = imageText.length;
				width = Math.round((options.fontSize / 1.7)*(textLength)); 
			}
			else
			{
				width = options.width;
			}
			
			
			//Then the height calculations
			if(options.height == 0)
			{
				height = options.fontSize * 1.5;
			}
			else
			{
				height = options.height;	
			}
			
			
			
			
			//Time to generate the url string for the image
			//First we need to clean the options array a little
			path 		= jQuery.trim(options.path);
			fontFile	= jQuery.trim(options.fontFile);
			fontColor	= jQuery.trim(options.fontColor).replace("#", "");
			background	= jQuery.trim(options.background).replace("#", "");
			
			
			//Now we can generate the url
			url = path + 
				 'fontReplace.php?font=' + encodeURIComponent(fontFile) +
				 '&text=' + encodeURIComponent(imageText) +
				 '&fontcolor=' + fontColor + 
				 '&backgroundcolor=' + background + 
				 '&size=' + options.fontSize;
			
			
			//Set some css values on the matched element
			obj.addClass("font-replaced");
			obj.css({
					
						'width' 				: width + 'px',
						'height' 				: height + 'px'
						//'background-image' 		: 'url(' + url + ')',
						//'text-indent' 			: options.textIndent
						
					});
			
			//Generate the image string
			image = '<img src="' + url + '" />';
			
			obj.html(image);
				
   		});
		
 	};
 
})(jQuery);
