// Copyright (c) 2007-2010 WoollySheep
// <info@woolly-sheep.net>
// <http://www.woolly-sheep.net>

var Site = {
	start: function() {
		new SmoothScroll();
		Site.scroller = new Fx.Scroll(document.body);
		Site.pulsing();
		Site.program();
		Site.imgRounds();
		Table.init();
		Gallery.init();
	},
	
	imgRounds: function() {
		$$('div.people').setStyles({
			'-moz-border-radius': '15px',
			'-webkit-border-radius': '15px',
			'radius': '15px'
		});
	},

	pulsing: function() {
		var div = $$('.winners')[0], calendar = $$('.calendar')[0];
		if (!div) return Site;
		
		div.addEvent('click', function(){
			var winners = $('thewinners');
			if (winners) Site.scroller.toElement(winners);
			else window.location.href = '/#winners';
		});
		
		if (calendar) {
			calendar.addEvent('click', function() {
				window.location.href= '/?o=calendar#calendario';
			});
		}

		Site.fx = new Fx.Tween(calendar, {
			duration: 800, 
			transition: 'quad:in:out', 
			onComplete: function() {
				if (this.to[0].value == 1) Site.fx.start('opacity', 0.3);
				else Site.fx.start('opacity', 1);
			}
		}).set('opacity', 1).start('opacity', 0.3);
	},
	
	program: function() {
		if (!$('tbl_programma') || !$$('.legend')) return;
		$$('.legend li').each( function(li) {
			li.setStyle("cursor", "pointer");
			var classname = li.getElement('span').getProperty('class');
			var curbg = li.getElement('span').getStyle('background-color');
			li.addEvents({
				'mouseover': function() {
					$$('#tbl_programma .' + classname).each( function(el) {
						var effetto = new Fx.Tween(el, {duration: 400, transition: Fx.Transitions.Quad.easeOut});
						effetto.start('background-color', '#fff', curbg);
					});
				},
				'click': function() {
					$$('#tbl_programma .' + classname).each( function(el) {
						var effetto = new Fx.Tween(el, {duration: 600, transition: Fx.Transitions.Quad.easeOut});
						effetto.start('background-color', '#fff', curbg);
					});
				}
			});
		});
	}
};

var Table = {
	init: function() {
		var calendar = $('table-calendar');
		if (!calendar) return Table;
		
		Table.els = calendar.getElements('tbody tr').filter(function(tr) {
			return !tr.className.test('days');
		}).getChildren();
		
		Table.days = {
			"8": $$('tr.days th:nth-child(2)'), 
			"9": $$('tr.days th:nth-child(3)'),
			"10": $$('tr.days th:nth-child(4)'), 
			"11": $$('tr.days th:nth-child(5)'), 
			"12": $$('tr.days th:nth-child(6)')
		};
		
		$$('.external').set('target', '_blank');
		
		if (Browser.Engine.trident) {
			var legends = $$('th.legend'), wrappers = $$('.legend-wrapper');
			if (legends.length && legends.length == wrappers.length) {
				(function() {wrappers.each(function(wrapper, i) {
					legends[i].inject(wrapper);
				});}).delay(5000);
			}
		}
		
		Table.tds();
		Table.events();
	},
	
	tds: function() {
		Table.tds = [];
		Table.els.each(function(el) {
			Table.tds.push(el.slice(1));
		});
//		.log(Table.tds[0]);
	},
	
	events: function() {
		Table.tds.each(function(tds, i) {
			if (!tds.length) return;
			tds.each(function(td, j) {
				td.addEvents({
					'mouseenter': function() {Table.getTitle(td, i, j).addClass('highlight');Table.toggleZoom(td); },
					'mouseleave': function() {Table.getTitle(td, i, j).removeClass('highlight');Table.toggleZoom(td); },
					'click': function() {if (td.className.test("dsc-")) return Details.open(td);}
				});
			});
		});
	},
	
	toggleZoom: function(td) {
		if (!td.className.test("dsc-")) return;
		td.toggleClass('zoom');
	},
	
	getTitle: function(td, index, position) {
		return $$(Table.getHour(td, index), Table.getDay(td, position));
	},
	
	getHour: function(td, index) {
		var rowspan = td.get('rowspan') || false;
		if (rowspan <= 1) return Table.els[index][0];
		else {
			var tmp = [];
			(rowspan).times(function(j) {
				tmp.push(Table.els[index + j][0]);
			});
			return $$(tmp);
		}
	},
	
	getDay: function(td, position) {
		if (!td.retrieve('days')) {
			var dates = td.className.split(' ');
			dates = dates.pop();
			dates = dates.split("-").slice(1);
			td.store("days", dates);
		} else dates = td.retrieve("days");
		var tmp = [];
		dates.each(function(day) {
			tmp.push(Table.days[day]);
		});
		return tmp;
	}
};

