var Configuratore = new Class({
	Implements: [Events, Options],
	
	options: {
		'rootPath':'',
		'url':'',
		'selector':'#configuratore',
		'trads': {}
	},
 
	
	initialize: function(options)
	{
		this.setOptions(options);
		this.stepGet = 1;
		this.stepSave = 1;
		//this.step = 7;
		var obj = this;
		$$(this.options.selector).each(function(el){obj.attach(el);});
	},
	
	trad: function(str)
	{
		return this.options.trads[str] || '['+str+']';
	},
	
	attach: function(el)
	{
		var obj = this;
		el.addEvent('click', function(ev){
			ev.stop();
			this.fireEvent('clicked');
			obj.start();
		});
	},
	
	start: function()
	{
		this.cnt = new Element('div', {'id':'configCnt'});
		this.win = new CosMooPopup({'rootPath':this.options.rootPath, 'content':this.cnt, width: 900, height: 500});
		this.win.show();
		var obj = this;
		this.win.sticky.addEvent('close', function(){
			obj.stepGet = 1;
			obj.stepSave = 1;
		});
		
		this.drawStep();
	},
	
	drawStep: function()
	{
		//$$('.step .over').each(function(el){el.removeClass('over');});
		
		if (this.cnt.getChildren().length==5)
			this.cnt.grab(new Element('div', {'class':'separator'}));
		//this.step++;
		var stepCnt = new Element('div', {'class':'step'});
		stepCnt.inject(this.cnt);
		var obj = this;
		var req = new Request.JSON({
			url: obj.options.url,
			onComplete: function(resp){
				obj.createStep(resp, stepCnt);
			}
		}).post({'step':this.stepGet})
	},
	
	createStep: function(resp, cnt)
	{
		if (!resp) return;
		var data = resp.data;
		this.stepGet = resp.nextstep;
		
		var obj = this;
		cnt.grab(new Element('div', {'class':'title', 'html':data.title}));
		if (data.options) data.options.each(function(opt){
			var el = new Element('div');
			el.addClass('opt');
			el.set('html', opt.nome);
			if (opt.immagine)
			{
				var imgDiv = new Element('div', {'class':'imgCnt'});
				imgDiv.setStyle('overflow', 'hidden');
				var img = new Element('img', {src:opt.immagine});
				imgDiv.inject(el, 'top');
				img.inject(document.body);
				var size = img.getSize();
				img.inject(imgDiv);
				//imgDiv.store('h', size.y);
				imgDiv.store('h', 100);
				imgDiv.setStyle('height',0);
				
			}
			el.inject(cnt);
			el.store('step', obj.stepSave);
			el.store('stepnext', obj.stepGet);
			el.store('id', opt.id);
			el.addEvent('mouseenter', function(ev){
				this.addClass('over');
				var img = this.getElements('.imgCnt')[0];
				if (!img) return;
				img.tween('height', img.retrieve('h'));
			});
			el.addEvent('mouseleave', function(){
				el.removeClass('over');
				if (el.hasClass('selected')) return;
				var img = el.getElements('.imgCnt')[0];
				if (!img) return;
				img.tween('height', 0);
			});
			el.addEvent('click', function(ev){
				if (this.hasClass('selected')) return false;
				if (obj.stepSave!=this.retrieve('step')) 
				{
					obj.stepSave=this.retrieve('step');
					obj.stepGet=this.retrieve('stepnext');
					var step = this.getParent();
					while(step.getNext()) step.getNext().destroy(); 
					var divRes = $('resultContainer');
					if (divRes) divRes.destroy();
				}
				//el.removeClass('over');
				el.getParent().getElements('.selected').each(function(s){s.removeClass('selected');});
				el.addClass('selected');
				obj.saveStep(this.retrieve('id'));
			});
		});
		
		var inputs = Array();
		if (data.input) data.input.each(function(opt){
			var el = new Element('div');
			el.addClass('opt');
			el.inject(cnt);
			el.store('step', obj.stepSave);
			el.store('stepnext', obj.stepGet);
			el.store('id', opt.id);
			
			if (opt.type!='button')
				el.grab(new Element('label', {'html':opt.nome}));
			var input;
			if (opt.type=='combo')
			{
				input = new Element('select', {'name':opt.id, 'id':'configuratorField_'+opt.id});
				input.grab(new Element('option', {'value':'', 'html':obj.trad('Qualsiasi')}));
				opt.values.each(function(opt){
					input.grab(new Element('option', {'value':opt, 'html':opt}));
				});
				if (opt.id=='potenza')
				{
					input.addEvent('change', function(ev){
						var fld = $('configuratorField_t')
						if (this.value!='') 
						{
							fld.value = 0;
							fld.set('readonly',true);
						}
						else{
							fld.set('readonly',false);
						}
					})
				}
			}
			else input = new Element('input', {'type':opt.type, 'name':opt.id, 'value':opt.value, 'id':'configuratorField_'+opt.id});
			if (opt.type=='hidden') {el.setStyle('display','none');}
			if (opt.type=='button') 
			{
				input.set('value', opt.nome);
				input.addEvent('click', function(){
					var post = {};
					post.step = 'final';
					post.sendData = 1;
					post.res = {};
					for(var k=0; k<inputs.length; k++)
					{
						if (inputs[k].get('type')=='text' && inputs[k].value=='')
						{
							alert(obj.trad("Devi_compilare"));
							inputs[k].focus();
							return false;
						}
						
						if (inputs[k].get('type')!='checkbox') post.res[inputs[k].get('name')] = inputs[k].get('value');
						else post.res[inputs[k].get('name')] = (inputs[k].checked)?1:0;
					}
					
					var req = new Request.JSON({
						url: obj.options.url,
						onRequest: function()
						{
							var divRes = $('resultContainer');
							if (!divRes)
							{
								divRes= new Element('div', {'id':'resultContainer'});
								divRes.inject(obj.cnt, 'after');
							}
							else
								divRes.empty();
							
							divRes.grab(new Element('img', {'src':obj.options.rootPath+'styles/milkbox/loading.gif'}));
						},
						onComplete: function(data)
						{
							var divRes = $('resultContainer');
							if (!divRes)
							{
								divRes= new Element('div', {'id':'resultContainer'});
								divRes.inject(obj.cnt, 'after');
							}
							else
								divRes.empty();
							
							try{
								var dim = data.dim[0];
								if (data.dim[1]) dim+="x"+data.dim[1];
								if (data.dim[2] && data.dim.length==3) dim+="x"+data.dim[2];
								var img = new Element('img', {'src':obj.options.rootPath+data.immagine});
								img.setStyle('float', 'right');
								divRes.setStyle('overflow', 'hidden');
								divRes.grab(img);
								divRes.grab(new Element('div', {'html':'<b>'+obj.trad('Dimensioni')+'</b>'}));
								divRes.grab(new Element('div', {'html':dim+' mm', styles:{'margin-bottom':10}}));
								divRes.grab(new Element('div', {'html':'<b>'+obj.trad('Componenti')+'</b>'}));
								data.pezzi.each(function(el){
									var txt = el.quantita+" x "+el.descrizione+" ("+el.codice+")";
									divRes.grab(new Element('div', {'html':txt}));
								});
								var buttonCopy = new Element('a', {'class':'scaricaCsv','html':obj.trad('Scarica_CSV'), 'href':obj.options.rootPath+'catalogo/cfgcsv', 'target':'_blank'});
								divRes.grab(buttonCopy);
								
								var buttonCopy = new Element('a', {'class':'scaricaCsv','html':obj.trad('Scarica_PDF'), 'href':obj.options.rootPath+'catalogo/cfgpdf', 'target':'_blank'});
								divRes.grab(buttonCopy);
								
								if (data.faretti.length>0)
								{
									var buttonFaretti = new Element('div', {'id':'scegliFaretti', 'html':obj.trad('Aggiungi_faretti')});
									buttonFaretti.addEvent('mouseenter', function(ev){this.addClass('over');});
									buttonFaretti.addEvent('mouseleave', function(ev){this.removeClass('over');});
									buttonFaretti.addEvent('click', function(ev){
										obj.addFaretti(data.faretti);
									});
									divRes.grab(buttonFaretti);
								}
								
								if (data.corpo_cieco.length>0)
								{
									var buttonCC = new Element('div', {'id':'scegliCC', 'html':obj.trad('Aggiungi_ciechi')});
									buttonCC.addEvent('mouseenter', function(ev){this.addClass('over');});
									buttonCC.addEvent('mouseleave', function(ev){this.removeClass('over');});
									buttonCC.addEvent('click', function(ev){
										obj.addCC(data.corpo_cieco);
									});
									divRes.grab(buttonCC);
								}
								
								var parent = obj.cnt.getParent();
								(function(){parent.getParent().setStyle('height',parent.getDimensions().y);}).delay(500);
							}
							catch(ex){
								divRes.set('html', 'Operazione fallita');
							}
						}
					}).post(post);
				});
				
				inputs.each(function(el){
					if (el.get('type')!='text') return;
					el.addEvent('keydown', function(ev){
						if (ev.key == 'enter') input.fireEvent('click');
					});
				});
			}
			else inputs.push(input);
			el.grab(input);
		});
	},
	
	addFaretti: function(faretti)
	{
		var obj = this;
		var form = new Element('div', {'id':'formFaretti'});
		var popupFaretti;
		faretti.each(function(f){
			var cntF = new Element('div');
			var qt = new Element('input', {'type':'text', 'id':'qta_'+f.id, 'name':'qta['+f.id+']', 'value':parseInt(f.quantita), 'class':'quantita'});
			qt.addEvent('keyup', function(ev){
				if (isNaN(this.value)) this.value = 0;
			})
			var label = new Element('label', {'for':'qta_'+f.id, 'html':f.descrizione+' ('+f.codice+')'});
			cntF.grab(qt);
			cntF.grab(label);
			form.grab(cntF);
		});
		var add = new Element('button', {'html':obj.trad('Aggiungi'), 'id':'buttonAggiungiFaretti'});
		add.addEvent('click', function(ev){
			var post = {};
			post.step = 'faretti';
			post.sendData = 1;
			post.res = {};
			form.getElements('input').each(function(qt){
				post.res[qt.get('id').substr(4)] = qt.value;
			});
			var req = new Request.JSON({
				'url':obj.options.rootPath+'catalogo/config',
				onComplete: function(data)
				{
					$('configuratorField_submit').fireEvent('click');
				}
			}).post(post);
			popupFaretti.hide();
		});
		add.inject(form);
		popupFaretti = new CosMooPopup({'rootPath':this.options.rootPath, 'content':form, 'width': 400, 'height': 'auto'});
		popupFaretti.show();
	},
	
	addCC: function(corpo)
	{
		var obj = this;
		var form = new Element('div', {'id':'formCC'});
		var popupCC;
		corpo.each(function(f){
			var cntF = new Element('div');
			var qt = new Element('input', {'type':'text', 'id':'qta_'+f.id, 'name':'qta['+f.id+']', 'value':parseInt(f.quantita), 'class':'quantita'});
			qt.addEvent('keyup', function(ev){
				if (isNaN(this.value)) this.value = 0;
			})
			var label = new Element('label', {'for':'qta_'+f.id, 'html':f.descrizione+' ('+f.codice+')'});
			cntF.grab(qt);
			cntF.grab(label);
			form.grab(cntF);
		});
		var add = new Element('button', {'html':obj.trad('Aggiungi'), 'id':'buttonAggiungiCC'});
		add.addEvent('click', function(ev){
			var post = {};
			post.step = 'corpo_cieco';
			post.sendData = 1;
			post.res = {};
			form.getElements('input').each(function(qt){
				post.res[qt.get('id').substr(4)] = qt.value;
			});
			var req = new Request.JSON({
				'url':obj.options.rootPath+'catalogo/config',
				onComplete: function(data)
				{
					$('configuratorField_submit').fireEvent('click');
				}
			}).post(post);
			popupCC.hide();
		});
		add.inject(form);
		popupCC = new CosMooPopup({'rootPath':this.options.rootPath, 'content':form, 'width': 400, 'height': 'auto'});
		popupCC.show();
	},
	
	saveStep: function(data)
	{
		var obj = this;
		var req = new Request.JSON({
			url: obj.options.url,
			onComplete: function(data){
				obj.stepSave = obj.stepGet;
				obj.drawStep();
			}
		}).post({'step':this.stepSave, 'res':data, 'sendData':1});
	}
});
