(function() {
	var Dom = YAHOO.util.Dom;
	var Event = YAHOO.util.Event;
	var news = [];
	var current = -1;
	var tapparella;
	var ruota;
	var timer;
	var stop = false;
	
	next = function(e) {
		current++;
		if (current == news.length) current = 0;
		if (e === false || e == undefined) {
			anim();
		} else {
			Event.preventDefault(e);
			ruota.innerHTML = "<a href=\"" + news[current].link + "\">" + news[current].title + "</a>";
			clearTimeout(timer);
			stop = false;
			timer = setTimeout(next, 5000,false);
		}
	}

	prev = function(e) {
		current--;
		if (current < 0) current = news.length - 1;
		Event.preventDefault(e);
		ruota.innerHTML = "<a href=\"" + news[current].link + "\">" + news[current].title + "</a>";
		clearTimeout(timer);
		stop = false;
		timer = setTimeout(next, 5000,false);
	}

	anim = function() {
		var anim = new YAHOO.util.Anim(tapparella, {
			width: { to: 400 }
		}, 1, YAHOO.util.Easing.easeOut);
		anim.onComplete.subscribe(function() {
			ruota.innerHTML = "<a href=\"" + news[current].link + "\">" + news[current].title + "</a>";
			var anim = new YAHOO.util.Anim(tapparella, {
				width: { to: 0 }
			}, 1, YAHOO.util.Easing.easeOut);
			anim.onComplete.subscribe(function() {
				if (!stop) timer = setTimeout(next, 2000,false);
			});
			anim.animate();
		});
		anim.animate();
	}

	Event.on("ruota","mouseenter",function(e) {
		clearTimeout(timer);
		stop = true;
	},this);

	Event.on("ruota","mouseleave",function(e) {
		clearTimeout(timer);
		stop = false;
		timer = setTimeout(next, 5000,false);
	},this);

	Event.onDOMReady(function() {
		callback = {
			success: function(o) {
				var xml = o.responseXML;
				var items = xml.getElementsByTagName("item");
				for (var i=0; i<4 && i < items.length; i++) {
					if (items[i].getElementsByTagName("title")[0].text == undefined) {
						var title = items[i].getElementsByTagName("title")[0].textContent;
						var link = items[i].getElementsByTagName("link")[0].textContent;					
					} else {
						var title = items[i].getElementsByTagName("title")[0].text;
						var link = items[i].getElementsByTagName("link")[0].text;
					}
					news.push({"title": title, "link": link});
				}
				next(false);
			},
			failure: function(o) {
				//alert('fail');
			}
		};
		tapparella = Dom.get("tapparella");
		ruota = Dom.get("ruota");
		Event.on("news_next","click",next);
		Event.on("news_prev","click",prev);
		YAHOO.util.Connect.asyncRequest("GET", "/jobmagazine.xml", callback, null);
	},this);
})();

