﻿/* costanti */
var cTABCONVMAXCHAR = 15;

/* variabili */
var _cultureInfo = 'en-US';
var _user = null;
var _addressList = null;
var _contacts = null;
var _activeConv = null;
var _currentConvIndex = null;

function scriptMain(cultureInfo, elmIdSignIn) {
	///<summary>inizializzazione del bottone di SignIn</summary>

	_cultureInfo = cultureInfo;
	var privUrl = "http://" + document.domain + "/privacy.htm";
	var chanUrl = "http://" + document.domain + "/channel.htm";

	var _signin_c = new Microsoft.Live.Messenger.UI.SignInControl(elmIdSignIn, privUrl, chanUrl, cultureInfo);
	/* imposto lo stile del bottone di messenger */
	/*?? var _signin_c_style = new Microsoft.Live.Messenger.UI.SignInControlStyle(); ??*/
	var _signin_c_style = _signin_c.get_style();
	_signin_c_style.set_backColor("#8C63AB");
	_signin_c_style.set_borderColor("#E20177");
	_signin_c_style.set_buttonBackColor("#EF59A1");
	_signin_c_style.set_buttonBorderColor("#E20177");
	_signin_c_style.set_buttonForeColor("#FFFFFF");
	_signin_c_style.set_foreColor("#FFFFFF");
	_signin_c_style.set_linkColor("#FFFFFF");

	_signin_c.add_authenticationCompleted(Delegate.create(null, signIn_AuthenticationCompleted));
}

function user_SignInCompleted(sender, e) {
	///<summary>procedura di Accesso completata</summary>
	if (e.get_resultCode() === Microsoft.Live.Messenger.SignInResultCode.success) {
		signInCloudUncloud(true);
		//var settings = _user.get_settings();
		//var mailBox = _user.get_mailbox();
		var contact = null;
		var address = null;
		var presence = _user.get_presence();
		_contacts = _user.get_contacts();
		_addressList = new Array(_contacts.get_count());
		var contactsEnum = _contacts.getEnumerator();
		var conversations = _user.get_conversations();
		var pendingContacts = _user.get_pendingContacts();

		_user.add_signOutCompleted(Delegate.create(null, user_SignOutCompleted));
		_user.add_signedOutRemotely(Delegate.create(null, user_SignedOutRemotely));
		presence.add_propertyChanged(Delegate.create(null, user_Presence_PropertyChanged));
		conversations.add_collectionChanged(Delegate.create(null, conversations_CollectionChanged));
		_contacts.add_collectionChanged(Delegate.create(null, contacts_CollectionChanged));
		pendingContacts.add_collectionChanged(Delegate.create(null, pendingContacts_CollectionChanged));

		var contactsEnum = _contacts.getEnumerator();
		while (contactsEnum.moveNext()) {
			contact = contactsEnum.get_current();
			address = contact.get_currentAddress();

			address.get_presence().add_propertyChanged(Delegate.create(null, contact_Presence_PropertyChanged));
			contact.add_currentAddressChanging(Delegate.create(null, contact_CurrentAddressChanging));
			contact.add_propertyChanged(Delegate.create(null, contact_PropertyChanged));
		}
		displayUserInfo(true);
		displayContacts();
	}
	else if (e.get_resultCode() === Microsoft.Live.Messenger.SignInResultCode.failure) {
		/*"!!FAILED!!"*/
	}
	else {
		/*"??????"*/
	}
}

function user_SignedOutRemotely(sender, e) {
	///<summary>Called by the Messenger Library on remote sign-out (i.e. user logged into Messenger on another computer).</summary>

	/* alert('You have been signed out remotely.'); */
	user_SignOutCompleted(sender, e);
}

/* -- Questa procedura ritorna un messaggio quindi serve impostare la lingua di riferimento?? -- */
function signIn_AuthenticationCompleted(sender, e) {
	///<summary>procedura di Autenticazione completata</summary>

	var authStatus = e.get_status();
	if ((authStatus & Microsoft.Live.Core.AuthenticationStatus.unsupportedBrowser)) {
		alert('Siamo spiacenti, il tuo browser non è compatible con Web Messenger. È possibile che non siano supportate tutte le funzionalità.');
	}
	_user = new Microsoft.Live.Messenger.User(e.get_identity());
	_user.add_signInCompleted(Delegate.create(null, user_SignInCompleted));
	_user.signIn(null);
}

function user_SignOutCompleted(sender, e) {
	///<summary>Imposta le variabili dopo un sign out.</summary>
	
	jQuery("#msngContactList").html('');
	jQuery("#chatAreaConv").html('');
	jQuery("#msngPersonalImage").html('');
	jQuery("#userInfo").html('');
	jQuery("#tabConversationsScroller").html('');
	document.getElementById("btnSend").style.visibility = "hidden";
	document.getElementById("personalMessage").value = "";
	document.getElementById("displayName").value = "";
	document.getElementById("selectStatus").selectedIndex = 0;

	var txtMessage = document.getElementById("txtMessage");
	txtMessage.value = "";
	txtMessage.readOnly = true;
	txtMessage.blur();

	/* azzero tutte le variabili per evitare che si continui a ricevere messaggi dopo il logout */
	_user = null;
	_addressList = null;
	_contacts = null;
	_activeConv = null;

	signInCloudUncloud(false);
}

