var activePage = "";
var tmpCookie = new CookieJar({ expires: 21600, path: '/' });


// Prototype Event extend
Object.extend(Event, {
	withinElement: function(event, element) {
		var parent = event.relatedTarget;
		while (parent && parent != element) {
			try { parent = parent.parentNode; } 
			catch (error) { parent = element; }
		}
		return parent == element;
	}
});

// configuratore
var Configuratore = {}
Object.extend(Configuratore, {
	element: function() { return $("configuratore") },
	riepilogo: function() { return $("riepilogo") },
	wrapper: function() { return this.element().up() },
	show: function(toggle) {
		this.wrapper().show();
		Effect.ScrollTo(this.wrapper());		
	},
	setup: function() {
		if (this.element() == null) return;
		this.layout();
		buttonConfigura = $("tip_for_button_configura");
		if (buttonConfigura) {
			$$(".button_configura").each(function(el) {
				new Tip(el, buttonConfigura.innerHTML, {
					showOn: 'click',
					title: buttonConfigura.title,
					style: 'configuratore',
					stem: 'bottomLeft',
					hook: {tip: 'bottomLeft', target: 'topRight'},
					offset: {x: -35, y: 0}		
				});
			});
		}

		this.element().select("h4.togglable").each(function(el) {
			if (!el.hasClassName("accessori")) {
				
				if ($('campione_neutro')) {
					 if ($('campione_neutro').checked != true) el.addClassName("closed").next(".configuratore_content").hide();
				} else el.addClassName("closed").next(".configuratore_content").hide();		
			}
		});
	},
	layout: function() {
		this.observeTogglable();
		
		if (typeof Tips != 'undefined') Tips.hideAll();
		
		this.element().select(".scegli_materiale").each(function(el) {
			if (!el.hasClassName("tipped")) {
				new Tip(el, el.up("p").previous(".tip_content").innerHTML, {
					title: el.up("p").previous(".tip_content").getAttribute("title"),
					stem: "topMiddle",
					offset: { x: 0,  y: 5 },
					hook: { target: "bottomMiddle", tip: "topMiddle" },
					style: "configuratore"
				});
				el.addClassName("tipped");
			}
		});

		this.element().select(".accessorio .add").each(function(el) {
			if (el.hasClassName("tipped")) return;
			el_tip = el.up("p").previous(".tip_content");
			if (el_tip) {
				new Tip(el,el_tip.innerHTML,{
					title: el_tip.getAttribute("title"),
					stem: "bottomLeft",
					style: "configuratore",
					hook: { tip: "bottomLeft", target: "rightTop" }
				});
				el.addClassName("tipped");
			}
		});
			
	},
	observeTogglable: function() {
		this.element().select("h4.togglable").each(function(el) {
			var c = el.next(".configuratore_content");
			if (c && !el.hasClassName("toggleAdded")) {
				el.observe("click", function(event) {
					this.toggleClassName("closed").next(".configuratore_content").toggle();
				}).addClassName("toggleAdded");
				if (c.hasClassName("closed")) c.hide();
			}
		});
	}
});

// form validation
function onlyDigits(inputElement) {
	if (inputElement.tagName.toLowerCase() != "input") return;
//	if (!/^[\d]*$/.test(inputElement.value)) { 
	inputElement.value = inputElement.value.replace(",",".");
	if (isNaN(inputElement.value)) {
		alert("Sono ammessi solo numeri");
		inputElement.clear();
	}
}
function observeOnlyDigits(inputElement) {
	inputElement.observe("keyup", function(e) { onlyDigits(Event.element(e)) });
}

// photo gallery zoom 
function gfZoom(path) {
	fotoGrande = $$("#zoom_content .foto_grande");
	if (fotoGrande.size() == 1) {
		fotoGrande[0].update(new Element("img", {src:"/galleria_foto/"+path, alt:''}))
	}
} 

