// ajax requests global defaults
$.ajaxSetup({
	cache: false,
	timeout: 2 * 60 * 1000, // 2 minuti
	type: "POST"	
});


/*	Dettaglio articolo: galleria immagini	*/
var HorizontalUlSlider = Class.extend({
	// configuration
	liSel: "#slideUl li",
	openWidth: "332px",
	closedWidth: "77px",
	duration: 500,
	easing: "linear",
	
	// fields
	elms: null,
	
	// methods
	init: function (options) {
		$.extend(this, options);
		this.elms = $(this.liSel);
		var length = this.elms.length;
		for (var i = 0; i < length; i++) {
			this.elms.eq(i).mouseover(this.onMouseOver.bind(this, i));
		}
	},

	onMouseOver: function (index) {
		this.elms.stop();
		this.elms.eq(index).animate({ width: this.openWidth }, { duration: this.duration, easing: this.easing, queue: false });
		this.elms.filter('li:not(:eq(' + index + '))').animate({ width: this.closedWidth }, { duration: this.duration, easing: this.easing, queue: false });
	}
});

//Search
function ricerca_sitesearch(qt, type) {
	if (typeof type == 'undefined' || type == null) {
		type = 'sito';
	}
	
	if ($(qt).val() == '') {
		$(qt).css({ 'background-color': '#FFCCCC' });
		$(qt).focus();
		return;
	} else {
		$(qt).css({ 'background-color': '' });
	}
	
	if (type == 'sito') {
		document.location = "http://www.motosprint.it/cerca/" + $(qt).val();
	} else {
		document.location = "http://www.motosprint.it/cerca" + type + "/" + $(qt).val();
	}
}

function clean_sitesearch(elm) {
	if ($(elm).val().toUpperCase() == 'CERCA IN MOTOSPRINT.IT') {
		$(elm).val('');
	}
}

/*	HP: apertura 3 notizie	*/
var VerticalUlSlider = Class.extend({
	// configuration
	liSel: ".list_MainNews_Tab li",
	openWidth: "415px",
	closedWidth: "30px",
	duration: 500,
	easing: "linear",
	selectedClass: "li_Selected",
	
	// fields
	elms: null,
	
	// methods
	init: function (options) {
		$.extend(this, options);
		this.elms = $(this.liSel);
		var length = this.elms.length;
		for (var i = 0; i < length; i++) {
			this.elms.eq(i).click(this.onClick.bind(this, i));
		}
	},

	onClick: function (index) {
		if (this.elms.eq(index).hasClass(this.selectedClass)) {
			return true;
		}
		
		this.elms.stop();
		this.elms.eq(index).animate({ height: this.openWidth }, { duration: this.duration, easing: this.easing, queue: false, complete: function (index) {
			this.elms.eq(index).addClass(this.selectedClass);
		}.bind(this, index) });
		this.elms.filter('li:not(:eq(' + index + '))').animate({ height: this.closedWidth }, { duration: this.duration, easing: this.easing, queue: false, complete: function (index) {
			this.elms.filter('li:not(:eq(' + index + '))').removeClass(this.selectedClass);
		}.bind(this, index) });
		
		return false;
	}
});

