var Site = function() {
	$(document).ready(this.init.createCallback(this));
}

$.extend(Site.prototype, {

	ghostPage: 4,			// Indice pagina accordion per contenuti fuori dell'accordion
	inited: false,			// Indica se la pagina è pronta e l'accordion caricato
	accordion: null,		// Accordion
	currentcontent: null,	// Current content
	currentaccordion: null, // Current accordion page
	languages: ["it", "en", "fr", "de", "es"],
	onInitOpenPage: null,
	
	
	init: function() {
		if (!$.cookie("language"))
			$.cookie("language", "it", { expires: 31});
		this.applyLanguage();
			
		// Inizializzo l'accordion
		this.initAccordion();
		
		// Riassocio i link dell'accordion con il sistema di deeplinking
		$('.accordion-handle a').address();

		this.inited = true;
		//setInterval('console.debug(Deeper.current)', 1000);
		
		if (this.onInitOpenPage != null)
			this.openAccordionPage(this.onInitOpenPage);
	},
	
	initAccordion: function() {
		this.accordion = $(".accordion").hrzAccordion({
			containerClass     	: "accordion-container",
			listItemClass      	: "accordion-listitem",					
			contentWrapper     	: "accordion-wrapper",
			contentInnerWrapper	: "accordion-innerwrapper",
			handleClass        	: "accordion-handle",
			handleClassOver    	: "accordion-handleover",
			handleClassSelected	: "accordion-handleselected",
			handlePosition		: "left",
			openOnLoad			: null,
			fixedWidth			: 860
		})[0];
	},
	
	openAccordionPage: function(index) {
		if (this.inited == false) {
			this.onInitOpenPage = index;
			return;
		}
		this.accordion.openPage(index);
		this.currentcontent = this.getContentForAccordion(index);
		this.currentaccordion = this.currentcontent;
	},
	
	openAccordionGhostPage: function() {
		this.changeBg(null);
		this.openAccordionPage(this.ghostPage);
		this.currentcontent = this.getContentForAccordion(this.ghostPage);
	},
	
	getContentForAccordion: function(index) {
		return $('#accordionContent' + index + ' .accordion-content');
	},
	
	getContent: function() {
		return this.currentcontent;
	},
	
	setLoader: function() {
		this.currentcontent.html('<div class="loader"><div class="loader-inner"><div class="loader-img"></div></div></div>');	
	},
	
	existLanguage: function(l) {
		var e = false;
			for(var i = 0; i < this.languages.length; i++)
				if (this.languages[i] == l)
					e = true;
		return e;
	},
	
	changeLanguage: function(l) {
		if (!this.existLanguage(l))
			return;

		$.cookie("language", l, { expires: 31});
		location.reload(true);
	},
	
	applyLanguage: function() {
		var l = $.cookie("language");
		if (!this.existLanguage(l))
			return;
		
		for(var i = 0; i < this.languages.length; i++)
			$(document.body).removeClass("language-" + this.languages[i]);
		
		$(document.body).addClass("language-" + l);
	},
	
	embedFlash: function(name, div, w, h, delay) {
		if (!delay) delay = 3;
		
		var embed = function() {
			swfobject.embedSWF("/flash/" + name + ".swf", div, w, h, "9.0.0", "flash/expressInstall.swf");
		}
		setTimeout(embed, delay * 1000);
	},
	
	loadPage: function(page, callback) {
		this.setLoader();
		this.pagecallback = callback;
		
		$.ajax({
			url: '/pages/' + page + '.php',
			dataTypeString: 'html',
			success: this.setContent.createCallback(this),
			error: this.setError.createCallback(this)
		});
	},
	
	loadPhoto: function(path) {
		$.fancybox({
			'href'			: '/imgs/' + path,
			'type'			: 'image'
		});
	},
	
	fadeOutCurrentAccordionContent: function(callback) {
		this.pagecallback = callback;
		this.currentaccordion.fadeTo(500, 0, function() {
			this.currentaccordion.html("");
			this.currentaccordion.fadeTo(0, 1);
			this.pagecallback();
		}.createCallback(this));
	},
	
	loadOmbrellone: function(ombrellone, callback) {
		this.currentcontent = $('#productarea');
		this.setLoader();

		this.pagecallback = callback;
		
		$.ajax({
			url: '/pages/ombrelloni.php',
			data: {
				ombrellone: ombrellone
			},
			type: 'POST',
			dataTypeString: 'html',
			success: function(data) {
				this.setContent(data);
				this.initGalleryPager();
			}.createCallback(this),
			error: this.setError.createCallback(this)
		});
	},
	
	initGalleryPager: function() {
		this.currentgallerypage = 1;
		var thumbinpage = 3;
		
		var count = $(".thumbsscroller").children().length;
		this.totalpage = Math.ceil(count / thumbinpage);
	},
	
	nextGalleryPage: function() {
		if (this.currentgallerypage == this.totalpage || this.loadingphoto) return;
		this.loadingphoto = true;
		
		this.currentgallerypage += 1;
		
		this.scrollGallery('-');
	},
	
	prevGalleryPage: function() {
		if (this.currentgallerypage == 1 || this.loadingphoto) return;
		this.loadingphoto = true;
		
		this.currentgallerypage -= 1;
		
		this.scrollGallery('+');
	},
	
	scrollGallery: function(sign) {
		var w = $(".thumbs").width();
		
		$(".thumbsscroller").animate({
			left: sign + '=' + (w - 18.5)
		}, 500, null, function(){
			this.loadingphoto = false;
		}.createCallback(this));
	},
	
	loadOmbrellonePhoto: function(img, big) {
		if (this.loadingphoto) return;
		this.loadingphoto = true;
		
		this.bigphoto = big;
		
		var image = new Image();
		image.onload = function() {
			var img = $('#productimage img');
			
			img.fadeTo(500, 0, function() {
				var dom = img.get(0);							  
				dom.src = image.src;
				
				img.fadeTo(500, 1, function(){
					delete this.loadingphoto;
				}.createCallback(this));
			}.createCallback(this));	
			
		}.createCallback(this);
		
		image.src = img;
		
		return false;
	},
	
	addZoomHelper: function() {
		if ($('#productimage a').length == 0) {
			setTimeout(this.addZoomHelper.createCallback(this), 500);
			return;
		}
		
		$('#productimage a').mouseover(function(){
			$('#imagezoomhelper').fadeTo(500, 1);
		}).mouseleave(function(){
			$('#imagezoomhelper').fadeTo(500, 0);
		});
	},
	
	loadBigPhoto: function() {
		if (this.loadingphoto) return;
		
		$.fancybox({
			'width'			: 1200,
			'height'		: 900,
			'href'			: this.bigphoto,
			'type'			: 'image'
		});
		
		return false;
	},
	
	loadSchedaTecnica: function(id) {
		$.fancybox({
			'width'			: 620,
			'height'		: 800,
			'href'			: '/pages/schedatecnica.php?idombrellone=' + id,
			'type'			: 'iframe'
		});
		return false;
	},
	
	//*** Galleria *****************************************************************************
	//******************************************************************************************
	
	galleryGotoPage: function(p) {
		$('#photogallery-page .pages a span').removeClass('currentpage');
		
		$($('#photogallery-page .pages a span').get(p - 1)).addClass('currentpage');
	
		$('.gallery-scroller').animate({
			'margin-left': (p - 1) * 816 * -1
		}, 1000);
	},
	
	galleryOpenBig: function(photo, desc) {
		$.fancybox({
			'width'			: 840,
			'height'		: 700,
			'href'			: photo,
			'type'			: 'image',
			'title'			: desc
		});
	},
	
	//*** Preventivo ***************************************************************************
	//******************************************************************************************
	
	clearPreventivoError: function() {
		this.preventivoerror = null;
		$('.preventivo-error').html('');
	},
	
	setPreventivoError: function(msg) {
		if (this.preventivoerror == null) {
			this.preventivoerror = msg;
			$('.preventivo-error').html(msg);
		}
	},
	
	havePreventivoError: function() {
		return this.preventivoerror != null;
	},
	
	getComboSelectedValue: function(element) {
		for (var j = 0; j < element.options.length; j++) {
			var option = element.options[j];
			if (option.selected)
				return option.value;
		}
		return "";
	},
	
	sendPreventivo: function() {
		var elements = document.forms['preventivo-form'].elements;
		this.clearPreventivoError();
		
		var params = {
			nome: elements["nome"].value,
			ditta: elements["ditta"].value,
			indirizzo: elements["indirizzo"].value,
			citta: elements["citta"].value,
			telefono: elements["telefono"].value,
			mail: elements["mail"].value,
			note: elements["note"].value,
			ricontattato: elements["ricontattato"].value,
			ombrelloni: []
		};
		
		if (params.nome == '')
			this.setPreventivoError('Devi inserire nome e cognome');
		
		if (params.ricontattato == 'E-mail' && params.mail == '')
			this.setPreventivoError('Hai scelto di essere riconttatato via mail e non hai inserito la mail');
		
		if (params.ricontattato == 'Telefono' && params.telefono == '')
			this.setPreventivoError('Hai scelto di essere riconttatato via telefono e non hai inserito il numero di telefono');
		
		if (params.mail != '') {
			var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
			if(!reg.test(params.mail))
				this.setPreventivoError('L\'indirizzo mail non è valido');
		}
			
		for (var i = 0; i < elements.length; i++) {
			var el = elements[i];
			if (el.type.toUpperCase() == 'CHECKBOX') {
				var s = el.name.split('-');
				
				if (s.length > 1 && s[0] == 'ombrellonecheck' && el.checked) {
					var id = s[1];
					
					var ombrellone = {
						nome: $('#ombrellonetext-' + id).html(),
						misure: this.getComboSelectedValue(elements["ombrellonemisure-" + id]),
						capote: this.getComboSelectedValue(elements["ombrellonecapote-" + id])
						
					};
					
					if (ombrellone.misure == "")
						this.setPreventivoError("Per l'ombrellone '" + ombrellone.nome + "' devi selezionare una misura");
						
					if (ombrellone.capote == "")
						this.setPreventivoError("Per l'ombrellone '" + ombrellone.nome + "' devi selezionare un tipo di capote");
					
					params.ombrelloni.push(ombrellone);
				}
			}
		}
		
		if (params.ombrelloni.length == 0)
			this.setPreventivoError('Devi selezionare almeno un ombrellone');

		if (!this.havePreventivoError()) {
			this.setCenteredMessage("Invio in corso", function() {
				
				$.ajax({
					url: '/pages/sendpreventivo.php',
					dataTypeString: 'html',
					data: params,
					type: 'POST',
					success: this.preventivoSuccessCallback.createCallback(this),
					error: this.preventivoErrorCallback.createCallback(this)
				});
				
			});
		}
		
		return false;
	},
	
	preventivoErrorCallback: function() {
		this.setCenteredMessage("Errore invio preventivo. Riprovare più tardi.");
	},
	
	preventivoSuccessCallback: function(content) {
		if (content == "OK")
			this.setCenteredMessage("Preventivo inviato correttamente, verrà contattato al più presto.");
		else
			this.preventivoErrorCallback();
	},
	
	setCenteredMessage: function(msg, callback) {
		this.currentcontent.fadeTo(1000, 0, function() {
			this.currentcontent.html('<div class="message"><div class="messageinner">' + msg + '</div></div>');
			this.currentcontent.fadeTo(1000, 1, function() {
				if ($.browser.msie){this.currentcontent.get(0).style.removeAttribute('filter');}

				if (callback)
					callback.createCallback(this)();
				
			}.createCallback(this));
		}.createCallback(this));
	},
	
	setContent: function(content) {
		this.currentcontent.fadeTo(0, 0);
		this.currentcontent.html(content);
		this.currentcontent.fadeTo(500, 1, function() {
			if ($.browser.msie){this.currentcontent.get(0).style.removeAttribute('filter');}
			this.pagecallback();
		}.createCallback(this));
	},

	setError: function() {
		//this.currentcontent.html('<div class="loader"><div class="loader-inner">Errore caricamento pagina / Error loading page</div></div>');
		this.currentcontent.html('');
		this.pagecallback();
	},
	
	changeBg: function(bg) {
		$('#bgimage').fadeTo(500, 0, function() {
			$('body').removeClass('classici-piccoli-medi');
			$('body').removeClass('grandi-superfici');
			$('body').removeClass('top-gamma');
			$('body').removeClass('home');
			
			if (bg != null) {
				$('body').addClass(bg);
			
				$('#bgimage').fadeTo(500, 1);
			}
		});
	}
		
});

