// 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: 110,
	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>' +
			'<h2 class="tit_ForumSection"><a href="#{link}" title="#{titleNoQuot}" target="_blank">#{category}</a></h2>' +
			'<h3 class="tit_PostTitle"><a href="#{link}" title="#{titleNoQuot}" target="_blank">#{title}</a></h3>' +
			'<div class="txt_PostedBy">Postato da: #{author}</div>' +
			'<a href="#{link}" class="link_PostNumber" title="#{titleNoQuot}" target="_blank">#{replies}</a>' +
			'<div class="clear">&nbsp;</div>' +
		'</li>'),
	forum_item_template_first: new Template(
	    '<li class="first_element_forum">' +
			'<h2 class="tit_ForumSection"><a href="#{link}" title="#{titleNoQuot}" target="_blank">#{category}</a></h2>' +
			'<h3 class="tit_PostTitle"><a href="#{link}" title="#{titleNoQuot}" target="_blank">#{title}</a></h3>' +
			'<div class="txt_PostedBy">Postato da: #{author}</div>' +
			'<a href="#{link}" class="link_PostNumber" title="#{titleNoQuot}" target="_blank">#{replies}</a>' +
			'<div class="clear">&nbsp;</div>' +
		'</li>'),
	blog_item_template: new Template(
		'<div class="box_Img news2">' +
			'<a href="#{link}" class="media_Galleria" title="#{titleNoQuot}">' +
				'<span>&nbsp;</span>' +
				'<img class="img_blog_entry" style="display: none" src="" alt="#{titleNoQuot}" />' +
			'</a>' +
		'</div>' +
		'<h2 class="tit_News"><a href="#{link}" title="#{titleNoQuot}">#{title}</a></h2>' +
		'<div class="txt_Abstract"><p>#{postAbstract}</p></div>' +
		'<a href="#{link}" class="link_Open" title="Apri">Apri</a>' +
		'<div class="clear">&nbsp;</div>'),
	blog_item_template_hp: new Template(
		'<div class="list_direttore_home"><ul>' +
			'<li class="img_direttore_home"><a href="#{link}" class="media_Galleria" title="#{titleNoQuot}">' +
				'<img class="img_blog_entry" style="display: none" src="" alt="#{titleNoQuot}" />' +
			'</a><br/></li>' +
    		'<li class="bg_direttore_home">' +
    		  '<span class="title_list_direttore">#{title}</span><br/>' + 
    		  '<span class="abstract_list_direttore"><a href="#{link}">#{postAbstract}</a></span>' +
    		  '<a href="#{link}" class="link_Open" title="Apri">Apri</a>' +
    		'</li>'+
    	'</ul></div>'),
	blog_speciale_item_template: new Template(
		'<li>' +
			'<h2 class="tit_News"><a href="#{link}" title="#{titleNoQuot}">#{title}</a></h2>' +
			'<div class="box_Img news2">' +
				'<a href="#{link}" class="media_Galleria" title="#{titleNoQuot}">' +
					'<span>&nbsp;</span>' +
					'<img class="img_blog_entry" style="display: none" src="" alt="#{titleNoQuot}" />' +
				'</a>' +
			'</div>' +
			'<div class="txt_Abstract"><p>#{postAbstract}</p></div>' +
			'<div class="clear">&nbsp;</div>' +
			'<a href="#{linkCommenti}" class="link_Comment" title="Commenti">#{numCommenti}</a>' +
			'<div class="clear">&nbsp;</div>' +
		'</li>')
};

