// JavaScript Document
Number.implement({
	toStringWithPrecision: function (decimals) {
		var rounded = this.round(decimals).toString();
				
		rounded += (!rounded.contains("."))? ".": "";
		
		return rounded + "0".repeat((decimals - (rounded.length - (rounded.indexOf(".")+1))).limit(0, decimals));
	}
});

var Site = {
	init: function () {
		if ($('menu')) { var m = new Menu(); }				
		if ($('header-content')) { var h = new Header(); }
		if ($('footer-content')) { Mail.link($('footer-content')); }
		if ($('quick_info')) { Mail.link($('quick_info')); }
		if ($('enter')) { $('enter').set('html', '<a href="html/main.html">[&nbsp;Entra&nbsp;nel&nbsp;Sito&nbsp;]</a>'); }
	}
	
}

var Menu = new Class ({
	Implements: Chain,
	initialize: function() {
		var self = this;
		
		// Array di FX
		var fxs = new Array();
		
		this.fx = new Array();
		
		// La root del men
		var root = $('menu');
		
		this.error = 0;
		
		var content = $('content');
		
		this.items_container = $('items_container');
		
		this.main_wrapper = new Element ('div', {id:'main_wrapper'}).inject(content).grab(this.items_container);
		
		this.main_wrapper.store('slide', this.fx_Slide = new Fx.Slide (this.main_wrapper, { duration:800, mode:'horizontal' }));
		
		this.disclaimer = new Element ('div', {id:'disclaimer'})
						.inject(this.main_wrapper).setStyle('display', 'none');
				
		this.form = new Element ('div', {id:'form_sell'})
						.inject(this.main_wrapper).setStyle('display', 'none');
						
		this.form_validator = null;
		
		this.request = new Request.Queue({stopOnFailure: true,autoAdvance:true,concurrent:2 });
		
		// AJAX Request per il men
		var r_menu = new Request.JSON ({
				url: '../data/menu/info.json',
				method: 'post',
				onFailure: function() {
					self.error = 1;
					self.generateErrorState('del men&ugrave;');
				},
				onSuccess: function (jsonObj) {
					jsonObj.level1.each(function (e) {
						/*
							Si costruisce la struttura:
								<li>
									<a href="#" rel="0"><span>Sezione</span></a>
									<ul>
										<li><a href="#">Voce</a></li>
									</ul>
								</li>
							
							per il men.
						*/
						var li = new Element('li').inject(root);
						var a = new Element('a', {
									'href': '#',
									'rel' : e.id
								}).inject(li);
						var span = new Element('span').set('html', e.nome).inject(a);
						
						// Se esistono le sotto sezioni
						if (e.sezioni != null) {
							var ul = new Element('ul').inject(li);
							
							// Si aggiunge la possibilit di aprire e chiudere il sottomen
							fxs.push(new Fx.Slide(ul, {duration: 350}).hide());
							self.addOpenAbility(a, fxs[fxs.length-1]);
							
							// per ciascuna sezione si ripete la costruzione del link
							e.sezioni.each (function (sube) {
							
								var subli = new Element ('li').inject(ul);
															
								var suba = new Element ('a', {'href' : '#'})
										.addEvent('click', self.generateSection.bindWithEvent(self, sube))
										.set('html', sube.nome)
										.inject(subli);
								
								
								// si carica la sezione di default
								if (sube.iniziale) self.generateSection.run([null, sube], self);

							});
						}
					});
				}
		});
		
						
		var r_disclaimer = new Request.HTML({
					url: '../data/order/disclaimer.html',
					update: self.disclaimer,
					onFailure: function () {
						self.error = 1;
						self.generateErrorState('del servizio prenotazioni online');
					},
					onSuccess: function (html) {
						Mail.link(self.disclaimer);
						$('disclaimer_back').addEvent('click', function(e){
								e = new Event(e).stop();
								self.fx_Slide.toggle().chain(function () {
									self.disclaimer.setStyle('display', 'none');
									self.items_container.setStyle('display', 'block');
									self.fx_Slide.toggle();
								});
						});
						
						$('disclaimer_go').addEvent('click', function(e){
								e = new Event(e).stop();
								self.fx_Slide.toggle().chain(function () {
									self.disclaimer.setStyle('display', 'none');
									self.form.setStyle('display', 'block');
									self.fx_Slide.toggle();
								});
						});	
					}
			});
			
		var r_form = new Request.HTML({
					url: '../data/order/form.html',
					update: self.form,
					onFailure: function () {
						self.error = 1;
						self.generateErrorState('del servizio prenotazioni online');
					},
					onSuccess: function (html) {
						
						var legend = new Element('fieldset').inject($('mailform'), 'top').setStyle('display', 'none');
						
						var return_label = new Element('label').inject(legend);
						
						var formBehaviour = function (d, stop) {
							var c = new Chain();
							
							c.chain(
								function () {
									legend.setStyle('display', 'block');
								},
								(function () {
									
									legend.setStyle('display','none');
									if (stop == 1) {
										self.form.setStyle('display', 'none');
										self.items_container.setStyle('display', 'block');
									}
									/*self.form.getElements('fieldset').each(function(e){
										if (e != legend) e.setStyle('display', 'block');
									});*/
														
								}).delay(d));
							
							c.callChain();
						};
						
						$('mailform').addEvent('reset', function(e) {
							e.stop();
							self.fx_Slide.toggle().chain(function(){
								self.form.setStyle('display', 'none');
								self.items_container.setStyle('display', 'block');
								self.fx_Slide.toggle();
							});
						});
						
						if (self.form_validator == null) 
							self.form_validator = new FormCheck ('mailform', {
								submitByAjax: true,
								onAjaxSuccess: function (response){
									var msg = response.split('|');
									
									return_label.set('html', msg[1]);
									
									switch(msg[0]) {
										case '0': {	formBehaviour.run(['4000', 1]); } break;
										case '2': {	formBehaviour.run(['4000', 1]); } break;
										case '1': { formBehaviour.run(['2000', 0]); } break;
									}
								},
								display: {fadeDuration:100}
							});
					}
			});
			
		this.request.addRequest('menu', r_menu);
		this.request.addRequest('disclaimer', r_disclaimer);
		this.request.addRequest('form', r_form);
		r_menu.send();
		r_disclaimer.send();
		r_form.send();			
	}, 
	addOpenAbility: function (a, fx) {
		a.addEvent ('click', function (e) {
			e = new Event(e).stop();
			fx.toggle();
		});
	},
	generateErrorState: function(msg) {
		var menu = $('menu').setStyle('display', 'none');
		var container = $('items_container');
		
		var error_div = new Element('div', {id:'info'})
						.inject(container);
		var error_div_container = new Element('div', {'class':'info_container'})
						.inject(error_div)
						.set('html', '<h3>ATTENZIONE</h3>&Egrave; stato rilevato un errore durante il caricamento <strong>'+ msg + '</strong>. <br />Al fine di risolvere al pi&ugrave presto il problema tecnico, si prega di contattare l\'amministratore del sito al seguente indirizzo e-mail: ');
						
		var error_link = new Element('a', {'rel':'info AT officeproservice DOT it'}).set('html', 'info AT officeproservice DOT it').inject(error_div_container);
		
		
		
		Mail.link(container);
	},
	generateSection: function (e, elem) {
		if (e != null) e.stop();
		
		var fxs = [];
		
		var self = this;
		
		if (self.items_container.getStyle('display') == 'none') {
			self.fx_Slide.toggle().chain(function(){
								self.form.setStyle('display', 'none');
								self.disclaimer.setStyle('display', 'none');
								self.items_container.setStyle('display', 'block');
								self.fx_Slide.toggle();
							});
		}					

								
		// Si cancellano tutti gli elementi visualizzati in precedenza (escluso il titolo)
		self.items_container.empty();
									
		// Rimpiazza il titolo della Sezione
		var title = $('title').getElement('h2').set('html', elem.nome);
		
		var section = null;
		
		// Se la sezione da rimpiazzare  dinamica...
		if (elem.file_dati.contains(".json")) {
			
			var error = self.error;

			// Richiede i dati della sezione
			section = new Request.JSON({
										
				url: '../data/catalogo/' + elem.file_dati,
				method: 'post',
				onFailure: function() {
					self.error = 1;
					self.generateErrorState('della sezione ' + elem.nome);
				},
				onSuccess: function (jsonObj) {
								
					jsonObj.oggetti.each(function(o){
						/*
							Si crea la struttura espositiva come:
													
							<div class="item"> 
								<div class="item_content">
									<div class="leftcol">
										<img src="	" />
									</div>
									<div class="rightcol">
								 		<h4> Oggetto </h4>
										<p class="item_text"> Descrizione Oggetto </p>
										<p class="item_price">Euro: Prezzo oggetto</p>
									</div>
				 				</div>
				 			</div>
						*/
						var div_item = new Element('div', {'class':'item'})
									.inject(self.items_container);
						var div_item_content = new Element ('div', {'class':'item_content'})
											.inject(div_item);
						var div_leftcol = new Element ('div', {'class':'leftcol'})
										.inject(div_item_content);
						
						/*var img_big_link = new Element('a')
										.inject(div_leftcol)
										.addEvent('click', function(e){
												var newImg = new Image();
												newImg.src = '../img/items/big/'+o.immagine;
												var height = newImg.height;
												var width = newImg.width;
												Mediabox.open('../img/items/big/'+o.immagine, o.nome, width + ' ' +height)
										});	*/	
										
						var img = new Element ('img', {'src': /*'../img/items//*small'*/ '../img/items/' + o.immagine })
									.inject (/*img_big_link*/div_leftcol);
									
						var div_rightcol = new Element ('div', {'class':'rightcol'})
										.inject(div_item_content);
												
						var h4 = new Element ('h4')
									.set('html', o.nome)
									.inject(div_rightcol);
									
						if (o.descrizione) {
							var open = new Element ('a', 
											{	
												'class': 'open_item',
												'href': '#'
											})
											.inject(div_rightcol)
											.set("text", "Descrizione");
											
							var span = new Element('span')
										.set('html', '&nbsp;')
										.inject(open, 'top');
										
							var p_text = new Element('p', {'class':'item_text'})
										.set('html', o.descrizione)
										.inject(div_rightcol);
												
							var fx = new Fx.Slide(p_text, {duration: 150}).hide();
							fxs.push(fx);
					
							open.addEvent('click', function(ev){
												new Event(ev).stop();
												this.setStyle ('border-bottom-style',	 
												((this.getNext().getSize().y == 0) ?'dashed':'solid')); 
												fx.toggle();
							});
						}
						
												
						var p_price = new Element('p', {'class':'item_price'})
									.set('html', 'Euro:&nbsp;'+ o.prezzo.toStringWithPrecision(2))
									.inject(div_rightcol);
									
						if ((o.codice) && (error == 0)) {
							var a_multibox = new Element('a', 
											{
												'class':'buy_item',
												'href':'#'
											})
											.inject(p_price, 'top')
											.set('html', 'Prenota l\'offerta direttamente alla modica cifra di ')
											.addEvent('click', self.sellIt.bindWithEvent(self, [o.codice, o.nome]));
						}
									
					});
					// si verificano eventuale email
					Mail.link(self.items_container);
				}
			});										
		}	
		else {
			
			// se  una pagina statica (html) la si richiede la pagina e la si inserisce nella sezione opportuna (content)
			section = new Request.HTML({
					url: '../data/info/' + elem.file_dati,
					evalScripts:true,
					evalResponse:true,
					update: self.items_container,
					onFailure: function() {
						self.error = 1;
						self.generateErrorState('della sezione ' + elem.nome);
					},
					onSuccess: function () {
						// si verificano eventuali email
						Mail.link(self.items_container);
					}
			});
		}	
		
		this.request.addRequest('section', section);
		section.send();
	
	},
	sellIt: function (e, code, title) {
		e.stop();
		$('item_title').setProperty('value', title);
		$('item_code').setProperty('value', code);
		
		this.fx_Slide.toggle().chain(
				function(){
					this.items_container.setStyle('display','none');
					this.disclaimer.setStyle('display', 'block');
					this.fx_Slide.toggle();
		}.bind(this));
	}
});