function selectStatusChanged() {
	///<summary>Modifica/Aggiornamento dello Stato Personale.</summary>

	if (_user == null)
		return;

	var selectStatus = document.getElementById("selectStatus");
	var presenceStatus = [Microsoft.Live.Messenger.PresenceStatus.appearOffline, Microsoft.Live.Messenger.PresenceStatus.away, Microsoft.Live.Messenger.PresenceStatus.beRightBack, Microsoft.Live.Messenger.PresenceStatus.busy, Microsoft.Live.Messenger.PresenceStatus.idle, Microsoft.Live.Messenger.PresenceStatus.inACall, Microsoft.Live.Messenger.PresenceStatus.online, Microsoft.Live.Messenger.PresenceStatus.outToLunch];
	if (_user.get_presence().get_status() !== Microsoft.Live.Messenger.PresenceStatus.offline) {
		_user.get_presence().set_status(presenceStatus[selectStatus.selectedIndex]);
	}
}

function setPersonalMessage() {
	///<summary>Modifica/Aggiornamento del Messaggio personale che viene visualizzato agli altri utenti.</summary>

	if (_user == null)
		return;

	var personalMessage = document.getElementById("personalMessage");
	var personalMessageText = personalMessage.value;
	personalMessageText = personalMessageText.replace(/</g, "").replace(/>/g, "");

	_user.get_presence().set_personalMessage(personalMessageText);
}

function setDisplayedName() {
	///<summary>Modifica/Aggiornamento del Nome che viene visualizzato agli altri utenti.</summary>

	if (_user == null)
		return;

	var displayName = document.getElementById("displayName");
	var displayNameText = displayName.value;
	displayNameText = displayNameText.replace(/</g, "").replace(/>/g, "");

	if (displayNameText !== '')
		_user.get_presence().set_displayName(displayNameText);
}

function getSenderEmailFromConversation(sender) {
	///<summary>Recupero l'indirizzo email del contatto della conversazione.</summary>

	//senderEmailClean = indirizzo_email.replace(/[^a-zA-Z0-9]/gi, '');
	var userIMemail = _user.get_address();
	var roster = sender.get_roster();
	var rosterCount = roster.get_count();
	var rosterEnum = sender.get_roster().getEnumerator();
	var senderEmailDirty = '';

	while (rosterEnum.moveNext()) {
		rosterIMAddr = rosterEnum.get_current();
		rosterAddress = rosterIMAddr.get_address();

		if (rosterCount > 2) {
			if (rosterIMAddr != userIMemail) {
				senderEmailDirty = rosterAddress;
			}
		}
		else {
			if (rosterIMAddr != userIMemail) {
				senderEmailDirty = rosterAddress;
			}
		}
	}

	return senderEmailDirty;
}

function checkIfUserIsOnline(usrStatus) {
	///<summary>Controlla lo stato "messenger" specifico dell'utente. Ritorna un bool (true o false) indipendentemente dal differente stato di online. Es.: "away"=true</summary>
	///<param name="usrStatus" type="string">Lo stato che deve essere valutato</param>

	var bRetVal = false;
	switch (usrStatus) {
		case "online":
		case "away":
		case "beRightBack":
		case "busy":
		case "idle":
		case "inACall":
		case "outToLunch":
			bRetVal = true;
			break;
		default:
			/* "appearOffline" - "offline" */
			bRetVal = false;
			break;
	}
	return bRetVal;
}

function getStatusImage(usrStatus) {
	///<summary>Ritorna l'item image (html) in base allo stato dell'utente.</summary>

	var itemImgStatus = '';
	switch (usrStatus) {
		case "online":
		case "offline":
		case "appearOffline":
			itemImgStatus = '';
			break;
		case "away":
			itemImgStatus = '<img src="common/images/imgMessenger/msngIcoAway.gif" alt="away" />';
			break;
		case "beRightBack":
			itemImgStatus = '<img src="common/images/imgMessenger/msngIcoBeRightBack.gif" alt="beRightBack" />';
			break;
		case "busy":
			itemImgStatus = '<img src="common/images/imgMessenger/msngIcoBusy.gif" alt="busy" />';
			break;
		case "idle":
			itemImgStatus = '<img src="common/images/imgMessenger/msngIcoIdle.gif" alt="idle" />';
			break;
		case "inACall":
			itemImgStatus = '<img src="common/images/imgMessenger/msngIcoInACall.gif" alt="InACall" />';
			break;
		case "outToLunch":
			itemImgStatus = '<img src="common/images/imgMessenger/msngIcoOutToLunch.gif" alt="OutToLunch" />';
			break;
	}
	return itemImgStatus;
}

function viewEmoticons() {
	///<summary>Visualizza le emoticon di sistema.</summary>

	jQuery('div#viewImgEmoticons').load("common/include/msngEmoticon.aspx #defMsngEmoticon",
		function() {
			jQuery('div#viewImgEmoticons').show('slow');
			jQuery('select#selectStatus').hide();
		}
	);
}
function hideEmoticons() {
	///<summary>Nasconde il pannello delle emoticon.</summary>

	jQuery('select#selectStatus').show();
	jQuery('div#viewImgEmoticons').hide('slow');
	jQuery('div#viewImgEmoticons').html('');
}
function insertEmoticon(emoticonCode) {
	///<summary>Seleziono l'immagine delle emoticon da inserire nel testo.</summary>

	if (_activeConv == null)
		return;
	var txtMessageArea = document.getElementById('txtMessage');
	txtMessageArea.value += emoticonCode;
	hideEmoticons();
}

