// *****************************************************************************
// ** IMMO.JS
// *****************************************************************************
// ** product: Agent Immobilier
// **    file: immo.js
// ** authors: Sylvain Camus, Vincent Louis, Thierry Martinez, Franck Panaget
// ** version:
// **    date: 08/12/2009
// **  status: standard
// *****************************************************************************
// ** 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) 2008-2009, Dialonics - All rights reserved
// ** www.dialonics.com - license@dialonics.com
// *****************************************************************************

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

var NABUTALK_URL    = "/dialonics/nabutalk.php";
var NABUTALK_COOKIE = "immo"; // should be the same as in "nabutalk.php"
var REFRESH_QUERY   = "event=welcome&last=yes";

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

var VIEW_COOKIE = "view";

var ANSWER_ID        = "avi_answer";
var AVATAR_ID        = "avi_avatarVideoFlash";
var NABUTALK_VIEW_ID = "avi_nabutalkView";
var SEARCH_VIEW_ID   = "avi_searchView";
var UTTERANCE_ID     = "avi_utterance";
var VIEW_ID          = "avi_view";

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

var $              = NabuTalk.$;

var nabutalk       = null;
var avatar         = null;
var avatarListener = NabuTalk.Avatar.EmptyListener();

var bienCourant    = "";
var stopDiapo      = false;

/* ========= *
 * 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 "current-estate="+bienCourant;
}

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

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

	if ( query ) {
		if ( utterance.value == "" ) {
			stopDiapo = false;
			this.queried = true;
			blinkUtterance(true);
			utterance.style.textAlign = "center";
			utterance.style.fontStyle = "italic";
			utterance.value = "Écrivez ici\npour dialoguer avec\nl'" + (avatar.Get("sex") == "male" ? "assistant virtuel" : "assistante virtuelle");
			utterance.onkeypress = function() { queryUtterance(false); return true; };
			utterance.onclick = function() { queryUtterance(false); };
			utterance.onblur = null;
		}
	} else {
		if ( this.queried ) {
			stopDiapo = true;
			this.queried = false;
			blinkUtterance(false);
			utterance.value = "";
			utterance.style.textAlign = "left";
			utterance.style.fontStyle = "normal";
			utterance.onkeypress = null;
			utterance.onclick = null;
			utterance.onblur = function() { queryUtterance(true); };
		}
	}
}

function blinkUtterance(mode)
{
	var blinkColors = ["rgb(255,150,50)", "rgb(20,100,255)"];
	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="patienter">Veuillez patienter...</div>';
}

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

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(/[ \xA0]+/g, " ")
		.replace(/ ([^a-zA-Z0-9àÀâÂéÉèÈêÊëËîÎïÏôÔùÙçÇ<&])/g, "\xA0$1")
		.replace(/\xA0/g, "&nbsp;")
		.replace(/((?:[^.!]|\.[a-z]|\.InterpretLink\()*.)(<\/channel>)/, '<div id="relance">$1</div>$2');
	// NabuTalk.Info("setAnswer: "+answer);
	$(ANSWER_ID).innerHTML = answer;
	queryUtterance(true);

	if ( channels ) {
		var properties = channels["properties"];
		var sex = properties["sex"]
		var name = sex == "male" ? "robert" : "cecile";
		var hair = properties["hair_color"];
		var animation = channels["avatar"];

		if ( !animation ) animation = "answer";
		if ( animation == "welcome" && answer.length < 512 ) displayLogo(true);
		// if ( mode == NabuTalk.Manager.MODE_REFRESH ) animation = "idle";
		avatar.Update({name: name, sex: sex, hair: hair, animation: animation}, false);
		if ( mode == NabuTalk.Manager.MODE_FIRST ) avatar.SetLoadedCallback(cacheAnimations);
	}
}

function processURL(url, element)
{
	// NabuTalk.Info("url: "+url);
}

function pushPage(url, channels)
{
	// NabuTalk.Info("push: "+url);
	document.location = url;
}

function displayLogo(on)
{
	var style = "transparent";
	if ( on ) style += " url(/dialonics/img/dialonics.png) no-repeat 260px 125px";
	$(ANSWER_ID).style.background = style;
}

/* ==== *
 * VIEW *
 * ==== */

function selectView(switchView)
{
	var showNabuTalk = NabuTalk.GetCookie(VIEW_COOKIE) != "search";
	var view;

	if ( switchView ) {
		showNabuTalk = !showNabuTalk;
		view = showNabuTalk ? "nabutalk" : "search";
		nabutalk.Log("SWITCH VIEW | "+view);
		NabuTalk.SetCookie(VIEW_COOKIE, view);
	}

	if ( showNabuTalk ) {
		$(NABUTALK_VIEW_ID).style.display = "block";
		$(SEARCH_VIEW_ID).style.display = "none";
		document.forms["formRecherche"].elements["utterance"].focus();
	} else {
		$(NABUTALK_VIEW_ID).style.display = "none";
		$(SEARCH_VIEW_ID).style.display = "block";
	}
}

function switchView()
{
	selectView(true);
}

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

function cookiesDisabled(isInterpret)
{
	var message = "Vous devez configurer votre navigateur pour qu'il accepte\nles cookies afin de pouvoir dialoguer avec l'assistant virtuel !";
	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()
{
	if ( $(NABUTALK_VIEW_ID) === null ) {
		$(SEARCH_VIEW_ID).style.display = "block";
		return;
	}

	selectView(false);
	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-page"            : pushPage,
		"set-answer"           : setAnswer,
		"wait-answer"          : waitAnswer});
	avatar = new NabuTalk.Avatar(AVATAR_ID, avatarListener, AVATAR_URL_PATTERN, "idle");
	avatar.Set(AVATAR_INITIAL_PARAMETERS);
	resetUtterance();
	nabutalk.Refresh();
}

window.onload = startNabuTalk;
