// Box MultiHeight
/**
* Modifica l'altezza di un "box multi altezza"
*
* elementId       id del componente "box multi altezza"
* className       class della nuova altezza
* classNamePrefix prefisso dei class di impostazione altezza (per rimozione)
*/
function setHeigthBoxMultiHeight(elementId, className, parentClassName, classNamePrefix) {
/*	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
		var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
		if (ieversion <= 6) {
			// disable buttons
			$(elementId).up().getElementsByClassName('box_NewsVisualizer')[0].hide();
			return;
		}
	}
*/
	var classNames = $w($(elementId).className);  
	
	for (var i = 0; i < classNames.size(); i++) {
		if (classNames[i].startsWith(classNamePrefix)) {
			$(elementId).removeClassName(classNames[i]);
		}
	}

	var parent = $(elementId).up();
	classNames = $w(parent.className); 
	
	for (var i = 0; i < classNames.size(); i++) {
		if (classNames[i].startsWith(classNamePrefix)) {
			parent.removeClassName(classNames[i]);
		}
	}
	
	$(elementId).addClassName(className);
	parent.addClassName(parentClassName);
	
	var ulElm = $(elementId).getElementsBySelector('ul')[0];
	resetTopBoxMultiHeight(ulElm, 'top_NMH_01', 'top_');
}

/**
* Imposta il bottone selezionato di un "box multi altezza"
*
* selectedId  id del bottone da selezioanre
* unselected  id dei bottoni da deselezioanre separati da spazi
*/
function setSelectedBoxMultiHeight(selectedId, unselected) {
	var unselectedElements = $w(unselected);
  
	for (var i = 0; i < unselectedElements.size(); i++) {
		if ($(unselectedElements[i])) {
			$(unselectedElements[i]).removeClassName('selected');
		}
	}
  
	$(selectedId).addClassName('selected');
}

/**
* Imposta l'offset di un "box multi altezza" per permetterne lo scrolling
*
* elementId       id del componente "box multi altezza"
* up		      true se sale
*/
function setTopBoxMultiHeight(elementId, up, count) {
	var divElm = $(elementId);
	var ulElm = divElm.getElementsBySelector('ul')[0];
	
	if (divElm.hasClassName('height_NMH_01')) {
		if (up) {
			if (ulElm.hasClassName('top_NMH_02')) {
				ulElm.removeClassName('top_NMH_02');
				ulElm.addClassName('top_NMH_01');
			} else if (ulElm.hasClassName('top_NMH_03')) {
				ulElm.removeClassName('top_NMH_03');
				ulElm.addClassName('top_NMH_02');
			}
		} else {
			if (ulElm.hasClassName('top_NMH_01') && count > 4) {
				ulElm.removeClassName('top_NMH_01');
				ulElm.addClassName('top_NMH_02');
			} else if (ulElm.hasClassName('top_NMH_02') && count > 8) {
				ulElm.removeClassName('top_NMH_02');
				ulElm.addClassName('top_NMH_03');
			}
		}
	} else if (divElm.hasClassName('height_NMH_02')) {
		if (up) {
			if (ulElm.hasClassName('top_NMH_02')) {
				ulElm.removeClassName('top_NMH_02');
				ulElm.addClassName('top_NMH_01');
			}
		} else {
			if (ulElm.hasClassName('top_NMH_01') && count > 8) {
				ulElm.removeClassName('top_NMH_01');
				ulElm.addClassName('top_NMH_02');
			}
		}
	}
}

function resetTopBoxMultiHeight(elementId, className, classNamePrefix) {
	var classNames = $w($(elementId).className);  
	
	for (var i = 0; i < classNames.size(); i++) {
		if (classNames[i].startsWith(classNamePrefix)) {
			$(elementId).removeClassName(classNames[i]);
		}
	}
  
	$(elementId).addClassName(className);
}