function contacts_CollectionChanged(sender, e) {
	///<summary>Funzione chiamata dal verificarsi dell'evento di cambiamento della collezione dei contatti.</summary>

	var items = null;
	if (e.get_action() === Microsoft.Live.Core.NotifyCollectionChangedAction.add) {
		//"New Starting Index: " + e.get_newStartingIndex();
		items = e.get_newItems();
		for (i = 0; i < items.length; i++) {
			// Aggiungo gli eventi di "presenza" (presence events) al nuovo contatto
			contact = items[i];
			address = contact.get_currentAddress();

			address.get_presence().add_propertyChanged(Delegate.create(null, contact_Presence_PropertyChanged));
			contact.add_currentAddressChanging(Delegate.create(null, contact_CurrentAddressChanging));
			contact.add_propertyChanged(Delegate.create(null, contact_PropertyChanged));
		}
	}
	else if (e.get_action() === Microsoft.Live.Core.NotifyCollectionChangedAction.remove) {
		//"Old Starting Index: " + e.get_oldStartingIndex();
		//"New Items Length: " + items.length;
		items = e.get_oldItems();
	}
	else if (e.get_action() === Microsoft.Live.Core.NotifyCollectionChangedAction.replaced) {
		/*"?? REPLACED ??"*/
	}
	else if (e.get_action() === Microsoft.Live.Core.NotifyCollectionChangedAction.reset) {
		/*"?? RESET ??"*/
	}
}

function pendingContacts_CollectionChanged(sender, e) {
	///<summary></summary>
	var items = null;

	if (e.get_action() === Microsoft.Live.Core.NotifyCollectionChangedAction.add) {
		//"New Starting Index: " + e.get_newStartingIndex();
		//"New Items Length: " + items.length;
		items = e.get_newItems();
	}
	else if (e.get_action() === Microsoft.Live.Core.NotifyCollectionChangedAction.remove) {
		//"Old Starting Index: " + e.get_oldStartingIndex();
		//"New Items Length: " + items.length;
		items = e.get_oldItems();
	}
	else if (e.get_action() === Microsoft.Live.Core.NotifyCollectionChangedAction.replaced) {
		/*"?? REPLACED ??"*/
	}
	else if (e.get_action() === Microsoft.Live.Core.NotifyCollectionChangedAction.reset) {
		/*"?? RESET ??"*/
	}
}

function contact_CurrentAddressChanging(sender, e) {
	///<summary></summary>

	//'Contact Current Address Changing: ' + e.get_propertyName();
	e.get_oldAddress().get_presence().remove_propertyChanged(Delegate.create(null, presence_PropertyChanged));
	e.get_newAddress().get_presence().add_propertyChanged(Delegate.create(null, presence_PropertyChanged));
}

function contact_PropertyChanged(sender, e) {
	///<summary></summary>

	//'Contact Property Changed: ' + e.get_propertyName();
}

function setCurrentConvo(newIndex) {
	///<summary>reimposta l'indice della conversazione corrente</summary>

	_currentConvIndex = newIndex;
}

function conversation_SendMessageFailed(sender, e) {
	///<summary></summary>

	if (e.get_resultCode() === Microsoft.Live.Messenger.SendMessageResultCode.success) {
		//"Message OK From: " + e.get_message().get_sender().get_address();
	}
	else if (e.get_resultCode() === Microsoft.Live.Messenger.SendMessageResultCode.failure) {
		/* Message FAIL: Succede quando si tenta di inviare un messaggio ad un contatto offline */
		alert("Invio del messaggio non riuscito, provare a verificare che il contatto " + getSenderEmailFromConversation(sender) + " sia ancora online:");
	}
	else {
		//"Result CODE NOT FOUND!";
	}
}

function user_Presence_PropertyChanged(sender, e) {
	///<summary>Called by the Messenger Library when status changes of the user occur.</summary>

	if (_user.get_presence().get_status() === Microsoft.Live.Messenger.PresenceStatus.offline) {
		user_SignOutCompleted(sender, e);
	}
	if (_user == null)
		return;

	if (e.get_propertyName() === 'DisplayPictureUrl') {
		var displayPictureUrl = ((!sender.get_displayPictureUrl()) ? 'common/images/imgMessenger/noDisplayPersonalPicture.png' : sender.get_displayPictureUrl().toString());
		jQuery("#msngPersonalImage").html('<img src="' + displayPictureUrl + '" alt="" />');
	}
	displayUserInfo(false);
}

function displayUserInfo(isSignIn) {
	///<summary>Visualizza le informazioni dell'utente loggato</summary>

	if (isSignIn) {
		var displayPictureUrl = 'common/images/imgMessenger/noDisplayPersonalPicture.png';
		jQuery("#msngPersonalImage").html('<img src="' + displayPictureUrl + '" alt="" />');
		document.getElementById("selectStatus").selectedIndex = 6;
	}

	getMyDiaryBuddyImage();

	var userInfo = document.getElementById("userInfo");
	var userAddress = _user.get_address().get_address();
	var userDispName = _user.get_presence().get_displayName();
	var userPersonalMessage = _user.get_presence().get_personalMessage();
	var userStatus = Enum.toString(Microsoft.Live.Messenger.PresenceStatus, _user.get_presence().get_status());
	var statusLine = document.createElement('p');
	removeChildrenFromNode("userInfo");
	var viewDispName = userAddress;
	if (userDispName !== '')
		viewDispName = userDispName;

	statusLine.innerHTML = '<label>' + viewDispName + '</label>';
	userInfo.appendChild(statusLine);
	document.getElementById("personalMessage").value = userPersonalMessage;
	document.getElementById("displayName").value = viewDispName;
}
function getMyDiaryBuddyImage() {
	///<summary>Imposto l'immagine personale con quella del MyDiary se esiste l'utente.</summary>
	var userAddress = _user.get_address().get_address();

	jQuery.getJSON("common/include/getMyDiaryPersonalImg.aspx?em=" + userAddress,
		function(data) {
			if (data.ImageUrl != "")
				jQuery("#msngPersonalImage").html('<img src="' + data.ImageUrl + '" alt="" />');
		}
	);
}

