var ieversionmatch = /msie (\d+)/i.exec(navigator.userAgent),
	ieversion = ieversionmatch && ieversionmatch[1] ? ieversionmatch[1] : null,
	ie6 = ieversion !== null && ieversion < 7;

$(function () {
	var pageWidth = $("#page").width(),
		docel = document.documentElement,
		body = document.body;
		
	//min height
	var imgs = document.getElementsByTagName("img"),
			last = imgs[imgs.length - 1];
	if (last.src.indexOf("php-stats") > -1) {
		last.parentNode.removeChild(last);
	}
	var contentBox = $("#content"),
		cbh = contentBox.height(),
		cby = contentBox.offset().top,
		fiH = $("#footerimages").outerHeight(true),
		footerH = $("#footer").height(),
		winH = window.innerHeight || docel.offsetHeight;
	if ((cbh + cby + fiH + footerH) < winH) {
		contentBox.css("height", winH -  (cby + fiH + footerH));
	}
		
	//Overlay
	var overlay = $("<div id='loading'></div>").appendTo(body),
		closeImage = new Image();
	closeImage.src = "templates/default/images/close.gif";
	closeImage.style.cursor = "pointer";
	closeImage.alt = closeImage.title = "Chiudi";
	window.openOverlay = function (src, closable) {
		var img = new Image(),
			scrollTop = docel.scrollTop || body.scrollTop || document.scrollTop || 0,
			width = docel.offsetWidth,
			height = docel.offsetHeight;
		overlay.css({width:width, height:height, display:"block"});
		img.onload = function () {
			var t = (($(window).height() - this.height) / 2) + scrollTop,
				l = (width - this.width) / 2;
			$(this).css({left: l, top: t}).appendTo(overlay);
			if (closable) {
				closeImage.style.top = t + "px";
				closeImage.style.left = (l + this.width - closeImage.width) + "px";
				overlay.append(closeImage);
			}
		};
		img.src = src;
	};
	window.hideOverlay = window.stopLoading = function () {
		overlay.css("display", "none").empty();
	};
	window.startLoading = function () {
		window.openOverlay("templates/default/images/loading.gif");
	};
	closeImage.onclick = window.hideOverlay;
	
	//Lightbox
	$("a[rel=popImage]").click(function () {
		window.openOverlay($(this).attr("href"), true);
		return false;
	});
			
	//Menu
	var width = 0;
	$("#menubar li").mouseover(function () {
		$(this).addClass("menu-over");
	}).mouseout(function () {
		$(this).removeClass("menu-over");
	}).each(function () {
		var subUl = $(this).find("ul").eq(0),
			subUlWidth = subUl.width(),
			mw = $(this).width();
		if ((width + subUlWidth) > pageWidth) {
			subUl.css("margin-left", mw - subUlWidth);
		}
		if (ie6) subUl.css("margin-left", 0);
		width += mw;	
	});
	
	//Popup
	$("a.popup").click(function () {
		var href = $(this).attr("href"),
			start = href.indexOf('#');
		if (start !== -1) {
			href = href.replace('#' + href.substr(start + 1), '?onthehelp=true&div=' + href.substr(start + 1));
		} else {
			href += '?onthehelp=true';
		}
		var popupWin = window.open(href, 'help', 'width=350,height=400,,location=no,toolbar=no,menubar=no,status=no,resizable=yes,scrollbars=no');
		if (popupWin) {
			popupWin.focus();
		}
		return false;
	});
	
	//Sliders
	$("div.slider").each(function () {
		new Slider(this);
	});
	
	//Display:table-cell fix
	if (ieversion !== null && ieversion < 8) {
		$(".block-v-center").each(function () {
			var html = this.innerHTML,
				table = "<table cellpadding='0' cellspacing='0' width='100%' height='"+$(this).height()+"'><tr><td style='vertical-align:middle'>";
			this.innerHTML = table + html + "</td></tr></table>";
		});
	}
	
	//Tabs
	$("div.tabs").each(function () {
		var $this = $(this),
			tabHeaders = $this.find(".tabheader"),
			tabBar = $("<div class='tabbar clear'></div>").append(tabHeaders),
			tabContent = $this.find(".tabcontent").css("display", "none"),
			selected = null;
		$this.prepend(tabBar);
		tabHeaders.each(function (i) {
			$(this).click(function(){
				if (selected !== null) {
					tabContent.eq(selected).css("display", "none");
					tabHeaders.eq(selected).removeClass("tabselected");
				}
				tabContent.eq(i).css("display", "block");
				$(this).addClass("tabselected");
				selected = i;
			});
		});
		tabHeaders.eq(0).click();
	});
	
	//Torna su
	if (!ie6) {
		var moveup = $("<div id='moveup'>Torna su</div>").click(function () {
				$(scrollEl).animate({scrollTop:0});
			}).appendTo(body),
			scrollEl,
			moveupvis = false;
		window.onscroll = function () {
			if (Math.max(body.scrollTop, docel.scrollTop) >= 400) {
				if (!moveupvis) {
					moveup.fadeIn();
					moveupvis = true;
				}
				if (!scrollEl) scrollEl = docel.scrollTop ? docel : body;
			} else if (moveupvis) {
				moveup.fadeOut();
				moveupvis = false;
			}
		};
		window.onscroll();
	}
});