var RssBox = Class.create();
RssBox.prototype = {
	initialize: function (boxId, url, type, large, fromStatic) {
		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' || this.type == 'forum_speciale') {
			var num_items = this.type == 'forum_speciale' ? 3 : (this.large ? 12 : 4);
			for (var i = 0; i < num_items && i < newContent.entries.length; i++) {
				var target = this.baseElm;
				if (i >= 4) {
					target = $(this.boxId + '_contents_2');
				}
				if (i >= 8) {
					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);

				if(i==0){
				    itemText = this.options.forum_item_template_first.evaluate({
					title: entry.title,
					titleNoQuot: entry.title.replace(/\"/g, "&quot;"),
					category: entry.category,
					link: linkUrl,
					author: entry.author,
					postAbstract: postAbstract,
					replies: entry.description
				    });
				}
				else{
     				itemText = this.options.forum_item_template.evaluate({
     					title: entry.title,
     					titleNoQuot: entry.title.replace(/\"/g, "&quot;"),
     					category: entry.category,
     					link: linkUrl,
     					author: entry.author,
     					postAbstract: postAbstract,
     					replies: entry.description
     				});
     			}
			
				new Insertion.Bottom(target, itemText);
			}
		} else if (this.type == 'blog' || this.type == 'blog_speciale' || this.type == 'blog_home') {
			var num_items = this.type == 'blog_speciale' ? 2 : (this.large ? 3 : 1);
			for (var i = 0; i < num_items && i < newContent.entries.length; i++) {
				var target = this.baseElm;
				if (i >= 1 && this.type == 'blog') {
					target = $(this.boxId + '_contents_2');
				}
				if (i >= 2 && this.type == 'blog') {
					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];
				
				//var template = this.type == 'blog_speciale' ? this.options.blog_speciale_item_template : this.options.blog_item_template;
				var template="";
				switch(this.type) {  
                      case 'blog_speciale':
                          template =this.options.blog_speciale_item_template; 
                      break;                    
                      case 'blog_home':
                        template=this.options.blog_item_template_hp;
                      break; 
                      default:
                        template=this.options.blog_item_template;
                }
				
				// LM condizione che nel caso del layout del blog in home page, riduce il num. dei caratteri visibili
				if(this.type=='blog_home'){
					itemText = template.evaluate({
						title: (entry.title.length>100) ? entry.title.substring(0,100)+ "...": 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.length>40 ? postAbstract.substring(0,40)+"..." : postAbstract,
						linkCommenti: entry.repliesLink,
						numCommenti: entry.repliesCount + ' ' + (entry.repliesCount == 1 ? 'commento' : 'commenti')
					});
				}
				else{
					itemText = 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, i);
				imgPreloader.src = image;
			}
		}
	},
	
	onImageLoaded: function (imgPreloader, target, index) {
		var imgElm = target.getElementsByClassName('img_blog_entry')[index];
		$(imgElm).src = imgPreloader.src;
	
		var ratio = imgPreloader.width / imgPreloader.height;
		if (ratio > (159 / 80)) {
			$(imgElm).setStyle({ 
				width: '159px' 
			}); 
		} else {
			$(imgElm).setStyle({ 
				height: '80px' 
			}); 
		}
		$(imgElm).show();
		imgPreloader.onload = function() {};
	},
	
	updateRssError: function () {
		this.baseElm.innerHTML = '';
		var text = this.type == 'blog' || this.type == 'blog_speciale'? 
			this.options.blog_error_message.evaluate({ url: this.url }) : 
			this.options.forum_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 = 760; }
		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);
	}
}

// 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 = "http://www.auto.it/cerca/" + $(qt).value;
	} else {
		document.location = "http://www.auto.it/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() == 'SCRIPT' ||
				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 hiddenParent = $(elm).up('.bnr_Hidden');
		if (hiddenParent) {
			if (bannerPresent(elm)) {
				hiddenParent.removeClassName('bnr_Hidden');
			} else {
				hiddenParent.hide();
			}
		}
	});
}

Event.observe(window, 'load', checkAllBanners);

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();
}


// MHBManager
var MHBManager = Class.create();
MHBManager.prototype = {
	initialize: function (where, classname) {
		this.where = where;
		this.classname = classname;
		this.cookieName = 'amodei.auto.mhb.' + this.where;

		this.reorderTo(this.getBoxListFromCookie());
		
		this.getBoxList().each(function (box) {
			var upLink = box.getElementsByClassName('btn_NMH_Up')[0];
			var downLink = box.getElementsByClassName('btn_NMH_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();
					}
				}
			}
		}		
	}
}

// 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) {
	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);
}