var Details = {
	doOvrly: function() {
		if (!Details.ovrly) {
			Details.ovrly = new Element('div', {'class': 'ovrly', 'styles': {'opacity': 0}}).inject(document.body);
			Details.ovrlyFx = new Fx.Morph(Details.ovrly, {link: 'chain', duration: 200, transition: 'quad:out'});
		}
		
		var size = window.getScrollSize();
		Details.winSize = {
			'size': window.getSize(),
			'scroll': window.getScroll()
		};
		Details.ovrly.setStyles({'width': size.x + ((Browser.Engine.webkit) ? -15 : 0), 'height': size.y});
		if (Browser.Engine.presto) Details.ovrly.setStyle('width', Details.winSize.size.x);
		
		return Details.ovrly;
	},
	doBox: function() {
		if (!Details.ovrly) Details.doOvrly();
		if (!Details.box) {
			Details.box = new Element('div', {
				'class': 'opacity',
				'styles': {
					'-moz-border-radius': '15px',
					'-webkit-border-radius': '15px',
					'radius': '15px'
				}
			}).inject(document.body);
			Details.closeButton = new Element('div', {'class': 'close-button'}).set('opacity', 0).inject(Details.box, 'top');
			Details.fx = new Fx.Morph(Details.box, {duration: 600, transition: 'circ:in:out'});
			
			Details.closeButton.addEvent('click', function() {
				var coords = Details.current.retrieve('calendar:coords');
				Details.closeButton.fade('out');
				Details.fx.start({
					'width': coords.width,
					'height': coords.height,
					'top': coords.top,
					'left': coords.left,
					'opacity': 0
				});
				Details.ovrlyFx.start({'opacity': 0});
			});
		}
		
		return Details.box;
	},
	doTabs: function() {
		var tabs = Details.box.getElements('.tab'), fxs = [];
		if (!tabs.length) return;
		
		var tabsBar = new Element('div', {'class': 'tabs-bar'}).inject(Details.box, 'top');
		tabs.each(function(tab, i) {
			var title = "";
			var fx = new Fx.Tween(tab, {duration: 300, link: 'cancel'}).set('opacity', (!i) ? 1 : 0);
			fxs.push(fx);
			if (!i) title = "Dettagli Evento";
			else {
				title = tab.getElement('h1').get('html');
				tab.setStyle('display', 'none');
			}
			
			if (tab.getScrollSize()) tab.getElements('.people').setStyle('width', 680);
			
			var button = new Element('div', {'class': 'tab-button'}).inject(tabsBar).adopt(new Element('span').set('html', title));
			if (!i) button.addClass('active');
			button.addEvents({
				'click': function() {
					tabsBar.getElements('.tab-button').removeClass('active');
					this.addClass('active');
					fxs.each(function(fxx, j) {
						if (j != i) {tabs[j].setStyle('display', 'none'); fxx.start('opacity', 0);}
						else {tabs[j].setStyle('display', 'block'); fxx.start('opacity', 1);}
					});
					if (Details.box.getScrollSize().y > Details.box.getSize().y) {
						Details.box.setStyles({
							'-moz-border-radius': '15px 0 0 15px',
							'-webkit-border-bottom-right-radius': '0 0',
							'-webkit-border-top-right-radius': '0 0',
							'radius': '15px 0 0 15px'	
						}); 
					} else {
						Details.box.setStyles({
							'-moz-border-radius': '15px 15px 15px 15px',
							'-webkit-border-bottom-right-radius': '15px 15px',
							'-webkit-border-top-right-radius': '15px 15px',
							'radius': '15px 15px 15px 15px'	
						});
					}
				}
			});
		});
	},
	open: function(td) {
		Details.current = td;
		var id = Details.getDSC(td);
		if (!td.retrieve('calendar:coords')) td.store('calendar:coords', td.getCoordinates());
		var pos = td.retrieve('calendar:coords');
		Details.winSize = {
			'size': window.getSize(),
			'scroll': window.getScroll()
		};
		Details.doBox(td).setStyles({
			'width': pos.width,
			'height': pos.height,
			'left': pos.left,
			'top': pos.top,
			'opacity': 0
		});
		Details.closeButton.inject(document.body);
		Details.box.empty().set('html', $(id).innerHTML);
		Details.doTabs();
		Details.closeButton.inject(Details.box.getFirst());
		Details.ovrlyFx.start({'opacity': 0.8}).chain(function() {
			Details.fx.start({
				'width': 700,
				'height': 500,
				'left': ((Details.winSize.scroll.x + Details.winSize.size.x) / 2) - (700 / 2),
				'top':  (Details.winSize.scroll.y + (Details.winSize.size.y / 2)) - (500 / 2),
				'opacity': 1
			}).chain(function() {
				Details.closeButton.fade('in');
			});
		});
	},
	getDSC: function(td) {
		var split = td.className.split(" "), result;
		if (split.length) split.each(function(cls) {
			if (cls.test("dsc-")) result = cls;
		});
		
		return result;
	}
};