// Box Feed RSS
var rssFeedOptions = {
	get_feed_url: '/dinamiche/Feed',
	forum_json: '/rss/forum_home.json',
	blog_json: '/rss/blog_home.json',
	max_abstract_length: 90,
	forum_error_message: new Template('<li><h3 class="tit_ForumSection"><a href="#{url}">Errore nel caricamento del feed RSS.</a></h3>'),
	blog_error_message: new Template('<h3 class="tit_BlogSection"><a href="#{url}">Errore nel caricamento del feed RSS.</a></h3>'),
	forum_item_template: new Template(
		'<li>' +
			'<h3 class="tit_ForumSection"><a href="#{link}" title="#{titleNoQuot}">#{title}</a></h3>' +
			'<div class="txt_PostedBy">Postato da: #{author}</div>' +
			'<a href="#{link}" class="link_PostNumber" title="#{titleNoQuot}">#{replies}</a>' +
			'<a href="#{link}" class="link_ReadPost" title="leggi tutto">leggi tutto</a>' +
			'<div class="clear">&nbsp;</div>' +
		'</li>'),
	blog_item_template: new Template(
		'<div class="box_Img" style="width: 185px;">' +
			'<a href="#{link}" title="#{titleNoQuot}">' +
				'<img class="img_blog_entry" style="display: none" src="" alt="#{titleNoQuot}" />' +
			'</a>' +
		'</div>' +
		'<h3 class="tit_BlogSection"><a href="#{linkBlog}" title="#{titleBlogNoQuot}">#{titleBlog}</a></h3>' +
		'<h4 class="tit_News"><a href="#{link}" title="#{titleNoQuot}">#{title}</a></h4>' +
		'<div class="txt_Abstract"><p>#{postAbstract}</p></div>' +
		'<a href="#{linkCommenti}" class="link_Comment" title="Commenti">#{numCommenti}</a>' +
		'<div class="clear">&nbsp;</div>')
};

// Box Feed RSS
var rssFeedOptions2 = {
	get_feed_url: '/dinamiche/Feed',
	forum_json: '/rss/forum_home.json',
	blog_json: '/rss/blog2_home.json',
	max_abstract_length: 90,
	forum_error_message: new Template('<li><h3 class="tit_ForumSection"><a href="#{url}">Errore nel caricamento del feed RSS.</a></h3>'),
	blog_error_message: new Template('<h3 class="tit_BlogSection"><a href="#{url}">Errore nel caricamento del feed RSS.</a></h3>'),
	forum_item_template: new Template(
		'<li>' +
			'<h3 class="tit_ForumSection"><a href="#{link}" title="#{titleNoQuot}">#{title}</a></h3>' +
			'<div class="txt_PostedBy">Postato da: #{author}</div>' +
			'<a href="#{link}" class="link_PostNumber" title="#{titleNoQuot}">#{replies}</a>' +
			'<a href="#{link}" class="link_ReadPost" title="leggi tutto">leggi tutto</a>' +
			'<div class="clear">&nbsp;</div>' +
		'</li>'),
	blog_item_template: new Template(
		'<div class="box_Img" style="width: 185px;">' +
			'<a href="#{link}" title="#{titleNoQuot}">' +
				'<img class="img_blog_entry" style="display: none" src="" alt="#{titleNoQuot}" />' +
			'</a>' +
		'</div>' +
		'<h4 class="tit_News"><a href="#{link}" title="#{titleNoQuot}">#{title}</a></h4>' +
		'<div class="txt_Abstract"><p>#{postAbstract}</p></div>' +
		'<a href="#{linkCommenti}" class="link_Comment" title="Commenti">#{numCommenti}</a>' +
		'<div class="clear">&nbsp;</div>')
};

var rssFeedOptions3 = {
	get_feed_url: '/dinamiche/Feed',
	forum_json: '/rss/forum_home.json',
	blog_json: '/rss/blog_home.json',
	max_abstract_length: 90,
	forum_error_message: new Template('<li><h3 class="tit_ForumSection"><a href="#{url}">Errore nel caricamento del feed RSS.</a></h3>'),
	blog_error_message: new Template('<h3 class="tit_BlogSection"><a href="#{url}">Errore nel caricamento del feed RSS.</a></h3>'),
	forum_item_template: new Template(
		'<li>' +
			'<h3 class="tit_ForumSection"><a href="#{link}" title="#{titleNoQuot}">#{title}</a></h3>' +
			'<div class="txt_PostedBy">Postato da: #{author}</div>' +
			'<a href="#{link}" class="link_PostNumber" title="#{titleNoQuot}">#{replies}</a>' +
			'<a href="#{link}" class="link_ReadPost" title="leggi tutto">leggi tutto</a>' +
			'<div class="clear">&nbsp;</div>' +
		'</li>'),
	blog_item_template: new Template(
		'<div class="box_Img" style="width: 185px;">' +
			'<a href="#{link}" title="#{titleNoQuot}">' +
				'<img class="img_blog_entry" style="display: none" src="" alt="#{titleNoQuot}" />' +
			'</a>' +
		'</div>' +
		'<h4 class="tit_News"><a href="#{link}" title="#{titleNoQuot}">#{title}</a></h4>' +
		'<div class="txt_Abstract"><p>#{postAbstract}</p></div>' +
		'<a href="#{linkCommenti}" class="link_Comment" title="Commenti">#{numCommenti}</a>' +
		'<div class="clear">&nbsp;</div>')
};


