//	CLASSE GESTIONE PREVENTIVI INFALL
String.extend({
	'decode':function() {
		return unescape(this.replace(/\+/g,  " "));
	}
});
Element.extend({
    fadeIn: function(options){
		ini = (($defined(options))&&(options.ini)) ? options.ini : this.getStyle('opacity');
		end = (($defined(options))&&(options.end)) ? options.end : 1;
		new Fx.Styles(this,options).start({'opacity':[ini,end]});
		return this;
		
    },
    fadeOut: function(options){
		ini = (($defined(options))&&(options.ini)) ? options.ini : this.getStyle('opacity');
		end = (($defined(options))&&(options.end)) ? options.end : 0;
		new Fx.Styles(this,options).start({'opacity':[ini,end]});
		return this;
    },
	getChild:function() {
		return ((this.getChildren().length>0) ? this.getChildren()[0] : false)
	}
});



var FormBox = new Class(
{
	
	initialize:function(o) {
		this.step=2;
		this.opt = 
		{
			container:	$E('body'),
			hiddenCssClass: 'hidden',
			iniURL: ABS+"/inc/tmpl/preventivo_ajax.php?step="+this.step
		}
		this.data = {
			anagrafica:$H({
				nome:'',
				azienda:'',
				tel:'',
				fax:'',
				email:'',
				zona:''
			}),
			items:[]
		}
		this.itemIndex = 0;
		if ($type(o)== "object") $extend(o,this.opt);
		
		/*	GRAPHIC OUTPUT :: GENERATING THE BOX	*/
		
		if (window.ie6) $$('select').addClass(this.opt.hiddenCssClass);
		this.bgLayer = new Element('div',{
											'class':'bg_overlay fixed preventivoBox',
											'styles':
												{
													'opacity':0
												},
											'events':
												{
													'click':this.close.bind(this)
												}
						 				});
		this.box = new Element('div',
							{
								'class':'form_box fixed preventivoBox',
								'styles':
									{
										'opacity':0
									}
							});
		this.contentBox = new Element('div',
										{
											'class':'contentBox',
											'styles':
											{
												'position':'relative',
												'width':'100%',
												'height':'100%',
												'overflow':'hidden'
											}
										});							
		this.bgLayer.injectInside(this.opt.container);
		this.bgLayer.fadeIn({
				wait:false, 
				duration:150, 
				onComplete:(function() 
					{
						this.box.injectInside(this.opt.container);
						this.contentBox.injectInside(this.box);
						this.centerBox();
						this.box.setStyle('opacity',1);
						this.loadContent(this.opt.iniURL);
					}).bind(this),
				ini:0,
				end:.75
				});
		if (window.ie6) {
			$$('.fixed').each(function(fix) {
				fix.top = (fix.getStyle('top').test("%")) ? window.getHeight()*fix.getStyle('top').toInt()/100 : fix.getStyle('top').toInt();
				window.addEvent('scroll',function(ev) {				
					fix.setStyle('top',window.getScrollTop()+fix.top.toInt());
				});
			});
		}
		/*	END OUTPUT	*/
		
	},
	getError:function() {
		$$('.requiredFieldPreventivo').each(function(item) {
					item.getParent().removeClass('error');
					if (item.value.trim().length==0) {
						item.getParent().addClass('error');
						if (!window.ie6) item.getParent().setStyles({'background-color':'#ffffef'});	// ONE MORE IE6 HACK >:-|
						var myTips = new Tips(item.getParent(), {
								  onShow:function(tip) {new Fx.Styles(tip,{wait:false,duration:250}).start({'opacity':[0,.75]});},
								  onHide:function(tip) {new Fx.Styles(tip,{wait:false,duration:250}).start({'opacity':[.75,0]});},
								  offsets: {
									  x:-75,
									  y:20
								  }
							});					
						returnVal=false;
					}
				});		// CONTROLLO ERRORI
		$$('.emailChecker').each(function(email) {
			var email_reg_exp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
			if (!email.getValue().match(email_reg_exp) || (email.getValue() == "") || (email.getValue() == "undefined")) {
				email.getParent().addClass('error');
			}
		});
		return ($$('.error').length>0) ? true : false;
	},
	close:function(mode) {
		if (mode!='noconfirm') {
			if (confirm('sei veramente sicuro di chiudere l\'attuale preventivo?')) {
				$$('.preventivoBox').each(function(item) {item.fadeOut({onComplete:function(){item.remove();}});});
				if (window.ie6) $$('select').removeClass(this.opt.hiddenCssClass);
			}
		}	else {
				$$('.preventivoBox').each(function(item) {item.fadeOut({onComplete:function(){item.remove();}});});
				if (window.ie6) $$('select').removeClass(this.opt.hiddenCssClass);
		}
	},
	centerBox:function() {
		formBox = $E('.form_box');
		this.box.setStyles({
			'top':	(window.getHeight().toInt()-this.box.getStyle('height').toInt())/2,
			'left': (window.getWidth().toInt()-this.box.getStyle('width').toInt())/2
		});
		window.addEvent('resize',this.centerBox.bind(this));
	},
	loadContent:function(url) {
		//alert(url)
		
		this.contentBox.fadeOut({
									duration:150,
									onComplete:(function() {
										new Ajax(url,
											{
												method:'post',
												update:this.contentBox,
												evalScripts:true,
												data:'ABS_URI='+ABS, 
												onSuccess:this.setBehaviourOnContent.bind(this)
											}).request();

									}).bind(this)
								});
		
	},
	setBehaviourOnContent:function(r) {
		this.contentBox.fadeIn({duration:150});
		//Log.print('OGGETTO N. '.toLowerCase()+this.itemIndex);
				
		if(this.step==1) {
			
			$$('#boxForm input.text').each((function(i) {
				i.setProperty('value',this.data.anagrafica.get(i.getProperty('id')))
			}).bind(this));
			
				el = new Element('div').setHTML(this.html2send);
				el.getElements('.showItemDetail').each(function(i) {i.remove();});
				el.getElements('.removeItem').each(function(i) {i.remove();});
			
				$('html').setProperty('value',el.innerHTML);
			
		} else if (this.step==2) {
				//	SETTO LE INPUT IN CASO SIANO GIA' SETTATE 
				if (($defined(this.data.items[this.itemIndex]))&&($defined(this.data.items[this.itemIndex].get('tipologia')))) {
					$$('.tipo_choice').removeClass('selected');
					tipo = this.data.items[this.itemIndex].get('tipologia');
					$$('label.'+tipo.toLowerCase()).each(function(i) {
						i.addClass('selected');
						i.getElement('input').click();
					});
					
					//Log.print(this.data.items[this.itemIndex].get('tipologia'));
					
				}
				if (window.ie6) {
					$$('.tipo_choice').addEvent('mouseover',function() {
						this.addClass('hover');
					});
					$$('.tipo_choice').addEvent('mouseout',function() {
						this.removeClass('hover');
					});				
				}
					$$('.tipo_choice').addEvent('click',function() {
						$$('.tipo_choice').removeClass('selected');
						this.addClass('selected');
						this.getElement('input').blur();
					});				
		} else if (this.step==3) {
				//	SETTO LE INPUT IN CASO SIANO GIA' SETTATE 
				//Log.print(this.data.items[this.itemIndex].length);
				if (((this.data.items[this.itemIndex].length>1))) {
				
					$$('#boxForm .text').each((function(i) {
						v = this.data.items[this.itemIndex].get(i.getProperty('id'));
						if (i.getProperty('type')=='text') 
						i.setProperty('value',v)
						else if (i.getTag()=='select') {
							i.getElements('option').each(function(o,k) {
								if (o.getProperty('value') == v) o.selected=true;
							});
						}
						
					}).bind(this));
				
				}


		} else if (this.step==4) {
			
					
					if ($E('#tableMisure tr.addItem')) {
						addRow = $E('#tableMisure tr.addItem').clone();
						//addRow.getElements('input[type=text]').setProperty('value','');
						addRow.getElements('input[type=checkbox]').removeProperty('checked');
					}
					applyAddButtonBehaviour = (function() {
						$$('input.qta').addEvent('keypress', function(ev) {
							evt = new Event(ev);
							if (((evt.code>46)&&(evt.code<57))||(evt.code==8)||(evt.code==9)||(evt.code==46)) {}
							else {evt.stop();}
							//	GESTIRE PREVENT PULSANTI NON NUMBERS
						});
						//Log.print($$('#tableMisure .addMisura').length);
							$E('#tableMisure .addMisura').onclick = (function(ev) {						  
							evt = new Event(ev);							
							this.data.items[this.itemIndex].set('misure',null);
							this.data.items[this.itemIndex].set('misure',[]);
						
						//	GENERO LA LINEA CON PULSANTE DI AGGIUNTA DATI
							
							insert_row_tr = new Element('tr',{'id':'newRow','class':'newRow'});
							insert_row_td = new Element('td', {'colspan':addRow.getElements('td').length,'styles':{'text-align':'center'}});
							___r = addRow.clone();
							insert_row_button = new Element('input', {
																	'type':'button', 
																	'value':'Aggiungi',
																	'styles':{'margin':5},
																	'events':{
																		'click':function(ev) {
																			___r.injectAfter($('newRow'));
																			$$('.newRow').each(function(tr) {tr.remove();});																			
																			new applyAddButtonBehaviour();
																		}
																	}
															});
							insert_row_td.injectInside(insert_row_tr);
							insert_row_button.injectInside(insert_row_td);
							
			//	END LINEA "AGGIUNGI"
							
							$$('.addMisura').removeClass('addMisura');
							
							$$('#tableMisure tr.valueRow').each((function(tr, k) {
								obj = $H();
								tr.getElements('td').each(function(td) {
									if (tr.hasClass('addItem')) {
										type = (($defined(td.getChild()))&&(td.getChild().getProperty('type'))) ? td.getChild().getProperty('type') : '';
										if ((type=='button')) {
											td.setHTML('<a href="#" class="removeItem" rel="'+k+'">Cancella</a>');	
										} else {
											
											if ((td.hasClass('zanzariera'))||(td.hasClass('persiana'))||(td.hasClass('avvolgibile'))) {
												v = (td.getChild().getValue()) ? '<span class="ok">Si</span>' : '<span class="no">No</span>';
											} else 	v = (td.getChild().getValue()) ? td.getChild().getValue() : '--';
											td.setHTML(v);
											obj.set(td.className,v);
										}
										
									} else if (tr.hasClass('item')) {

										if (td.className.trim().length>0) {
											v = td.innerHTML.trim();
											obj.set(td.className,v);
										}
										
									}
								});
								
								this.data.items[this.itemIndex].get('misure')[k] = obj;
								if (tr.hasClass('addItem')) tr.removeClass('addItem').addClass('item');
							}).bind(this));
							
							//	PRINTO I VALORI REGISTRATI
							
							//removeRows = 							
							/*$$('#tableMisure .item','#tableMisure .addItem').each(function(r) {r.remove()});
							values = this.data.items[this.itemIndex].get('misure');
							
							values.each(function(row,k) {
								new Element('tr',{'class':'item'}).injectAfter($$('#tableMisure tr').getLast()).innerHTML=''+
								'<td class="qta">'+row.get('qta')+'</td>'+
								'<td class="misure">'+row.get('misure')+'</td>'+
								'<td class="tipologia">'+row.get('tipologia')+'</td>'+
								'<td class="num_ante">'+row.get('num_ante')+'</td>'+
								'<td class="zanzariera">'+((row.get('zanzariera')) ? 'Si' : 'No')+'</td>'+
								'<td class="persiana">'+((row.get('persiana')) ? 'Si' : 'No')+'</td>'+
								'<td class="avvolgibile">'+((row.get('avvolgibile')) ? 'Si' : 'No')+'</td>'+
								'<td><a href="#" class="removeItem" rel="'+k+'">Cancella</a></td>';
							});*/
							//$$('#tableMisure .removeItem').removeEvent('click', removeRows)
							$$('#tableMisure .removeItem').each((function(a) {
								a.onclick =  (function(ev) {
									evt =new Event(ev);
									evt.stopPropagation();
									
									$$('.item')[evt.target.getProperty('rel').toInt()].remove();
									new applyAddButtonBehaviour();
									
									/*	PROCEDURA DI RIALLINEAMENTO DATI (TABELLA / HASH)	*/
									obj = $H();	//azzero oggetto gestione misure
									this.data.items[this.itemIndex].set('misure',[]);	// azzero valori dell'oggetto
									
									$$('#tableMisure tr.item').each((function(tr,k) {
										$$('#tableMisure td').each((function(td) {
											if (td.className.trim().length>0) {
												v = td.innerHTML.trim();
												obj.set(td.className,v);
											}
										}).bind(this));
										this.data.items[this.itemIndex].get('misure')[k] = obj;
									}).bind(this));
									
									/*	*	*	*	*	*	*	*	*	*	*	*	*	*	*/
									
									$$('#tableMisure .removeItem').each(function(i,k) {
										i.setProperty('rel',k);
									});
									}).bind(this);
																	
								}).bind(this));
								//	AGGIUNGO UNA LINEA
								insert_row_tr.injectAfter($$('#tableMisure tr').getLast());	
								//Log.print(insert_row_tr.innerHTML)
								//insert_row_tr.injectInside($E('#tableMisure'));
								new applyAddButtonBehaviour();
							
						}).bind(this);
					//}).bind(this));
					//alert(this.data.items[this.itemIndex].get('misure').length);
					
					$$('select.tipologia').addEvent('change',function() {
						if (this.getProperty('value').test('scorrevole')) $$('input.num_ante').setProperty('disabled','disabled');
						else $$('input.num_ante').removeProperty('disabled');
					});
					$$('.riepilogoMisure tr.item').each(function(tr,k) {
						if (k%2) tr.addClass('alt');
					});
	
				}).bind(this);
				$$('input.num_ante').setProperty('disabled','disabled');
				new applyAddButtonBehaviour();
			
			
		} else if (this.step==5) {
			
				generateListItems = (function() {
					this.data.anagrafica.each(function(v,k) {
						out += ''+k+': <strong>'+v+'</strong><br/>';					
					});
					
					out='<table cellpadding="0" cellspacing="0">'+
						'<tr>'+
						"<th style=\width:70px;\">Quantita'</th>"+
						'<th style="width:380px;">Tipologia prodotto e dettagli</th>'+
						'<th style="width:70px;"></th>'+
						'<th></th>'+
					'</tr>';
					this.data.items.each(function(itm,k) {
												  
						qta = 0;
						if ($type(itm)=='object') {
							itm.get('misure').each(function(q) {
								qta += q.get('qta').toInt();						 
							})
							out+='<tr>'
							out += '<td class="qta">'+qta+'</td>';
							out += '<td>'+itm.get('tipologia')+' (<em>'+
							((itm.get('materiale')) ? itm.get('materiale') : itm.get('tipo'))+
							((itm.get('colore').trim().length>0) ? ', '+itm.get('colore'): ', nessun colore specificato')+
							'</em>)';
							//	DETTAGLIO ARTICOLO RICHIESTO
							out += '<div class="itemDetail"><strong>Dettagli</strong>:<br/>';
							
							
							itm.each(function(v,k) {
								if ((k!='misure')&&(k!='colore')&&(k!='materiale')&&(k!='tipologia')) out += k.capitalize()+': '+v.decode()+'<br/>';						
							})
								//if ((itm.get('misure'))&&(itm.get('tipologia').toLowerCase()=='infisso')) {
									out += "<strong>Quantita' e misure</strong>:";
									out += '<ol>';
									itm.get('misure').each(function(m) {
										out+='<li>';
										out+='N. <strong>'+m.get('qta').toInt()+'</strong> ';
										if (itm.get('tipologia')=='Infisso') {
											out+=itm.get('tipologia')+', <strong>'+m.get('tipologia')+' ';
											if ((m.get('tipologia')!='Finestra scorrevole')&&(m.get('tipologia')!='Porta scorrevole')) 
											out+='(numero ante: '+m.get('num_ante')+') ';
											out+='</strong>';
											}
										if (m.get('measure').trim()!='--') out+='di '+m.get('measure')+' cm<br/>';	
										else out+='(Nessuna misura specificata)<br/>';
										
										if (itm.get('tipologia')=='infisso') {
											out +='<strong>Accessori</strong>:<br/>'+
											'Avvolgibile: '+m.get('avvolgibile')+' | '+
											'Persiana: '+m.get('persiana')+' | '+
											'Zanzariera: '+m.get('zanzariera');
										}
										
										out+='</li>';										
									});
									out += '</ol>';									
								//}
							out += '</div>';
							
							out+='</td>'+
							'<td><a href="#" rel="'+k+'" class="showItemDetail">Dettaglio</a></td>'+
							'<td><a href="#" rel="'+k+'" class="removeItem">Rimuovi oggetto</a></td>';
							
							
							
							
							out+='</tr>';
						}
					});
					out+='</table>';
					
					outBox = new Element('div',{'class':'riepilogoMisure riepilogoItems'}).setHTML(out).injectAfter($E('#boxForm h2'));					
					addItem = new Element('div',{'class':'addNewItem'});
					addItemButton = new Element('input',{'type':'button','value':'Aggiungi nuovo prodotto','events':
						{
							'click':(function(ev) 
								{
									this.step=2;
									this.loadContent(ABS+'/inc/tmpl/preventivo_ajax.php?step=2')
								}).bind(this)
						}
					});
					
					addItemButton.injectInside(addItem);
					addItem.injectInside(outBox);
					
					
					this.html2send = out;
					$$('.itemDetail').setOpacity('0');
					$$('.riepilogoItems tr').each(function(tr,k) {
						if (k%2) tr.addClass('alt');
					});
					
					$$('a.showItemDetail').addEvent('click',(function(ev) {
						evt = new Event(ev);
						a= evt.target;
						tmp = '';
						detailElement = a.getParent().getPrevious().getElement('.itemDetail');
						if (detailElement.getStyle('opacity')!=0) {
							detailElement.fadeOut({duration:150,onComplete:function(t){t.setStyle('display','none')}});
						} else {
							detailElement.setStyle('display','block');
							detailElement.fadeIn({duration:150});
						}
					}).bind(this));
					
					//	PROCEDURA DI ELIMINAZIONE ARTICOLO
					$$('.removeItem').each((function(a) {
					
						a.onclick = (function(e) {
							if (confirm('Sei sicuro di eliminare l\'oggetto?')) {
								evt = new Event(e);
								tmpArray = [];
								this.data.items.each(function(obj,k) {
									if (k!=evt.target.getProperty('rel').toInt()) {
										tmpArray.extend([obj]);
									}
								});
								this.data.items = tmpArray
								$E('.riepilogoItems').remove();
								generateListItems();
							}
						}).bind(this);
					
					}).bind(this));
					
				}).bind(this);
				
				generateListItems();
				
			
		} else if (this.step==6) {
				//Log.print('uh?');
		}
		
		if ($E('#boxForm .nextBtn')) {
			$$('#submit_step_0').addEvent('click',(function(ev) {
				evt = new Event(ev);
				if (!this.getError()) {
					if ($$('#boxForm .error').length==0) {
						this.data.anagrafica = $H({
							nome:$('nome').getValue(),
							azienda:$('azienda').getValue(),
							tel:$('tel').getValue(),
							fax:$('fax').getValue(),
							email:$('email').getValue(),
							zona:$('zona').getValue()
						})		//	SAVING DATA IN THIS.DATA.ANAGRAFICA OBJECT
						this.step = evt.target.getProperty('rel').toInt();
						//this.loadContent(ABS+'/inc/tmpl/preventivo_ajax.php?step='+this.step)
						//Log.print($('boxForm').toQueryString());
						new Ajax(ABS+'/inc/tmpl/preventivo_ajax.php?step=send', {
								 	update:this.contentBox,
									data:'html='+el.innerHTML+'&'+$('boxForm').toQueryString()+'&ABS_URI='+ABS,
									onSuccess:function(r) {
											
									}
								 }).request();
					}
				}
				
				
			}).bind(this));	//	BEHAVIOUR PASSAGGIO ALLO STEP 2
			$$('#submit_step_2').addEvent('click',(function(ev) {
				evt = new Event(ev);
				if (!this.getError()) {
					tipologia = $$('#boxForm').toQueryString()[0].split('=')[1]
					this.data.items[this.itemIndex] = ($H({
						'tipologia':tipologia
					}));
					//Log.print($type(this.data.items[this.itemIndex]));

					this.step = evt.target.getProperty('rel').toInt();
					this.loadContent(ABS+'/inc/tmpl/preventivo_ajax.php?step='+this.step+'&tipologia='+tipologia)					
				}
			}).bind(this));	//	BEHAVIOUR PASSAGGIO ALLO STEP 3
			$$('#submit_step_3').addEvent('click',(function(ev) {
				evt = new Event(ev);
				if (!this.getError()) {
					$('boxForm').toQueryString().split("&").each((function(i) {
						key = i.split('=')[0];
						value = i.split('=')[1];
						//Log.print('KEY: '+key+', VALUE: '+value.decode()+' TIPO: '+$type(this.data.items[this.itemIndex]));
						this.data.items[this.itemIndex].set(key,value.decode());
					}).bind(this));
					this.step = evt.target.getProperty('rel').toInt();
					
					this.loadContent(ABS+'/inc/tmpl/preventivo_ajax.php?step='+this.step+'&tipologia='+this.data.items[this.itemIndex].get('tipologia'));
				}
			}).bind(this));	//	BEHAVIOUR PASSAGGIO ALLO STEP 4
			
			
			$$('#submit_step_4').addEvent('click',(function(ev) {
				if (confirm('Scegli OK per proseguire oppure ANNULLA per modificare la richiesta. \nScegliendo Ok nn ti sarą pił possibile modificare misure e quantitavi relativi a questo articolo.')) {
					evt = new Event(ev);
					out='';
					this.step = evt.target.getProperty('rel').toInt();
					if ($$('tr.item ').length>0){
						this.itemIndex++;
						this.loadContent(ABS+'/inc/tmpl/preventivo_ajax.php?step='+this.step)
					} else {
						alert('Non hai specificato alcun tipo di misura. Si prega di riprovare');
					}
				}
			}).bind(this));	//	BEHAVIOUR PASSAGGIO ALLO STEP 5

			$$('#submit_step_5').addEvent('click',(function(ev) {
				evt = new Event(ev);
				this.step = evt.target.getProperty('rel').toInt();
				this.loadContent(ABS+'/inc/tmpl/preventivo_ajax.php?step='+this.step)
				
			}).bind(this));
			
		}
		
		$$('#go_back_3').addEvent('click',(function(ev) {
			evt = new Event(ev);
			this.step = evt.target.getProperty('rel');
			this.loadContent(ABS+'/inc/tmpl/preventivo_ajax.php?step='+this.step);
		}).bind(this));

		$$('#go_back_4').addEvent('click',(function(ev) {
			evt = new Event(ev);
			this.step = evt.target.getProperty('rel');
			this.loadContent(ABS+'/inc/tmpl/preventivo_ajax.php?step='+this.step+'&tipologia='+this.data.items[this.itemIndex].get('tipologia'));
		}).bind(this));
		$$('#go_back_1').addEvent('click',(function(ev) {
			evt = new Event(ev);
			this.step = evt.target.getProperty('rel');
			this.loadContent(ABS+'/inc/tmpl/preventivo_ajax.php?step='+this.step);
		}).bind(this));

		$$('#go_step_back').addEvent('click',(function(ev) {
			evt = new Event(ev);
			this.step = evt.target.getProperty('rel').toInt();
			this.loadContent(ABS+'/inc/tmpl/preventivo_ajax.php?step='+this.step)
		}).bind(this));	//	BEHAVIOUR PASSAGGIO ALLO STEP 2
		if (window.ie6) {
			$$('.text').each(function(i) {
				i.addEvent('focus', function() { i.addClass('hover');});
				i.addEvent('blur', function() { i.removeClass('hover');});
			}); //	GESTION ON FOCUS ELEMENT FORM
		}
		if ((!window.ie6)&&($E('#boxForm .text'))) $E('#boxForm .text').focus();
		
		$$('#boxForm').addEvent('submit',function(ev) {
			new Event(ev).stop();
		});
		
		$$('a[href$=#]').addEvent('click', function(ev) {
			new Event(ev).stop();
		});
	}
	
});



window.addEvent('domready',function() {	
	$$('#preventivo a','a.preventivoRequest').addEvent('click',function(ev) {
		evt = new Event(ev);
		f = new FormBox();
		evt.stop();
	});
});