// show Welcome Message
function welcomeMessage() {	
	if (!$("meta")) return;
	welcomeBox = new Element("div").update("<div class=\"welcome_box_loading\"><img src=\"/images/spinner.gif\"> Caricamento in corso...</div>");
	welcomeBox.id = "welcome_box";
	welcomeBoxButton = new Element("a", {href:"#" + welcomeBox.id, onclick:"return false;"}).update("Lascia il tuo commento");
	welcomeBoxButton.id = "welcome_box_button";

	$(document.body).insert(welcomeBox);
	$$("#footer p")[0].insert({top: "&nbsp;|&nbsp;"}).insert({top: welcomeBoxButton});
	new FancyZoom(welcomeBoxButton, {width: 732, height: 393});
	
	new Ajax.Request("/nuovo_sito.php", {
		onSuccess: function(transport) {
			setTimeout(function() {
				$$(".welcome_box_loading").each(function(el) {
					el.replace(transport.responseText);
				});
			},500);
		}
	});
}

// show Alert Message
function alertMessage() {	
	if (!$("meta")) return;
	
	new Ajax.Request("/alert_message.php", {
		onSuccess: function(transport) {			
			if (!transport.responseText.blank()) {
				alertBox = new Element("div").update(transport.responseText)
				alertBox.id = "alert_box";
				alertBoxButton = new Element("a", {href:"#" + alertBox.id, onclick:"return false;"}).update("Messaggio di avviso");
				alertBoxButton.id = "alert_box_button";
				$(document.body).insert(alertBox);
				$$("#footer p")[0].insert({top: "&nbsp;|&nbsp;"}).insert({top: alertBoxButton});
				new FancyZoom(alertBoxButton, {width: 732, height: 393});
				
				if (navigator.cookieEnabled) {
					alCookie = tmpCookie.get("alertMessage") || {};
					if (!alCookie.hide) {
						FancyZoomBox.show({
							stop: function() {},
							findElement: function() { return alertBoxButton },
							pointerY: function() {return 0},
							pointerX: function() {return 0}
						});
						alCookie.hide = 1;
						tmpCookie.put("alertMessage", alCookie);
					}							
				}				
			}
		}
	});
}