var Gallery = {
	'maxscroll': 0,
	'current_pos': 0,
	'current_photo': 1,
	'gfx': '',
	'ms_fade': 200,
	'ms_scroll': 1000,

	init: function() {
		if (!$('gallery')) return;
		Gallery.scrollerBar();
		Gallery.attachEvents();
	},

	scrollerBar: function() {
		if (!$('scroller')) return;
		// calculate single thumb size
		var current_coords = 0;
		var firstel = $$('#scroller-inner ul li img')[0];
		var thumbs_size = firstel.getSize().x + firstel.getStyle('margin-left').toInt();
		// init vars
		var totels = $$('#scroller-inner ul li').length;
		var max_els_in_scroller = $('scroller').getSize().x / thumbs_size;
		Gallery.maxscroll = Math.ceil(totels / max_els_in_scroller) - 1;
		var scrollsize = (thumbs_size * Math.floor($('scroller').getSize().x / thumbs_size));
		var maxcoords = (totels * thumbs_size) - scrollsize;
		$('scroller-inner').setStyle('width', (totels * thumbs_size));
		// init scroll effect
		Gallery.gfx = new Fx.Scroll('scroller', { link: 'cancel', duration: Gallery.ms_scroll, transition: Fx.Transitions.Quad.easeInOut });
		// setup button
		Gallery.setupGalleryButton();
		// add actions for buttons left/right
		$('scrollr').addEvents({
			'click': function(e) {
				e.stop();
				if (Gallery.current_pos == Gallery.maxscroll) return;
				Gallery.current_pos += 1;
				current_coords = current_coords + scrollsize;
				if (current_coords > maxcoords) current_coords = maxcoords;
				Gallery.gfx.start(current_coords, 0); 
				Gallery.setupGalleryButton();
			},
			'mouseover': function() { 
				$('scrollr').setStyle('background-position', '-15px 0px');
			},
			'mouseout': function() { 
				$('scrollr').setStyle('background-position', '0px 0px');
			}
		});
		$('scrolll').addEvents({
			'click': function(e) { 
				e.stop();
				if (Gallery.current_pos <= 0) {
					Gallery.current_pos = 0;
					$('scrolll').setStyles({'opacity': 0.3, 'cursor': 'default'});
					return;
				}
				Gallery.current_pos -= 1; 
				current_coords = current_coords - scrollsize;
				if (current_coords < 0) current_coords = 0;
				Gallery.gfx.start(current_coords, 0); 
				Gallery.setupGalleryButton();
			},
			'mouseover': function() { 
				$('scrolll').setStyle('background-position', '-15px 0px');
			},
			'mouseout': function() { 
				$('scrolll').setStyle('background-position', '0px 0px');
			}
		});
	},

	attachEvents: function() {
		$$('#scroller-inner ul li a').each(function(el) {
			el.addEvent('click', function(e) { e.stop(); Gallery.loadImage(el)} );
		});
	},

	showhideImage: function(oper) {
		var image = $('gallery-image').getElement('img');
		var myFx = new Fx.Tween(image, {duration: Gallery.ms_fade});
		if (oper == 'hide') image.setStyle('opacity', 0);
		else myFx.start('opacity', [0, 1]);
	},

	loadImage: function(el) {
		var img = el.get('href').split("/");
		if (img[2] == Gallery.current_photo) return;
		var images = ['/assets/gallery/'+ img[2] +'.jpg'];
		Gallery.showhideImage('hide');
		// preload image
		new Asset.images(images, {
			onComplete: function() {
				$('gallery-image').getElement('img').setProperties({'src': images[0], 'alt': 'foto '+img[2]});
				Gallery.current_photo = img[2];
				Gallery.showhideImage('show');
				// setup class active
				$$('#scroller-inner img').each(function(el) { el.setProperty('class', ''); });
				el.getElement('img').setProperty('class', 'imgactive');
			}
		});
	},

	setupGalleryButton: function() {
		// left button
		if (Gallery.current_pos == 0) $('scrolll').setStyles({'opacity': 0.3, 'cursor': 'default'});
		else $('scrolll').setStyles({'opacity': 1, 'cursor': 'pointer'});
		// right button
		if (Gallery.current_pos == Gallery.maxscroll) $('scrollr').setStyles({'opacity': 0.3, 'cursor': 'default'});
		else $('scrollr').setStyles({'opacity': 1, 'cursor': 'pointer'});
	}

};

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