/** FUNZIONI */


var ajax, obj, useAjax, timerID, inputTimerId;
//var BotDialogUrl = "http://www.dreams-co.com/BOTdialogue.php";
var BotDialogUrl = "BOTdialogue.php";
//var BotDialogUrl = "BOTdialogue.old.php";

// Funzione di dialogo con il bot (tramite ajax)
//function GetNLIAnswer(sessionname, sessionval, nochacheval, resetdialog)
function GetNLIAnswer(sessionname, sessionval, resetdialog)
{
	// Parametri di input :
	// sessionname, sessionval, nochacheval => variabili per il dialogo con il BOT
	// resetdialog =>
	//		0 = nessun reset
	//		1 = inizializzazione del bot
	//		2 = reset periodico
	// Parametri di output :
	// false => chiamata eseguita con Ajax
	// true => chiamata da eseguire tramite submit classico della form
	
	var BotQuestion = document.QuestionForm.BOTQuestion.value;
	
	// controllo se e' stata passata una domanda corretta (e non si deve effettuare un reset)
	if (! verifyBotQuestion(BotQuestion) && resetdialog == 0)
		return false;
	
	BotQuestion = BotQuestion.replace('è', '§egrave;');
	BotQuestion = BotQuestion.replace('é', '§eacute;');
	BotQuestion = BotQuestion.replace('ì', '§igrave;');
	BotQuestion = BotQuestion.replace('à', '§agrave;');
	BotQuestion = BotQuestion.replace('ò', '§ograve;');
	BotQuestion = BotQuestion.replace('ù', '§ugrave;');
	
	// Blocco la form, in modo da non avere altri dati in input mentre vengono elaborati questi
	document.QuestionForm.BOTQuestion.disabled = true;
	document.QuestionForm.btnsend.disabled = true;
	
	// assegnazione oggetto XMLHttpRequest
	if (! ajax)
		ajax = GetXMLHttpRequest();

	obj = GetObjectFromID("BOTAnswerDiv");
	useAjax = true;

	// Setto un timeout per riabilitare la casella di input, nel caso la risposta si bloccasse
	if(inputTimerId)
		clearTimeout(inputTimerId);
	inputTimerId = setTimeout('userinput_setfocus()', 30000); 

	// se l'oggetto XMLHttpRequest non è nullo
	if(ajax)
	{
		// setto a false per non eseguire il submit della form
		useAjax = false;
		
		// impostazione richiesta asincrona in GET
		// del file specificato
		ajax.open("post", BotDialogUrl, true);
    
		// imposto il giusto header
		ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
		
		// rimozione dell'header "connection" come "keep alive"
		ajax.setRequestHeader("connection", "close");

		if (resetdialog == 0)
			// effettuo la richiesta inviando la variabile leggi con contenuto Dante
			//ajax.send(sessionname + "=" + sessionval + "&BOTQuestion=" + document.QuestionForm.BOTQuestion.value + "&nocache=" + nochacheval);
			ajax.send(sessionname + "=" + sessionval + "&BOTQuestion=" + BotQuestion);
		else
			// effettuo una richiesta di inizializzazione la connessione con il bot
			ajax.send(sessionname + "=" + sessionval + "&BOTQuestion=" + BotQuestion +"&resetdialog=1");

		// impostazione controllo e stato della richiesta
		ajax.onreadystatechange = function()
		{
			// verifica dello stato
			if(ajax.readyState === readyState.COMPLETED)
			{
				// verifica della risposta da parte del server
				if (resetdialog < 2)
				{
					if(statusText[ajax.status] === "OK")
					{
						// operazione avvenuta con successo
						obj.innerHTML = ajax.responseText;

						//alert (ajax.responseText);
					}
					else
					{
						// errore di caricamento
						obj.innerHTML = "Impossibile effettuare l'operazione richiesta.<br />";
						obj.innerHTML += "Errore riscontrato: " + statusText[ajax.status];
					}
				}
				
				// Elimino il timer per riabilitare la casella di input se la risposta è stata processata correttamente
				if(inputTimerId)
					clearTimeout(inputTimerId);
										
				document.QuestionForm.BOTQuestion.disabled = false;
				document.QuestionForm.btnsend.disabled = false;
				document.QuestionForm.BOTQuestion.value = "";
				
				document.QuestionForm.BOTQuestion.focus();
			}
		}
	}
	
	if(timerID)
		clearTimeout(timerID);
	timerID = setTimeout('sessionTimeout()', 180000);
  
  return useAjax;
};

