var Site = {
	init: function() {
		Site.data = new Request.JSON({url: 'scripts/data.json', onSuccess: Site.load}).send();
		Site.tip = document.id('tooltip').setStyles({'opacity': 0, 'visibility': 'hidden'});
		Site.tip.set('tween', {duration: 350});
		Site.arrows();
		Site.external();
		Site.guida();
		Cards.init();
	},
	load: function(json) {
		Site.types = new Hash(json.Types);
		Site.legenda = new Hash(json.Legenda);
		Site.fishes = new Hash(json.Fishes);
		Site.icons = [];
		Site.legenda.each(function(legend, key) {
			Site.legenda.set(key.toLowerCase(), legend);
			var icon = key.toLowerCase();
			var icons = $$('.' + icon + '-icon');
			Site.iconsEvents(icons);
		});
	},
	external: function() {
		$$('.external').each(function(el) {
			el.setProperty('target', '_blank');
		})
	},
	iconsEvents: function(icon) {
		var items = icon || Site.icons;
		items.addEvents({
			'mouseenter': function() {
				var cls = this.className.replace('-icon', '').replace('hover', '').trim().clean();
				this.addClass('hover');
				var pos = {
					top: this.getPosition().y - Site.tip.getSize().y + 3,
					left: this.getPosition().x - Site.tip.getSize().x + 47
				};
				Site.tip.setStyles(pos).className = cls;
				Site.tip.getFirst().set('text', Site.legenda.get(cls).text);
				if (Browser.Engine.trident) Site.tip.setStyle('opacity', 1);
				else Site.tip.fade('in');
			},
			'mouseleave': function() {
				this.removeClass('hover');
				if (Browser.Engine.trident) Site.tip.setStyle('opacity', 0);
				else Site.tip.fade('out');
			}
		});
	},
	arrows: function() {
		((Browser.Engine.trident) ? document : window).addEvent((Browser.Engine.webkit || Browser.Engine.trident) ? 'keydown' : 'keypress', function(e) {
			var previous = document.body.getElement('.arrows .previous');
			var next = document.body.getElement('.arrows .next');
			var esc = document.body.getElement('.hints .key');
			var wrapper = document.id('scheda-wrapper');

			if (!document.id('scheda')) return;
			if (e.key == 'right' && next.get('href')) {
				
				if (!esc) window.location = next.get('href');
				else if (wrapper && !next.hasClass('spinner') && !previous.hasClass('spinner')) next.fireEvent('click');
				else if (next.hasClass('spinner') || previous.hasClass('spinner')) e.stop();
				else window.location = next.get('href');
			} else if (e.key == 'left' && previous.get('href')) {
				if (!esc) window.location = previous.get('href');
				else if (wrapper && !previous.hasClass('spinner') && !next.hasClass('spinner')) previous.fireEvent('click');
				else if (previous.hasClass('spinner') || next.hasClass('spinner')) e.stop();
				else window.location = previous.get('href');
			}
			else if (e.key == 'esc') Cards.close();
		});
	},
	guida: function() {
		var guida = document.id('guida');
		var content = guida.getElement('.content').empty();
		var button = document.id('guida-button');
		new Request({
			url: '/guida.html',
			onSuccess: function(response) {
				content.set('html', response);
			}
		}).send();
		
		guida.store('pesci_fx', new Fx.Tween(guida.store('status', true), {
			duration: 300,
			onComplete: function() {
				if (!this.to[0].value) guida.store('status', false);
				else guida.store('status', true);
			}
		}).set('left', -602));
		content.store('pesci_scroll', new Fx.Scroll(content, {wheelStops: false}));
		var fx = guida.retrieve('pesci_fx');
		button.addEvent('click', function(e) {
			if (e) e.stop();
			if (guida.retrieve('status')) {
				fx.start('left', 0);
				button.removeClass('open').addClass('close');
			}
			else {
				fx.start('left', -602);
				button.addClass('open').removeClass('close');
			}
		});
	}
};