function displayContacts() {
	///<summary>Visualizzazione l'elenco dei contatti dell'utente loggato</summary>

	var sbOnline = new StringBuilder();
	var sbOffline = new StringBuilder();

	var contactEnum = _contacts.getEnumerator();
	var index = 0;

	while (contactEnum.moveNext()) {
		var contact = contactEnum.get_current();
		var address = contact.get_currentAddress();
		var dispName = address.get_presence().get_displayName();
		var currAddress = address.get_address();
		var currAddressClean = currAddress.replace(/[^a-zA-Z0-9]/gi, '');
		var status = Enum.toString(Microsoft.Live.Messenger.PresenceStatus, address.get_presence().get_status());
		var statusimg = getStatusImage(status);
		_addressList[index] = address;

		if (dispName === '')
			dispName = currAddress;

		var htmlJsConvLink = '<a href="#" onclick="';
		var htmlJsBlockUnblock = '<a href="#" onclick="blockUnblockContact(\'' + address.get_address() + '\', ' + address.get_type() + ', \'' + status + '\'';
		if (contact.get_isAllowed()) {
			if (checkIfUserIsOnline(status))
				htmlJsConvLink += 'createConversation(\'' + address.get_address() + '\', ' + address.get_type() + ');';

			htmlJsBlockUnblock += ', true);return false;">' +
				'<img src="common/images/imgMessenger/icoBlock.gif" alt="" /> blocca</a>';
		}
		else if (contact.get_isBlocked()) {
			statusimg = '<img src="common/images/imgMessenger/msngIcoBlocked.gif" alt="" />';

			htmlJsBlockUnblock += ', false);return false;">' +
				'<img src="common/images/imgMessenger/icoUnblock.gif" alt="" /> sblocca</a>';
		}
		htmlJsConvLink += 'return false;">';

		var htmlContactViewLine = '<div id="msngItemNr' + currAddressClean + '" class="cssContactLineView">' +
				'<div class="sxListPart">' + htmlJsConvLink + '<img src="common/include/getContactBuddyImg.aspx?bdem=' + currAddress + '" alt="' + status + '" class="cssBuddyContactImage" /></a></div>' +
				'<div class="dxListPart">' +
					'<div class="divTop">' + statusimg + ' ' + htmlJsConvLink + dispName + '</a><br /></div>' +
					'<div class="divBottom">' + htmlJsBlockUnblock + '</div>' +
				'</div>' +
			'</div>';

		if (checkIfUserIsOnline(status)) {
			sbOnline.append(htmlContactViewLine);
		}
		else {
			sbOffline.append(htmlContactViewLine);
		}

		index++;
	}

	var sb = new StringBuilder();
	/* aggiungo prima le persone "online" */
	sb.append(sbOnline.toString());
	/* poi aggiungo le persone "offline" */
	sb.append(sbOffline.toString());

	jQuery("#msngContactList").html('<div id="msngContactListItems">' + sb.toString() + '</div>');

	/* - */
	cloudNotOnlineUser();
	/* abilito lo scroll dei contatti */
	scrollContactItems();
}

function blockUnblockContact(address, type, status, bBlock) {
	///<summary>Blocco / sblocco il contatto selezionato e reimposto la visualizzazione.</summary>

	var confirmMessage = false;
	var contact = _contacts.find(address, type);
	var dispName = contact.get_currentAddress().get_presence().get_displayName();
	if (dispName === '')
		dispName = address;
	var contactAddressClean = address.replace(/[^a-zA-Z0-9]/gi, '');
	/* recupero l'elemento "html" lo ripulisco e lo ricostruisco */
	var contactItemElem = jQuery('#msngItemNr' + contactAddressClean);
	var statusimg = getStatusImage(status);
	var htmlJsConvLink = '';
	var htmlJsBlockUnblock = '';
	var htmlContactViewLine = '';

	if (contact != null) {
		if (bBlock) {
			confirmMessage = confirm("vuoi bloccare questo contatto?");
			if (!confirmMessage)
				return;
			contact.block();

			/* ricostruzione del contatto */
			htmlJsConvLink = '<a href="#" onclick="return false;">' + dispName + '</a><br />';
			htmlJsBlockUnblock = '<a href="#" onclick="blockUnblockContact(\'' + address + '\', ' + type + ', \'' + status + '\', false);return false;">' +
				'<img src="common/images/imgMessenger/icoUnblock.gif" alt="" /> sblocca</a>';

			htmlContactViewLine = '<div class="sxListPart"><img src="common/include/getContactBuddyImg.aspx?bdem=' + address + '" alt="' + status + '" class="cssBuddyContactImage" /></div>' +
				'<div class="dxListPart">' +
					'<div class="divTop"><img src="common/images/imgMessenger/msngIcoBlocked.gif" alt="" /> ' + htmlJsConvLink + '</div>' +
					'<div class="divBottom">' + htmlJsBlockUnblock + '</div>' +
				'</div>';
			contactItemElem.html(htmlContactViewLine);
		}
		else {
			confirmMessage = confirm("vuoi sbloccare questo contatto?");
			if (!confirmMessage)
				return;
			contact.allow();

			/* ricostruzione del contatto */
			htmlJsBlockUnblock = '<a href="#" onclick="blockUnblockContact(\'' + address + '\', ' + type + ', \'' + status + '\', true);return false;">' +
				'<img src="common/images/imgMessenger/icoBlock.gif" alt="" /> blocca</a>';
			htmlJsConvLink = '<a href="#" onclick="';
			if (checkIfUserIsOnline(status))
				htmlJsConvLink += 'createConversation(\'' + address + '\', ' + type + ');';
			htmlJsConvLink += 'return false;">';

			htmlContactViewLine = '<div class="sxListPart">' + htmlJsConvLink + '<img src="common/include/getContactBuddyImg.aspx?bdem=' + address + '" alt="' + status + '" class="cssBuddyContactImage" /></a><br /></div>' +
				'<div class="dxListPart">' +
					'<div class="divTop">' + statusimg + ' ' + htmlJsConvLink + dispName + '</a><br /></div>' +
					'<div class="divBottom">' + htmlJsBlockUnblock + '</div>' +
				'</div>';
			contactItemElem.html(htmlContactViewLine);
		}
	}
}

