var Popup = new Class({
	Implements: [Options],
	

	version: '0.1',
 
	options: {
		width: '300px',
		height: '200px',
		url: '',
		classPopup: '',
		classClose: '',
		imgClose: 'immagini/grafica/chiudi.jpg',
		modal: 'true',
		position: 'center',
		edge: 'upperLeft',
		offset: {x: 0, y: 0},
		realtiveTo: $(document.body),/*se settato a "elemento" la stycky win si posiziona rispetto all'elemento*/
		onComplete: null,
		onStickyReady: function(){return;}
	},
 
	
	initialize: function(options)
	{
		this.setOptions(options);
	},
	
	attach: function(selector)
	{
		var obj = this;
		
		$$(selector).each(function(el){
			
			el.addEvent('click', function()
			{
				
				var divCont = new Element('div', {'styles':{'width':obj.options.width, 'height':obj.options.height}});
				divCont.addClass(obj.options.classPopup);
				
				var req = new Request.HTML({
					url: obj.options.url,
					async: false,
					evalScripts: true,
					onComplete: function(tree, elements, html, js) {
						//divCont.set('html', html);
						var html2 = html;
						if(js)
							html2 = html2+" <script type=\"text/javascript\">"+js+"</script>"
						divCont.set("html", html2);
						
						if(obj.options.onComplete)
						{
							obj.options.onComplete();
						}
					},
					onFailure: function() {
						divCont.set('html', 'The Request has failed...');
					}
				}).post({'id':el.get('rel')});
				
				var divClose = new Element('div'/*, {'styles':{'position':'absolute', 'top':'5px','right':'5px'}}*/);
				divClose.addClass(obj.options.classClose);
				var imgClose = new Element('img',{'src':obj.options.imgClose, 'border':'0'});
				divClose.grab(imgClose);
				divCont.grab(divClose);
				
				var relativeTo = obj.options.relativeTo;
				if(obj.options.relativeTo=="elemento")
					relativeTo = el;
				
				var stickys = $$('.StickyWinInstance');
				stickys.each(function(el){el.destroy();});
				
				if(obj.options.modal)
				{
					var myChain = new Chain();
					myChain.chain(
					    function()
					    { 
					    	var sticky = new StickyWinFxModal({content: divCont, fadeDuration: 400, position: obj.options.position, relativeTo: relativeTo, offset: obj.options.offset, edge: obj.options.edge});
					    	divClose.addEvent('click', function(){this.destroy();}.bind(sticky));
					    	this.callChain();
					    },
					    function(){ obj.options.onStickyReady(); }
					);
					myChain.callChain();
				}
				else
				{
					var myChain = new Chain();
					myChain.chain(
					    function()
					    {
					    	var sticky = new StickyWinFx({content: divCont, fadeDuration: 300, position: obj.options.position, relativeTo: relativeTo, offset: obj.options.offset, edge: obj.options.edge});
					    	divClose.addEvent('click', function(){this.destroy();}.bind(sticky));
					    	this.callChain();
					    },
					    function(){ obj.options.onStickyReady(); }
					);
					myChain.callChain();
				}
				
			});
			
		});
	}
});