var Elettrostampi = function() {
	var headerCollapsed = null;
	var textSize = null;
	var currentTextSize = 1;
	var sections = ['index', 'attrezzature', 'contatti', 'azienda',
					'servizi', 'prodotti', 'filosofia', 'dove-siamo', 'reparti'];
	
	var initTextChanger = function() {
		$('text-size-changer').style.display = 'block';
		
		textSize = new fx.RememberText('wrapper');
		var links = document.getElementsByClassName('text-size', 'text-size-changer');
		
		var resetStyles = function() {
			for (var i = 0; i < links.length; i++) {
				Element.removeClassName(links[i], 'current');
			}
		};
		var cookie = textSize.readCookie();
		if (cookie) {
			resetStyles();
			switch(cookie) {
				case '1.2':
					Element.addClassName('text-size-large', 'current');
					currentTextSize = 1.2;		
					break;
				case '0.9':
					Element.addClassName('text-size-small', 'current');
					currentTextSize = 0.9;
					break;
				default:
					Element.addClassName('text-size-medium', 'current');
					break;
			}
		}
		
		links.each(function(link){
			Event.observe(link, 'click', function(e){
				Event.stop(e);
				link.blur();
				resetStyles();
				Element.addClassName(link, 'current');
				if (link.className.match('small')) {
					textSize.custom(currentTextSize, 0.9);
					currentTextSize = 0.9;
				} else if (link.className.match('large')) {
					textSize.custom(currentTextSize, 1.2);
					currentTextSize = 1.2;		
				} else {					
					textSize.custom(currentTextSize, 1);
					currentTextSize = 1;		
				}
			});
		});	
	};
	
	var hideContents = function() {
		Element.cleanWhitespace('content-frame');
		var nodes = $('content-frame').childNodes;
		for (var i = 0; i < nodes.length; i++) {
			Element.hide(nodes[i]);
		}
	};
	
	var prepareLinks = function() {
		var links = document.getElementsByTagName('a');
		var currentPage = window.location.pathname.toLowerCase();
		
		var handleClick = function(e) {
			var targetPage = this.pathname;
			var found = false; 
			$A(sections).each(function(section){
				if (targetPage.match(section)) {
					hideContents();
					Element.show(section);
					found = true;
				}
			});
			if (!found) {				
				return;
			}	
			
			Event.stop(e);
			this.blur();
			
			$A(sections).each(function(section){
				if (targetPage.match(section)) {			
					// Initialize navigation
					var navLinks = $('nav-bar').getElementsByTagName('li');
					for (var i = 0; i < navLinks.length; i++) {
						Element.removeClassName(navLinks[i], 'current');
					}
					switch (section) {
						case 'filosofia':
						case 'dove-siamo':
						case 'reparti':
						case 'attrezzature':
							section = 'azienda';
							break;
					}
					
					Element.addClassName(section + '-btn', 'current');
				}
			});
		};
		
		$A(links).each(function(link){
			if (link.href.indexOf('mailto:') == -1 && 
				(link.host.match(window.location.host) || !link.host) ) {
				link.onclick = handleClick;
			} else {
			}
		});	
	};
	
	var getHeaderReminder = function() {
		var reminder = new Remember();
		var reminderEl = document.createElement('div');
		reminderEl.id = 'reminder';
		reminder.el = reminderEl;
		reminder.prefix = ''; 
		return reminder;
	};
	
	var toggleHeader = function(disableAnimation) { 
		var animationDuration = 0.6;
		if (disableAnimation)
			animationDuration = 0.01;
		    
		if (headerCollapsed) {
			headerCollapsed = null;
			new Effect.Parallel(
				[new Effect.MoveBy('wrapper', 120, 0, {duration:0.6}),
	      		new Effect.MoveBy('logo', -50, 0, {duration:0.6}),
	      		new Effect.Fade('logo', {
	      			from:0.2,
	      			to: 1,
	      			duration:animationDuration
	      		})], { 
					duration: animationDuration
			});			
		} else {
			headerCollapsed = true;
			new Effect.Parallel(
				[new Effect.MoveBy('wrapper', -120, 0, {duration:0.6}),
	      		new Effect.MoveBy('logo', 50, 0, {duration:0.6}),
	      		new Effect.Fade('logo', {
	      			from:1,
	      			to: 0.2,
	      			duration:animationDuration
	      		})], { 
					duration: animationDuration,
					sync:true
			});
		}
		getHeaderReminder().setCookie(headerCollapsed);	
	};
	
	var preloadContents = function() {			
		$A(sections).each(function(section){
			var div = document.createElement('div');
			div.className = 'loading-section';
			div.id = section;
			$('content-frame').appendChild(div);	
			Element.hide(div);		
			window.setTimeout(function(){
				new Ajax.Updater(section, section + '.php', {
					method:'get',
					parameters : 'ajax=1',
					onSuccess : function() {
						Element.removeClassName(section, 'loading-section');
						window.setTimeout(prepareLinks, 150);
					}
				});	
			}, 2000);
		});
	};
	
	var restoreTabs = function() {
		
	};
	
	
	return { 
		init: function() {
			// Initialize text changer
			initTextChanger();
			
			// Initialize navigation
			var navLinks = $('nav-bar').getElementsByTagName('li');
			var removeTabs = function() {
				for (var i = 0; i < navLinks.length; i++) {
					Element.removeClassName(navLinks[i], 'current');
				}
			};
			var currentPage = window.location.pathname.toLowerCase();	
			if (currentPage != '/' && currentPage != '/index.php') {				
				$A(sections).each(function(section){
					if (currentPage.match('/' + section)) {
						removeTabs();						
						switch (section) {
							case 'filosofia':
							case 'dove-siamo':
							case 'reparti':
							case 'attrezzature':
								section = 'azienda';
								break;
						}
						Element.addClassName(section + '-btn', 'current');
					}
				});
			}
			
			// Header toggle
			Event.observe('header-toggle', 'click', function(e) {
				$('header-toggle').blur();
				Event.stop(e);
				toggleHeader();				
			});
			
			// Preload section contents
			//preloadContents();
			
			// Prepare links
			//prepareLinks();
			
			// Toggle header
			if (getHeaderReminder().readCookie() == 'true') {
				headerCollapsed = true;
				Element.addClassName('wrapper', 'header-toggled');
				Element.setOpacity('logo', 0.2);
			}
		},
		showContactErrors: function(text) {
			var el = $('contactErrors');
			
			if (!el) {
				el = document.createElement('div');
				el.id = 'contactErrors';
				$('contact').insertBefore(el, $('contactForm'));
			}
			
			el.innerHTML = text;
			Element.setOpacity(el, 0);
			el.style.display = 'block';
			new Effect.Opacity(el, { 
				duration: 0.5, 
				transition: Effect.Transitions.sinoidal, 
				from: 0.0, 
				to: 1.0 
			});	
		},
		hideContactErrors : function() {
			var el = $('contactErrors');
			
			if (el) {
				new Effect.Opacity(el, { 
					duration: 0.2, 
					transition: Effect.Transitions.sinoidal, 
					from: 1.0, 
					to: 0.0 
				});		
			}
		},
		sendFeedback: function() {
			var nome = $F('nome-text').strip();
			var azienda = $F('azienda-text').strip();
			var telefono = $F('telefono-text').strip();
			var email = $F('email-text').strip();
			var message = $F('message-text').strip();
			
			// Check values
			var requiredField = '';
			
			if (!nome)
				requiredField += '<li>Nome</li>'
			if (!telefono)
				requiredField += '<li>Telefono</li>'
			if (!email)
				requiredField += '<li>Email</li>'
			if (!message)
				requiredField += '<li>Richiesta</li>'
			
			if (requiredField != '') {
				Elettrostampi.showContactErrors('<p>I seguenti campi devono essere compilati:</p><ul>'+requiredField+'</ul>');
				return false;				
			}
			
			var emailRegex = /^[\w\d]+((-[\w\d]+)|(\.[\w\d]+)|(_[\w\d]+))*\@[\d\w]+((\.|-)[\w\d]+)*\.[\d\w]+$/i;
			if (!emailRegex.test(email) || email.length < 8){
				Elettrostampi.showContactErrors('<p>L\'indirizzo email inserito non &egrave; valido</p>');
				return false;
			}

			// Preparing parameters
			var pars = [];
	
			pars.push('cback=sendFeedback');
			var elem = Form.getElements($('contactForm'));
			for (var i = 0; i < elem.length; i++) {
					pars.push(elem[i].id+'='+encodeURIComponent(elem[i].value));
			}

			// Preparing for sending
			Elettrostampi.hideContactErrors();
			$('send').value = 'Invio in corso...';
			$('send').disabled = true;

	        var completed = function(response) {
				var result = eval('(' + response.responseText + ')');
				if (result.isSuccessful) {	
					var content = document.getElementsByClassName('text-content');
					for (var i = 0; i < content.length; i++) {
						content[i].style.display = 'none';
					}
					Effect.Appear('contactSent');
				} else{
					Elettrostampi.showContactErrors(result.error);
				}
				$('send').disabled = false;
				$('send').value = 'Invia';
				
			};
			
			// Send!
			var ajax = new Ajax.Request('contatti.php', { 
				method: 'post', 
			    parameters: pars.join('&'),
			    onSuccess:completed 
			});
		}
	};
}();
Event.observe(window, 'load', Elettrostampi.init);