function contact_Presence_PropertyChanged(sender, e) {
	///<summary>Evento che permette di controllare quando la presenza di uno dei contatti è cambiata.</summary>

	var dispName = sender.get_displayName();
	var currAddress = sender.get_imAddress().get_address();
	var contact = _contacts.find(currAddress, sender.get_imAddress().get_type());
	var status = '';

	/* se il contatto non è stato trovato allora non faccio niente */
	if (contact == null)
		return;

	/* ?? sarebbe interessante recuperare il previous status ?? */
	if (e.get_propertyName() === 'Status') {
		status = Enum.toString(Microsoft.Live.Messenger.PresenceStatus, sender.get_status());
		if (status == "online" || status == "offline") {
			displayContacts();
			return;
		}
	}

	if ((e.get_propertyName() === 'DisplayName') || (e.get_propertyName() === 'Status')) {
		var currAddressClean = currAddress.replace(/[^a-zA-Z0-9]/gi, '');
		status = Enum.toString(Microsoft.Live.Messenger.PresenceStatus, sender.get_status());

		var statusimg = getStatusImage(status);
		/* recupero l'elemento "html" del contatto e lo ricostruisco */
		var contactItemElem = jQuery('#msngItemNr' + currAddressClean);
		contactItemElem.html('');

		if (dispName === '')
			dispName = currAddress;

		var htmlJsConvLink = '<a href="#" onclick="';
		var htmlJsBlockUnblock = '<a href="#" onclick="blockUnblockContact(\'' + currAddress + '\', ' + sender.get_imAddress().get_type() + ', \'' + status + '\'';
		if (contact.get_isAllowed()) {
			if (checkIfUserIsOnline(status))
				htmlJsConvLink += 'createConversation(\'' + currAddress + '\', ' + sender.get_imAddress().get_type() + ');';

			htmlJsBlockUnblock += ', true);return false;">' +
				'<img src="common/images/imgMessenger/icoBlock.gif" alt="" /> blocca</a>';
		}
		else if (contact.get_isBlocked()) {
			statusimg = '<img src="common/images/imgMessenger/msngIcoBlocked.gif" alt="" />';

			htmlJsBlockUnblock += ', false);return false;">' +
				'<img src="common/images/imgMessenger/icoUnblock.gif" alt="" /> sblocca</a>';
		}
		htmlJsConvLink += 'return false;">';

		var htmlContactViewLine = '<div class="sxListPart">' + htmlJsConvLink + '<img src="common/include/getContactBuddyImg.aspx?bdem=' + currAddress + '" alt="' + status + '" class="cssBuddyContactImage" /></a></div>' +
			'<div class="dxListPart">' +
				'<div class="divTop">' + statusimg + ' ' + htmlJsConvLink + dispName + '</a><br /></div>' +
				'<div class="divBottom">' + htmlJsBlockUnblock + '</div>' +
			'</div>';

		contactItemElem.html(htmlContactViewLine);
	}
	else {
		//"Contact Email: " + currAddress + " Property: " + e.get_propertyName();
	}

	/* opacizzo i contatti che non sono online */
	cloudNotOnlineUser();
}

function createConversation(address, type) {
	///<summary>Creazione di una nuova conversazione</summary>

	var contact = _contacts.find(address, type);
	var contactIMAddress = contact.get_currentAddress();
	var contactIMAddressClean = contactIMAddress.get_address().replace(/[^a-zA-Z0-9]/gi, '');
	var convoEnum = _user.get_conversations().getEnumerator();
	var convos = null;
	var convo = null;
	var newConvo = null;
	var rosterEnum = null;
	var rosterIMAddr = null;
	var convoExists = false;
	var index = -1;

	if (contactIMAddress && contactIMAddress.get_isOnline()) {
		/* Per evitare di avere una conversazione con me stesso */
		if (contactIMAddress.get_address() !== _user.get_address().get_address()) {
			while (convoEnum.moveNext()) {
				index++;
				convo = convoEnum.get_current();
				rosterEnum = convo.get_roster().getEnumerator();

				while (rosterEnum.moveNext()) {
					rosterIMAddr = rosterEnum.get_current();

					if (rosterIMAddr === contactIMAddress) {
						convoExists = true;
						break;
					}
				}
				if (convoExists) {
					break;
				}
			}
			if (convoExists) {
				//La conversazione esiste per questo indirizzo email
				if (_currentConvIndex) {
					if (_currentConvIndex != index) {
						_currentConvIndex = index;
						clickTabConversation(contactIMAddressClean, true); /* La funzione chiama al suo interno la //switchToConvo(); */
					}
				}
				else {
					_currentConvIndex = index;
					clickTabConversation(contactIMAddressClean, true); /* La funzione chiama al suo interno la //switchToConvo(); */
				}
			}
			else {
				//La conversazione per questo indirizzo non esiste e quindi la creo
				convos = _user.get_conversations();
				newConvo = convos.create(contactIMAddress);

				_currentConvIndex = convos.get_count() - 1;
				clickTabConversation(contactIMAddressClean, true); /* La funzione chiama al suo interno la //switchToConvo(); */
			}
		}
	}
}

