/** 
 * MooSwfir
 * - A MooTools version of swfir ( www.swfir.com )
 * Version: 0.1
 * Author: Jabis Sevón
 * License: read from the original below.
 * Notes: 
 * - This is quite a direct port... -.- 
 * - Added chaining of settings ( .set(k,v).set(k,v).swap(selector) ), 
 *   and a convenience method for inputting object of settings...
 * - Added a simple opacity morph for the transition
 * - Working with MooTools Core 1.2.3
 * - There is still some work on both the classes...
 * - Changes in syntax:
 * swfir:
 *  -- .specify() -> .set()
 *  -- * added .sets({key:value,key:value})
 * swfirController:
 *  -- .addswfir() -> set()
 *  -- .getswfirs() -> getAll()
 *  -- * added .get(key) 
**/



/** 
//	=============================================
//	swfir!
//	=============================================
//	Copyright 2006, 2007 Jon Aldinger, Mark Huot
//	and Dan Mall
//	
//	This software is licensed under the CC-GNU LGPL
//	http://creativecommons.org/licenses/LGPL/2.1/
//	---------------------------------------------
//	=============================================
//	Get DOM Elements with CSS Selectors
//	=============================================
//	Use this function to call DOM elements by
//	passing in a CSS selector such as 'p .date'
//	---------------------------------------------
**/

