/**
 * fancyFonts plugin v1.0 by Szabolcs Kurdi;
 * szabolcs.kurdi@gmail.com - http://www.rosamez.com/
 *
 * Released under the MIT license;
 * for the legal mumbo-jumbo get a copy of the MIT license
 * from here: http://en.wikipedia.org/wiki/MIT_License
 *
 *
 * INTRODUCTION
 *
 * This is pretty much a sIFR-like text to flash plugin;
 * it can deal with links and link hovers, window resizes
 * (word wrap), and the text can be customized via parametrizing
 * the TextFormat flash class.
 *
 * DEPENDENCIES
 *
 * -jQuery (tested with 1.3.2)
 * -swfObject (get it from Google Code)
 * -jQuery JSON plugin (labs_json Script by Giraldo Rosales)
 *
 * SETTING THE FONT
 *
 * The font can be set directly in the as3 file;
 * the as3 file can be compiled with the mxmlc compiler,
 * but a FlashDevelop project file is available, I strongly
 * recommend using that. FlashDevelop is an opensource
 * flash IDE and as3 editor.
 *
 * USAGE
 *
 * Please see the index.html file for examples; the
 * function itself tries to detect the container
 * height, font size (px/pt) and the color, but most of these
 * can be set explicitly. The window.jQuery object must be
 * available, otherwise I assume you know what you're doing.
 *
 * For the TextFormat parameters search for
 * flash.text.TextFormat (ActionScript 3.0), or try here:
 * http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/text/TextFormat.html
 *
 * 
 * $(".element").fancyFont();
 *
 * $(".element").fancyFont({
 *     text: "This overwrites the original text",
 *     swfFileName: "FancyFontText_ariblk.swf",
 *     format: {letterSpacing: 2}, //<--- this is for the TextFormat
 *     hoverFormat: {color: "orange"} //<--- basic css color names are supported
 * });
 *
 */
if (!window.jQuery) throw("jQuery global not found; " +
		"please customize this script for your needs or download jQuery.");

