/**
 * Flash Tag Object v2.5a + jQuery FlashTag plugin - by Lucas Fererira
 * @author Lucas Ferreira - http://lucasferreira.com/
 * @date June 17, 2010
 * @copyright (c) 2010 Lucas Ferreira (lucasferreira.com)
 * @example Visit http://www.lucasferreira.com/flashtag/ for more informations about this
 */

var FlashTag = function()
{
	
	var FP_VERSION = null;
	
	return {
		
		YOUTUBE_URL_PLAYER: "http://www.youtube.com/v/%s",
		
		init: function()
		{
			FP_VERSION = this.getPlayerVersion();
			
			for(var i=0, s=document.getElementsByTagName("SCRIPT"); i<s.length; i++)
			{
				if(s[i].getAttribute("src") && s[i].getAttribute("src").indexOf("?correct-all") > -1) FlashTag.automatic();
			}
			
			//FlashTag embed functions...
			return (
				function(movie, id, width, height, initParams)
				{
					//variables...
					this.onNotDetect = function(){};
					this.variables = new Array();
					this.flashversion = (initParams && initParams.flashversion != undefined) ? initParams.flashversion : "6,0,21";
					this.protocol = (window.location.protocol.indexOf("https") < 0) ? "http" : "https";
					this.attributes = {
						"classid": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
						"codebase": this.protocol + "://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab",
						"type": "application/x-shockwave-flash",
						"rel": "flashtag"
					};
					this.params = { "pluginurl": this.protocol + "://www.macromedia.com/go/getflashplayer" };
					
					//methods...				
					this.addAttribute = function(prop, val){ this.attributes[prop] = val; };
					this.addParameter = function(prop, val){ this.params[prop] = val; };
					this.addVariable = function(prop, val){ this.variables.push([prop, val]); };
					this.redirectToUrl = function(url){ window.location.href = url; };					
					
					this.getFlashVars = function()
					{
						for(var i=0, tempString = new Array(); i<this.variables.length; i++) tempString.push(this.variables[i].join("="));
						return tempString.join("&");
					};
					
					this.getObject = function()
					{
						return FlashTag.getObject(this);
					};					
					
					this.getSWF = function()
					{
						this.params.flashVars = this.getFlashVars();
						
						if(FlashTag.isIE()) //IE
						{
							var htmlAttr = "", attr = FlashTag.getObjectByExceptions(this.attributes, ["type", "data", "variables"]);
							for(var i in attr) if(i.toString() != "extend") htmlAttr += " " + i.toString() + " = \"" + attr[i] + "\"";

							var htmlParams = "", params = FlashTag.getObjectByExceptions(this.params, ["pluginurl", "extend", "version", "variables"]);
							for(var i in params) if(i.toString() != "extend") htmlParams += "<param name=\"" + i.toString() + "\" value=\"" + params[i] + "\" /> ";
							
							return "<object " + htmlAttr + ">" + htmlParams + "</object>";
						}
						else //non-IE
						{
							var elObject = document.createElement("OBJECT");
							
							var attr = FlashTag.getObjectByExceptions(this.attributes, ["classid", "codebase", "variables"]);
							for(var i in attr) if(i.toString() != "extend") elObject.setAttribute(i.toString(), attr[i]);
							
							var params = FlashTag.getObjectByExceptions(this.params, ["extend", "version", "variables"]);
							for(var i in params)
							{
								var elParam = document.createElement("PARAM");
								elParam.setAttribute("name", i.toString());
								elParam.setAttribute("value", params[i]);
								elObject.appendChild(elParam);
							}
							
							return elObject;
						}
					};
					
					this.writeIn = function(o)
					{
						if(typeof o == "undefined")
						{
							o = document.createElement("SPAN");
							o.className = "flash-tag-object";
						}
						else if(typeof o == "string")
						{
							o = document.getElementById(o) || null;
						}
						
						if(o == undefined || o == null) return false;
						
						var f = FlashTag.getPlayerVersion();
						if(!f || (typeof this.params["version"] != "undefined" && !FlashTag.isMajor(f, this.params["version"])))
						{
							this.onNotDetect(f);
							
							if(typeof this.params["redirectUrl"] != "undefined")
							{
								this.redirectToUrl(this.params["redirectUrl"]);
							}
						}
						else
						{
							if(FlashTag.isIE())
							{
								o.innerHTML = this.getSWF();
							}
							else
							{
								o.innerHTML = "";
								o.appendChild(this.getSWF());
								try { o.outerHTML = o.outerHTML; } catch(ex) {};
							}
							
							if(o.className.toLowerCase() == "flash-tag-object") document.write( o.innerHTML );
						}
						
						return true;
					};
					
					this.write = this.writeIn;
					
					this.YouTube = function(youtube_url, id, width, height, initParams)
					{
						if(!youtube_url) return false;

						var movie = youtube_url.match(/\?([v=]?[^\&?]+)/);
						if(movie.length > 1)
						{
							movie = movie[1].replace(/v=/gi, "");
							movie = FlashTag.YOUTUBE_URL_PLAYER.split("%s").join(movie);

							return (new Flash(movie, id, width, height, initParams));
						}

						return false;
					};
					
					//initial methods...
					if(movie)
					{
						this.addAttribute("data", movie);
						this.addParameter("movie", movie);
					}

					if(id && id != null && (this.id = id)) 
					{
						this.addAttribute("id", this.id);
						this.addAttribute("name", this.id);
					}
					else
					{
						this.id = null;
					}

					if(width) this.addAttribute("width", width);
					if(height) this.addAttribute("height", height);

					if(initParams != undefined)
					{
						if(typeof initParams["variables"] != "undefined")
						{
							initParams["flashVars"] = initParams["variables"];
							initParams["variables"] = {};
						}
						for(var i in initParams)
						{
							if(i.toLowerCase() != "flashvars")
							{
								this.addParameter(i.toString(), initParams[i]);
							}
							else
							{
								for(var j in initParams[i]) this.addVariable(j.toString(), initParams[i][j]);
							}
						}
					}					
				}
			);
		},
		
		isIE: function()
		{
			return (window.ActiveXObject && document.all && navigator.userAgent.toLowerCase().indexOf("msie") > -1  && navigator.userAgent.toLowerCase().indexOf("opera") == -1) ? true : false;
		},
		
		getObjectByExceptions: function(obj, excep)
		{
			var tempObj = {};
			for(var i in obj)
			{
				for(var j=0, EOF=false; j<excep.length; j++)
					if(excep[j] == i.toString()) { EOF = true; break; };
					
				if(!EOF) tempObj[i] = obj[i];
			}
			return tempObj;
		},	
		
		getObject: function(fo)
		{
			if(fo.id == null) return null;
			try
			{
				return (window.document[fo.id]) ? window.document[fo.id] : document.getElementById(fo.id);
			}
			catch(e) { return null; }
		},
		
		createInstanceFromObject: function(o)
		{
			var attrs = {}, params = {}, src, on;

			for(var i=0; i<o.attributes.length; i++)
			{
				var attrn = (o.attributes[i].nodeName || i.toString()).toLowerCase(), attrv = o.getAttribute(attrn);
				if(attrn != "contenteditable" && attrn != "style" && attrv != "" && attrv != null && attrv != "null") 
				{
					try { attrs[attrn] = attrv; } catch(ex) { null; }
				}
				if(attrn == "style" && attrv != "" && attrv != null && attrv != "null" && o.outerHTML)
				{
					try
					{
						attrv = o.outerHTML.replace(/\s=/g, "=").replace(/=\s/g, "=").match(/style=[\"\'](.+)[\"\']/);
						if(attrv.length > 1) attrs[attrn.toString()] = attrv[1];
					}
					catch(ex) { null; }
				}
			}
			
			for(var i=0; i<o.childNodes.length; i++)
			{
				if((on=o.childNodes[i]).nodeType && on.nodeType == 1 && on.nodeName && on.nodeName.toLowerCase() == "param")
				{
					try { params[on.getAttribute("name")] = on.getAttribute("value"); } catch(ex) { null; }
				}
			}
			
			if((src = (attrs["src"] || attrs["data"] || attrs["movie"] || params["movie"] || null)) != null)
			{
				var tempInstance = new Flash(src, (attrs["id"] || null), (attrs["width"] || "100%"), (attrs["height"] || "100%"));
				for(var i in attrs) tempInstance.addAttribute(i.toString(), attrs[i]);
				for(var i in params) tempInstance.addParameter(i.toString(), params[i]);
				
				return tempInstance;
			}
			
			return false;
		},
		
		correctAll: function()
		{
			var o = document.getElementsByTagName("OBJECT"), e = document.getElementsByTagName("EMBED"), objects = [];
			
			for(var i=0; i<e.length; i++) if(!e[i].getAttribute("rel") || e[i].getAttribute("rel") != "flashtag") objects.push(e[i]);
			for(var i=0; i<o.length; i++) if(!o[i].getAttribute("rel") || o[i].getAttribute("rel") != "flashtag") objects.push(o[i]);
			
			for(var i=0; i<objects.length; i++)
			{
				if(objects[i].outerHTML)
				{
					try
					{
						
						var to = FlashTag.createInstanceFromObject(objects[i]);
						if(!to) continue;
						
						objects[i].style.visibility = "hidden";
						objects[i].outerHTML = to.toString();
						objects[i].style.visibility = "visible";
						
					} catch(ex){ null; }
				}
			}
		},
		
		automatic: function()
		{
			if(FlashTag.isIE() && document.getElementsByTagName && window.attachEvent)
			{
				window.attachEvent("onload", FlashTag.correctAll);
			}
		},
		
		isMajor: function(f1, f2)
		{
			for(var i=0, f1 = f1.replace(/[,]/g, ".").split("."); i<f1.length; (f1[i]=parseInt(f1[i])), i++);
			for(var i=0, f2 = f2.replace(/[,]/g, ".").split("."); i<f2.length; (f2[i]=parseInt(f2[i])), i++);			

			if(f1.length > 0 && f2.length > 0)
			{
				for(var i = -1, l = Math.min(f1.length, f2.length); ++i < l && f2[i] == f1[i];);
				return +(i != l && f2[i] - f1[i]) > 0 ? false : true;
			}
			
			return false;			
		},
		
		getPlayerVersion: function()
		{
			if(FP_VERSION == null)
			{
				if(!this.isIE() && navigator.plugins && navigator.mimeTypes.length && (f=navigator.plugins["Shockwave Flash"]) && f.description)
				{
					return (f.description.replace(/[^0-9r.]/g, "").replace(/[r]/g, "."));
				}
				else
				{
					var acx = null;
					try
					{
						acx = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
					}
					catch(e)
					{
						var v = 8;
						do
						{
							try
							{
								acx = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + v);
								try { acx.AllowScriptAccess = "always"; } catch(eex){}
								
							} catch(ee) { acx = null; }
						}
						while(v-- && v > 2 && acx==null);
					}
					return (acx != null && acx) ? acx.GetVariable("$version").replace(/[^0-9,]/g, "").replace(/[,]/g, ".") : false;
				}
			}
			else
			{
				return FP_VERSION;
			}
		}
		
	};
	
}();

var Flash = FlashTag.init();
var YouTube = new Flash().YouTube;

/* JQUERY PLUGIN */
(function($) {

	$.fn.flash = function(movie, id, width, height, initParams, youtube)
	{
		if(typeof movie == "object")
		{
			if(typeof movie["src"] == "undefined" && typeof movie["url"] == "undefined")
			{
				return false;
			}
			
			var defaultMovie = {"id": null, "width": "100%", "height": "100%"};
			
			movie = $.extend({}, defaultMovie, movie);
			
			var initParams = {}, _excep = ["src", "url", "id", "width", "height"];
			for(var i in movie)
			{
				if($.inArray(i, _excep) < 0)
				{
					initParams[i] = movie[i];
				}
			}
			
			var id = movie["id"], width = movie["width"], height = movie["height"], movie = (movie["src"] || movie["url"]);
		}

		var _tempInstance = ((!youtube) ? new Flash(movie, id, width, height, initParams) : new YouTube(movie, id, width, height, initParams));
		
		if(initParams && initParams["variables"])
		{
			for(var i in initParams["variables"]) _tempInstance.addVariable(i.toString(), initParams["variables"][i]);
		}
		
		this.each(function(){ _tempInstance.writeIn(this); });
		
		return this;
	};

	$.fn.youtube = function(youtube_url, id, width, height, initParams)
	{
		return this.flash(youtube_url, id, width, height, initParams, true);
	};

})(jQuery);
