var Widget = Class.create();

Widget.prototype =
{	
	initialize: function() 
	{
		this.step = 1;		
		this.widgets = $$('#toGoApp .chooseWidget a');		

		this.widgets.each(function(x) 
		{  
			x.onclick = function(e) { this.choose(e, x) }.bindAsEventListener(this);
		}.bind(this));
		
		this.next = $$('#toGoApp a.next');
		this.next[0].onclick = function(e) {  Event.stop(e); }.bindAsEventListener(this);

		this.loading = new app.loading();
	},	
		
	choose: function(e, x)
	{
		Event.stop(e);

		this.nextShow();

	  	new Effect.Opacity(x.down(), { 
			duration: 0.3, 
	      	from: 0.0, to: 1.0 });

		this.widgets.each(function(_x)
		{					
			if (x != _x)
			{						
				_x.down().setOpacity(0.5);
				_x.removeClassName('selected');				
			}
			else
			{
				_x.addClassName('selected');				
			}
		});
		
		this.selection = x.id.substr(1);
		
		if (this.selection != this.id)
		{
			this.swf = new Widget.SWF('widget', json.defaults.base, json.paths[this.selection], json.defaults.lang, json.ratio);
			if (json.defaults[this.selection])
				this.swf.vars(json.defaults[this.selection]);
			if (json.sizes[this.selection])
				this.swf.resize(json.sizes[this.selection]);
				
			this.swf.draw();
		}
		
		if (this.saved_id != this.selection)
		{		
			this.next = $$('#toGoApp a.next');
			this.next[0].onclick = function(e) { this.saved_id = this.id; this.getSteps(e) }.bindAsEventListener(this);
		}
		else
		{
			this.next[0].onclick = function(e) { this.nextStep(e) }.bindAsEventListener(this);			
		}
			
		this.id = this.selection;
	},
	
	getSteps: function(e)
	{
		Event.stop(e);
		
		this.config = new Object();
		this.update = new Object();		
		this.conditions = new Object();
		this.onopen = new Object();
		this.ondelete = new Object();
		
		var obj = this;

		var toGoBox = $$('#toGoApp .toGoBox');
		toGoBox.each(function(x, i) { if (i) x.remove(); });
		var stepCollapsed = $$('#toGoApp .stepCollapsed');
		var removeSteps = new Array();
		stepCollapsed.each(function(x, i) { if (i>1) removeSteps.push(x); });

		this.loading.set(this.gut());

		var insertion = removeSteps.length ? 
			function(receiver, response)
			{	
				removeSteps.each(function(x) { x.remove(); });
				new Insertion.Bottom(receiver, response);
			} : 
			Insertion.Bottom;

		var callback = function(json)
		{
			obj.next = $$('#toGoApp a.next');
			obj.next.each(function(x)
			{
				if (!x.hasClassName('done'))
					x.onclick = function(e) { obj.nextStep(e) }.bindAsEventListener(this);
			});

			var toGoBox = $$('#toGoApp .toGoBox');			
			var step = toGoBox[obj.step-1];
			var next = toGoBox[obj.step];

			var stepCollapsed = $$('#toGoApp .stepCollapsed');			

			new Effect.Parallel(
				[ new Effect.BlindUp(step, {sync:true}),
				  new Effect.Appear(stepCollapsed[obj.step], {sync:true}),
				  new Effect.Appear(next, {sync:true}),
				  new Effect.BlindDown(next, {sync:true})
				], { afterFinish: 
					function() { 
						step.setOpacity('');			
						next.setOpacity('');
				 	} });

			obj.step++;

			stepCollapsed.each(function(x, i)
			{
				if (i > 0)
				{
					x.onmouseover = function() { x.className = 'stepCollapsed hover'; }
					x.onmouseout = function() { x.className = 'stepCollapsed'; }
					x.onclick = function() { x.className = 'stepCollapsed'; obj.openStep(i); }
				}
			});
		}
		
		var errorCallback = function()
		{
			$('loading').hide();
		}

		var args = new Hash({ widget: obj.id });
		if (json && json.defaults && json.defaults.auto) args['auto'] = json.defaults.auto;

		app.blockLoad('steps', 'createWidget', '/app/create.php?'+args.toQueryString(), callback, errorCallback, insertion, this.loading);
	},
	
	nextStep: function(e)
	{
		Event.stop(e);

		if (this.conditions[this.step] && this.conditions[this.step].fn)
		{
			if (!this.conditions[this.step].fn())
			{
				this.conditions[this.step].alert();
				return;
			}
		}

		var toGoBox = $$('#toGoApp .toGoBox');
		var stepCollapsed = $$('#toGoApp .stepCollapsed');

		if (stepCollapsed[this.step+1] && stepCollapsed[this.step+1].visible())
			return this.openStep(this.step+1);

		var step = toGoBox[this.step-1];
		var next = toGoBox[this.step];

		new Effect.Parallel(
			[ new Effect.BlindUp(step, {sync:true}),
			  new Effect.Appear(stepCollapsed[this.step], {sync:true}),
			  new Effect.Appear(next, {sync:true}),			
			  new Effect.BlindDown(next, {sync:true})
			], { afterFinish: 
				function() { 
					step.setOpacity('');			
					next.setOpacity('');
					
					if (this.update[this.step])
					{
						this.update[this.step] = false;
						this.swf.vars(this.config);
						this.swf.draw();
					}	
					
					this.step++;

					if (this.onopen[this.step])
						this.onopen[this.step]();										
			 	}.bind(this) });

	},

	openStep: function(s)
	{
		if (this.step == 1 && this.selection != this.saved_id)
		{
			this.id = this.saved_id;
			x = $('w'+this.id);

			this.widgets.each(function(_x)
			{			
				if (x != _x)
				{						
					_x.down().setOpacity(0.5);
					_x.removeClassName('selected');				
				}
				else
				{
					_x.down().setOpacity(0.999999);					
					_x.addClassName('selected');				
				}						
			});
		
			this.selection = this.id;
		
			this.swf = new Widget.SWF('widget', json.defaults.base, json.paths[this.selection], json.defaults.lang, json.ratio);
			if (json.defaults[this.selection])
				this.swf.vars(json.defaults[this.selection]);

			this.swf.vars(this.config);
			this.swf.draw();
		}

		var toGoBox = $$('#toGoApp .toGoBox');
		var stepCollapsed = $$('#toGoApp .stepCollapsed');
		
		var step = toGoBox[this.step-1];
		var next = toGoBox[s-1];

		stepCollapsed[s].setStyle({display:'none'});

		new Effect.Parallel(
			[ new Effect.Appear(stepCollapsed[this.step], {sync:true}),
			  new Effect.BlindDown(next, {sync:true}),
			  new Effect.BlindUp(step, {sync:true})
			 ], { afterFinish: 
				function() { 
					step.setOpacity('');			
					next.setOpacity('');
					
					if (this.update[this.step])
					{
						this.update[this.step] = false;
						this.swf.vars(this.config);
						this.swf.draw();
					}	
					
					this.step = s;

					if (this.onopen[this.step])
						this.onopen[this.step]();					
			 	}.bind(this) });
	},
	
	gut: function()
	{
		return $$('#toGoApp .toGoBox .step')[this.step-1];		
	},
	
	nextButton: function(s)
	{
		return this.next[s-1];
	},
	
	nextShow: function()
	{
		if (this.next[this.step-1].visible())
			return;

		this.next[this.step-1].up().setOpacity('0.0');
		
		new Effect.Opacity(this.next[this.step-1].up(), { 
	      	from: 0.0, to: 0.999999, 
			beforeStart: function() {
				this.next[this.step-1].show();
			}.bind(this)});		
	},
	
	nextHide: function()
	{
		if (!this.next[this.step-1].visible())
			return;
		
		new Effect.Opacity(this.next[this.step-1].up(), { 
	      	from: 0.999999, to: 0.0, 
			afterFinish: function() {
				this.next[this.step-1].hide();
			}.bind(this) });
	}	
}