/**
* 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');
}

/**
* DisplayCorrelatedTitle
*/
var DisplayCorrelatedTitle = Class.create();
DisplayCorrelatedTitle.prototype = {
	initialize: function (idDiv) {
		if (idDiv == undefined) {
			this.idDiv = 'titolo_altra_fotogallery';
		} else {
			this.idDiv = idDiv;
		}
	},
	
	add: function (elmId, titolo) {
		Event.observe(elmId, 'mouseover', this.showTitle.bind(this, titolo));
		Event.observe(elmId, 'mouseout', this.showTitle.bind(this, ''));
	},
	
	showTitle: function (titolo) {
		$(this.idDiv).innerHTML = titolo;
	}
}

/**
* initFileUploads
*/
function initFileUploads() {
	var W3CDOM = (document.createElement && document.getElementsByTagName);
	if (!W3CDOM) return;
		var fakeFileUpload = document.createElement('div');
		fakeFileUpload.className = 'fakefile';
		var fakeInput = document.createElement('input');
		fakeInput.className = 'inp_Text';
		fakeFileUpload.appendChild(fakeInput);
		var image = document.createElement('img');
		image.src='/res/imgs/btn_Browse.png';
		fakeFileUpload.appendChild(image);
		var x = document.getElementsByTagName('input');
		for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className != 'fileinputs') continue;
		x[i].className = 'file hidden';
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
		this.relatedElement.value = this.value;
		}
	}
} 

/**
* 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('<a href="javascript:;" id="condividi_button" onclick="openBoxCondividi()" class="btn_ShareThis" title="Condividi">Condividi</a>');
	var target = $('condividi_button').up();
	var url = document.location.href;
	new Insertion.Before(target,
		'<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">&nbsp;</div>' +
		'</div>'		
	);
}

function openBoxCondividi() {
	Effect.Appear('condividi_box', { duration: 0.6 });
}

function closeBoxCondividi() {
	Effect.Fade('condividi_box', { duration: 0.6 });
}


/**
* BottoneCondividi2
**/
function bottoneCondividi2()
{
    var lnkFB=document.createElement('a');
    var lnkUK=document.createElement('a');
    var lnkOKN=document.createElement('a');;
    var url = document.location.href; 
    var urlFB="http://www.facebook.com/share.php?u=" + url;
    var urlOKN="http://oknotizie.alice.it/post?url=" + url;
    var divFB=$('div_facebook_icon');
    var divW=$('div_wikio_icon');
    var divOKI= $('div_okno_icon');
    
    Element.extend(lnkFB);    
    lnkFB.setAttribute("target","_blank");
    lnkFB.setAttribute("title","Condividi su FaceBook");
    lnkFB.setAttribute("href",urlFB); 
    lnkFB.setAttribute("onclick","return fbs_click()");
    divFB.update(lnkFB);
    
     Element.extend(lnkUK);
     lnkUK.setAttribute("target","_blank");
     lnkUK.setAttribute("title","Condividi su Wikio");
     lnkUK.setAttribute("href","http://www.wikio.it/vote"); 
     divW.update(lnkUK);
     
     Element.extend(lnkOKN);
     lnkOKN.setAttribute("target","_blank");
     lnkOKN.setAttribute("href",urlOKN); 
     lnkOKN.setAttribute("title","Condividi su OKNOtizie");
     divOKI.update(lnkOKN);
}
/**
*	setSegmento
*/
function setSegmento(value, formId, divId, elm) {
	var form = $(formId);
	$$('#' + divId + ' li').each(function (liElm) {
		liElm.removeClassName('li_Selected');
	});
	$(elm).up().addClassName('li_Selected');
	if (form) {
		form['segmento'].value = value;
		form.submit();
	}
}

// link torna al confronto
function setBackLinkConfronta(cType, cId1, cId2, cId3, cId4) {
	var expireDate = new Date();
	expireDate.setTime(expireDate.getTime() + 30 * 60 * 1000);
	document.cookie = 'amodei.auto.backlinkcfr=' + cType + '_' + cId1 + '_' + cId2 + '_' + cId3 + '_' + cId4 + '_' + document.location.href + '; expires=' + expireDate.toGMTString() + '; path=/';
}