/*	Tab switcher	*/
var TabSwitcher = Class.extend({
	// configuration
	tabSelectedClass: "li_Selected",
	conSelectedClass: "con_Selected",	
	conNotSelectedClass: "con_NotSelected",
	
	// fields
	tabSel: null,
	actions: $A(),
	active: true,
	
	// internal fields
	tabElms: null,
	currentIndex: -1,
	
	// methods
	init: function (options) {
		$.extend(this, options);
		if (this.tabSel != null) {
			this.tabElms = $(this.tabSel);
			var length = this.tabElms.length;
			for (var i = 0; i < length; i++) {
				this.tabElms.eq(i).click(this.onClick.bind(this, i));
				if (this.tabElms.eq(i).hasClass(this.tabSelectedClass)) {
					this.currentIndex = i;
				}
			}
		}
	},
	
	reset: function () {
		this.active = true;
		this.currentIndex = -1;
		this.onClick(0);
	},
	
	deactivate: function () {
		this.active = false;
		for (var i = 0; i < this.actions.length; i++) {
			var action = this.actions[i];				
			var type = action.type;
			
			if (type == 'content') {
				$(action.selector).removeClass(this.conSelectedClass).addClass(this.conNotSelectedClass);
			} else if (type == 'tab') {
				for (var j = 0; j < action.tabs.length; j++) {
					action.tabs[j].deactivate();
				}
			}
		}
	},

	onClick: function (index) {
		if (this.active && this.currentIndex != index) {
			this.currentIndex = index;
			this.tabElms.removeClass(this.tabSelectedClass).eq(index).addClass(this.tabSelectedClass);
			for (var i = 0; i < this.actions.length; i++) {
				var action = this.actions[i];				
				var type = action.type;
				
				if (type == 'content') {
					$(action.selector).removeClass(this.conSelectedClass).addClass(this.conNotSelectedClass).eq(index).removeClass(this.conNotSelectedClass).addClass(this.conSelectedClass);
				} else if (type == 'show') {
					$(action.selector).hide().eq(index).show();
				} else if (type == 'class') {
					$(action.selector).attr("class", action.values[index]);
				} else if (type == 'link') {
					$(action.selector).attr("href", action.values[index]);
				} else if (type == 'css') {
					$(action.selector).css(action.values[index]);
				} else if (type == 'tab') {
					for (var j = 0; j < action.tabs.length; j++) {
						if (j != index) {
							action.tabs[j].deactivate();
						}
					}
					action.tabs[index].reset();
				}
			}
		}
		return false;
	}
});

var targetDate = null;
function countdownTo(year, month, day, hours, minutes, seconds) {
	targetDate = Date.UTC(year, month - 1, day, hours, minutes, seconds);
	updateCountdown();
}
function updateCountdown() {
	var diff = targetDate - new Date();
	if (diff < 0) {
		diff = 0;
	}
	var days = Math.floor(diff / (24 * 60 * 60 * 1000));
	diff = diff % (24 * 60 * 60 * 1000);
	var hours = Math.floor(diff / (60 * 60 * 1000));
	diff = diff % (60 * 60 * 1000);
	var minutes = Math.floor(diff / (60 * 1000));
	$(".box_NextGP .box_CountDown span.days").html(days);
	$(".box_NextGP .box_CountDown span.hours").html(hours);
	$(".box_NextGP .box_CountDown span.minutes").html(minutes);
	setTimeout('updateCountdown()', 60 * 1000);
}