function closeConversation(elemTabId) {
	///<summary>Close the selected conversation.</summary>

	var thisConvId = null;
	/* recupero l'id del link della conversazione */
	var thisLinkSelectId = thisLinkSelectId = jQuery('#convTab_' + elemTabId + ' div.dx a.cssConvLinkDX').attr('id');
	/* rimuovo la parte testuale dell'id per recuperare il valore numerico */
	if (thisLinkSelectId != '')
		thisConvId = thisLinkSelectId.replace(/cLinkDx_/i, '');
	if (isNaN(thisConvId))
		return;

	var conversation = _user.get_conversations().get_item(thisConvId);
	if (conversation == null)
		return;

	if (conversation == _activeConv) {
		/* se la conversazione è quella attiva ripulisco gli oggetti */
		removeChildrenFromNode("chatAreaConv");
		document.getElementById("btnSend").style.visibility = "hidden";
		var txtMessage = document.getElementById("txtMessage");
		txtMessage.value = "";
		txtMessage.readOnly = true;
	}
	/* rimuovo il tab della conversazione */
	jQuery('#convTab_' + elemTabId).remove();
	var newHtmlTabs = '';
	jQuery(".__scrollable").each(function() {
		newHtmlTabs += jQuery(this).html();
	});
	jQuery("#tabConversationsScroller").html(newHtmlTabs);
	jQuery('.tabConvItem').css('border-right', '');
	jQuery('.tabConvItem:last').css('border-right', 'solid 1px #999999');

	/* chiudo la conversazione */
	conversation.close();
	/* ricostruisco lo scroller tab */
	scrollTabConvItems();
}

function switchToConvo() {
	///<summary></summary>

	var chatAreaConv = jQuery('#chatAreaConv');
	var updatedChatArea = null;
	var convo = _user.get_conversations().get_item(_currentConvIndex);
	var histEnum = null;
	var histLinks = null;
	var histLink = null;

	/* l'attivazione viene fatta con il click sul tab */
	//var tabElem = jQuery('.tabConvItem').eq(_currentConvIndex);
	//tabElem.attr('class', 'tabConvItem active');

	chatAreaConv.html('');

	histEnum = convo.get_history().getEnumerator();

	while (histEnum.moveNext()) {
		displayMessage(histEnum.get_current());
	}

	updatedChatArea = convertUrlsToLinks(chatAreaConv);
	chatAreaConv.html(updatedChatArea.html());

	try {
		chatAreaConv[0].scrollTop = chatAreaConv[0].scrollHeight;
	}
	catch (e) { /* "error scrolling" */ }

	document.getElementById("btnSend").style.visibility = "visible";
	var txtMessage = document.getElementById("txtMessage");
	txtMessage.value = "";
	txtMessage.readOnly = false;
	txtMessage.focus();
}
function convertUrlsToLinks(dirtyStringObj) {
	///<summary></summary>

	var dirtyString = '';
	var cleanString = '';
	try {
		//dirtyString = dirtyStringObj[0].innerHTML;
		/* this dame regex converts all urls to links except the ones that start with settings.messenger.live.com (so smileys wont be affected) */
		// append a space at the end for the RegEx to work
		//cleanString = dirtyString.replace(/(?:(w{3}.)|http(.?):\/\/)((?!settings.messenger.live.com).*?)(?:\s)+/g, "<a href=\"http$2://$1$3\" target=\"_blank\">http$2://$1$3</a> ");
	}
	catch (e) {
		cleanString = dirtyString;
	}
	//dirtyStringObj.html(cleanString);

	return dirtyStringObj;
}

