var RealTimeFeed = function (list_name, visiblePostsNum, coloured_background_color, animation, sound) {
	/*
	 * Variabili di configurazione
	 */
	var list_name = list_name ? list_name : "posts";
	var visiblePostsNum = visiblePostsNum ? visiblePostsNum : 10;
	var coloured_background_color = coloured_background_color ? coloured_background_color : "";
	var animation = animation;
	var sound = sound;
	var scriptURL = "";
	
	/*
	 * Variabili di applicazione
	 */
	var posts = new Array();
	var old_posts_requested = false;
	var anim = null;
	
	/* Sound manager
	// soundManager.url = 'http://' + conf.staticUrl + '/js/widgets/rtf/soundmanager/swf/'; // directory where SM2 .SWFs live
	soundManager.url = 'soundmanager/swf/'; // directory where SM2 .SWFs live
	soundManager.debugMode = false;
	
	soundManager.onload = function() {
	  soundManager.createSound({
	    id: 'aSound',
	    // url: 'http://' + conf.staticUrl + '/js/widgets/rtf/soundmanager/audio.mp3',
	    url: 'soundmanager/audio.mp3',
	    volume: 30
	  });
	};
	*/
	var createElement = function (notify, colour) {
		var el = document.createElement("div");
		YAHOO.util.Dom.setAttribute(el, "id", "el_" + notify.id);
		YAHOO.util.Dom.addClass(el, "postContainer");
		YAHOO.util.Dom.addClass(el, "toDelete");
		YAHOO.util.Dom.addClass(el, "stats_rft");
		if(colour) YAHOO.util.Dom.setStyle(el, "background-color", coloured_background_color);
		el.innerHTML = notify.rtfFormat();
		
		// Animazione
		anim = new YAHOO.util.Anim(el, { opacity: { from: 0, to: 1 } }, 1);
		
		return el;
	};
	
	var appendToArray = function (notify, insert_in_head) {
		if(insert_in_head) posts.unshift(notify);
		else posts[posts.length] = notify;
	};
	
	var appendToList = function (notify, insert_in_head) {
		var list = YAHOO.util.Dom.get(list_name);
		var items = getListItems();
		
		var colour = "";
		if(items != "" && items.length > 0) colour = ((insert_in_head) ? !isPredColoured(items[0]) : !isPredColoured(items[items.length - 1]));
		
		// Primo inserimento
		if(items == "" || !insert_in_head)
			// document.getElementById(list_name).appendChild(createElement(notify, colour));
			new YAHOO.util.Element(list_name).appendChild(createElement(notify, colour));
			
		else
			insertInHead(createElement(notify, colour), items[0]);
		
		// Aggiunge il listener per visualizzare l'overlay con le azioni interazioni eseguibili con l'utente
		addUserDetailsListener(notify);
		
		if(animation) anim.animate();
	};
	
	var append = function (notify, insert_in_head) {
		appendToArray(notify, insert_in_head);
		appendToList(notify, insert_in_head);
		
		// if(sound) soundManager.play('aSound');
		
		var items = getListItems();
		
		// Rimuove l'elemento in coda
		if(items.length > visiblePostsNum && !old_posts_requested) {
			new YAHOO.util.Element(list_name).removeChild(items[items.length - 1]);
			showLoaderLink();
		}
	};
	
	var isPredColoured = function (item) {
		return (YAHOO.util.Dom.getStyle(item, "background-color") != "transparent" && YAHOO.util.Dom.getStyle(item, "background-color") != "rgba(0, 0, 0, 0)");
	};
	
	this.loadOld = function () {
		if(!old_posts_requested) old_posts_requested = true;
		showLoader();
		
		window.setTimeout(function () {
			var start = YAHOO.util.Dom.getChildren(list_name).length;
			var to = ((posts.length < (start + visiblePostsNum)) ? posts.length : (start + visiblePostsNum));
			
			for(var i=start; i<to; i++)
				appendToList(posts[i], false);
			
			// Sono mostrati tutti
			if(posts.length <= YAHOO.util.Dom.getChildren(list_name).length)
				hideLoaderLink();
		
			hideLoader();
		}, 2500);
	};
	
	this.loadNotify = function (notify) {
		if(YAHOO.util.Dom.get(list_name))
			append(notify, true);
	};
	
	var hideLoaderLink = function () {
		YAHOO.util.Dom.setStyle("old_posts_loader", "display", "none");		
	};
	
	var showLoaderLink = function () {
		YAHOO.util.Dom.setStyle("old_posts_loader", "display", "block");
	};
	
	var getListItems = function () { 
		return (YAHOO.util.Dom.getElementsByClassName("postContainer", "div"));
	};
	
	var hideLoader= function () {
		YAHOO.util.Dom.setStyle("old_posts_loader_img", "display", "none");		
	};
	
	var showLoader = function () {
		YAHOO.util.Dom.setStyle("old_posts_loader_img", "display", "block");
	};
	
	var insertInHead = function (el, before_el) {
		// if(YAHOO.env.ua.ie > 0) // Internet Explorer
			// new YAHOO.util.Element(list_name).appendTo(el, before_el);
		// else
		new YAHOO.util.Element(list_name).insertBefore(el, before_el);
	};
	
	var addUserDetailsListener = function (notify) {
		addListener('avatar_' + notify.webNotification.id + '_' + notify.webNotification.sender.profile_id, null, {
			profile_id: notify.webNotification.sender.profile_id,
			nick: notify.webNotification.sender.nick,
			gender: notify.webNotification.sender.gender,
			avatar: Utilities.getUserAvatar(notify.webNotification.sender.avatar, notify.webNotification.sender.gender, "profileThumb")
		});
		if(notify.webNotification.type == 'status' && notify.subtype == 'answer')
			addListener('avatar_' + notify.webNotification.id + '_' + notify.question.user.profile_id, null, {
				profile_id: notify.question.user.profile_id,
				nick: notify.question.user.nick,
				gender: notify.question.user.gender,
				avatar: Utilities.getUserAvatar(notify.question.user.avatar, notify.question.user.gender, "profileThumb")
			});		
	};
	
	var addListener = function (anchorId, features, user) {
		YAHOO.util.Event.on(anchorId, 'mouseover', N.stop);
		YAHOO.util.Event.on(anchorId, 'mouseout', N.start);
		
		// Aggancia il listener per visualizzare la finestra con l'utente
		if(user.profile_id != my_profile.pid) YAHOO.neo.overlay.generateOverlay(anchorId, features, user, true);
	};
	
	// Ottiene notifiche per utenti ospiti
	this.loadForGuest = function () {
		var callback = {
		    success : function (o) {
				try {
					rtf.loadNotify(Utilities.jsonParse(o.responseText));
				}
		        catch(e) {  }
		    },
		    failure : function (o) {  }
		};
		
		var data = "u=guest";
		var conn = YAHOO.util.Connect.asyncRequest("POST", scriptURL, callback, data);
	};
	
	this.sendComment = function (form) {
		var callback = {
			    upload : function (o) {
					try {
						if(Utilities.needLP(o.responseText))
							Utilities.checkFeature(o.responseText);
						else {
							var data = Utilities.jsonParse(o.responseText);
	
							//new YAHOO.util.Element(list_name).insertBefore(el, before_el);
							if(String(data['code']) == 'OK'){
								var ul = document.getElementById('ul_' + data['status']['postId']);
								var li = document.getElementById('li_insert_' + data['status']['postId']);
								
								var li_new = document.createElement('li');
								li_new.setAttribute('id', 'li_comment_' + data['status']['commentId']);
								li_new.innerHTML = '<div class="avatar"><a href="" class="' + data['status']['genderClass'] + '"><span></span><img src="' + data['status']['avatar'] + '" alt=""></a></div>' +
													'<div class="detail">' +
														'<a href="' + Utilities.getUserUrl(data['status']['nick']) + '">' + data['status']['nick'] + '</a>' + ' ' + data['status']['comment'] + 
															'<div>' +
																'<span class="timestamp">' + data['status']['time'] + '</span>' + 
																'<span class="actions">&bull;<a href="javascript:OverlayConfiguration.comment.delete1(\'' + data['status']['commentId'] + '\', \'' + data['status']['postId'] + '\');">elimina</a></span>' +
															'</div>' +
													'</div>';
								new YAHOO.util.Element(ul).insertBefore(li_new, li);
								
								// aggiornamento contatore commenti
								document.getElementById('numComments_' + data['status']['postId']).value = Number(document.getElementById('numComments_' + data['status']['postId']).value) + 1;
								document.getElementById('comments_counter_' + data['status']['postId']).innerHTML = 'commenti (' + document.getElementById('numComments_' + data['status']['postId']).value + ')';
							}
							else{
								// alert(data['message']);
								if(data['message'] == 'not_logged')
									OverlayManager.show('genericMessage', 'Attenzione!', 'Devi essere loggato per inserire un commento.<br/>Per registrarti clicca <a href="#">qui</a>.', 'rosso');
								else
									OverlayManager.show('genericMessage', 'Attenzione!', data['message'], 'rosso');
							}
							
							document.getElementById('ta_' + data['status']['postId']).value = '...scrivi un commento';
						}
					}
			        catch(e) {  
			        }
			    },
			    failure : function (o) { 
			    	alert(o);
			    } 
			};
			
			YAHOO.util.Connect.setForm(form, true);
			var conn = YAHOO.util.Connect.asyncRequest("POST", "http://" + conf.baseUrl + "/status_input/add_comment", callback);
	};
};