function clearBackLinkConfronta() {
	if (!preserveBackLink) {
		document.cookie = 'amodei.auto.backlinkcfr=; expires=' + new Date().toGMTString() + '; path=/';
	}
}

var preserveBackLink = false;
function getBackLinkConfronta(cType, cId) {

	var regexp = new RegExp('amodei.auto.backlinkcfr=([^_]+)_([^_]+)_([^_]+)_([^_]+)_([^_]+)_([^;]+)');
	var result = regexp.exec(document.cookie);
	
	if (result == null) {
		return;
	}
	
	if (result[1] != cType || (cId != result[2] && cId != result[3] && cId != result[4] && cId != result[5])) {
		clearBackLinkConfronta()
		return;
	}
	
	if ($('btn_confronta_vettura')) {
		$('btn_confronta_vettura').hide();
	}
	document.write('<a href="' + result[6].replace(/"/g, '&quot;') + '" class="btn_BackToSection" title="Torna al confronto"><span class="inlineLeft">&nbsp;</span><span class="inlineMain">Torna al confronto</span><span class="inlineRight">&nbsp;</span></a>');
}

function populateModello(idSelectMarca, idSelectModello) {
	var selectMarca = $(idSelectMarca);
	var selectModello = $(idSelectModello);
	
	for (var i = selectModello.options.length - 1; i >= 0; i--) {
		selectModello.options[i] = null;
	}
	var idMarca = selectMarca.value;
	if (idMarca != '0') {
		new Ajax.Request("/inc/modelli/_trovamodelli_" + idMarca + ".inc", {
			onSuccess: function (transport) {
				new Insertion.Bottom(selectModello, transport.responseText);
				selectModello.options[0].selected = true;
			}.bind(this)
		});
	} else {
		selectModello.options[0] = new Option("---", "0");
		selectModello.options[0].selected = true;
	}
}

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;
	}
}


function PopolaListHtmlAnnunci(idMarca,labelMarca,query_string){
	if (idMarca != '') {
		new Ajax.Request("/annunci/js/modelli_" + idMarca + ".js", {
			onSuccess: function call_back(transport){
							PopolaListHtmlAnnunci_onSuccess(transport,idMarca,labelMarca,query_string)
						}	
		});
	} else {
		var listModelliHtml = $("listModelliHtml");
		listModelliHtml.innerHTML = '';
	}
}


function PopolaListHtmlAnnunci_onSuccess(transport,idMarca,labelMarca,query_string) {
	eval(transport.responseText);
	var listModelliHtml = $("listModelliHtml");
	var query_string_to_call = "?";
	var olHtml = "";
	$A(query_string).each(function (elm) {
		if(elm.anno_da != null && elm.anno_da != "" && elm.anno_da != -1)
			query_string_to_call += "annoDa=" + elm.anno_da + "&";
		if(elm.anno_a != null && elm.anno_a != "" && elm.anno_a != -1)
			query_string_to_call += "annoA=" + elm.anno_a + "&";
		if(elm.prezzo_da != null && elm.prezzo_da != "" && elm.prezzo_da != -1)
			query_string_to_call += "prezzoDa=" + elm.prezzo_da + "&";
		if(elm.prezzo_a != null && elm.prezzo_a != "" && elm.prezzo_a != -1)
			query_string_to_call += "prezzoA=" + elm.prezzo_a + "&";
		if(elm.km_da != null && elm.km_da != "" && elm.km_da != -1)
			query_string_to_call += "kmDa=" + elm.km_da + "&";
		if(elm.km_a != null && elm.km_a != "" && elm.km_a != -1)
			query_string_to_call += "kmA=" + elm.km_a + "&";
		if(elm.carburante != null && elm.carburante != "" && elm.carburante != -1)
			query_string_to_call += "carburante=" + elm.carburante + "&";
		if(elm.regione != null && elm.regione != "" && elm.regione != -1)
			query_string_to_call += "regione=" + elm.regione + "&"
		if(elm.usato != false && elm.usato != "")
			query_string_to_call += "usato=" + elm.usato + "&"
		if(elm.km0 != false && elm.km0 != "")
			query_string_to_call += "km0=" + elm.km0 + "&"
	});
	olHtml += '<span class="black_center_text">Modelli:</span><ol>';
	if(query_string_to_call == "?")
		query_string_to_call = "";
	else query_string_to_call = query_string_to_call.substring(0,query_string_to_call.length-1);
	$A(modelli).each(function (elm) {
		if($A(modelli).last() == elm)
			olHtml += '<li><a href="/cerca/annunci/'+labelMarca+'/'+elm.label+'/'+query_string_to_call+'">'+ elm.label + '</a>.</li>';
		else olHtml += '<li><a href="/cerca/annunci/'+labelMarca+'/'+elm.label+'/'+query_string_to_call+'">'+ elm.label + '</a>,</li>';
	});	
	olHtml += '</ol>';
	listModelliHtml.innerHTML = olHtml;
}