var Cards = {
	init: function() {
		Cards.fishes = $$('.box a');
		Cards.wrapper = document.id('scheda-wrapper') || new Element('div', {id: 'scheda-wrapper'}).inject(document.body).set('opacity', 0);
		Cards.wrapper.set('morph', {'transition': 'back:out', 'duration': 500});
		Cards.request = new Request.HTML({onSuccess: Cards.success});
		Cards.fishList = {};
		Cards.fishes.each(function(fish) {
			fish.addEvent('click', function(e) {
				e.stop();
				Cards.fishes.getParent('li').removeClass('loading');
				fish.getParent('li').addClass('loading');
				_gaq.push(['_trackPageview', this.href.cleanURI()]);
				Cards.request.cancel().get(this.href);
			});
			
			Cards.fishList[fish.href] = fish;
		});
		
		if (document.id('scheda')) Cards.hookGuida(document.id('scheda'));
		Cards.altButton = Cards.wrapper.getElement('.alternatives');
		Cards.alt = Cards.wrapper.getElement('.alternative-wrapper') || document.id('container').getElement('.alternative-wrapper');
		
		Cards.scrollbar = document.id(document.body).getElement('.alternative-scrollbar');
		Cards.knob = Cards.scrollbar ? Cards.scrollbar.getElement('.alternative-knob') : false;
		
		if (Cards.alt) Cards.sameButtons();
		
	},
	
	success: function(tree, elements, html, js) {
		var scheda = document.id('scheda');
		var tmp = new Element('div', {'class': 'trash'}).inject(document.body).adopt(tree);
		scheda = tmp.getElement('.grid-9');
		
		new Asset.image(scheda.getElement('.image img').get('src'), {
			onload: function() {
				Cards.fishes.getParent('li').removeClass('loading');
				
				if (!Cards.wrapper.innerHTML.length) {
					Cards.wrapper.setStyles({
						'top': -200,
						'left': document.id('green').getPosition().x - 4,
						'opacity': 0
					});
				}
				
				Site.iconsEvents(scheda.getElements('.note span'));
				scheda.getElement('a.home').removeClass('home').addClass('close');
				if (!Cards.wrapper.innerHTML.length) {
					Cards.hookGuida(scheda);
					scheda.getElements('.arrows a').addEvent('click', function(e) {
						if (e) e.stop();
						var spinner = scheda.getElements('.arrows a').hasClass('spinner').contains(true);
						if (!this.hasClass('home') && !this.hasClass('close') && !this.hasClass('spinner') && !spinner) {
							this.addClass('spinner');
							_gaq.push(['_trackPageview', this.href.cleanURI()]);
							Cards.request.cancel().get(this.href);
						}
						else if (this.hasClass('spinner') || spinner) e.stop();
						else Cards.close();
					});
					scheda.inject(Cards.wrapper);
					
					scheda.getElements('.same-list a').each(function(same) {
						same.addEvent('click', function(e) {
							e.stop();
							_gaq.push(['_trackPageview', this.href.cleanURI()]);
							Cards.fishList[this.href].fireEvent('click', e);
						});
					});
					
					Cards.altButton = Cards.wrapper.getElement('.alternatives');
					Cards.alt = Cards.wrapper.getElement('.alternative-wrapper');
					if (Cards.alt) Cards.alternatives();

					Cards.wrapper.morph({
						'top': document.id('green').getPosition().y + window.getScroll().y,
						'opacity': 1
					});
				} else {
					Cards.wrapper.morph({
						'top': document.id('green').getPosition().y + window.getScroll().y
					});
					var wrappers = Cards.wrapper.getElements('.grid-9').addClass('trash-wrappers');
					wrappers.getElements('.arrows a').each(function(a) { a.removeEvents(); });
					scheda.setStyle('opacity', 0).inject(Cards.wrapper);
					Cards.hookGuida(scheda);
					
					scheda.getElements('.arrows a').addEvent('click', function(e) {
						if (e) e.stop();
						var spinner = scheda.getElements('.arrows a').hasClass('spinner').contains(true);
						if (!this.hasClass('home') && !this.hasClass('close') && !this.hasClass('spinner') && !spinner) {
							this.addClass('spinner');
							_gaq.push(['_trackPageview', this.href.cleanURI()]);
							Cards.request.cancel().get(this.href);
						}
						else if (this.hasClass('spinner') || spinner) e.stop();
						else Cards.close();
					});
					
					wrappers.set('tween', {
						onComplete: function() { 
							this.element.empty().dispose();
						}
					});
					
					wrappers.tween('opacity', 0);
					scheda.fade(1);
									
					scheda.getElements('.same-list a').each(function(same) {
						same.addEvent('click', function(e) {
							e.stop();
							_gaq.push(['_trackPageview', this.href.cleanURI()]);
							Cards.fishList[this.href].fireEvent('click', e);
						});
					});
					
					Cards.altButton = scheda.getElement('.alternatives');
					Cards.alt = scheda.getElement('.alternative-wrapper');
					if (Cards.alt) Cards.alternatives();
				}
				
				tmp.empty().dispose();
			}
		});
	},
	hookGuida: function(scheda) {
		scheda.getElements('.helpz').each(function(keyword) {
			keyword.addEvent('click', function(e) {
				e.stop();
				var guida = document.id('guida');
				if (guida.retrieve('status')) document.id('guida-button').fireEvent('click');
				guida.getElement('.content').retrieve('pesci_scroll').toElement(this.get('rel'));
			});
		});
	},
	close: function() {
		if (Cards.wrapper) {
			Cards.wrapper.set('morph', {
				'transition': 'back:out', 
				'duration': 500,
				onComplete: function() { 
					Cards.wrapper.empty().get('morph').removeEvents('onComplete');
				}
			});
			Cards.wrapper.morph({'opacity': 0, 'top': -200});
		}
	},
	alternatives: function() {
		if (!Cards.alt.retrieve('consumare:height')) Cards.alt.store('consumare:height', Cards.alt.getSize().y);
		Cards.alt.setStyle('top', -Cards.alt.retrieve('consumare:height'));
		
		Cards.scrollbar = document.body.getElements('.alternative-scrollbar').getLast();
		Cards.knob = Cards.scrollbar ? Cards.scrollbar.getElement('.alternative-knob') : false;
		
		Cards.sameButtons();
		
		Cards.alt.setStyle('display', 'none');
		Cards.altButton.addEvents({
			'click': function() {
				Cards.alt.set('tween', {duration: 350, transition: 'sine:in', 'link': 'cancel', onStart: function() { Cards.alt.store('consumare:fx', !Cards.alt.retrieve('consumare:fx')); }, onComplete: function() { if (!Cards.alt.retrieve('consumare:fx')) Cards.alt.setStyle('display', 'none'); }});
			
				if (Cards.alt.retrieve('consumare:fx')) {
					this.removeClass('pushed');
					Cards.alt.tween('top', -Cards.alt.retrieve('consumare:height'));
					Cookie.write('consumaregiusto', 0);
				} else {
					this.addClass('pushed');
					Cards.alt.setStyle('display', 'block').tween('top', 0);
					Cookie.write('consumaregiusto', 1);
				}
			},
			'mouseenter': function() { this.addClass('hover'); },
			'mouseleave': function() { this.removeClass('hover'); }
		});
		
		if (Cookie.read('consumaregiusto') == 1 && !Cards.alt.retrieve('consumare:fx')) Cards.altButton.fireEvent('click');
	},
	sameButtons: function() {
		var max = 0, sum = 0, superSum = 0, alternatives = Cards.alt.getElements('.alternative');
		Cards.alt.getElements('.alternative').each(function(alt) {
			var size = alt.store('consumare:altSize', alt.getSize());
			sum += alt.retrieve('consumare:altSize').x;
			$H(alt.getStyles('padding-left', 'padding-right')).each(function(val) { sum += val.toInt(); superSum += val.toInt(); });
			max = Math.max(alt.retrieve('consumare:altSize').y, max);
		});
		
		superSum = sum - superSum;
		
		if (Cards.alt.getElement('.alternative-container').getSize().x < sum) {
			if (sum < 619) {
				var width = 0;
				Cards.alt.getElements('.alternative').each(function(alt) {
					width += (alt.getSize().x + alt.getStyle('margin-left').toInt());
				});
				
				Cards.alt.setStyles({'overflow': 'hidden', 'width': width + 24 });
				Cards.scrollbar.setStyle('display', 'none');
			}
			else {
				Cards.alt.setStyles({'width': '90%'});
				Cards.alt.getElement('.alternative-container').setStyle('width', sum + 2);
				Cards.scrollbar.setStyle('display', 'block');
			}
			
			Cards.alt.store('consumare:height', Cards.alt.getSize().y);
			if (!document.id('tables').getElement('.grid-9')) Cards.alt.setStyle('top', -Cards.alt.retrieve('consumare:height'));
		} else {
			Cards.scrollbar.setStyle('display', 'none');
			var margin = Cards.alt.getElement('.alternative-container').getSize().x - superSum;
			if (alternatives.length > 1) Cards.alt.getElement('.alternative').setStyle('margin-left', margin / 2);
			else Cards.alt.getElement('.alternative').setStyles({'padding-left': Cards.alt.getElement('.alternative').getStyle('padding-right'), 'margin-left': 0});
		}
		
		Cards.alt.getElements('.alternative').each(function(alt) {
			var marginTop = max - alt.retrieve('consumare:altSize').y;
			alt.getElement('.button').setStyle('margin-top', marginTop);
			if (document.id('tables').getChildren().length >= 4) {
				alt.getElement('.button').addEvents({
					'click': function(e) {
						e.stop();
						_gaq.push(['_trackPageview', this.href.cleanURI()]);
						Cards.fishList[this.href].fireEvent('click', e);
					},
					'mousedown': function() {this.addClass('focus');},
					'mouseup': function() {this.removeClass('focus');},
					'mouseleave': function() {this.removeClass('focus');}
				});
			}
		});
		
		$$('.alternative-shadowright', '.alternative-shadowleft').setStyle('height', Cards.alt.getElement('.alternative-container').getSize().y);
		this.doScrollbars();
	},
	
	doScrollbars: function() {
		var card = Cards.alt.getElement('.alternative-padding');
		var knobWidth = card.getSize().x * Cards.scrollbar.getSize().x / card.getScrollSize().x;
		var scrollSize = card.getScrollSize().x;
		
		card.scrollTo(0, 0);
		Cards.knob.setStyle('width', knobWidth).makeDraggable({
			'container': Cards.scrollbar, 
			modifiers: {'x': 'left', 'y': false}, 
			onDrag: function() {
				var now = this.value.now.x;
				var scroll = scrollSize * now / Cards.scrollbar.getSize().x;
				card.scrollTo(scroll, 0);
			}
		});
	}
};

String.implement({
	cleanURI: function() {
		var uri = window.location.protocol + '//' + window.location.hostname + '/';
		return this.replace(uri, '');
	}
});

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