// ******************************************************************************
// ** ACA.JS                                                                   **
// ******************************************************************************
// ** product: CAD22 Artificial Agent                                          **
// **    file: www/dialonics/aca.js                                            **
// ** authors: Sylvain Camus, Vincent Louis, Thierry Martinez, Franck Panaget  **
// ** version:                                                                 **
// **    date:                                                                 **
// **  status: restricted                                                      **
// ******************************************************************************
// ** This file is the property of Dialonics. It may be provided only under    **
// ** license. If you do not have received a notice with this file, or if you  **
// ** disagree with the terms and conditions of this notice, you must not use, **
// ** copy or communicate this file to third-parties, and you must destroy any **
// ** copy of this file in your possession.                                    **
// **                                                                          **
// ** Copyright (C) 2010-2011, Dialonics - All rights reserved                 **
// ** www.dialonics.com - license@dialonics.com                                **
// ******************************************************************************

/* ============= *
 * CONFIGURATION *
 * ============= */

var NABUTALK_URL    = "/dialonics/nabutalk.asp";
var NABUTALK_COOKIE = /ASPSESSIONID[^=]*/; // must be the same as in "nabutalk.asp"
var REFRESH_QUERY   = "event=welcome&last=yes";

var AVATAR_URL_PATTERN        = "avatars/{name}_{hair}/{name}_{hair}_{animation}.flv";
var AVATAR_INITIAL_PARAMETERS = {};

var PUSH_ENABLED    = true;    

var ANSWER_ID       = "ntAnswer";
var AVATAR_FLASH_ID = "ntAvatarFlash";
var FORM_ID         = "ntForm";
var LOGO_ID         = "ntLogo";
var UTTERANCE_ID    = "ntUtterance";

/* ======= *
 * GLOBALS *
 * ======= */

var $               = NabuTalk.$;
var nabutalk        = null;
var nabutalkName    = "l'assistante virtuelle";
var avatar          = null;
var avatarListener  = NabuTalk.Avatar.EmptyListener();
var queryParameters = null;

/* ========= *
 * UTTERANCE *
 * ========= */

function getUtterance()
{
	queryUtterance(false);
	return $(UTTERANCE_ID).value;
}

function emptyUtterance()
{
	alert("Veuillez d'abord saisir un message !");
	queryUtterance(true);
	return false;
}

function preprocessUtterance()
{
	avatar.Update({animation: "search"}, true);
	queryUtterance(false);
	resetUtterance();
	return queryParameters;
}

function resetUtterance()
{
	$(UTTERANCE_ID).value = "";
}

function queryUtterance(query)
{
	var utterance = $(UTTERANCE_ID);

	if ( query ) {
		if ( utterance.value == "" ) {
			this.queried = true;
			blinkUtterance(true);
			utterance.style.textAlign = "center";
			utterance.style.fontStyle = "italic";
			utterance.value = "Écrivez ici pour dialoguer avec\n{}".replace("{}", nabutalkName);
			utterance.onkeypress = function() { queryUtterance(false); return true; };
			utterance.onclick = function() { queryUtterance(false); };
			utterance.onblur = null;
		}
	} else {
		if ( this.queried ) {
			this.queried = false;
			blinkUtterance(false);
			utterance.style.textAlign = "left";
			utterance.style.fontStyle = "normal";
			utterance.value = "";
			utterance.onkeypress = null;
			utterance.onclick = null;
			utterance.onblur = function() { queryUtterance(true); };
		}
	}
}

function blinkUtterance(mode)
{
	var blinkColors = ["rgb(138,197,60)", "rgb(0,185,242)"];
	var style = $(UTTERANCE_ID).style;

	if ( arguments.length == 1 ) {
		if ( mode ) {
			this.index = 0;
			style.color = blinkColors[this.index];
			this.timer = setInterval("blinkUtterance()", 500);
		} else {
			style.color = "black";
			clearInterval(this.timer);
		}
	} else {
		this.index++;
		if ( this.index >= blinkColors.length ) this.index = 0;
		style.color = blinkColors[this.index];
	}
}

function keypress(event)
{
	switch ( event.keyCode ) {
		case 13 : nabutalk.Interpret(); return false;
		case 27 : resetUtterance();     return false;
	}
	return true;
}

function notReady()
{
	alert("Veuillez patienter !");
}

/* ====== *
 * ANSWER *
 * ====== */