// funzione per prendere un elemento con id univoco
function GetObjectFromID(id_object)
{
	var obj;
	if(document.getElementById)
		obj = document.getElementById(id_object);
	else
		obj = document.all[id_object];
	return obj;
};


// funzione per assegnare un oggetto XMLHttpRequest
function GetXMLHttpRequest()
{
	var
		XHR = null,
		UserBrowser = navigator.userAgent.toUpperCase();
		
	if(typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object")
		XHR = new XMLHttpRequest();
	else
		if(window.ActiveXObject && UserBrowser.indexOf("MSIE 4") < 0)
		{
			if(UserBrowser.indexOf("MSIE 5") < 0)
				XHR = new ActiveXObject("Msxml2.XMLHTTP");
			else
				XHR = new ActiveXObject("Microsoft.XMLHTTP");
		}
	return XHR;
};


function userinput_setfocus()
{
	document.QuestionForm.btnsend.disabled = false;
	document.QuestionForm.BOTQuestion.focus();
};


function PopUp(newUrl)
{
	parent.mainFrame.location.href="../" + newUrl;
};


function sessionTimeout()
{
	var text = new Array();
	var voice = new Array();
	var random = Math.round(2*Math.random());
	var output;
	text[0] = "&gt; Non stai pi&ugrave; parlando con me. Fra un p&ograve; me ne vado.";
	text[1] = "&gt; A quanto pare non vuoi pi&ugrave; chiedermi niente. Penso che fra poco me ne andr&ograve;.";
	text[2] = "&gt; Non mi chiedi pi&ugrave; niente?";
	voice[0] = "exc001";
	voice[1] = "exc002";
	voice[2] = "exc003";
	
	output = "<div id=\"avatar_flash\">";
	output = output + "<OBJECT classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"";
 	output = output + "codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0\"";
 	output = output + "width=\"176\" height=\"173\" id=\"avatar\">";
 	output = output + "<PARAM NAME=\"movie\" value=\"avatar.swf\"> <PARAM name=FlashVars value=\"response="+voice[random]+"\"> <PARAM name=\"quality\" value=\"best\"> <PARAM name=\"scale\" value=\"noscale\"> <PARAM name=\"wmode\" value=\"transparent\"> <EMBED src=\"avatar.swf\" scale=\"noscale\" FlashVars=\"response="+voice[random]+"\" wmode=\"transparent\" quality=\"best\" width=\"176\" height=\"173\" name=\"avatar\"";
 	output = output + "type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\"></EMBED>";
	output = output + "</OBJECT>\n</div>\n<br />";
	output = output + text[random];
	
	//document.getElementById('BOTAnswerDiv').innerHTML = output;
	if(timerID)
		clearTimeout(timerID);
	//timerID = setTimeout('GetNLIAnswer ("", "", 2);', 60000);
	GetNLIAnswer ("", "", 2);
};
	

function verifyBotQuestion(InputQuestion)
{
	if (InputQuestion.length == 0)
		return false;
	else
		return true; 
};


// Funzioni richiamate da js_execute all'interno di NLI:
function Open_Win(theURL,target,W,H,scroll)
{
	var par;
	par = 'width=' + W + ',height=' + H + ',left=0,top=0,resizable=yes,toolbar=yes,directories=yes,menubar=yes,scrollbars=' + scroll;
	newWin = window.open(theURL,target,par);
	if (window.focus) 
		newWin.focus();
};


function Open_Popup(theURL,target,W,H,scroll)
{
	var xPos;
	if (W != '') 
		xPos = screen.width - W;
	else
		xPos = W;
	var par;
	//par = 'width=' + W + ',height=' + H + ',left=0,top=0,toolbar=no,directories=no,menubar=no,scrollbars=' + scroll;
	par = 'width=' + W + ',height=' + H + ',left='+xPos+',top=0,toolbar=no,directories=no,menubar=no,scrollbars=' + scroll;
	newWin = window.open(theURL,target,par);
	if (window.focus) 
		newWin.focus();
};


function Shut_bot(str)
{
	setTimeout('self.location.href=(\''+str+'\')', 6000);
};


function Close_bot()
{
	setTimeout('self.close()', 10000);
};


function Close_bot(str)
{
	document.getElementById('answer').innerHTML = str;
	setTimeout('self.close()', 5000);
};


// Funzioni per la gestione delle webaction quando il bot si trova in una popup
function Open_Win_From_Popup(theURL,target,W,H,scroll)
{
	window.open (theURL, '_new', 'width=800,height=600,toolbar=no,directories=no,menubar=no,scrollbars=yes,resizable=yes');
	//window.opener.location.href=theURL;
	//passa il focus sulla nuova pagina e dopo un tot sul bot nuovamente
	//if (window.focus)
	//	window.opener.focus();		
	//window.setTimeout("window.focus()",5000);
};


function Open_Win_From_Popup_And_Close(theURL,target,W,H,scroll)
{
	window.opener.location.href=theURL;
	window.setTimeout("self.close()",10000);
}


// Funzioni per i link cliccabili negli output del Bot:
function sendInput(str)
{
	//top.vaframes.document.QuestionForm.BOTQuestion.value=str;
	document.QuestionForm.BOTQuestion.value=str;
	/*try
	{
		top.vaframes.document.QuestionForm.BOTQuestion.value=str;
		//parent.set_recv_output();*/
		//top.vaframes.document.QuestionForm.submit();/*
		document.QuestionForm.submit();/*
	}
	catch(e)
	{
		document.write('Funzionalità di memoria utente temporaneamente disabilitata per motivi tecnici.');
	}*/
};


// Funzione per la parte audio del bot
function PlaySound(what)
{
	document.write ("<EMBED src='"+what+"' autostart='true' loop='false' volume='100' hidden='true'>");
	document.write ("<NOEMBED><BGSOUND src='"+what+"'></NOEMBED>");
};


/** OGGETTI / ARRAY */

// oggetto di verifica stato
var readyState = {
		INACTIVE:	0,
		INITIALIZED:	1,
		REQUESTED:	2,
		RESPONSED:	3,
		COMPLETED:	4
};


// array descrittivo dei codici restituiti dal server
// [la scelta dell' array è per evitare problemi con vecchi browsers]
var statusText = new Array();
statusText[100] = "Continue";
statusText[101] = "Switching Protocols";
statusText[200] = "OK";
statusText[201] = "Created";
statusText[202] = "Accepted";
statusText[203] = "Non-Authoritative Information";
statusText[204] = "No Content";
statusText[205] = "Reset Content";
statusText[206] = "Partial Content";
statusText[300] = "Multiple Choices";
statusText[301] = "Moved Permanently";
statusText[302] = "Found";
statusText[303] = "See Other";
statusText[304] = "Not Modified";
statusText[305] = "Use Proxy";
statusText[306] = "(unused, but reserved)";
statusText[307] = "Temporary Redirect";
statusText[400] = "Bad Request";
statusText[401] = "Unauthorized";
statusText[402] = "Payment Required";
statusText[403] = "Forbidden";
statusText[404] = "Not Found";
statusText[405] = "Method Not Allowed";
statusText[406] = "Not Acceptable";
statusText[407] = "Proxy Authentication Required";
statusText[408] = "Request Timeout";
statusText[409] = "Conflict";
statusText[410] = "Gone";
statusText[411] = "Length Required";
statusText[412] = "Precondition Failed";
statusText[413] = "Request Entity Too Large";
statusText[414] = "Request-URI Too Long";
statusText[415] = "Unsupported Media Type";
statusText[416] = "Requested Range Not Satisfiable";
statusText[417] = "Expectation Failed";
statusText[500] = "Internal Server Error";
statusText[501] = "Not Implemented";
statusText[502] = "Bad Gateway";
statusText[503] = "Service Unavailable";
statusText[504] = "Gateway Timeout";
statusText[505] = "HTTP Version Not Supported";
statusText[509] = "Bandwidth Limit Exceeded";
