﻿// plugin definition
$.fn.sifrl = function(options) {
	var defaults = {
		txtLeading: 0,
		txtAlign: 'left',
		offsetX: 0,
		offsetY: 0
	};	
	var opts = $.extend(defaults, options);
	
	return this.each(function(elCount) {	
		var $this = $(this);
		$this.width($this.width()); //prevent shrinking of element while swf is loaded into
		$this.height($this.height()); //prevent shrinking of element while swf is loaded into

		//vars
		var txt = $this.html();
		txt = txt.replace(/&/g, "%26");	
		var color = $this.css('color');				
		color = rgb2hex(getRGB(color)); //browsers retrun color in different formats

		var flashvars = {
		  txt: txt,		  
		  txtColor: color,
		  txtLeading: opts.txtLeading,
		  txtAlign: opts.txtAlign,
		  offsetX: opts.offsetX,
		  offsetY: opts.offsetY
		};
							
		if(opts.txtSize) flashvars.txtSize = opts.txtSize;
		//create replaceable node
		var uniqueId = $.data($this);
		$this.html('').append('<span id="sifrl_'+uniqueId+'"></span>');		
		var h = $this.height();		
		swfobject.embedSWF(opts.swf, 'sifrl_'+uniqueId, ""+$this.width(), ""+h, "9.0.0", null, flashvars);		
	});
	
	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
		
	//Function to get hex format a rgb colour
	function rgb2hex(rgb) {
			//generates the hex-digits for a colour.
			function hex(x) {
					hexDigits = new Array("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[0]) + hex(rgb[1]) + hex(rgb[2]);
	} 	
};

	