function waitAnswer()
{
	displayLogo(false);
	$(ANSWER_ID).innerHTML = '<div id="ntWait">Veuillez patienter...</div>';
}

function noAnswer(answer)
{
	setAnswer("Je n'arrive pas à traiter votre demande !");
	// if ( answer ) alert(answer);
}

function processAnswer(answer)
{
	return answer;
}

function setAnswer(answer, channels, mode)
{
	// NabuTalk.Info("setAnswer: "+answer);
	answer = answer
		.replace(/([^ \xA0])([:?!])/g, "$1 $2") // do *NOT* include ";"
		.replace(/(https?|mailto|javascript) :/g, "$1:")
		.replace(/(\.php) \?/g, "$1?")
		.replace(/ +/g, " ") // /[ \xA0]+/g may be used as an alternative
		.replace(/ ([^a-zA-Z0-9áÁàÀâÂéÉèÈêÊëËíÍîÎïÏóÓôÔúÚùÙçÇ<&])/g, "\xA0$1")
		.replace(/\xA0/g, "&nbsp;")
		.replace(/(([^.!]|\.[a-z0-9]|\.InterpretLink\()*.)$/, '<div id="ntQuestion">$1</div>'); // no "(?:...)" for IE 5.x
	// NabuTalk.Info("setAnswer: "+answer);

	if ( channels ) {
		var properties = channels["properties"];
		var name = properties["name"];
		var sex = properties["sex"];
		var hair = properties["hair_colour"];
		if ( !hair ) hair = properties["hair_color"];

		var avatarName = sex == "male" ? "robert" : "cecile";
		if ( name ) nabutalkName = name;

		var animation = channels["avatar"];
		if ( animation == "welcome" && answer.length < 512 ) displayLogo(true);
		// if ( mode == NabuTalk.Manager.MODE_REFRESH ) animation = "idle";
		if ( !animation ) animation = "idle";

		avatar.Update({name: avatarName, sex: sex, hair: hair, animation: animation}, false);
		if ( mode == NabuTalk.Manager.MODE_FIRST ) avatar.SetLoadedCallback(cacheAnimations);
	}

	$(ANSWER_ID).innerHTML = answer;
	queryUtterance(true);
}

function processURL(url, element)
{
}

function pushEnabled()
{
	return PUSH_ENABLED;
}

function pushPage(url, channels)
{
	var parts = url.split(":");
	url = "http://www.cad22.com/implantation_locaux/locaux_disponibles_fiche_bien.asp?sortfield=Reference&sortorder=asc&ty=" + parts[0] + "&pagebien=" + parts[1];
	// alert("push: "+url);
	document.location = url;
}

function validURL(url)
{
	return url.search(/^https?:/) >= 0;
}

function displayLogo(on)
{
	$(LOGO_ID).style.display = on ? "block" : "none";
}

/* ============= *
 * MISCELLANEOUS *
 * ============= */

function cookiesDisabled(isInterpret)
{
	var message = "Vous devez configurer votre navigateur pour qu'il accepte\nles cookies afin de pouvoir dialoguer avec " + nabutalkName + " !";
	setAnswer(message);
	if ( isInterpret ) alert(message);
}

function cacheAnimations()
{
	avatar.SetLoadedCallback(null);
	avatar.Cache(
		{name: "cecile", hair: "blond", animation: "search"},
		{name: "cecile", hair: "dark",  animation: "search"});
}

/* ============== *
 * INITIALISATION *
 * ============== */

function startNabuTalk()
{
	NabuTalk.Manager.CreateInstance("nabutalk", NABUTALK_URL, NABUTALK_COOKIE, REFRESH_QUERY, {
		"cookies-disabled"     : cookiesDisabled,
		"empty-utterance"      : emptyUtterance,
		"get-utterance"        : getUtterance,
		"no-answer"            : noAnswer,
		"not-ready"            : notReady,
		"preprocess-utterance" : preprocessUtterance,
		"process-answer"       : processAnswer,
		"process-url"          : processURL,
		"push-enabled"         : pushEnabled,
		"push-page"            : pushPage,
		"set-answer"           : setAnswer,
		"wait-answer"          : waitAnswer});

	avatar = new NabuTalk.Avatar(AVATAR_FLASH_ID, avatarListener, AVATAR_URL_PATTERN, "idle");
	avatar.Set(AVATAR_INITIAL_PARAMETERS);

	resetUtterance();
	nabutalk.Refresh();
	$(FORM_ID).elements[UTTERANCE_ID].focus();
}

