//################################
// HEADLINE REPLACEMENT
//################################
(function($) {
	$.fn.flir = function(options)
	{
		return $(this).hide().each(function(){ 
			$.flir(this,options); 
		}).show();
	};

	$.flir = function(elem, options)
	{
		//Settings
		var $e   = $(elem);
		var meta = ($.metadata) ? $(elem).metadata(): {};
		var o    = $.extend(
					{ 
						size:    parseInt($e.css("font-size"), 10), 
						color:   $.flir.rgb2hex( $e.css("color") ).substring(1), 
						casing:  $e.css("text-transform"), 
						text:    $e.text().split("'").join("&#039;") 
					},
					$.flir.defaults,
					meta,
					options
				   );
		var e = encodeURIComponent;
		
		$e.html(""); //clear out the current contents
		$e.hide();
		$.each( o.wrap ? o.text.split(" ") : [o.text], function() {
			if( $.trim(this) != "" ) {
				var url = o.php;
				url += "generate/";
				url += e(o.text) + "/";
				url += e(o.font) + "/";
				url += e(o.size) + "/";
				url += e(o.color) + "/";
				url += e(o.casing) + "/";
				url += e(o.width) + "/";
				url += e(o.height) + "/";
				url += e(o.kerning) + "/";
				url += e(o.lineSpacing) + "/";
				url += e(o.cache);

				//have to manually tweak the vertical-align so that it works properly when inlined
				var $img = $("<img alt='" + this.replace("'", "&rsquo;") + "' src='" + url + "'>");
				$e.append( $img );
				// rescale parent element if it's not big enough
				$img.bind( 'load', {holder: $e}, function(event)
					{
						event.data.holder.height($(this).height());
						//event.data.holder.height("auto");
					} 
				);
				$e.append( " " );            
			}
		});
		
		return $e;
	};
	
	$.flir.rgb2hex = function(color) 
	{
		var rgb = color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        if( rgb )
        {
            function hex( x )
            {  
                var hexDigits = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];  
                return ( isNaN( x ) ) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];  
            }
            
            return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
        }

        return color;	
	};
	
	$.flir.defaults = {
		php: "/pir.php",
		font: "denmark.ttf",
		wrap: false,
		prettyPrint: false
	};
	
	//Version
	$.flir.version = "0.1";

	//Auto-run
	//$(function(){ $(".flir").flir(); });

})(jQuery);