Site = new Site();

var title = document.title;

var log = function(msg) {
	if (console)
		console.debug(msg);
}

// Serialization utility
var serialize = function(obj, re) {
	var result = [];
	$.each(obj, function(i, val) {
		if ((re && re.test(i)) || !re)
			result.push(i + ': ' + (typeof val == 'object' ? val.join 
				? '\'' + val.join(', ') + '\'' : serialize(val) : '\'' + val + '\''));
	});
	return '{' + result.join(', ') + '}';
}

Deeper.onPageNotFound(function(path){
	console.debug("Cannot open path: " + path);
});


var Base = new Page({
	
	name: '',
	title: '',
	
	onTransitionIn: function() {
		this.transitionInComplete();
	},
	
	onTransitionOut: function() {
		this.transitionOutComplete();
	}	
	
});

var Home = new Page({
	
	name: 'home',
	title: 'Home',
	parent: Base,
	
	homepage: true,
	
	onTransitionIn: function() {
		Site.openAccordionPage(3);
		Site.changeBg(this.name);
		
		setTimeout(function() {
			Site.loadPage(this.name, this.transitionInComplete);
		}.createCallback(this), 500);
	},
	
	onTransitionOut: function() {
		this.transitionOutComplete();
	}	
	
});

var Chi = new Page({
	
	name: 'chisiamo',
	title: 'Chi siamo',
	parent: Base,
	
	onTransitionIn: function() {
		Site.openAccordionGhostPage();
		Site.loadPage(this.name, this.transitionInComplete);
	},
	
	onTransitionOut: function() {
		Site.fadeOutCurrentAccordionContent(this.transitionOutComplete);
	}	
	
});