// Box Feed RSS
var rssFeedOptionsAutosprint = {
	get_feed_url: '/dinamiche/Feed',
	forum_json: '/rss/forum_autosprint.json',
	blog_json: '/rss/blog_autosprint.json',
	max_abstract_length: 110,
	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>' + 
			'<span class="title_forum_list_as">' +
				'<a href="#{link}" title="#{titleNoQuot}" target="_blank">#{title}</a>' +
			'</span>' +
			'<span class="post_commenti_as">Postato da: #{author}</span>' + 
			'<span class="risposte_commenti_as"><a href="#{link}" title="#{titleNoQuot}" target="_blank">#{replies}</a></span>' +
		'</li>'),	
	blog_item_template: new Template(
	        '<div class="box_forum_home_as_list">' +
                '<ul>' +
                    '<li><span class="title_blog_list_as"><a href="#{link}">#{title}</a></span></li>' +
                        '<li>#{postAbstract}</li>' +
                    '</ul>' +
				'</div>' +
			'<div class="box_forum_home_as_img"><img class="img_blog_entry" style="display: none" src="" alt="#{titleNoQuot}" /></div>' +
            '<div class="clear">&nbsp;</div>'),
	blog_speciale_item_template: new Template(
		'<li>' +
			'<h2 class="tit_News"><a href="#{link}" title="#{titleNoQuot}">#{title}</a></h2>' +
			'<div class="box_Img news2">' +
				'<a href="#{link}" class="media_Galleria" title="#{titleNoQuot}">' +
					'<span>&nbsp;</span>' +
					'<img class="img_blog_entry" style="display: none" src="" alt="#{titleNoQuot}" />' +
				'</a>' +
			'</div>' +
			'<div class="txt_Abstract"><p>#{postAbstract}</p></div>' +
			'<div class="clear">&nbsp;</div>' +
			'<a href="#{linkCommenti}" class="link_Comment" title="Commenti">#{numCommenti}</a>' +
			'<div class="clear">&nbsp;</div>' +
		'</li>')
};