var RssBox = Class.create();
RssBox.prototype = {
	initialize: function (boxId, url, type, large, fromStatic) {
		if(type == 'blog2')
			this.options = rssFeedOptions2;
		else if(fromStatic)
			this.options = rssFeedOptions3;
		else this.options = rssFeedOptions;
		this.boxId = boxId;
		this.url = url;
		this.type = type;
		this.large = large;
		
		this.baseElm = $(this.boxId + '_contents');
		
		if (fromStatic) {
			new Ajax.Request(this.type == 'forum' ? this.options.forum_json : this.options.blog_json, {
				onSuccess: this.updateRssContent.bind(this),
				onFailure: this.updateRssError.bind(this) 
			});
		} else {
			new Ajax.Request(this.options.get_feed_url, {
				parameters: { 
					link: this.url, 
					last: '' 
				},
				onSuccess: this.updateRssContent.bind(this),
				onFailure: this.updateRssError.bind(this) 
			});
		}
	},

	updateRssContent: function (transport) {
		// evaluating response -> defines var newContent
		eval(transport.responseText);

		this.baseElm.innerHTML = '';
		if (this.large) {
			$(this.boxId + '_contents_2').innerHTML = '';
			$(this.boxId + '_contents_3').innerHTML = '';
		}
		
		// checking whether link it is allowed
		if (newContent.not_allowed) {
			this.updateRssError();
			return;
		}
		
		if (this.type == 'forum') {
			var num_items = this.large ? 9 : 3;
			for (var i = 0; i < num_items && i < newContent.entries.length; i++) {
				var target = this.baseElm;
				if (i >= 3) {
					target = $(this.boxId + '_contents_2');
				}
				if (i >= 6) {
					target = $(this.boxId + '_contents_3');
				}
				var entry = newContent.entries[i];
				var linkUrl = entry.link;
				if (!linkUrl || linkUrl == '') {
					linkUrl = newContent.link;
				}
				
				itemText = this.options.forum_item_template.evaluate({
					title: entry.title,
					titleNoQuot: entry.title.replace(/\"/g, "&quot;"),
					category: entry.category,
					link: linkUrl,
					author: entry.author,
					replies: entry.description
				});
			
				new Insertion.Bottom(target, itemText);
			}
		} else if (this.type == 'blog' || this.type == 'blog2') {
			var num_items = this.large ? 3 : 1;
			for (var i = 0; i < num_items && i < newContent.entries.length; i++) {
				var target = this.baseElm;
				if (i >= 1) {
					target = $(this.boxId + '_contents_2');
				}
				if (i >= 2) {
					target = $(this.boxId + '_contents_3');
				}
				var entry = newContent.entries[i];
				var linkUrl = entry.link;
				if (!linkUrl || linkUrl == '') {
					linkUrl = newContent.link;
				}
				
				var contents = entry.contents;
				var postAbstract = contents.stripTags().truncate(this.options.max_abstract_length);

				var regexp = new RegExp('<img [^>]*src="([^"]+)"[^>]*>');
				var result = regexp.exec(contents);
				var image = result == null ? "" : result[1];
				
				itemText = this.options.blog_item_template.evaluate({
					title: entry.title,
					titleNoQuot: entry.title.replace(/\"/g, "&quot;"),
					category: entry.category,
					link: linkUrl,
					linkBlog: newContent.link,
					titleBlog: newContent.title,
					titleBlogNoQuot: newContent.title.replace(/\"/g, "&quot;"),
					postAbstract: postAbstract,
					linkCommenti: entry.repliesLink,
					numCommenti: entry.repliesCount + ' ' + (entry.repliesCount == 1 ? 'commento' : 'commenti')
				});
			
				new Insertion.Bottom(target, itemText);
				var imgPreloader = new Image(); 
				imgPreloader.onload = this.onImageLoaded.bind(this, imgPreloader, target);
				imgPreloader.src = image;
			}
		}
	},
	
	onImageLoaded: function (imgPreloader, target) {
		var imgElm = target.getElementsByClassName('img_blog_entry')[0];
		$(imgElm).src = imgPreloader.src;
	
		var ratio = imgPreloader.width / imgPreloader.height;
		if (ratio > (185 / 103)) {
			$(imgElm).setStyle({ 
				width: '185px' 
			}); 
		} else {
			$(imgElm).setStyle({ 
				height: '103px' 
			}); 
		}
		$(imgElm).show();
		imgPreloader.onload = function() {};
	},
	
	updateRssError: function () {
		this.baseElm.innerHTML = '';
		var text = this.type == 'forum' ? this.options.forum_error_message.evaluate({ url: this.url }) : this.options.blog_error_message.evaluate({ url: this.url }) ;
		new Insertion.Bottom(this.baseElm, text);
	}	
}

//
// popup
//
var PopUp = Class.create();
PopUp.prototype = {
	initialize: function(options) {
		this.options = {
			url: '#',
			pageName: '',
			width: 450,
			height: 270,
			toolbar: 0,
			resizable: 1,
			scrollbars: 1,
			left: 200,
			top: 200
		}
		Object.extend(this.options, options || {});
		if (this.options.pageName == 'NotiziaPrint') { this.options.width=765; this.options.height = 600; }
		if (this.options.pageName == 'NotiziaMail') { this.options.width=650; this.options.height = 690; }
		if (this.options.pageName == 'InformativaPrivacy') { this.options.height = 500; }
		if (this.options.pageName == 'CondizioniUtilizzo') { this.options.height = 500; }
		if (this.options.pageName == 'web2info') { this.options.scrollbars = 0; this.options.height = 560; }
		window.open(this.options.url, this.options.pageName, 'width='+this.options.width+',height='+this.options.height+',toolbar='+this.options.toolbar+',scrollbars='+this.options.scrollbars+',resizable='+this.options.resizable);
	}
}

// Menu
function impostaMenu(id1, id2, id3, id4, id5)
{
	var toggle = true;
	
	try
	{
		if(!Object.isUndefined(toggleMenu))
		{
			if(toggleMenu != null && toggleMenu==false)
				toggle = false
		}
	}
	catch(e) {}
	
	if(toggle)
	{
		if(!Object.isUndefined(id1) && id1 != null && $('nav_'+id1) != null)
		{
				$('nav_'+id1).toggleClassName('selected');
		}
		if(!Object.isUndefined(id2) && id2 != null && $('nav_'+id2) != null)
		{
				$('nav_'+id2).toggleClassName('selected');
		}
		if(!Object.isUndefined(id3) && id3 != null && $('nav_'+id3) != null)
		{
				$('nav_'+id3).toggleClassName('selected');
		}
		if(!Object.isUndefined(id4) && id4 != null && $('nav_'+id4) != null)
		{
				$('nav_'+id4).toggleClassName('selected');
		}
	}
	else
	{
		if(!Object.isUndefined(id1) && id1 != null && $('nav_'+id1) != null && !($('nav_'+id1).hasClassName('selected')))
		{
				$('nav_'+id1).addClassName('selected');
		}
		if(!Object.isUndefined(id2) && id2 != null && $('nav_'+id2) != null && !($('nav_'+id2).hasClassName('selected')))
		{
				$('nav_'+id2).addClassName('selected');
		}
		if(!Object.isUndefined(id3) && id3 != null && $('nav_'+id3) != null && !($('nav_'+id3).hasClassName('selected')))
		{
				$('nav_'+id3).addClassName('selected');
		}
		if(!Object.isUndefined(id4) && id4 != null && $('nav_'+id4) != null && !($('nav_'+id4).hasClassName('selected')))
		{
				$('nav_'+id4).addClassName('selected');
		}
	}
}

// Search
function ricerca_sitesearch(qt, type) 
{
	if(Object.isUndefined(type) || type == null)
		type = 'sito';
	
	if ($(qt).value == '') 
	{
		$(qt).setStyle({ 'background-color': '#FFCCCC' });
		$(qt).focus();
		return;
	} 
	else 
	{
		$(qt).setStyle({ 'background-color': '' });
	}
	if(type=='sito')
		document.location="/cerca/"+$(qt).value;
	else
		document.location="/ricerca"+type+"/"+$(qt).value;
}

// Check if banner is present
function bannerPresent(divElm) {
	var banner = $(divElm).descendants().find(function (elm) {
		if (elm.nodeType != 1) { // not an element
			return false;
		}
		if (elm.tagName.toUpperCase().indexOf('SCRIPT')>=0 ||
				elm.tagName.toUpperCase() == 'A') {
			return false;
		}
		
		if (elm.tagName.toUpperCase() == 'IMG') {
			return elm.width > 10 && elm.height > 10;
		}
		
		return true;
	});
	
	if (banner) {
		return true;
	}
	return false;
}

function checkAllBanners() {
	$$('.box_Banner').each(function (elm) {
		var parent = $(elm).up();
		var parentUp = $(elm).up().up();
		if (parent.hasClassName('bnr_Hidden')) {
			if (bannerPresent(elm)) {
				parent.removeClassName('bnr_Hidden');
			} else if (!parent.hasClassName('box_LeaderBoard')) {
				parent.hide();
			}
		} else if (parentUp.hasClassName('bnr_Hidden')) {
			if (bannerPresent(elm)) {
				parentUp.removeClassName('bnr_Hidden');
			} else {
				parentUp.hide();
			}
		}
    else if (parent.hasClassName('bnr_ToHidden')) {
			if (!bannerPresent(elm)) {
				parent.addClassName('bnr_Hidden');
			}
		} else if (parentUp.hasClassName('bnr_ToHidden')) {
			if (!bannerPresent(elm)) {
				parentUp.addClassName('bnr_Hidden');
			}
		}
	});
}

Event.observe(window, 'load', checkAllBanners);

// mediacenter - link back
function setBackLinkMediacenter(cType, cId) {
	document.cookie = 'amodei.ts.backlinkmc=' + cType + '_' + cId +  '_' + document.location.href + '; path=/';
}

function clearBackLinkMediacenter() {
	if (!preserveBackLink) {
		document.cookie = 'amodei.ts.backlinkmc=; expires=' + new Date().toGMTString() + '; path=/';
	}
}

var preserveBackLink = false;
function getBackLinkMediacenter(cType, cId) {
	var regexp = new RegExp('amodei.ts.backlinkmc=([^_]+)_([^_]+)_([^;]+)');
	var result = regexp.exec(document.cookie);
	
	if (result == null) {
		return;
	}
	
	if (result[1] != cType || result[2] != cId) {
		return;
	}
	
	document.write('<a href="' + result[3].replace(/"/g, '&quot;') + '" class="link_BackToArticle" title="Torna all\'articolo">Torna all\'articolo</a>');
	Event.observe(window, 'unload', clearBackLinkMediacenter);
}

// mediacenter foto -> slideshow
var SlideShow = Class.create();
SlideShow.prototype = {
	initialize: function (urlTemplate, pid, index, totalCount) {
		this.urlTemplate = new Template(urlTemplate);
		this.pid = pid;
		this.index = index;
		this.totalCount = totalCount;
		this.changeInterval = 5; // seconds
		
		var temp = $$('.link_PlaySlideshow');
		if (temp.length == 0) {
			return;
		}
		
		this.elm = temp[0];
		this.checker = null;
		this.active = this.getActiveCookie();
		
		if (this.active) {
			this.changeButton();
			this.startChecker();
		}
		
		Event.observe(this.elm, 'click', this.doButtonPressed.bind(this));
	},
	
	doButtonPressed: function () {
		this.active = !this.active;
		if (this.active) {
			this.startChecker();
		} else {
			this.stopChecker();
		}
		this.setActiveCookie();
		this.changeButton();
	},
	
	stopChecker: function () {
		if (this.checker != null) {
			this.checker.stop();
			this.checker = null;
		}
	},
	
	startChecker: function () {
		this.stopChecker();
		this.checker = new PeriodicalExecuter(this.doPageChange.bind(this), this.changeInterval);
	},
	
	doPageChange: function () {
		if (this.active) {
			var target = this.urlTemplate.evaluate({ 
				index: (this.index < (this.totalCount - 1) ? (this.index + 1) : 0) 
			});
			preserveBackLink = true;
			document.location.href = target;
		}
	},
	
	getActiveCookie: function () {
		var regexp = new RegExp('amodei.ts.slideshowpg=([^ ;]+)');
		var result = regexp.exec(document.cookie);
		return result != null && result[1] == this.pid;
	},
	
	setActiveCookie: function () {
		if (this.active) {
			document.cookie = 'amodei.ts.slideshowpg=' + this.pid + '; path=/';
		} else {
			document.cookie = 'amodei.ts.slideshowpg=; expires=' + new Date().toGMTString() + '; path=/';
		}
	},
	
	changeButton: function () {
		if (this.active) {
			this.elm.removeClassName('link_PlaySlideshow');
			this.elm.addClassName('link_StopSlideshow');
			this.elm.title = "Ferma Slideshow";
		} else {
			this.elm.removeClassName('link_StopSlideshow');
			this.elm.addClassName('link_PlaySlideshow');
			this.elm.title = "Esegui Slideshow";
		}
	}	
};

// meidacenter foto -> lista thumbs
function moveThumbs(right, boxDim, totalCount) {
	if (totalCount < 5) {
		return;
	}
	var elm = $('box_thumbsContent');
	var left = parseInt(elm.style.left.replace('px',''));
	var newLeft = left + (right ? -1 : 1) * boxDim;
	if (newLeft > 0) {
		newLeft = 0;
	}
	// 4 boxes to show
	if (newLeft < -1 * (totalCount - 4) * boxDim) {
		newLeft = -1 * (totalCount - 4) * boxDim;
	}
	elm.setStyle({ left: newLeft + 'px' });
}

// mediacenter foto -> main image
function setMainImage(imgUrl, divId) {
	var imgPreloader = new Image(); 
	imgPreloader.onload = function () { 
		$(divId).src = imgPreloader.src; 
		$(divId).up().setStyle({ 
			width: imgPreloader.width + 'px' /*, 
			height: imgPreloader.height + 'px' */
		}); 
		$(divId).show(); 
		imgPreloader.onload = function() {}; 
	};
	imgPreloader.src = imgUrl; 
}

function showError(msg, ok) {
	if (ok) {
		$('error_message').className = "txt_Info";
	} else {
		$('error_message').className = "txt_Error";
	}
	$('error_message').innerHTML = msg;
	$('error_message').show();
	$('error_message').scrollTo();
}

function VotaTopFlop(matchName) {
	var myForm = $('topflop_data');
	var params = myForm.serialize(true);
	myForm.disable();

	var topflopVotaUrl = "/dinamiche/TopFlop";
	var topflopMedieUrl = "medie_" + matchName + ".html";
	
	new Ajax.Request(topflopVotaUrl, {
		method: 'POST',
		parameters: params,
		onSuccess: function (transport) {
			eval(transport.responseText); // defines vote
			if (vote.ok) {
				document.location.href = topflopMedieUrl + "?ok=true";
			} else if (vote.duplicate) {
				document.location.href = topflopMedieUrl + "?dup=true";
			} else if (vote.msg) {
				showError('Errore nel salvataggio dei voti: ' + vote.msg);
			} else {
				showError('Errore nel salvataggio dei voti.');
			}
		},
		onFailure: function () {
			showError('Errore di connessione al server. Riprovare fra qualche istante.');
		}
	});			
}

function setTopFlopVoteResult() {
	var params = document.location.href.toQueryParams();
	if (params.ok) {
		this.showError("Grazie per aver votato.<br/>Il tuo voto sar\u00e0 conteggiato entro 3 minuti", true);
	} else if (params.dup) {
		this.showError("Attenzione! Hai gi\u00e0 votato per questa partita");
	}
}

// MHBManager
var MHBManager = Class.create();
MHBManager.prototype = {
	initialize: function (where, classname) {
		this.where = where;
		this.classname = classname;
		this.cookieName = 'amodei.tuttosport.mhb.' + this.where;

		this.reorderTo(this.getBoxListFromCookie());
		
		this.getBoxList().each(function (box) {
			var upLink = box.getElementsByClassName('link_NHM_Up')[0];
			var downLink = box.getElementsByClassName('link_NHM_Down')[0];
			if (upLink) {
				Event.observe(upLink, 'click', this.move.bind(this, box, true));
			}
			if (downLink) {
				Event.observe(downLink, 'click', this.move.bind(this, box, false));
			}
		}.bind(this));
	},
	
	getBoxListFromCookie: function () {
		var regexp = new RegExp(this.cookieName + '=([^ ;]+)');
		var result = regexp.exec(document.cookie);
		
		if (result == null) {
			return null;
		}
		
		var temp = result[1].split(",");
		return $A(temp);
	},
	
	saveCookie: function () {
		var cookieValue = this.getBoxList().pluck('id').join(',');
		document.cookie = this.cookieName + '=' + cookieValue;
	},
	
	getBoxList: function () {
		return $$('.' + this.classname);
	},
	
	reorderTo: function (target) {
		if (!target) {
			return;
		}
		
		var boxList = this.getBoxList();		
		var counter = 0;
		for (var i = 0; i < target.length; i++) {
			var targetElm = $(target[i]);
			if (!targetElm) {
				continue;
			}
			if (counter < boxList.length && boxList[counter].id == targetElm.id) {
				counter++;
				continue;
			}
			var obj = targetElm.remove();
			if (counter < boxList.length) {
				new Insertion.Before(boxList[counter], obj);
			} else {
				new Insertion.After(boxList[boxList.length - 1], obj);
			}
			boxList = boxList.without(obj);
		}
	},
	
	move: function (what, up) {
		var boxList = this.getBoxList();
		for (var i = 0; i < boxList.length; i++) {
			if (boxList[i].id == what.id) {
				if (up) {
					if (i > 0) {
						// moving up
						var target = boxList[i - 1];
						var obj = what.remove();
						new Insertion.Before(target, obj);
						this.saveCookie();
					}
				} else {
					if (i < boxList.length - 1) {
						// moving down
						var target = boxList[i + 1];
						var obj = what.remove();
						new Insertion.After(target, obj);
						this.saveCookie();
					}
				}
			}
		}		
	}
}

function allineaTabellaDiretta(classTabella) {
	$$('.' + classTabella + ' th').each(function (cell) {
		if (cell.style.width == '139px') {
			cell.style.width = '130px';
		}
	});
}

function popup(url,width,height,pageName,scroll) {
	if (pageName == undefined) {
		pageName = "_blank";
	} else if (url == "/poker_live.html") {
		width=650;
		height=470;
	}
	var scrollyn = ((typeof scroll != "undefined") && (scroll = "1")) ? "yes":"no";
	var winl = (screen.width - width) / 2;
	var wint = (screen.height - height) / 2;
	window.open(url,pageName,'width='+width+',height='+height+',toolbar=no,scrollbars='+scrollyn+',menubar=no,resizable=no,top='+wint+',left='+winl+'');
}

function closeAD(){
    document.getElementById("ts_over").style.visibility = "hidden";
}

// This function displays the Google AdSense results.
// It must be defined above the script that calls show_ads.js
// to guarantee that it is defined when show_ads.js makes the call-back.
function google_ad_request_done(google_ads) {
	if (google_ads.length < 1 )
	  return;

	 var maxAds=google_ads.length>4 ? 4 : google_ads.length;

	document.write("<div class=\"box_000 box_Correlated inline_1\" id=\"sponsorLink\">");
	document.write("<h2 class=\"gads_tit_Box\"><a href=\"" + google_info.feedback_url + "\">Annunci Google</a></h2>");
							  
	if (google_ads[0].type == 'text') {
		if (google_ads.length>2) {
			document.write("<div class=\"list_sponsor_2c\">");
			
			document.write("<div class=\"list_sponsor_left\">");
			for(i = 0; i < 2; ++i) {
				document.write("<div class=\"list_sponsor_left\">");
				document.write("<h3 class=\"gads_tit_ad\"><a target='_blank' href='" + google_ads[i].url + "'>" + google_ads[i].line1 + "</a></h3>");
				document.write("<p class=\"gads_txt_ad\"><a target='_blank' href='" + google_ads[i].url + "'>" + google_ads[i].line2 + " "+google_ads[i].line3 + "</a><br/>");
				document.write("<span class=\"gads_url_ad\"><a target='_blank' href='" + google_ads[i].url + "'>" +google_ads[i].visible_url + "</a></span></p>");
				document.write("</div>");
			}
			document.write("</div>");

			document.write("<div class=\"list_sponsor_right\">");
			for(i = 2; i < maxAds; ++i) {
				document.write("<div class=\"list_sponsor_right\">");
				document.write("<h3 class=\"gads_tit_ad\"><a target='_blank' href='" + google_ads[i].url + "'>" + google_ads[i].line1 + "</a></h3>");
				document.write("<p class=\"gads_txt_ad\"><a target='_blank' href='" + google_ads[i].url + "'>" + google_ads[i].line2 + " "+google_ads[i].line3 + "</a><br/>");
				document.write("<span class=\"gads_url_ad\"><a target='_blank' href='" + google_ads[i].url + "'>" +google_ads[i].visible_url + "</a></span></p>");
				document.write("</div>");
			}
			document.write("</div>");
			document.write("</div>");
		}
		else {		
			for(i = 0; i < google_ads.length; ++i) {
				document.write("<div class=\"list_sponsor\">");
				document.write("<h3 class=\"gads_tit_ad\"><a target='_blank' href='" + google_ads[i].url + "'>" + google_ads[i].line1 + "</a></h3>");
				document.write("<p class=\"gads_txt_ad\"><a target='_blank' href='" + google_ads[i].url + "'>" + google_ads[i].line2 + " "+google_ads[i].line3 + "</a><br/>");
				document.write("<span class=\"gads_url_ad\"><a target='_blank' href='" + google_ads[i].url + "'>" +google_ads[i].visible_url + "</a></span></p>");
				document.write("</div>");
			}
		}
	
	}
	
	document.write("<div class=\"topLeft\">&nbsp;</div><div class=\"topRight\">&nbsp;</div><div class=\"bottomLeft\">&nbsp;</div><div class=\"bottomRight\">&nbsp;</div><div class=\"clear\"></div>");
	document.write("</div>");	
}


function fbs_click() {
	var u = location.href;
	var t = document.title;
	window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,width=626,height=436');
	return false;
}


function bottoneCondividi() {
	var url = document.location.href;
	document.write('<a href="javascript:;" id="condividi_button" onclick="openBoxCondividi()" class="btn_Share" title="Condividi"><span class="box_Ico">Share</span></a>');
	document.write(
		'<div id="condividi_box" style="display:none;" class="box_Lightbox">' +
			'<a href="javascript:;" onclick="closeBoxCondividi()" class="btn_Close" title="Chiudi">Chiudi</a>' +
			'<ul class="list_Lightbox">' +
				'<li><a href="http://www.facebook.com/share.php?u=' + url + '" onclick="return fbs_click()" target="_blank" class="fb_share_link">Facebook</a></li>' +
				'<li><img src="/res/imgs/ico_Wikio.png" alt="Wikio" /><a href="http://www.wikio.it/vote" title="Condividi su Wikio" target="_blank">Wikio</a></li>' +
				'<li><img src="/res/imgs/ico_OKNO.png" alt="OKNOtizie" /><a href="http://oknotizie.alice.it/post?url=' + url + '" title="Condividi su OKNOtizie" target="_blank">OKNOtizie</a></li>' +
			'</ul>' +
			'<div class="clear">&nbsp;</div>' +
		'</div>'		
	);
}

function openBoxCondividi() {
	Effect.Appear('condividi_box', { duration: 0.6 });
}

function closeBoxCondividi() {
	Effect.Fade('condividi_box', { duration: 0.6 });
}

/*
 * Fascioni
 */
Event.observe(window, 'load', page_loaded_specialstrip, false);
function page_loaded_specialstrip(evt) {
	try {
		var divs = $$(".specialstrip_Confederations_Cup");
		if (divs.length>0) {
			var tgt = $$(".specialstrip_Confederations_Cup")[0];
			Event.observe(tgt, 'click', function(){
				document.location.href="http://www.tuttosport.com/calcio/confederations_cup/";
			}, false);		
		}
		var divs = $$(".specialstrip_Mondiali_Nuoto");
		if (divs.length>0) {
			var tgt = $$(".specialstrip_Mondiali_Nuoto")[0];
			Event.observe(tgt, 'click', function(){
				document.location.href="http://www.tuttosport.com/mondiali_nuoto/";
			}, false);		
		}
		var divs = $$(".specialstrip_Speciale_derby");
		if (divs.length>0) {
			var tgt = $$(".specialstrip_Speciale_derby")[0];
			Event.observe(tgt, 'click', function(){
				document.location.href="http://www.tuttosport.com/speciale_derby/";
			}, false);		
		}
		var divs = $$(".specialstrip_MLB_2009");
		if (divs.length>0) {
			var tgt = $$(".specialstrip_MLB_2009")[0];
			Event.observe(tgt, 'click', function(){
				document.location.href="http://www.tuttosport.com/mlb_2009/";
			}, false);		
		}
		var divs = $$(".specialstrip_NFL");
		if (divs.length>0) {
			var tgt = $$(".specialstrip_NFL")[0];
			Event.observe(tgt, 'click', function(){
				document.location.href="http://www.tuttosport.com/nfl/";
			}, false);		
		}
		var divs = $$(".specialstrip_Vancouver_2010");
		if (divs.length>0) {
			var tgt = $$(".specialstrip_Vancouver_2010")[0];
			Event.observe(tgt, 'click', function(){
				document.location.href="http://www.tuttosport.com/vancouver_2010/";
			}, false);		
		}
		var divs = $$(".specialstrip_Sei_Nazioni");
		if (divs.length>0) {
			var tgt = $$(".specialstrip_Sei_Nazioni")[0];
			Event.observe(tgt, 'click', function(){
				document.location.href="http://www.tuttosport.com/sei_nazioni/";
			}, false);		
		}
	} catch(err) {
			try{ 
				$('.specialstrip_Sei_Nazioni').click( function(ev){document.location.href="http://www.tuttosport.com/sei_nazioni/"});
				$('.specialstrip_Vancouver_2010').click( function(ev){document.location.href="http://www.tuttosport.com/vancouver_2010/"});
			}
			catch(err_x){}
	}
}

var setModelloAnnunci = null;

function PopolaModelloAnnunci(idModello) {
	var selMarca = $(document.forms.formAnnunci.marca);
	var idMarca = selMarca.value;
	if (idMarca != '') {
		if (idModello == undefined) {
			setModelloAnnunci = '';
		} else {
			setModelloAnnunci = idModello;
		}
		new Ajax.Request("/annunci/js/modelli_" + idMarca + ".js", {
			onSuccess: PopolaModelloAnnunci_onSuccess
		});
	} else {
		var selModello = $(document.forms.formAnnunci.modello);
		selModello.innerHTML = '<option value="">---</option>';
	}
}


function PopolaModelloAnnunci_onSuccess(transport) {
	eval(transport.responseText);
	var selModello = $(document.forms.formAnnunci.modello);
	selModello.innerHTML = '<option value="">---</option>';
	$A(modelli).each(function (elm) {
		new Insertion.Bottom(selModello, '<option value="' + elm.id_modello + '">' + elm.label + '</option>');
	});
	if (setModelloAnnunci != null) {
		document.forms.formAnnunci.modello.value = setModelloAnnunci;
	}
}