var Multivalvola = new Page({
	
	name: 'multivalvola',
	title: 'Multivalvola',
	parent: Base,
	
	onTransitionIn: function() {
		Site.openAccordionGhostPage();
		Site.loadPage(this.name, this.transitionInComplete);
	},
	
	onTransitionOut: function() {
		Site.fadeOutCurrentAccordionContent(this.transitionOutComplete);
	}	
	
});

var Preventivi = new Page({
	
	name: 'preventivi',
	title: 'Preventivi',
	parent: Base,
	
	onTransitionIn: function() {
		Site.openAccordionGhostPage();
		Site.loadPage(this.name, this.transitionInComplete);
	},
	
	onTransitionOut: function() {
		Site.fadeOutCurrentAccordionContent(this.transitionOutComplete);
	}	
	
});

var Qualita = new Page({
	
	name: 'qualita',
	title: 'Qualità',
	parent: Base,
	
	onTransitionIn: function() {
		Site.openAccordionGhostPage();
		setTimeout(function() {
			Site.loadPage(this.name, this.transitionInComplete);
		}.createCallback(this), 500);
	},
	
	onTransitionOut: function() {
		Site.fadeOutCurrentAccordionContent(this.transitionOutComplete);
	}	
	
});

var Colori = new Page({
	
	name: 'colori',
	title: 'Colori',
	parent: Base,
	
	onTransitionIn: function() {
		Site.openAccordionGhostPage();
		setTimeout(function() {
			Site.loadPage(this.name, this.transitionInComplete);
		}.createCallback(this), 500);
	},
	
	onTransitionOut: function() {
		Site.fadeOutCurrentAccordionContent(this.transitionOutComplete);
	}	
	
});