function conversations_CollectionChanged(sender, e) {
	///<summary>Funzine che viene chiamata dall'evento (principalmente) di aggiungi / rimuovi conversazioni</summary>

	var items = null;
	var convo = null;
	var roster = null;
	var rosterCount = null;
	var rosterEnum = null;
	var rosterIMAddr = null;
	var userIMAddr = _user.get_address();
	var rosterDisName = null;
	var rosterAddress = null;
	var rosterAddressClean = null;
	var chatNameTitle = null;
	var chatName = null;

	if (e.get_action() === Microsoft.Live.Core.NotifyCollectionChangedAction.add) {
		//alert("Action: ADD");
		items = e.get_newItems();
		for (i = 0; i < items.length; i++) {
			convo = items[i];
			roster = convo.get_roster();
			rosterCount = roster.get_count();
			rosterEnum = convo.get_roster().getEnumerator();
			chatNameTitle = '';
			chatName = '';

			while (rosterEnum.moveNext()) {
				rosterIMAddr = rosterEnum.get_current();
				rosterDisName = rosterIMAddr.get_presence().get_displayName();
				rosterAddress = rosterIMAddr.get_address();

				if (rosterCount > 2) {
					if (rosterIMAddr != userIMAddr) {
						rosterAddressClean = rosterAddress.replace(/[^a-zA-Z0-9]/gi, '');
						if (rosterDisName === '') {
							chatNameTitle += rosterAddress + ' ';
						}
						else {
							chatNameTitle += rosterDisName + ' ';
						}
					}
				}
				else {
					if (rosterIMAddr != userIMAddr) {
						rosterAddressClean = rosterAddress.replace(/[^a-zA-Z0-9]/gi, '');
						if (rosterDisName === '') {
							chatNameTitle = rosterAddress;
						}
						else {
							chatNameTitle = rosterDisName;
						}
					}
				}
			}

			if (chatNameTitle.length > cTABCONVMAXCHAR) {
				chatName = chatNameTitle.substring(0, cTABCONVMAXCHAR) + '...';
			}
			else {
				chatName = chatNameTitle;
			}

			//chatNameTitle; //Questo è l'elemento originale non accorciato
			/* creazione dell'elemento Tab */
			var convId = e.get_newStartingIndex();
			var convoTabElem = '<div class="tabConvItem" id="convTab_' + rosterAddressClean + '">' +
				'<div class="sx">' +
				'<a href="#" class="cssConvLinkSX" id="cLinkSx_' + convId + '" onclick="clickTabConversation(\'' + rosterAddressClean + '\', false);return false;">' + chatName + '</a>' +
				'</div>' +
				'<div class="dx">' +
				'<a href="#" class="cssConvLinkDX" id="cLinkDx_' + convId + '" onclick="closeConversation(\'' + rosterAddressClean + '\');return false;">X</a>' +
				'</div>' +
				'</div>';

			convo.add_propertyChanged(Delegate.create(null, conversation_PropertyChanged));
			convo.add_messageReceived(Delegate.create(null, recvMsg));
			convo.add_sendMessageFailed(Delegate.create(null, conversation_SendMessageFailed));

			var newHtmlTabs = '';
			jQuery(".__scrollable").each(function() {
				newHtmlTabs += jQuery(this).html();
			});
			newHtmlTabs += convoTabElem;
			jQuery("#tabConversationsScroller").html(newHtmlTabs);

			/* --- */
			jQuery('#convTab_' + rosterAddressClean).css('width', '35px');
			jQuery('.tabConvItem').css('border-right', '');
			jQuery('.tabConvItem:last').css('border-right', 'solid 1px #999999');

			scrollTabConvItems();

			/* chiama la funzione di visualizzazione del tab se è l'unica conversazione presente */
			if (e.get_newStartingIndex() == 0) {
				clickTabConversation(rosterAddressClean, true);
			}
		}
	}
	else if (e.get_action() === Microsoft.Live.Core.NotifyCollectionChangedAction.remove) {
		//alert("Action: REMOVE");
		//"Old Starting Index: " + e.get_oldStartingIndex();
		//"New Items Length: " + items.length;
		items = e.get_oldItems();

		for (i = 0; i < items.length; i++) {
			convo = items[i];
			convo.remove_messageReceived(Delegate.create(null, recvMsg));
			convo.remove_propertyChanged(Delegate.create(null, conversation_PropertyChanged));
			convo.remove_sendMessageFailed(Delegate.create(null, conversation_SendMessageFailed));
		}

		/* riordina le conversazioni impostando il nuovo id della conversazione da sistemare xxxx */
		var cssConvLinkSX = jQuery('.cssConvLinkSX');
		if (cssConvLinkSX.length) {
			for (i = 0; i < cssConvLinkSX.length; i++) {
				cssConvLinkSX.eq(i).attr('id', 'cLinkSx_' + i);
			}
		}
		var cssConvLinkDX = jQuery('.cssConvLinkDX');
		if (cssConvLinkDX.length) {
			for (i = 0; i < cssConvLinkDX.length; i++) {
				cssConvLinkDX.eq(i).attr('id', 'cLinkDx_' + i);
			}
		}

		if (e.get_oldStartingIndex() == _currentConvIndex) {
			_activeConv = null;
			_currentConvIndex = null;
		}
	}
	else if (e.get_action() === Microsoft.Live.Core.NotifyCollectionChangedAction.replaced) {
		/* "REPLACED" */
	}
	else if (e.get_action() === Microsoft.Live.Core.NotifyCollectionChangedAction.reset) {
		/* "RESET" */
	}
}

function conversation_PropertyChanged(sender, e) {
	///<summary>Funzione che viene chiamata dall'evento che si verificano dalla modifica delle conversazioni</summary>

	if (_user == null)
		return;

	var convoEnum = null;
	var convo = null;
	var convoTabElem = null;
	var index = -1;

	var senderEmailClean = '';

	if (e.get_propertyName() === 'History') {
		if (sender === _user.get_conversations().get_item(_currentConvIndex)) {
			//'L'History della conversazione corrente è cambiata.';
			switchToConvo();
		}
		else {
			convoEnum = _user.get_conversations().getEnumerator();
			while (convoEnum.moveNext()) {
				index++;
				convo = convoEnum.get_current();
				if (sender === convo) {
					//'L'History di una conversazione non attiva è cambiata.';
					senderEmailClean = getSenderEmailFromConversation(sender).replace(/[^a-zA-Z0-9]/gi, '');
					/* visualizzo l'arrivo di un nuovo messaggio impostando il background */
					jQuery('#convTab_' + senderEmailClean).css('background-image', 'url(common/images/css/bgConvItemTabsBlink.gif)');
				}
			}
		}
	}
	else if (e.get_propertyName() === 'Closed') {
		/* "Closed" */
	}
	else if (e.get_propertyName() === 'Roster') {
		/* "Roster" */
	}
	else if (e.get_propertyName() === 'TypingAddresses') {
		/* "TypingAddresses" */
	}
}

function clickTabConversation(elemTabId, mimicCkick) {
	///<summary>Selezione della conversazione facendo click sul tab</summary>

	var thisConvId = null;
	/*
	* recupero l'id del link della conversazione 
	* e rimuovo la parte testuale dell'id per recuperare il valore numerico
	* che mi serve per impostare l'identificativo numerico della conversazione
	*/
	var thisLinkSelectId = jQuery('#convTab_' + elemTabId + ' div.sx a.cssConvLinkSX').attr('id');
	if (thisLinkSelectId != '')
		thisConvId = thisLinkSelectId.replace(/cLinkSx_/i, '');
	if (isNaN(thisConvId))
		return;

	_currentConvIndex = thisConvId;

	var thisConv = _user.get_conversations().get_item(thisConvId);
	if (thisConv != null) {
		_activeConv = thisConv;
	}

	jQuery('.tabConvItem').each(function() {
		var thisTab = jQuery(this);
		thisTab.attr('class', 'tabConvItem');
		thisTab.css('width', '35px');
		thisTab.css('border-right', '');
		//jQuery('#' + thisTab.attr("id") + ' > *').css('font-weight', 'bold');
		var thisTabBackground = thisTab.css('background-image');
		if (thisTabBackground.indexOf('common/images/css/bgConvItemTabsBlink.gif', 0) < 0) {
			thisTab.css('background-image', 'url(common/images/css/bgConvItemTabs.gif)');
		}
		if (thisTab.attr("id") == 'convTab_' + elemTabId) {
			thisTab.css('background-image', 'url(common/images/css/bgConvItemTabsActive.gif)')
			thisTab.css('width', '126px');
		}
	});
	jQuery('.tabConvItem:last').css('border-right', 'solid 1px #999999');

	/* devo simulare il click se richiesto */
	if (mimicCkick) {
		jQuery('#convTab_' + elemTabId).click();
		//jQuery('#convTab_' + elemTabId + ' div.sx a.cssConvLinkSX').click();
	}

	/* visualizzo la conversazione */
	switchToConvo();
}

