
function GetNLIAnswer_test(valore)
{
	document.getElementById('av_answertextdiv').innerHTML = "&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis orci nec turpis tempor venenatis. Aenean vitae eros orci. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque et varius nisl. Morbi nec porttitor dolor. In venenatis eros nec felis ultrices eleifend. Vivamus ac turpis. ";
	document.getElementById('av_questiontextdiv').innerHTML = "Hai chiesto: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit. ";
	
	output = "\t<animazione>\n";
	output = output + "	<div id=\"avatar_flash\">\n";
	output = output + "	<OBJECT classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"\n";
	output = output + "	codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0\"\n";
	output = output + "	width=\"211\" height=\"211\" id=\"avatar\">\n";
	output = output + "	<PARAM name=\"movie\" value=\"../../media/flash/av.swf\"> <PARAM name=FlashVars value=\"response=av/\"> <PARAM name=\"quality\" value=\"best\"> <PARAM name=\"scale\" value=\"noscale\"> <PARAM name=\"wmode\" value=\"transparent\"> <EMBED src=\"../../media/flash/av.swf\" scale=\"noscale\" FlashVars=\"response=av/\" wmode=\"transparent\" quality=\"best\" width=\"211\" height=\"211\" name=\"avatar\"\n";
	output = output + "	type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\"></EMBED>\n";
	output = output + "	</OBJECT>\n</div>\n";
	
	document.getElementById('av_avatardiv').innerHTML = output;
}


var ajax, obj_avatar, obj_answer, useAjax, timerID, inputTimerId;
//var BotDialogUrl = "getanswer.php";
var BotDialogUrl = "http://www.estenergy.it/getanswer.aspx";
//var BotDialogUrl = "http://estenergytest.ascotlc.it/media/av/testina.htm";


function GetNLIAnswer_test2(valore)
{
	document.charset = "iso8859-1";

	var BotQuestion = document.QuestionForm.BOTQuestion.value;
	//var BotQuestion = my_utf8_encode(document.QuestionForm.BOTQuestion.value)

	if (BotQuestion.indexOf("č") > -1)
	{
		alert ("Trovata 'č' su '"+BotQuestion+"'");
		BotQuestion = my_str_replace(BotQuestion, "č", "e\'");
	}
	else
	{
		alert ("NON Trovata 'č' su '"+BotQuestion+"'")
	}

	alert ("'"+BotQuestion+"'");
}

// Funzione di dialogo con il bot (tramite ajax)
function GetNLIAnswer(resetdialog)
{
	//document.charset = "iso8859-1";

	// 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
	
	if (readCookie("showav") == "1")
	{
	var BotQuestion = document.QuestionForm.BOTQuestion.value;
	//var BotQuestion = my_utf8_encode(document.QuestionForm.BOTQuestion.value)

	var sessionname = "PHPSESSID";
	var sessionval = GetObjectFromID("PHPSESSID").value;

	var parametri;

//alert ("'"+BotQuestion+"'");
	
	// 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_avatar = GetObjectFromID("av_avatardiv");
	obj_answer = GetObjectFromID("av_answertextdiv");
	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); 

//alert (ajax);

	// se l'oggetto XMLHttpRequest non č nullo
	if(ajax)
	{
		// setto a false per non eseguire il submit della form
		useAjax = false;

//alert (BotDialogUrl);

		// 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");

		if (resetdialog == 0)
			// effettuo la richiesta inviando la variabile leggi con contenuto Dante
			parametri = sessionname + "=" + sessionval + "&page=" + location.href.toString() + "&BOTQuestion=" + BotQuestion;
		else
			// effettuo una richiesta di inizializzazione la connessione con il bot
			parametri = sessionname + "=" + sessionval + "&page=" + location.href.toString() + "&BOTQuestion=" + BotQuestion +"&resetdialog=1";

		ajax.setRequestHeader('If-Modified-Since','Tue, 04 Apr 2006 00:00:00 GMT');  //some date in the past
		ajax.setRequestHeader("Content-length", parametri.length);

		// Non permetto la cache della pagina
		ajax.setRequestHeader("Pragma", "no-cache");
		ajax.setRequestHeader("Expires", "1");
		
		// rimozione dell'header "connection" come "keep alive"
		if(!document.all) {
			ajax.setRequestHeader("connection", "close");
		}

		// impostazione controllo e stato della richiesta
		ajax.onreadystatechange = function()
		{

//alert (ajax.readyState);

			// 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
						risposta = ajax.responseText.split("####");

						//alert (ajax.responseText);

						// Effettuo il trim
						risposta[2] = risposta[2].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
							
						obj_avatar.innerHTML = risposta[0];
						obj_answer.innerHTML = risposta[1];

						document.getElementById('PHPSESSID').value = risposta[2];

//alert (document.getElementById('PHPSESSID').value);

					}
					else
					{
						// errore di caricamento
						obj_answer.innerHTML = "Impossibile effettuare l'operazione richiesta.<br />";
						obj_answer.innerHTML += "Errore riscontrato: " + statusText[ajax.status];
					}
				}

/*
if (ajax.readyState == 4)
{
	strResponse = ajax.responseText;
	switch (ajax.status)
	{
		// Page-not-found error
		case 404:
			alert('Error: Not Found. The requested URL ' + BotDialogUrl + ' could not be found.');
			break;
		// Display results in a full window for server-side errors
		case 500:
			handleErrFullPage(strResponse);
			break;
		default:

		// Call JS alert for custom error or debug messages
		if (strResponse.indexOf('Error:') > -1 || strResponse.indexOf('Debug:') > -1)
		{
			alert(strResponse);
		}
		break;
	}
}
*/

//alert ("Risposta ottenuta: riabilito la form");

				// 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();
			}
		}

		ajax.send(parametri);

	}
	
	if(timerID)
		clearTimeout(timerID);
	timerID = setTimeout('sessionTimeout()', 180000);
  
	return useAjax;
	}
};