var Contatti = new Page({
	
	name: 'contatti',
	title: 'Contatti',
	parent: Base,
	
	onTransitionIn: function() {
		Site.openAccordionGhostPage();
		setTimeout(function() {
			Site.loadPage(this.name, this.transitionInComplete);
		}.createCallback(this), 500);
	},
	
	onTransitionOut: function() {
		Site.fadeOutCurrentAccordionContent(this.transitionOutComplete);
	}	
	
});

var Supporto = new Page({
	
	name: 'supporto',
	title: 'Supporto',
	parent: Base,
	
	onTransitionIn: function() {
		Site.openAccordionGhostPage();
		setTimeout(function() {
			Site.loadPage(this.name, this.transitionInComplete);
		}.createCallback(this), 500);
	},
	
	onTransitionOut: function() {
		Site.fadeOutCurrentAccordionContent(this.transitionOutComplete);
	}	
	
});

var Manutenzione = new Page({
	
	name: 'manutenzione',
	title: 'Manutenzione',
	parent: Base,
	
	onTransitionIn: function() {
		Site.openAccordionGhostPage();
		setTimeout(function() {
			Site.loadPage(this.name, this.transitionInComplete);
		}.createCallback(this), 500);
	},
	
	onTransitionOut: function() {
		Site.fadeOutCurrentAccordionContent(this.transitionOutComplete);
	}	
	
});