(function($){

	$.fancyFont = (function(){
		if (!window.swfobject) throw("SwfObject not found: please download" +
			"from http://code.google.com/p/swfobject/");
		
		if (!$.json) throw("jQuery JSON plugin not found, please look" +
			"for 'labs_json Script by Giraldo Rosales'");
			
		return {
			
			//set your flash version here via $.fancyFont.flashVersion
			flashVersion: "9.0.0",
			
			//swf file, you may override it in the insert params
			swfFileName: "FancyFontText.swf",
			
			//allow hover on links only
			hoverOnLinksOnly: true,
			
			//default flash params for swfObj
			flashParams: {                                             
				id: "",
				menu: "false",
				scale: "noScale",
				allowFullscreen: "false",                  
				allowScriptAccess: "always",
				bgcolor: "#FFFFFF",
				wmode: "transparent"
			},
			
			//the callback function for the flash movie
			setElementHeight: function(height, itemId){
				if ((!itemId) || (!$("#"+itemId).length)) return;
				$("#"+itemId + ", #"+itemId + " *").css({height: Math.round(height*1)});
			},
			
			//da magic
			insert: function(inEl, realParams) {
				if (!swfobject.hasFlashPlayerVersion(this.flashVersion)) return;
				var that = this;//fancyFont was a standalone object, now it's a jQuery plugin, hurray!
				
				//external ID for the wrapper element, internal for the
				//flash fake element (to be distroyed)
				var 
					flashParams = that.flashParams,
					extId,
					intId = "fancyFont_" + that._getUniq();
				
				//assign an id to the container if we have none;
				//this way the height sizer can find this object in the dom.
				if (!inEl.id) {
					extId = intId + "e";
					inEl.id = extId;
				} else {
					extId = inEl.id;
				}
				
				//fetch the innerhtml text and
				//save the original html (in case something goes really wrong)
				var origText = that._cleanHTML($("#" + extId)),
					origHtml = $(inEl).html(),
					origHeight = $("#"+extId).height(),
					hasLink = !!$("#" + extId).find("a").length;
				
				//create the div swfObject can overwrite;
				//probably I'd be better off ripping swfO apart, reusing things here...
				$(inEl).html("<div id='"+intId+"'></div>")
				
				//merge in params, escape and add to flashvars
				var rParams = $.extend(true, that._getDefaultParams(inEl), realParams);
				if (!rParams.text) rParams.text = origText;
				rParams.id = extId;
				if (rParams.format.color) {
					rParams.format.color = that._getFlashColor(rParams.format.color);
				}
				
				if (rParams.hoverFormat) {
					rParams.hoverFormat.color = that._getFlashColor(rParams.hoverFormat.color);
				}
				
				//remove hover effect for non links
				if ((!hasLink) && (that.hoverOnLinksOnly))
					delete(rParams.hoverFormat);
				
				var swfFileName = rParams.swfFileName;
				rParams = encodeURI($.json.encode(rParams));
				var flashvars = {pipe: rParams};
				
				//callback: restore original html if smg. broke badly
				var callBack = function(r){ if (!r.success) $("#"+extId).html(origHtml); };
				
				//100% height "sometimes" doesn't work with webkit
				//+in FF the empty container would collapse and cause 0 height
				swfobject.embedSWF(swfFileName, intId, "100%", origHeight, that.flashVersion, null,
					flashvars, flashParams, {}, callBack);
				
			},
			
			//tries to convert a color to flash compatible color string
			//basic css color names are supported, along with short cols (#fff)
			_getFlashColor: function(color){
				var toHex = function(n){
					var s = (n*1).toString(16);
					return s.length == 1 ? "0" + s : s;
				}, color, cssColors, rgb = []
				cssColors = {white:"ffffff",yellow:"ffff00",orange:"ffA500",red:"ff0000",fuchsia:"ff00ff",silver:"c0c0c0",gray:"808080",olive:"808000",purple:"800080",maroon:"800000",aqua:"00ffff",lime:"00ff00",teal:"008080",green:"008000",blue:"0000ff",navy:"000080",black:"000000"};
				if (cssColors[color]) {
					color = cssColors[color]; 
				} else if (color.indexOf("rgb") > -1) {
					color = color.replace(/[^\d,]*/g, "");
					rgb = color.split(",");
					color = toHex(rgb[0])+toHex(rgb[1])+toHex(rgb[2]);
				} else {
					color = color.replace(/#/,"");
					if (color.length == 3) {
						var temp = "";
						for (var i = 0; i < 3; i++)
							temp += color.substr(i,1) + color.substr(i,1);
						color = temp;
					}
				}
				if (isNaN(parseInt(color,16))) color = "ffffff";
				return "0x" + color;
			},
			
			//return a default parameter set; I get the
			//html color and font size here
			_getDefaultParams: function(el){
				var dP = {
						callback: "jQuery.fancyFont.setElementHeight",
						format:{}
					},
					fontSize = $(el).css("font-size");
				
				dP.swfFileName = this.swfFileName;
				dP.format.color = $(el).css("color");
				if (fontSize && ((fontSize.indexOf("px") > -1) || (fontSize.indexOf("pt") > -1))) {
					dP.format.size = fontSize.replace(/p[tx]/,"")*1;
				}
				return dP;
			},
			
			//creates a random number
			_getUniq: function(){
				return new Date()*1 + "" + Math.floor(Math.random()*1000);
			},
			
			//first I did a plain .html(), but oh boy, ie is a bitch;
			//now all this does is checking for a link and getting some attribs
			_cleanHTML: function(el){
				var 
					a = el.find("a"),
					s = $.trim(el.text()),
					target = a.attr("target"),
					href = a.attr("href");
				
				if (a.length) {
					s = '<a href="'+href+'" target="'+target+'">' + s + "</a>";
				}
				return s;
			},
			
			//external trace for debugging
			_exTrace: function(s){
				if (window.console && console.log) console.log(s);
		}
	};
	
	})();
	
	$.fn.fancyFont = function(params){
		return this.each(function(){
			$.fancyFont.insert(this, params);
		});
	};

})(jQuery);