Widget.SWF = Class.create();

Widget.SWF.prototype =
{
	initialize: function(container, base, path, lang, ratio)
	{
		this.container = $(container);
		this.base = base;
		this.path = path || 'togo.swf';
		this.lang = lang || 'en';
		this.ratio = ratio || 1;
		this.size = {};
		
		this.originalSize = this.container.getDimensions();
		
		this.swf = new SWFObject(
			this.base+this.path,
			'so_'+this.container.id,
			this.originalSize.width, 
			this.originalSize.height, 
			"8", "#ffffff", true);

		this.swf.addParam("salign", "lt");		
		this.swf.addParam("wmode", "transparent");
		
		this.vars({
			base: this.base,
			lang: this.lang,
			local: 'true'
		});
	},

	vars: function(a)
	{
		for (var key in a)
			if (a[key])
				this.swf.addVariable(key, a[key].toString());
	},

	resize: function(size)
	{	
		this.fullSize = size;	
		this.size.width = this.ratio * this.fullSize.width;
		this.size.height = this.ratio * this.fullSize.height;
		
		this.container.setStyle({ width: this.size.width+'px', height: this.size.height+'px' });
		
		this.swf.setAttribute('width', this.size.width);
		this.swf.setAttribute('height', this.size.height);
	},

	draw: function()
	{
		if (!Widget.SWF.saved)
		{
			var pre = new Image();
			pre.src = '/img/widget_bg-notext.gif';
			Widget.SWF.saved = '<img src="/img/widget_bg-notext.gif" />';
		}

		this.savedlocal = this.swf.getVariable('local')
		this.container.setStyle({ width: this.size.width+'px', height: this.size.height+'px' });
		
		this.swf.write(this.container.id);
		this.unset('local');
	},
	
	restore: function()
	{
		if (Widget.SWF.saved)
		{
			this.vars({local: this.savedlocal});
			this.container.setStyle({ width: this.originalSize.width+'px', height: this.originalSize.height+'px' });
			this.container.innerHTML = Widget.SWF.saved;
		}
	},
	
	unset: function(key)
	{
		if (this.swf.variables[key])
			delete this.swf.variables[key];
	},
	
	code: function(site)
	{
		switch(site)
		{
			case 'wordpress_com':
				var str = new Array();
				for (var key in this.swf.variables)
				{
					if (key == 'base' || key == 'ebay' || key == 'mode' || (key == 'lang' && this.swf.variables[key] == 'en')) continue;
					str.push(key+'='+this.swf.variables[key]);
				}
				return '[ebay '+str.join("&")+']';
			
			case 'livejournal':
				return this.embed().replace(/&/g, '&amp;');
			
			case 'facebook':
				var str = new Array();			
				for (var key in this.swf.variables)
				{
					if (key == 'auto' || key == 'root') continue;
					str.push(key+'='+this.swf.variables[key]);
				}
				var share = '<p><fb:share-button class="meta"><meta name="medium" content="video"/><meta name="title" content="eBay To Go"/><meta name="video_type" content="application/x-shockwave-flash"/><meta name="video_width" content="'+this.fullSize.width+'"/><meta name="video_height" content="'+this.fullSize.height+'"/><link rel="image_src" href="'+json.defaults.root+'img/facebook-loader.gif"/><link rel="video_src" href="'+this.swf.getAttribute('swf')+'&'+str.join("&")+'"/></fb:share-button></p>';
				return '<fb:wide><fb:swf width="'+this.fullSize.width+'" height="'+this.fullSize.height+'" waitforclick="false" swfsrc="'+this.swf.getAttribute('swf')+'" imgsrc="'+json.defaults.root+'img/facebook-loader.gif" flashvars="'+str.join("&")+'"></fb:swf>'+share+'</fb:wide><fb:narrow>eBay To Go needs enough room to spread out - drag it back to the wide column!</fb:narrow>';
			
			default:
				return this.embed();
		}
	},
	
	embed: function(display)
	{
		var params = this.swf.getParams();
		var pairs = this.swf.getVariablePairs().join("&");

		var width = display ? this.size.width : this.fullSize.width;
		var height = display ? this.size.height : this.fullSize.height;

		var swfNode = '<object width="'+width+'" height="'+height+'"><param name="movie" value="'+this.swf.getAttribute('swf')+'" />';
		
		for (var key in params)
		{
			switch(key)
			{
				case 'bgcolor': case 'quality': case 'scale': case 'salign': case 'wmode': break;
				default: 
				swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
			}
		}

		if (pairs.length > 0) { swfNode += '<param name="flashvars" value="'+ pairs +'" />'; }
		
		swfNode += '<embed src="'+this.swf.getAttribute('swf')+'" type="application/x-shockwave-flash" width="'+width+'" height="'+height+'" ';
		
		for (var key in params)
		{
			switch(key)
			{
				case 'bgcolor': case 'quality': case 'scale': case 'salign': case 'wmode': break;
				default: 
				swfNode += [key] +'="'+ params[key] +'" ';
			}
		}
		
		if (pairs.length > 0) { swfNode += 'flashvars="'+ pairs +'"'; }		
		
		swfNode += '></embed></object>';
		
		return swfNode;
	}
}

window.windowOnload.push(function()
{
	window.widget = new Widget();
});