var MooSwfirController = new Class({

	Implements:Options,
	options: {
		swfirs:[]
	},
	initialize:function(opts){
		this.setOptions(opts);
		this.swfirs = this.options.swfirs;
		return this;
	},
	set:function(swfirReference){
		var swfirId = this.swfirs.length;
		this.swfirs.push(swfirReference);
		return swfirId;
	},
	get:function(id) {
		return this.swfirs[id];
	},
	getAll:function(){
		return this.swfirs;
	},
	getNextId:function() {
		return this.swfirs.length;
	},
	resize:function( id, width, height ) {
		if(this.swfirs[id].elasticityWidth == false)
		{
			this.swfirs[id].setAttribute("width", width);
			this.swfirs[id].setStyle('width',width);
		}
		
		this.swfirs[id].setAttribute("height", height);
		this.swfirs[id].setStyle('height',height);
		return this;
	}
});
var MooSwfir = new Class({
	Implements:Options,
	options:{
		name : "swfir",
		version : "1.1.1",
		mooversion: "0.1",
		debug : false,
		params : {},
		background : "",
		src : "/media/swfir.swf",
		wmode : "transparent",
		elasticityWidth : false
	},
	initialize:function(options) {
		this.setOptions(options);
		this.setDefaults(this.options);
		this.controller = new MooSwfirController();
		return this;
	},
	setDefaults:function(opts) {
		for (var key in opts) { this[key] = opts[key]; }
		return this;
	},
	set:function( key, value )
	{
		if(key == "debug") {
			if(value == true || value == "true") this.debug = true;
			else this.debug = false;
			return this;
		}
		if(key == "wmode") this.wmode = value;
		if(key == "background-color") {
			this.background = this.cleanColor(value);
			return this;
		}
		if(key == "border-color" || key == "shadow-color") {
			value = this.cleanColor(value, "flash");
		}
		if(key == "shadow-blur") {
			this.params["shadowBlurX"] = value;
			this.params["shadowBlurY"] = value;
			acceptableFound = true;
		}
		if(key == "border-radius" || key == "border-width" || key == "border-alpha" || key == "shadow-blur-x" || key == "shadow-blur-y")
		{
			value = parseFloat(value);
			if((value == NaN || value == "NaN") && this.debug == true)
			{
				this.error("'"+key+"' must be a number.  Please make sure in your source there are no quotes (\") around the number.");
			}
		}
		if(key == "rotate" && Number(value) < 0) {
			value = 360 + Number(value);
			return this;
		}
		if(key == "src") {
			this.src = value;
			return this;
		}
		if(key == 'elasticity') {
			if(parseFloat(value)){this.elasticityWidth = value; }
			else {
			var tmp = new Element('div', {
			  styles:{ position:'absolute', left:'-10em', width: '1em', height: '1em' }
			}).inject(document.body);
			this.elasticityWidth = tmp.offsetHeight;
			tmp.dispose();
			}
			return this;
		}
		var translation = {};
			translation["border-radius"] = "borderRadius";
			translation["border-width"] = "borderWidth";
			translation["border-color"] = "borderColor";
			translation["shadow-offset"] = "shadowOffset";
			translation["shadow-angle"] = "shadowAngle";
			translation["shadow-alpha"] = "shadowAlpha";
			translation["shadow-blur-x"] = "shadowBlurX";
			translation["shadow-blur-y"] = "shadowBlurY";
			translation["shadow-strength"] = "shadowStrength";
			translation["shadow-color"] = "shadowColor";
			translation["shadow-quality"] = "shadowQuality";
			translation["shadow-inner"] = "shadowInner";
			translation["shadow-knockout"] = "shadowKnockout";
			translation["shadow-hide"] = "shadowHide";
			translation["rotate"] = "rotate";
			translation["overflow"] = "overflow";
			translation["link"] = "link";
		this.params[translation[key]] = value;
	   return this;
	},
	sets:function(obj) {
		for (var key in obj) { this.set(key,obj[key]); }
		return this;
	},
	swap:function(selector) {
		var elements = $$(selector);
		if(this.hasImg(elements) == false)
		{
			var elements = $$(selector+" img");
			if(this.hasImg(elements) == false && this.debug == true)
			{
				this.error("No images were selected with the selector '"+selector+"'");
				return;
			}
		}
		
		elements.each(function(element,i) {
			element.fade('0');
			var id = element.getParent().get("id") || "";
			var className = element.get("className") || "swfir";
			var style = "";
			var width = "";
			var height = "";
			var bgcolor = (this.background != "")?this.background:"";
			var src = this.src;
			var flashvars = "";

			if(element.getAttribute("style")) {
				if(element.style.cssText && elements[i].style.cssText != "") {
					style += element.style.cssText+";";
				}
				else if(typeof element.getAttribute("style") == "string") {
					style += element.getAttribute("style");
				}
			}
			width = element.width;
			height = element.height;
			if(this.elasticityWidth != false) {
				if(style != "") style += " ";
				style += "width:"+(width / this.elasticityWidth)+"em;";
			}
			else {
			
				if(element.getAttribute("width",2)) {
					if(style != "") style += " ";
					style += "width:"+element.getAttribute("width",2)+";";
				}
				if(element.getAttribute("height",2)) {
					if(style != "") style += " ";
					style += "height:"+element.getAttribute("height",2)+";";
				}
			}
			
			this.params['srcWidth'] = width;
			this.params['srcHeight'] = height;

			var reserveparams = this.params;
		
			if((elementLink = this.withinLink(element)) != false && !this.params["link"])	{
			reserveparams["link"] = elementLink.href.replace(/\?/g,"%3F").replace(/&/g,"%26");
			}
			reserveparams["url"] = elements[i].src;
			reserveparams["swfirId"] = this.controller.getNextId();

			var span = new Element('span');
			if(id) span.set("id", id);
			if(className) span.addClass(className);
			var parent = element.getParent();
			span.adopt(element);
			span.replaces(parent).setStyle('opacity',0);
			
			var so = new Swiff(this.src, {
			    id: "swfir"+this.controller.getNextId(),
			    width: width,
   			    height: height,
    			    params: {
                            wmode: this.wmode,
                            bgcolor: this.bgcolor
		           },
		           vars: reserveparams
			}).replaces(element);
			span.get('morph').start({'opacity':[0,1]});
			this.controller.set(so);
		},this);
		return this;
	},
	withinLink:function( element ) {
		while(element.nodeName != "A") {
			if(element.parentNode) element = element.parentNode;
			else return false;
		}
		return element;
	},
	cleanColor:function(color, style)	{
		color = color.replace(/^0x/, '');
		color = color.replace(/^#/, '');
		if(color.length == "3") {
			color = color.substring(0,1)+color.substring(0,1)+color.substring(1,2)+color.substring(1,2)+color.substring(2,3)+color.substring(2,3);
		}
		if(style == "flash") color = "0x"+color;
		else color = "#"+color;
		return color;
	},
	hasImg:function(elementList) {
		return (elementList.getElement('img') || elementList.getParent().getElement('img'))?true:false;
	},
	error:function( alertString ) {
		if(window.console) console.log(this.name+" "+this.version+" Error\n\n"+alertString);
	}

	
});