var RtfUtilities = {
	createAvatar: function (user, nid) {
			if(!nid){
				return '<a href="' + Utilities.getUserUrl(user.nick) + '" class="' + ((user.gender == "M") ? "male" : "female") + '"><span></span>' +
							'<img src="' + Utilities.getUserAvatar(user.avatar, user.gender) + '"/>' +
						'</a>';
			} else{
				return '<div id="avatar_' + nid + '_' + user.profile_id + '" class="avatar">' +
						'<a href="' + Utilities.getUserUrl(user.nick) + '" class="' + ((user.gender == "M") ? "male" : "female") + '"><span></span>' +
							'<img src="' + Utilities.getUserAvatar(user.avatar, user.gender) + '" alt="" />' +
						'</a>' +
					'</div>';
			}
	},
	
	createNick: function (nick) {
		return '<a href="' + Utilities.getUserUrl(nick) + '" class="nick">' + nick + '</a>';
	},

	createFooter: function (nid, user, creationDate, postId, mediaType) {
		return '<div>' +
					'<div class="timestamp">' + Utilities.prettyDate(creationDate) + '</div>' +
					RtfUtilities.createActions(nid, user, postId, mediaType) +
				'</div>' +
				(Utilities.isUserHome() ? RtfUtilities.createComments(nid, 0) : '');				
	},
	
	createActions: function (nid, user, postId, mediaType) {
		return '<div class="actions">' +
					(Utilities.isUserHome() ? '•<a id="comments_counter_' + nid + '" href="javascript:RtfUtilities.showComments(\'c_' + nid + '\');">commenta</a>•' : '') +
					((postId && user.profile_id != my_profile.pid) ? '•<a id="comments_counter_' + nid + '" href="javascript:OverlayManager.show(\'abusereport\', \'' + user.nick + '\', ' + user.profile_id + ', ' +
					'\'' + (mediaType ? AbuseTypes[mediaType] : AbuseTypes.status) + '\', ' +
					postId + ', ' +
					'\'' + (mediaType ? mediaType : 'status') + '\');">segnala abuso</a>' : '') +
				'</div>';
	},
	
	createAbuse: function (user, postId) {
		return '•<a href="javascript:OverlayManager.show(\'abusereport\', ' + user.nick + ', ' + user.profile_id + ', 4, ' + postId + ', \'status\');">Segnala Abuso</a>';
	},
	
	createComments: function (id, c_count) {
		return '<div id="c_' + id + '" class="c_container' + (c_count > 0 ? ' show' : '') + '">' +
			'<ul class="commenti" id="ul_' + id + '">' +		
				'<li class="addComment" id="li_insert_' + id + '">' +
					'<form action="" method="post" onsubmit="return false;" name="f_' + id + '" id="f_' + id + '">' +
						'<textarea id="ta_' + id + '" name="comment" onFocus=\"this.value=\'\'\">...scrivi un commento</textarea>' +
						'<input type="hidden" value="' + id + '" name="postId"/>' +
						'<input type="hidden" id="numComments_' + id + '" value="0">' +
						'<input type="button" class="button" value="..." onclick=\'javascript:rtf.sendComment("f_' + id + '");\'/>' +
					'</form>' +
				'</li>' +
			'</ul>';
	},
	
	showComments: function (id) {
		var div = YAHOO.util.Dom.get(id);
		if(!YAHOO.util.Dom.removeClass(id, 'show'))
			YAHOO.util.Dom.addClass(id, 'show');
	}
};