/*	HP: apertura 3 notizie	*/
var RssBox = Class.extend({
	// configuration
	getFeedUrl: "/dinamiche/Feed",
	type: null, /* blog,forum */
	boxId: null,
	rssUrl: null,
	column: "dx",
	fromStatic: true,
	blogAbstractLengthDx: 90,
	blogAbstractLengthMain: 150,
	forumJson: "/rss/forum_home.json",
	blogJson: "/rss/blog_home.json",
	forumErrorMessage: new Template('<li class="li_First"><h2 class="tit_Forum"><a href="#{url}" title="Vai al Forum" >Errore nel caricamento del feed RSS.</a></h2><div class="clear">&#160;</div></li>'),
	blogErrorMessage: new Template('<li class="li_First"><h2 class="tit_Post"><a href="#{url}" title="Vai al blog">Errore nel caricamento del feed RSS.</a></h2><div class="clear">&#160;</div></li>'),
	forumItem: new Template(
		'<li class="#{classCss}">' +
			'<h5 class="tit_Forum"><a title="" href="#{linkForum}">#{titleForum}</a></h5>' +
			'<h6 class="tit_Post"><a title="" href="#{link}">#{title}</a></h6>' +
			'<div class="txt_Author">Postato da: <span>#{author}</span></div>' +
			'<a href="#{link}" class="link_Reply" title="Leggi le repliche">#{replies}</a>' +
			'<div class="clear">&nbsp;</div>' +
		'</li>'
	),
	blogItem: new Template(
		'<li class="#{classCss}">' +
			'<h5 class="tit_Post"><a href="#{link}" title="">#{title}</a></h5>' +
			'<div class="box_Img #{imgSize}">' +
				'<a href="#{link}" title="">' +
					'<img style="display: none" src="" alt="" />' +
				'</a>' +
			'</div>' +
			'<div class="txt_Abstract"><a href="#{link}" title="">#{postAbstract}</a></div>' +
			'<a href="#{link}" class="link_More" title="Apri articolo">Apri articolo</a>' +
			'<div class="clear">&nbsp;</div>' +
		'</li>'
	),
	
	// fields
	baseElm: null,

	// methods
	init: function (options) {
		$.extend(this, options);
		this.baseElm = $('#' + this.boxId + '_contents');
		
		if (this.fromStatic) {
			$.ajax({
				url: this.type == 'forum' ? this.forumJson : this.blogJson,
				success: this.updateRssContent.bind(this),
				error: this.updateRssError.bind(this)
			});
		} else {
			$.ajax({
				url: this.getFeedUrl,
				data: { 
					link: this.rssUrl, 
					last: '' 
				},
				success: this.updateRssContent.bind(this),
				error: this.updateRssError.bind(this)
			});
		}
	},

	updateRssContent: function (data) {
		// evaluating response -> defines var newContent
		eval(data);

		// checking whether link it is allowed
		if (newContent.not_allowed) {
			this.updateRssError();
			return;
		}
		
		this.baseElm.html('');
		
		if (this.type == 'forum') {
			var num_items = 2;
			for (var i = 0; i < num_items && i < newContent.entries.length; i++) {
				var entry = newContent.entries[i];
				
				var itemText = this.forumItem.evaluate({
					titleForum: newContent.title,
					linkForum: newContent.link,
					title: entry.title,
					link: entry.link,
					author: entry.author,
					replies: entry.description,
					classCss: i == 0 ? 'li_First' : 'li_Last'
				});
			
				this.baseElm.append(itemText);
			}
		} else if (this.type == 'blog') {
			var num_items = 1;
			for (var i = 0; i < num_items && i < newContent.entries.length; i++) {
				var entry = newContent.entries[i];
				
				var contents = entry.contents;
				var postAbstract = contents.stripTags().truncate(this.column == 'dx' ? this.blogAbstractLengthDx : this.blogAbstractLengthMain);

				var regexp = new RegExp('<img [^>]*src="([^"]+)"[^>]*>');
				var result = regexp.exec(contents);
				var image = result == null ? "" : result[1];
				
				var itemText = this.blogItem.evaluate({
					title: entry.title,
					link: entry.link,
					postAbstract: postAbstract,
					imgSize: this.column == 'dx' ? 'img_xs' : 'img_m',
					classCss: i == 0 ? 'li_First' : 'li_Last'
				});
			
				this.baseElm.append(itemText);

				var imgPreloader = new Image(); 
				imgPreloader.onload = this.onImageLoaded.bind(this, imgPreloader, i);
				imgPreloader.src = image;
			}
		}
	},

	onImageLoaded: function (imgPreloader, index) {
		var imgElm = this.baseElm.find("li").eq(index).find("img");
		imgElm.attr("src", imgPreloader.src);
	
		var ratio = imgPreloader.width / imgPreloader.height;
		if (this.column == "dx") {
			if (ratio > (95 / 56)) {
				imgElm.css({ 
					width: '95px' 
				}); 
			} else {
				imgElm.css({ 
					height: '56px' 
				}); 
			}
		} else {
			if (ratio > (332 / 196)) {
				imgElm.css({ 
					width: '332px' 
				}); 
			} else {
				imgElm.css({ 
					height: '196px' 
				}); 
			}
		}
		imgElm.show();
		imgPreloader.onload = function() {};
	},

	updateRssError: function () {
		var text = this.type == 'blog' ? this.blogErrorMessage.evaluate({ url: this.rssUrl }) : this.forumErrorMessage.evaluate({ url: this.rssUrl });
		this.baseElm.html(text);
	}	
});

/** 
 * PopUp
 */