var Header = new Class ({
	initialize: function () {
		var header = $('header');
		var info = $('quick_info');
		var info_fx = new Fx.Tween (info, {duration: 100, wait:false}).set('opacity', 0);
		var h1 = new Fx.Tween (header.getElement('h1'), { duration:500, wait:true });
	
		var link = header.getElement('h1').getFirst();
		
		link.addEvent('click', function(e){
			e = new Event(e).stop();
			
			h1.start('opacity', 1, 0.05)
				.chain(function()
					{	info_fx.start('opacity', 0, 1)
						.chain(function() 
								{	info_fx.start.delay(7500, info_fx, ['opacity', 1, 0] ); } )
						.chain(function()
								{	h1.start('opacity', 0.05, 1); }); 
				});
		});
	}
});

var Mail = {
	link: function (root) {
		var as = root.getElements('a');
		
		as.each(function(l) {
			email = l.getProperty('rel');
			text = l.get('html');
			
			if (email != null) {
				
				if (email.contains(' DOT ') && email.contains(' AT ')) {
					numail = email.replace(' AT ', '@').replace(' DOT ', '.');
					l.setProperty('href', 'mailto:'+numail);

					if (text.contains(email)) l.set('html', text.replace(email, numail));
				}
			
			}
		});
	}
} 

window.addEvent ('domready', Site.init);