var Classici = new Page({
	
	name: 'classici-piccoli-medi',
	title: 'Classici piccoli medi',
	parent: Base,
	
	onTransitionIn: function() {
		Site.openAccordionPage(0);
		Site.changeBg(this.name);
		
		setTimeout(function() {
			Site.loadPage(this.name, this.transitionInComplete);
			Site.addZoomHelper();
		}.createCallback(this), 500);
	},
	
	onTransitionOut: function() {
		Site.fadeOutCurrentAccordionContent(this.transitionOutComplete);
	}	
	
});

var Grandi = new Page({
	
	name: 'grandi-superfici',
	title: 'Grandi superfici',
	parent: Base,
	
	onTransitionIn: function() {
		Site.openAccordionPage(1);
		Site.changeBg(this.name);
		
		setTimeout(function() {
			Site.loadPage(this.name, this.transitionInComplete);
			Site.addZoomHelper();
		}.createCallback(this), 500);
	},
	
	onTransitionOut: function() {
		Site.fadeOutCurrentAccordionContent(this.transitionOutComplete);
	}	
	
});

var Top = new Page({
	
	name: 'top-gamma',
	title: 'Top gamma',
	parent: Base,
	
	onTransitionIn: function() {
		Site.openAccordionPage(2);
		Site.changeBg(this.name);
		
		setTimeout(function() {
			Site.loadPage(this.name, this.transitionInComplete);
			Site.addZoomHelper();
		}.createCallback(this), 500);
	},
	
	onTransitionOut: function() {
		Site.fadeOutCurrentAccordionContent(this.transitionOutComplete);
	}	
	
});

var ProdottoClassici = new Page({
	
	name: '*',
	title: '',
	parent: Classici,
	
	onTransitionIn: function() {
		Site.loadOmbrellone(this.getCurrentBranch(), this.transitionInComplete);
	},
	
	onTransitionOut: function() {
		this.transitionOutComplete();
	}	
	
});

var ProdottoGrandi = new Page({
	
	name: '*',
	title: '',
	parent: Grandi,
	
	onTransitionIn: function() {
		Site.loadOmbrellone(this.getCurrentBranch(), this.transitionInComplete);
	},
		
	onTransitionOut: function() {
		this.transitionOutComplete();
	}	
	
});

var ProdottoTop = new Page({
	
	name: '*',
	title: '',
	parent: Top,
	
	onTransitionIn: function() {
		Site.loadOmbrellone(this.getCurrentBranch(), this.transitionInComplete);
	},
	
	onTransitionOut: function() {
		this.transitionOutComplete();
	}	
	
});

var Gallery = new Page({
	
	name: 'gallery',
	title: 'Gallery',
	parent: Base,
	
	onTransitionIn: function() {
		Site.openAccordionGhostPage();
		
		setTimeout(function() {
			Site.loadPage(this.name, this.transitionInComplete);
			
		}.createCallback(this), 500);
	},
	
	onTransitionOut: function() {
		Site.fadeOutCurrentAccordionContent(this.transitionOutComplete);
	}
	
});

var MultiValvolaClip = new Page({
	
	name: 'multivalvola_clip',
	title: 'Multivalvola System',
	parent: Base,
	
	onTransitionIn: function() {
		Site.openAccordionGhostPage();
		
		setTimeout(function() {
			Site.loadPage(this.name, this.transitionInComplete);
			
		}.createCallback(this), 500);
	},
	
	onTransitionOut: function() {
		Site.fadeOutCurrentAccordionContent(this.transitionOutComplete);
	}
	
});




if (typeof console == "undefined") {

	console = {
	
		debug: function(){},
		log: function(){}
		
	
	}

}