var PopUp = Class.extend({
	// configuration
	url: '#',
	pageName: '',
	width: 450,
	height: 270,
	toolbar: 0,
	resizable: 1,
	scrollbars: 1,
	left: 200,
	top: 200,
	
	// methods
	init: function (options) {
		$.extend(this, options);
		
		if (this.pageName == 'NotiziaPrint') { 
			this.width = 765; 
			this.height = 600; 
		} else if (this.pageName == 'NotiziaMail') { 
			this.width = 800; 
			this.height = 750; 
		} else if (this.pageName == 'Disclaimer') { 
			this.width = 800; 
			this.height = 700; 
		} else if (this.pageName == 'Privacy') { 
			this.width = 800; 
			this.height = 700; 
		} else if (this.pageName == 'LvscRaceCenter') { 
			this.width = 900 
			this.height = 850; 
		}

		window.open(this.url, this.pageName, 'width='+this.width+',height='+this.height+',toolbar='+this.toolbar+',scrollbars='+this.scrollbars+',resizable='+this.resizable);
	}
});

// mediacenter foto -> slideshow
var SlideShow = Class.extend({
	// configuration
	btnSelector: "div.box_MainPhoto a.link_PlaySlideshow, div.box_MainPhoto a.link_StopSlideshow",
	urlTemplate: null,
	idGalleria: null,
	index: 0,
	countImages: 0,
	changeInterval: 5, // seconds
	cookieName: "amodei.ms.slideshowpg",
	playClass: "link_PlaySlideshow",
	stopClass: "link_StopSlideshow",

	// fields
	urlTemplateObj: null,
	checker: null,
	active: false,
	
	// methods
	init: function (options) {
		$.extend(this, options);
		
		this.urlTemplateObj = new Template(this.urlTemplate);
		this.active = this.getActiveCookie();
		
		if (this.active) {
			this.changeButton();
			this.startChecker();
		}
		
		$(this.btnSelector).bind('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.urlTemplateObj.evaluate({ 
				index: (this.index < (this.countImages - 1) ? (this.index + 1) : 0) 
			});
			document.location.href = target;
		}
	},
	
	getActiveCookie: function () {
		var regexp = new RegExp(this.cookieName + '=([^ ;]+)');
		var result = regexp.exec(document.cookie);
		return result != null && result[1] == this.idGalleria;
	},
	
	setActiveCookie: function () {
		if (this.active) {
			document.cookie = this.cookieName + '=' + this.idGalleria + '; path=/';
		} else {
			document.cookie = this.cookieName + '=; expires=' + new Date().toGMTString() + '; path=/';
		}
	},
	
	changeButton: function () {
		if (this.active) {
			$(this.btnSelector).removeClass(this.playClass).addClass(this.stopClass).attr("title", "Ferma Slideshow");
		} else {
			$(this.btnSelector).removeClass(this.stopClass).addClass(this.playClass).attr("title", "Esegui Slideshow");
		}
	}	
});