function handleErrFullPage(strIn)
{
	var errorWin;

	// Create new window and display error
	try
	{
		errorWin = window.open('', 'errorWin');
		errorWin.document.body.innerHTML = strIn;
	}
	// If pop-up gets blocked, inform user
	catch(e)
	{
		alert('An error occurred, but the error message cannot be' +
		' displayed because of your browser\'s pop-up blocker.\n' +
		'Please allow pop-ups from this Web site.');
	}
}


function my_str_replace (frase, testo_in, testo_out)
{
	var idx = frase.indexOf (testo_in);
	while (idx > -1) {
		frase = frase.replace (testo_in, testo_out);
		idx = frase.indexOf (testo_in);
	}

	return frase;
};


// funzione per la gestione di weblink/webaction
function av_weblink (theUrl)
{
	var link_attuale = window.location.href.toString();

	if (link_attuale != theUrl)
		location.replace (theUrl);
}

// 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")
	{
		//alert ("OLD: XMLHttpRequest");
		XHR = new XMLHttpRequest();
	}
	else
		if(window.ActiveXObject && UserBrowser.indexOf("MSIE 4") < 0)
		{
			if(UserBrowser.indexOf("MSIE 5") < 0)
			{
				//alert ("OLD: Msxml2.XMLHTTP");
				XHR = new ActiveXObject("Msxml2.XMLHTTP");
			}
			else
			{
				//alert ("OLD: Microsoft.XMLHTTP");
				XHR = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
	return XHR;

/*
	var xmlhttp = null;
	
	if(window.XMLHttpRequest) 
	{
		//alert ("NEW: window.XMLHttpRequest");
		xmlhttp = new XMLHttpRequest(); // Gecko (Firefox, Moz), KHTML (Konqueror, Safari), Opera, Internet Explorer 7
	} 
	else if(window.ActiveXObject) 
	{
		try
		{
			//alert ("NEW: MSXML2.XMLHTTP");
			xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); // Internet Explorer 6 
		} 
		catch(e) 
		{
			//alert ("NEW: Microsoft.XMLHTTP");
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer 4,5 
		}
	} 
	else 
	{
		xmlhttp = null;
	}
	
	return xmlhttp;
*/

};

function my_utf8_encode(utftext) {
	var string = "";
	var i = 0;
	var c = c1 = c2 = 0;

	while ( i < utftext.length )
	{
		c = utftext.charCodeAt(i);

		if (c < 128)
		{
			string += String.fromCharCode(c);
			i++;
		}
		else if((c > 191) && (c < 224))
		{
			c2 = utftext.charCodeAt(i+1);
			string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
			i += 2;
		}
		else
		{
			c2 = utftext.charCodeAt(i+1);
			c3 = utftext.charCodeAt(i+2);
			string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}
	}

	return escape(string);
};

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] = "av/exc001";
	voice[1] = "av/exc002";
	voice[2] = "av/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=\"211\" height=\"211\" 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>");
};

function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
}

function Av_Zitto()
{
	var stringa ="<div id=\"avatar_flash\">\n";
	stringa += "<OBJECT classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"\n";
	stringa += "codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0\"\n";
	stringa += "width=\"211\" height=\"211\" id=\"avatar\">\n";
	stringa += "<PARAM name=\"movie\" value=\"http://www.sentichenotizia.it/EstEnergy/avatar.swf\">\n";
	stringa += "<PARAM name=FlashVars value=\"response=http://www.sentichenotizia.it/EstEnergy/000_0_0\">\n";
	stringa += "<PARAM name=\"quality\" value=\"best\">\n";
	stringa += "<PARAM name=\"scale\" value=\"noscale\">\n";
	stringa += "<PARAM name=\"wmode\" value=\"transparent\">\n";
	stringa += "<EMBED src=\"http://www.sentichenotizia.it/EstEnergy/avatar.swf\" scale=\"noscale\" FlashVars=\"response=http://www.sentichenotizia.it/EstEnergy/000_0_0\" wmode=\"transparent\" quality=\"best\" width=\"211\" height=\"211\" name=\"avatar\"\n";
	stringa += "type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\"></EMBED>\n";
	stringa += "</OBJECT>\n";
	stringa += "</div>\n";

	var obj_avatar = GetObjectFromID("av_avatardiv");
	obj_avatar.innerHTML = stringa;
}

/** 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";