function sendMessage() {
	///<summary>Send a message in the current conversation.</summary>

	if (_user == null)
		return;
	if (_activeConv == null)
		return;

	var txtMessage = document.getElementById("txtMessage");
	var messageText = txtMessage.value;
	if (messageText == "")
		return;

	var message = new Microsoft.Live.Messenger.TextMessage(messageText, null);
	_activeConv.sendMessage(message, null);

	txtMessage.value = "";
	txtMessage.focus();
}

function sendMessageToInvite() {
	///<summary>Crea il link e invia il messaggio che invita a visitare il MyDiary</summary>

	if (_user == null)
		return;
	if (_activeConv == null)
		return;

	var messageText = "Vieni a visitare il mio diario online su " +
				"http://www.mylifeclub.it/mydiary/";
	var message = new Microsoft.Live.Messenger.TextMessage(messageText, null);
	_activeConv.sendMessage(message, null);
}

function recvMsg(sender, e) {
	///<summary>Called by the Messenger Library when a new message is received.</summary>

	if (_user == null)
		return;
	//var message = e.get_message();
	//var timestamp = message.get_timestamp();
	//var dtFromTimestamp = new Date(timestamp);
}

function displayMessage(message) {
	///<summary>Show text for a received message in the conversation window.</summary>

	var userName = "";
	var messageGetSender = message.get_sender();
	if (messageGetSender.get_presence().get_displayName() != null && messageGetSender.get_presence().get_displayName() !== '')
		userName = messageGetSender.get_presence().get_displayName();
	else
		userName = messageGetSender.get_address();

	var htmlConversationDispName = document.createElement('label');
	htmlConversationDispName.innerHTML = userName + ':';
	if (_user.get_address().get_address() == messageGetSender.get_address())
		htmlConversationDispName.className = "lblConvDispNameMe";
	else
		htmlConversationDispName.className = "lblConvDispNameOt";

	var chatAreaConv = document.getElementById("chatAreaConv");
	chatAreaConv.appendChild(htmlConversationDispName);
	chatAreaConv.appendChild(document.createElement("br"));
	chatAreaConv.appendChild(message.createTextElement());
	chatAreaConv.appendChild(document.createElement("br"));
	chatAreaConv.appendChild(document.createElement("br"));
}

function removeChildrenFromNode(id) {
	///<summary>Rimuove tutti i controlli figlio da uno specifico nodo (i.e. clear messages from the conversation window).</summary>
	///<param name="id" type="string">Identificativo dell'elemento che deve essere "ripulito".</param>

	var node = document.getElementById(id);
	if (node == undefined || node == null) {
		return;
	}
	var len = node.childNodes.length;
	while (node.hasChildNodes()) {
		node.removeChild(node.firstChild);
	}
}

function scrollContactItems() {
	///<summary>Inizializzazione dello scrolle dei contatti.</summary>

	jQuery('div#msngContactListItems').jScrollPane({ showArrows: true, scrollbarMargin: 0, scrollbarWidth: 14, scrollbarDragWidth: 7, scrollbarDragBorder: 1, forcePaneWidth: 204 });
}
function scrollTabConvItems() {
	///<summary>Inizializzazione dello scrolle delle conversazioni.</summary>

	jQuery("div#tabConversationsContainer").scrollable({ size: 4, items: '.convItems', horizontal: true, prev: 'img#msngScrollConvSx', next: 'img#msngScrollConvDx' });
}

function cloudNotOnlineUser() {
	///<summary>"opacizzo" gli utenti che non sono online.</summary>

	jQuery(".cssContactLineView").each(function() {
		if (jQuery(this).find("img").attr("alt") == "offline")
			jQuery(this).fadeTo("fast", 0.33);
		else
			jQuery(this).fadeTo("fast", 1);
	});
}

function signInCloudUncloud(isSignIn) {
	///<summary>Impostazione del layout opacizzato o meno in base al fatto di essere online o offline. Non funziona bene con IE sia il 6 che il 7.</summary>

	if (isSignIn) {
		jQuery('#cloudUncloudWorkArea').hide('fast');
		jQuery('#balloonCharlieMessenger').hide('fast');
		jQuery('#mascotCharlieMessenger').hide('fast');
	}
	else {
		jQuery('#cloudUncloudWorkArea').show('fast');
		jQuery('#balloonCharlieMessenger').show('fast');
		jQuery('#mascotCharlieMessenger').show('fast');
	}
}

function keyEnterSendMessage(e) {
	var evt = (e) ? e : (window.event) ? window.event : null;
	if (evt) {
		var key = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
		if (key == "13") {
			//sendMessage();
			jQuery('a#btnSend').click();
			(evt.timeStamp) ? evt.preventDefault() : evt.returnValue = false;
		}
	}
}