var RssBoxAutosprint = Class.create();
RssBoxAutosprint.prototype = {
	initialize: function (boxId, url, type, large, fromStatic) {
		this.options = rssFeedOptionsAutosprint;
		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' || this.type == 'forum_speciale') {
			var num_items = this.type == 'forum_speciale' ? 3 : (this.large ? 12 : 4);
			for (var i = 0; i < num_items && i < newContent.entries.length; i++) {
				var target = this.baseElm;
				var cssFirst="first_element_forum";
				
				if (i >= 4) {
					target = $(this.boxId + '_contents_2');
				}
				if (i >= 8) {
					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);
				
				itemText = this.options.forum_item_template.evaluate({
				title: entry.title,
				titleNoQuot: entry.title.replace(/\"/g, "&quot;"),
				category: entry.category,
				link: linkUrl,
				author: entry.author,
				postAbstract: postAbstract,
				replies: entry.description
				});		
				
				new Insertion.Bottom(target, itemText);
			}
		} else if (this.type == 'blog' || this.type == 'blog_speciale') {
			var num_items = this.type == 'blog_speciale' ? 2 : (this.large ? 3 : 1);
			for (var i = 0; i < num_items && i < newContent.entries.length; i++) {
				var target = this.baseElm;
				if (i >= 1 && this.type == 'blog') {
					target = $(this.boxId + '_contents_2');
				}
				if (i >= 2 && this.type == 'blog') {
					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];
				
				var template = this.type == 'blog_speciale' ? this.options.blog_speciale_item_template : this.options.blog_item_template;
				itemText = 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, i);
				imgPreloader.src = image;
			}
		}
	},
	
	onImageLoaded: function (imgPreloader, target, index) {
		var imgElm = target.getElementsByClassName('img_blog_entry')[index];
		$(imgElm).src = imgPreloader.src;
	
		var ratio = imgPreloader.width / imgPreloader.height;
		if (ratio > (130 / 70)) {
			$(imgElm).setStyle({ 
				width: '130px' 
			}); 
		} else {
			$(imgElm).setStyle({ 
				height: '70px' 
			}); 
		}
		$(imgElm).show();
		imgPreloader.onload = function() {};
	},
	
	updateRssError: function () {
		this.baseElm.innerHTML = '';
		var text = this.type == 'blog' || this.type == 'blog_speciale'? 
			this.options.blog_error_message.evaluate({ url: this.url }) : 
			this.options.forum_error_message.evaluate({ url: this.url });
		new Insertion.Bottom(this.baseElm, text);
	}	
}

function LoadCircuiti(){
	new Ajax.Request("/live/F1/next-gp-autosprint.js", {
		onSuccess: function call_back(transport){
						LoadCircuiti_onSuccess(transport)
					}	
	});
}

function LoadCircuiti_onSuccess(transport) {
	eval(transport.responseText);
	//var listModelliHtml = $("listModelliHtml");
	//var query_string_to_call = "?";
	//var olHtml = "";
	var now = new Date();
	var curren_element = null;
	var dim = $A(race).size();
	//alert(race)
	$A(race).each(function (elm) {
		/*new Date ( year, month, date, hour, minute, second )*/
		/*2009-04-19T07:00:00Z*/
		d = getFormattedDate(elm.date);
		if(now < d){
			curren_element = elm;
			curren_element.date = d;
			throw $break;
		}
	});
	if(curren_element == null){
		curren_element = $A(race)[dim - 1]
		d = getFormattedDate(curren_element.date);
		curren_element.date = d;
	}
	$("imgCircuito").src = "/res/imgs/"+curren_element.id+".png"
	$("nome_circuito").innerHTML = curren_element.name
	$("location_circuito").innerHTML = "Circuito di " + curren_element.location
	$("data_circuito").innerHTML = dateFormat(curren_element.date, "dd mmmm yyyy")//19 luglio 2009
	
	countdownTo(curren_element.date.getFullYear (),curren_element.date.getMonth (),curren_element.date.getDate(),curren_element.date.getHours(),curren_element.date.getMinutes(),curren_element.date.getSeconds())
}

function getFormattedDate(s_date){
		year = s_date.substring(0,4);
		month = s_date.substring(5,7) - 1;
		date = s_date.substring(8,10);
		hour = parseInt(s_date.substring(11,13));
		minute = s_date.substring(14,16);
		second = s_date.substring(17,19);
		d = new Date(year, month, date, hour, minute, second );
		return d;
}


var targetDate = null;
function countdownTo(year, month, day, hours, minutes, seconds) {
	targetDate = Date.UTC(year, month , 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));
	//alert(days)
	$("span_giorni").innerHTML = days + "gg";
	$("span_ore").innerHTML = hours + "hh";
	$("span_minuti").innerHTML = minutes + "m";
	setTimeout('updateCountdown()', 60 * 1000);
}


var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Domenica", "Luned&igrave;", "marted&igrave;", "Mercoled&igrave;", "Gioved&igrave;", "Venerd&igrave;", "Sabato"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};