// 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_Abstract"><p>#{postAbstract}</p></div>' +
			'<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>')
};

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') {
			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;
				}
				
				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') {
			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.height / 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.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 = 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);
	}
}

// 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 () {
	},
	
	add: function (elmId, titolo) {
		Event.observe(elmId, 'mouseover', this.showTitle.bind(this, titolo));
		Event.observe(elmId, 'mouseout', this.showTitle.bind(this, ''));
	},
	
	showTitle: function (titolo) {
		$('titolo_altra_fotogallery').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 bottoneCondividi() {
	document.write('<a href="javascript:;" id="condividi_button" onclick="openBoxCondividi()" class="btn_ShareThis" title="Condividi">Condividi</a>');
	var target = $('condividi_button').up();
	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><img src="/res_ext/ico_Technorati.gif" alt="Technorati" /><a href="[link]" title="[link title]">Technorati</a></li>' +
				'<li><img src="/res_ext/ico_Technorati.gif" alt="Technorati" /><a href="[link]" title="[link title]">Technorati</a></li>' +
				'<li><img src="/res_ext/ico_Technorati.gif" alt="Technorati" /><a href="[link]" title="[link title]">Technorati</a></li>' +
				'<li><img src="/res_ext/ico_Technorati.gif" alt="Technorati" /><a href="[link]" title="[link title]">Technorati</a></li>' +
				'<li><img src="/res_ext/ico_Technorati.gif" alt="Technorati" /><a href="[link]" title="[link title]">Technorati</a></li>' +
				'<li><img src="/res_ext/ico_Technorati.gif" alt="Technorati" /><a href="[link]" title="[link title]">Technorati</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 });
}

/**
*	setSegmento
*/
function setSegmento(value, formId, divId, elm) {
	var form = $(formId);
	if (form) {
		form['segmento'].value = value;
	}
	$$('#' + divId + ' li').each(function (liElm) {
		liElm.removeClassName('li_Selected');
	});
	$(elm).up().addClassName('li_Selected');
}