function HomeSlide (selector)
{
	var el = $(selector),
		self = this;
	this.width = el.width();
	this.content = el.find(".slidecontent").mouseover(function () {
		window.clearTimeout(self.timer);
		self.paused = true;
	}).mouseout(function () {
		self.paused = false;
		self.play();
	});
	this.content.children("table+a").each(function () {
		var $this = $(this),
			table = $this.prev();
		table.prev().append(table);
		$this.remove();
	});
	var frames = this.content.children("a").click(function () {
		window.location.href = this.href;
	});
	this.num = frames.length;
	if (this.num > 1) {
		var controls = $("<div class='controls'><table cellpadding='0' cellspacing='0'><tr><td class='relpart'></td><td class='cntrl'></td></tr></table></div>"),
			midCell = controls.find(".cntrl");
		for (var i = 0; i < this.num; i++) {
			$("<span>&#8226;</span>").appendTo(midCell).click((function (ind) {
				return function () {self.goTo(ind);};
			})(i));
		}
		this.getControlSpans = function () {
			return controls[0].getElementsByTagName("span");
		};
		this.spans = this.getControlSpans();
		this.spans[0].className = "current-frame";
		var relpart = controls.find(".relpart");
		this.changeRel = function () {
			var curfr = frames[self.frame];
			relpart.html(html = "<a href=\""+curfr.getAttribute("relcatlink")+"\">"+curfr.getAttribute("relcat")+"</a>");
		};
		this.changeRel();
		controls.css("width", this.width).appendTo(el);
		el.css("height", el.height() + controls.height());
		this.play();
	}
}

HomeSlide.prototype = {
	time: 4000,
	frame: 0,
	pos:0,
	changeRel: function () {},
	play: function () {
		var self = this;
		this.timer && window.clearTimeout(this.timer);
		this.timer = window.setTimeout(function () {
			self.next(true);
		}, this.time);
	},
	next: function (timed) {
		if (timed && this.paused) return;
		this.goTo(this.frame + 1 < this.num ? this.frame + 1 : 0);
	},
	prev: function () {
		this.goTo(this.frame - 1 >= 0 ? this.frame - 1 : this.num - 1);
	},
	goTo: function (index) {
		if (this.animating) return;
		this.spans = this.getControlSpans();
		this.spans[this.frame].className = "";
		this.frame = index;
		this.changeRel();
		this.spans[this.frame].className = "current-frame";
		var current = this.pos,
			next = (this.frame * this.width) * -1;
		this.anim(current, next);
	},
	anim: function (current, next) {
		var self = this;
		
		this.content.animate({left: next}, 400, function () {
			self.pos = next;
			self.animating = false;
			self.play();
		});
	}
}

function Slider (el)
{
	this.container = $(el);
	this.content = this.container.find(".slidercontent");
	this.frames = this.content.find(".sliderframe");
	var h = parseInt(this.container.attr("height")),
		paddingSide = parseInt($(this.frames[0]).css("padding-left")) * 2,
		w = this.container.width(),
		fw = parseInt(this.container.attr("frameswidth"));
	this.scrollAmount = parseInt(this.container.attr("scroll"));
	this.container.css({height: h, width:w});
	this.content.css({height: h, width: this.frames.length * (fw + paddingSide)});
	this.frames.css("width", fw);
	this.controlLeft = $("<div class='slidercontrol sliderleft'></div>").css("height", h).prependTo(this.container);
	this.contentWrapper = $("<div class='sliderwrap'></div>").css({width: w - (this.controlLeft.width() * 2), height:h}).append(this.content).appendTo(this.container);
	this.controlRight = $("<div class='slidercontrol sliderright'></div>").css("height", h).appendTo(this.container);
	var self = this;
	this.controlLeft.mousedown(function () {
		self.startMove("left");
	}).mouseup(function () {
		self.stopMove();
	});
	this.controlRight.mousedown(function () {
		self.startMove("right");
	}).mouseup(function () {
		self.stopMove();
	});
	this.contentWrapper[0].scrollLeft = 0;
}

Slider.prototype = {
	timer: null,
	startMove: function (dir) {
		var inc = dir === "left" ? -1 : 1,
			wrapper  = this.contentWrapper[0],
			current = wrapper.scrollLeft,
			amount = this.scrollAmount * inc,
			scroll = function () {
				current += amount;
				wrapper.scrollLeft = current;
			};
		scroll();
		this.timer = window.setInterval(scroll, 10);
	},
	stopMove: function () {
		window.clearInterval(this.timer);
	}
};