// Dom loaded
document.observe("dom:loaded", function() {
	
	// set active page
	if (!activePage.empty()) {
		$$("#menu_pagine li."+activePage).invoke("addClassName", "active");
	} 
			
	// hotspots carousel!
	$$(".scroller").each(function(scroller) {
		scroller = $(scroller);
		new Carousel(scroller, scroller.select(".slide"), scroller.select('a.carousel-jumper', 'a.carousel-control'), {
			auto: true,
			duration: scroller_duration,
			frequency: scroller_frequency
		});
	});
	
	// load icon per product in categories
	$$(".moc li").each(function(li) {
		li.observe("mouseover", function() {
			this.up().previous().src = this.down("a").rel;
		}.bind(li));
	});	
	
	// tabs ..fixme: if default doesn't exists...
	$$(".tabs ul ").each(function(tab) {
		new ProtoTabs(tab, { defaultPanel: tab.next(".default").id });
	});
	
	// ricerca
	if (q=$("query")) {
		if (q.value == "") { 
			q.value = "ricerca";
			q.addClassName("gray");
		}
		q.observe("focus", function() {
			this.value = "";
			this.removeClassName("gray");
		}.bind(q)).observe("blur", function() {
			if (!$("autocomplete").visible()) {
				q.value = "ricerca";
				q.addClassName("gray");
			}
		}.bind(q)); 
	}
	
	// magic zoom fix
	$$("a.MagicZoom").each(function(magicZoom) {
		magicZoom.observe("mouseover", function() {
			$("panning-big").show();
			$("autocomplete").hide();
			if ($("zoom")) $("zoom").hide();
		});
		magicZoom.observe("mouseout", function() {
			$("panning-big").hide();
		});
	});	
		
	// configuratore	
	Configuratore.setup();
	
	// view_more
	$$(".more").each(function(el) {
		if (!el.empty()) {
			el.insert({before: new Element("span").update("dettagli").addClassName("view_more").observe("click", function() {
				this.toggle();
				return false;
			}.bind(el))});
		}
	});
	
	// menu 
	$$("#menu li.menu_item").each(function(li) {
		if (li.select("a").any(function (a){ return a.href.endsWith(location.pathname) })) li.addClassName("active");		
	});
	
	// form con errori
	$$(".profile_form span.errore").each(function(el) {
		container = el.up("p");
		if (el.empty() || container == null) return;
		target = container.select("input").last() || container.select("select").last() || container.select("textarea").last();
		if (target == null) return;
		new Tip(target, el.innerHTML, {
			stem: 'leftMiddle',
			hook: {tip: 'leftMiddle', target: 'rightMiddle'},
			offset: {x: 15, y: 0}
		});
		target.addClassName("show_prototip");

		errorImage = new Element("img", {src: "/images/form_errore.png", alt: "", align: "bottom"}).addClassName("errore");
		if (container.hasClassName("checkbox")) {
			container.down("label").insert({ bottom: errorImage });
		} else {
			target.insert({ after: errorImage });
		}
	});
	
	// wizard acquista
	if ($$("#wizard_acquisto li").size() > 0) $$("#wizard_acquisto li").last().setStyle({backgroundImage: 'none'});

	// observe only digit
	$$("input.only_digits").each(function(i) { observeOnlyDigits(i); });
	
	$$("#button_galleria_foto").each(function(el) {
		el.observe("click", function() {
			if ($$(".galleria_foto_loading").size() > 0) {
				new Ajax.Request("/stampadigitale/galleria_foto.php", {
					parameters: $(this).getAttribute("rel").evalJSON(),
					onSuccess: function(transport) {
						setTimeout(function() {
							$$(".galleria_foto_loading").each(function(el) {
								el.replace(transport.responseText);
							});
						},500);
					}
				});
			}
		});		
	});	
	
});

// init fancyzoom
function initFancyZoom() {
	$$("a.fancy-zoom").each(function(el) {
		if (!el.hasClassName("zoomed")) {
			el.addClassName("zoomed");
			zoomContainer = new Element("div", {style: "display:none"});
			zoomContainer.writeAttribute("id", zoomContainer.identify());
			$$("body")[0].insert(zoomContainer);

			zoomContainer.update(new Element("img", {src: el.href}));
			el.writeAttribute("href", "#" + zoomContainer.id);
			new FancyZoom(el);
		}
	});
}

// Window onload
Event.observe(window, "load", function() {

	// navbar
	$$("#navbar td").each(function(td) {
		tooltip = $(td.down("a").rel);
		if (tooltip != undefined) {
			td.insert({ bottom:tooltip });
			Element.clonePosition(tooltip, td.down("a"), { 
				setHeight: false, 
				setWidth: false, 
				offsetLeft: -(tooltip.getDimensions().width - td.down("a").getDimensions().width)/2+4,
				offsetTop: 22 })			
		}
	});
	if ($("panning-big") && $$(".scheda_prodotto").size() > 0) {
		Element.clonePosition($("panning-big"), $("panning-big").up(".scheda_prodotto"), { setHeight: false, setWidth: false, setLeft: false })
	}
	
	// fancyzoom
	if (window.FancyZoomBox != undefined) FancyZoomBox.directory = "/images/fancyzoom";
	initFancyZoom();
	
	// galleria foto
	$$("#button_galleria_foto").each(function(el) {
		new FancyZoom(el, {width:940, height:480});
	});
	
	// show prototip
	$$(".show_prototip").each(function(element) {
		element.prototip.show();
		element.removeClassName("show_prototip");
	});
	
	welcomeMessage();
	alertMessage();
	
});



// Global Ajax Responders
Ajax.Responders.register({
	onCreate: function() { $("spinner").show(); },
	onComplete: function() { $("spinner").hide(); }
});