// meidacenter foto -> lista thumbs
function moveThumbs(right, boxDim, totalCount) {
	var selector = "div.box_Photo_Slider ul.content";
	if (totalCount <= 4) {
		return;
	}
	var left = parseInt($(selector).css('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;
	}
	$(selector).css('left', newLeft + 'px');
}

/**
* bottoneCondividi
*/
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() {
	document.write('<label class="lbl_Condividi">Condividi</label><a href="javascript:;" id="condividi_button" onclick="openBoxCondividi()" class="link_Share" title="Condividi">Condividi</a>');
	//var target = .get(0);
	var url = document.location.href;
	$('#condividi_button').parent().before(
		'<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.gif" alt="Wikio" /><a href="http://www.wikio.it/vote" title="Condividi su Wikio">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">OKNOtizie</a></li>' +
			'</ul>'+
			'<div class="clear">&#160;</div>'+
		'</div>'
	);
}


function openBoxCondividi() {
	$('#condividi_box').show(600);
}

function closeBoxCondividi() {
	$('#condividi_box').hide(600);
}

function showError(where, message) {
	$('#error_' + where).html(message);
	$('#error_' + where).parent(".box_FormElement").addClass("box_Form_Error");
	scrollToElement($('#error_' + where).parent(".box_FormElement"));
}

function hideError(where) {
	$('#error_' + where).parent(".box_FormElement").removeClass("box_Form_Error");
}

function validateLoginCommenti() {
	var selFormLogin = "#formLoginCommenti";
	if ($(selFormLogin).find("input[name='user']").val() == '') {
		showError('user', 'Campo "nickname" non valorizzato');
		$(this.selForm).find("input[name='user']").focus();
		return false;
	} else {
		hideError('user');
	}
	if ($(selFormLogin).find("input[name='pwd']").val() == '') {
		showError('user', 'Campo "password" non valorizzato');
		$(this.selForm).find("input[name='pwd']").focus();
		return false;
	} else {
		hideError('pwd');
	}
	return true;
}

function toggleClassifica(){	
	if ($('#id_Tables').is(".View_Main_05_Pos")) {
	
		box_Risultati_Content_height_1 = box_Risultati_Content_1;
		box_Risultati_Content_height_2 = box_Risultati_Content_2;
		
		box_Classifica_Content_height_1 = box_Classifica_Content_1;
		box_Classifica_Content_height_2 = box_Classifica_Content_2;
		
		try{
			if(ts_main.currentIndex == 0){
				$("#id_Tables .box_Tabbed_Risultati").css({height: box_Risultati_Content_height_1});				
			} else {
				$("#id_Tables .box_Tabbed_Risultati").css({height: box_Risultati_Content_height_2});				
			}
			
			if(ts_classifica_main.currentIndex == 0){				
				$("#id_Tables .box_Tabbed_Classifica").css({height: box_Classifica_Content_height_1});
			} else {				
				$("#id_Tables .box_Tabbed_Classifica").css({height: box_Classifica_Content_height_2});
			}
			
			ts_main.actions[1].values = [{height: box_Risultati_Content_height_1}, {height: box_Risultati_Content_height_2}];
			ts_classifica_main.actions[1].values = [{height: box_Classifica_Content_height_1}, {height: box_Classifica_Content_height_2}];
		} catch(e){}
		
		$('#id_Tables').removeClass("View_Main_05_Pos").addClass("View_Main_All");
		$('#leggi_chiudi_classifica').removeClass("link_OpenList").addClass("link_CloseList");			
		
	} else {
	
		box_Risultati_Content_height_1 = box_Risultati_Content_close;
		box_Risultati_Content_height_2 = box_Risultati_Content_close;
		
		box_Classifica_Content_height_1 = box_Classifica_Content_1;
		box_Classifica_Content_height_2 = box_Classifica_Content_2;
		
		$("#id_Tables .box_Tabbed_Risultati").css({height: box_Risultati_Content_close});
		$("#id_Tables .box_Tabbed_Classifica").css({height: box_Risultati_Content_close});
		
		try{
			ts_main.actions[1].values = [{height: box_Risultati_Content_height_1}, {height: box_Risultati_Content_height_2}];
			ts_classifica_main.actions[1].values = [{height: box_Classifica_Content_height_1}, {height: box_Classifica_Content_height_2}];
		} catch(e){}

		$('#id_Tables').removeClass("View_Main_All").addClass("View_Main_05_Pos");
		$('#leggi_chiudi_classifica').removeClass("link_CloseList").addClass("link_OpenList");				
	}
}

// banner
function bannerPresent(divElm) {
	var banner = $(divElm).contents().filter(function (i) {
		if (this.nodeType != 1) { // not an element
			return false;
		}
		if (this.tagName.toUpperCase() == 'SCRIPT' || this.tagName.toUpperCase() == 'A') {
			return false;
		}
		
		if (this.tagName.toUpperCase() == 'IMG' || this.tagName.toUpperCase() == 'DIV') {
			return $(this).width() > 10 && $(this).height() > 10;
		}
		
		return true;
	});

	if (banner.length > 0) {
		return true;
	}
	return false;
}

function checkAllBanners() {
	$('.box_Banner, .box_StripBanner').each(function (i) {
		if (!bannerPresent(this)) {
			$(this).hide();
		}
	});
}
$(checkAllBanners);

function checkBannerHeight() {
	$('.banner_dx1').each(function (i) {
		if (this.offsetHeight > 255) {
			$(this).parent(".box_RightContent").addClass("box_BNR_600");
		}
	});
}
