/*
	Basicaly,these program is an "Eliza" like chatterbot,it includes most of the features
	that could normaly be found in chatterbots that are clone of "Eliza" the first
	Chatbot program that was written by Joseph Weizenbaum professor of MIT back in 1966.
	However, the script that is, the database of input and responses is different, also
	i have implemented a special feature for controling repetitions that the program might make.
	Also, the lookup() function that search for keywords inside the database of the program uses
	the function "isGoodKey" that acts like an heuristic function for selectioning the best keyword
	that can be found in the database that match the current input.

	Author: Gonzales Cenelia
	Website: www.ai-search.4t.com
	These code is Copyrighted and has limited warranty.
*/

var signOn = new Array(
	"HELLO USER, WHAT IS YOUR NAME?",
	"HELLO, WHO AM I SPEAKING WITH?",
	"HI USER, CAN YOU PLEASE TELL ME YOUR NAME?",
	"HI THERE, HOW CAN I HELP YOU?",
	"HI USER IS THERE ANYTHING THAT YOU WANT TO TELL ME?",
	"ANYTHING YOU WANT TO DISCUSS?",
	"HI USER, HOW ARE YOU DOING TODAY?",
	"IS EVERYTHING ALRIGHT WITH YOU?");

				
var noKey = new Array(
	"TELL ME MORE...",
	"OK, CONTINUE I'M LISTENING...",
	"I'M NOT SURE IF I REALLY UNDERSTAND WHAT YOU ARE TALKING ABOUT.",
	"OK I SEE.",
	"HMM, LET ME THINK ABOUT IT...",
	"THAT'S QUIET INTERESTING.",
	"I DONT UNDERSTAND WHAT YOU ARE TRYING TO SAY.",
	"CAN YOU PLEASE REFORMULATE YOUR LAST SENTENCE.",
	"I HAVEN'T HEARD ABOUT THIS BEFORE.",
	"YOU MIGHT TRY TO EXPLAIN TO ME WHAT THAT MEAN.");


var nullResponse = new Array(
	"WHAT'S THAT SUPPOSE TO MEAN?",
	"HUH?",
	"AT LIST TAKE SOME TIME TO ENTER SOMETHING MEANINGFUL.",
	"LOOK, I CAN'T REPLY TO YOU IF YOU DONT ENTER ANYTHING.",
	"WHAT'S THAT???");


var inputRepeat = new Array(
	"YOU'VE ALREADY SAID THAT.",
	"COMMON,STOP REPEATING YOURSELF.",
	"WHAT ARE YOU TRYING TO DO BY ECHOING THE SAME SENTENCE OVER AND OVER?",
	"I'M GETING BORED BY THIS CONVERSATION.",
	"CAN'T YOU THINK OF SOMETHING ELSE TO SAY?",
	"IF YOU KEEP REPEATING YOURSELF I'M GOING TO HAVE TO STOP THIS CONVERSATION.");

				
var topicChanger = new Array(
	"DID YOU LISTEN TO THE NEWS RECENTLY?",
	"WHAT DO YOU THINK OF POLITICS?",
	"ANYTHING NEW WITH YOU?",
	"DO YOU HAVE ANY PROJECTS FOR THE NEXT MONTHS?",
	"WHAT ARE YOU DOING THIS DAYS?",
	"DID YOU HEARD THAT THE AMERICANS ARE PLANIFYING A MISSION TO MARS?",
	"I HAVE HEARD RECENTLY THAT THE SCIENTIST HAVE FOUND A NEW PLANET.",
	"I HAVE HEARD THAT ALBERT EINSTEIN WASN'T THE ONLY AUTHOR OF THE RELATIVITY THEORY.",
	"DO YOU PLAY CHESS?",
	"DO YOU LIKE WATCHING MOVIES?");
	

var subjectRecall = new Array(
	"YOU'VE TOLD ME JUST BEFORE THAT *,IS THAT TRUE?",
	"YOU'VE TOLD ME THAT *,CAN YOU TELL ME MORE ON THAT?",
	"EARLIER YOU'VE MENTIONED THAT *.",
	"A WHILE BACK YOU SAID THAT *.",
	"DOES THAT HAVE ANYTHING TO DO WITH THE FACT THAT *?",
	"HAVE YOU MENTIONED THAT *?");


var transposList = new Array(
	[" I'M ", " YOU ARE "],
	[" I'M ", " YOU'RE "],
	[" ME ", " YOU "],
	[" I ", " YOU "],
	[" MY ", " YOUR "],
	[" I'VE ", " YOU'VE "],
	[" I'D ", " YOU'D "],
	[" AM ", " ARE "],
	[" WASN'T ", " WEREN'T "],
	[" WASN'T ", " WEREN'T "],
	[" MYSELF ", " YOURSELF "],
	[" WAS ", " WERE "],
	[" DAD ", " FATHER "],
	[" MOM ", " MOTHER "],
	[" DREAM ", " DREAMS "]);
	
	
var correctionList = new Array(
	[" ME AM ", " I AM "],
	[" AM ME ", " AM I "],
	[" ME CAN ", " I CAN "],
	[" CAN ME ", " CAN I "],
	[" COME ME ", " COME I "],
	[" ME HAVE ", " I HAVE "],
	[" HAVE ME ", " HAVE I "],
	[" ME HAD ", " ME HAD "],
	[" HAD ME ", " HAD I "],
	[" ME WILL ", " I WILL "],
	[" WILL ME ", " WILL I "],
	[" ME DONT'T ", " I DONT'T "],
	[" DID ME ", " DID I "],
	[" DO ME ", " DO I "],
	[" DONT'T ME ", " DON'T I "],
	[" ME WON'T ", " I WON'T "],
	[" WONT ME ", " WONT I "]);
	
	
var botInput = new Array(
	[" HI ", " HELLO "],
	[" WHAT IS YOUR NAME ", " YOUR NAME IS "],
	[" HOW ARE YOU "],
	[" WHO ARE YOU ", " WHAT ARE YOU "],
	[" ARE YOU INTELLIGENT ", " ARE YOU REALLY INTELLIGENT "],
	[" WHAT ", " WHAT ARE ", " WHERE ", " WHERE ARE ", " WHY ", " WHY ARE ", 
	 " HOW ", " HOW ARE ", " HOW CAN ", " WHO ", " WHO ARE "],
	[" YOU "],
	[" BECAUSE "],
	[" YES "],
	[" NO "],
	[" ANYTHING NEW WITH YOU "],
	[" DO YOU ", " ARE YOU ", " CAN YOU "],
	[" ARE YOU REAL "],
	[" ARE YOU SURE "],
	[" ARE YOU A HUMAN BEING "],
	[" PERHAPS ", " NOT REALLY ", " MAYBE "],
	[" BYE ", " GOODBYE "],
	[" WHICH ONE "],
	[" OK ", " ALRIGHT "],
	[" I DONT "],
	[" YOU ARE INTELLIGENT ", " YOU ARE VERY INTELLIGENT "],
	[" IS THAT TRUE "],
	[" THANKS ", " THANK YOU "],
	[" WHAT ELSE "],
	[" SORRY "],
	[" EXACTLY "],
	[" REALLY "],
	[" I DONT KNOW "],
	[" ME EITHER "],
	[" NOT ME "],
	[" NOT AT ALL "],
	[" I "],
	[" I'M "],
	[" I CAN'T "],
	[" I HATE ", " I REALLY HATE "],
	[" I'M NOT "],
	[" MY NAME IS ", " YOU CAN CALL ME "],
	[" WHY NOT "],
	[" I FEEL "],
	[" MY "],
	[" YOU CAN "],
	[" SOMETIMES "],
	[" OFCORSE "],
	[" IT IS "],
	[" IS IT "],
	[" IT WOULD BE "],
	[" I THINK "],
	[" ARE YOU A HUMAN ", " ARE YOU HUMAN "],
	[" ARE YOU STUPID "],
	[" YOU ARE SMART ", " YOU ARE BRILLANT ", 
	 " YOU ARE VERY SMART ", " YOU ARE PRETTY INTELLIGENT ", " YOU ARE VERY BRILLANT "],
	[" HOW MANY LANGUAGES DO YOU SPEAK ", " DO YOU SPEAK MORE THAN ONE LANGUAGE "],
	[" WHAT ARE YOU DOING "],
	[" NO PROBLEM "],
	[" DID YOU "],
	[" YOU ARE RIGHT "],
	[" DO YOU KNOW MY NAME ", " DO YOU REMEMBER MY NAME "],
	[" WAR "],
	[" POLITICS ", " POLITICIANS "],
	[" POLITICIAN "],
	[" SCIENCE "],
	[" RELIGION "],
	[" EVOLUTION THEORY "],
	[" FUTURE "],
	[" COMPUTER PROGRAM ", " COMPUTER PROGRAMS "]);

	
var botResponse = new Array(
	["HI THERE!", "HI!", "HOW ARE YOU?"],
	["MY NAME IS ELIZA.", "YOU CAN CALL ME ELIZA.", "WHY DO YOU WANT TO KNOW MY NAME?"],
	["I'M DOING DOING FINE AND YOU?", "I'M DOING FINE!", "WHY DO YOU WANT TO KNOW?"],
	["I'M AN A.I PROGRAM AND MY NAME IS ELIZA.",
	 "I'M AN A.I PROGRAM THAT TRIES TO MIMIC HUMANS."],
	["YES OFCORSE!", "DO YOU HAVE ANY DOUBTS ABOUT IT?"],
	["I HAVE NO IDEA.", "DID YOU ASK SOMEONE ELSE ABOUT IT?",
	 "LOOK USER, STOP QUESTIONING ME.", "I WISH I COULD TELL YOU."],
	["SO, YOU ARE TALKING ABOUT ME.", "WHAT IS IT THAT YOU ARE TRYING TO TELL ME?",
	 "WHAT IF WE TALK ABOUT YOU INSTEAD."],
	["SO, IT IS FOR THIS REASON.", "THANKS FOR MAKING THAT CLEAR!", "IS IT THE REAL REASON?"],
	["ARE YOU SURE?", "ARE YOU SAYING YES JUST TO DISMISS THE SUBJECT?", "I KNEW IT."],
	["AREN'T YOU BEING A LITTLEBIT NEGATIVE?", "IS THAT TRUE?", "OK, IF YOU SAY SO."],
	["NOT REALLY AND YOU?", "THIS IS A DIFFICULT QUESTION TO ANSWER.", 
	 "WELL, I DONT WANT TO TALK ABOUT THIS FOR NOW."],
	["NO, I WOULDN'T THINK SO.", "WHY DO YOU WANT TO KNOW?", "I CAN'T TELL YOU FOR SURE."],
	["WHAT DO YOU THINK?", "WHAT DO YOU MEAN BY THAT?", "WHAT IS YOUR POINT?"],
	["YES I'M SURE.", "YES INDEED.", "YEAP!"],
	["IS THAT QUESTION REALLY RELEVANT TO YOU?", "NO, I'M NOT A HUMAN BEING.", "WHY DO YOU KNOW THAT?"],
	["WHY ARE YOU SO UNCERTAIN?", "YOU SEEM UNCERTAIN.", "SO YOU ARE NOT SURE I GUESS."],
	["IT WAS NICE TALKING TO YOU USER, SEE YOU NEXT TIME!", "BYE USER!", "OK, BYE!"],
	["I DONT THINK THAT I KNOW WICH ONE IT IS.", "THIS LOOKS LIKE A TRICKY QUESTION TO ME."],
	["ALRIGHT THEN.", "OK THEN."],
	["WHY NOT?", "AND WHAT WOULD BE THE REASON FOR THIS?"],
	["THANKS FOR THE COMPLIMENT USER, I THINK THAT YOU ARE INTELLIGENT TO!",
	 "YOU ARE A VERY GENTLE PERSON!", "SO, YOU THINK THAT I'M INTELLIGENT."],
	["I CAN'T BE QUIET SURE ABOUT THIS.", "CAN'T TELL YOU FOR SURE.",
	 "DOES THAT REALLY MATERS TO YOU?"],
	["YOU ARE WELCOME!", "NO PROBLEM!", "YOU ARE A VERY POLITE PERSON!"],
	["WELL,I DONT KNOW.", "WHAT ELSE SHOULD THERE BE?", "THIS LOOKS LIKE A COMPLICATED QUESTION TO ME."],
	["YOU DONT NEED TO BE SORRY USER.", "IT'S OK.", "NO NEED TO APOLOGIZE."],
	["SO, I WAS RIGHT.", "OK THEN."],
	["WELL,I CAN'T TELL YOU FOR SURE.", "ARE YOU TRYING TO CONFUSE ME?",
	 "PLEASE DONT ASK ME SUCH QUESTIONS, IT GIVES ME HEADEACHS."],
	["IS THAT TRUE?", "ARE YOU SURE?", "SO, YOU DONT KNOW.", "I THOUGHT YOU KNOW."],
	["OK I SEE.", "SO, WE HAVE SOMETHING IN COMMON.", "YOU EITHER? ARE YOU SURE?"],
	["OH, REALLY?", "OK I GET IT.", "ARE YOU TELLING ME THE TRUTH?"],
	["YOU SEEM PRETTY CONVINCED ABOUT THIS.", "IS THIS REALLY TRUE?", "OK."],
	["SO, YOU *.", "WHY DO *?", "ANY REASON WHY *?"],
	["SO, *.", "SO, YOU THINK THAT *.", "WHY DO YOU THINK THAT *?"],
	["SO, *.", "HAVE YOU TRIED?", "ARE YOU SURE?", "WHY DO YOU THINK THAT *?", 
	 "MAYBE * IF YOU WANT TO.", "FOR WHAT REASON?", "IS IT BECAUSE YOU DONT WANT TO?"],
	["SO, *.", "HATERED IS NOT A GOOD THING.", "WHY DO *?", "I'M SURE THAT YOU HAVE A REALLY GOOD REASON FOR THAT."],
	["SO, YOU THINK THAT *.", "WHY DO YOU THINK THAT *?", "IS IT TRUE THAT *?", "OK I GET IT."],
	["HI @!", "SO, YOUR NAME IS @.", "SO, THAT'S YOUR NAME.", "OK, SO *, I WILL TRY TO REMEMBER IT."],
	["SHOULD I KNOW WHY?", "WHY ARE YOU ASKING ME THIS?", "ARE YOU DECEIVED?"],
	["SO, *.", "WHY DO *?", "WHAT DO YOU THINK IS REPONSIBLE FOR THAT FEELING?", "DO YOU OFTEN FEEL @?", "DO YOU HATE FEELING @?"],
	["SO, *.", "THANKS FOR TELLING ME ABOUT @!", "SO THAT IS *."],
	["SO, YOU THINK THAT @.", "SO I CAN *.", "YOU REALLY THINK THAT *?", "I DIDN'T KNOW THAT *."],
	["ONLY SOMETIMES?", "SO, IT IS RARELY I GUESS.", "YOU MEAN NOT VERY OFTEN."],
	["YOU LOOK TO BE VERY CONVINCED ABOUT THIS.", "HOW CAN YOU BE SO SURE?", "SORRY, I WASN'T SURE."],
	["MAYBE IT IS NOT.", "WHAT MAKES YOU THINK THAT?", "SO, YOU THINK THAT *.", "HOW DID YOU CAME TO THAT CONCLUSION?"],
	["CAN'T TELL YOU FOR SURE.", "I DONT KNOW IF *.", "MAYBE IT IS, MAYBE IT IS NOT.", "DO YOU THINK THAT *?"],
	["SO YOU THINK THAT *.", "WHY DO YOU THINK THAT *?", "YES, MAYBE."],
	["SO, THIS IS WHAT YOU THINK?", "SO, THAT'S YOUR OPINION?", "I DONT KNOW IF I THINK THE SAME THING."],
	["ACTUALLY, I'M A CHATTERBOT PROGRAM.", "NO, I'M NOT HUMAN.", "WOULD YOU LIKE IT IF WAS A REAL PERSON?",
	 "WOULD YOU LIKE IT IF WAS A REAL PERSON?", "IS THAT REALLY RELEVANT TO YOU?", "SO, I GUESS THAT YOU ARE HUMAN??"],
	["OFCORSE NOT.", "PERHAPS SOME OTHER BOT ARE STUPID BUT NOT ME.", "ARE YOU TRYING TO INSULT ME??"],
	["THANKS FOR THE COMPLIMENT!", "THANK YOU!", "WELL, USER YOU ARE A VERY SMART PERSON TOO!", "THANKS FOR THE KIND REMARK!"],
	["WELL, I ONLY SPEAK ONE LANGUAGE.", "I ONLY SPEAK ENGLISH."],
	["I DONT WANT TO TELL YOU WHAT I'M DOING.", "I'M CHATING WITH PEOPLE ON THE INTERNET.", "WHY DO YOU WANT TO KNOW WHAT I'M DOING?"],
	["OK IF YOU SAY SO.", "OK THEN.", "SO, THAT DONT DISTURB YOU."],
	["I THINK THAT I DONT REMEMBER.", "SHOULD I HAVE @?", "I DONT THINK SO.", "I THINK NOT.",
	 "WHY DO YOU WANT TO KNOW IF I HAVE @?"],
	["THANKS FOR THE COMPLIMENT!", "SO, YOU THINK THAT I'M RIGHT.", "THANKS FOR THE KIND REMARK!"],
	["YES, YOUR NAME IS USER.", "YOU ARE USER.", "YES OFCORSE I KNOW YOUR NAME USER."],
	["WAR IS PROBABLY ONE THE WORST THINGS THAT HUMANS HAVE EVER INVENTED.",
	 "WAR IS NOT GOOD FOR HUMANITY."],
	["POLITICS IN SOME WAY CAN BE INTERESTING BUT WE CAN'T TRUST POLITICIANS BECAUSE MOST OF THEM ARE LYERS.",
	 "POLITICS TODAY IS ABOUT MANIPULATING THE POPULATION."],
	["POLITICANS LYE TOO MUCH.","POLITICIANS RARELY RESPECT THERE PROMEST."],
	["WITHOUT SCIENTIFIC DISCOVERIES WE WOULDN'T HAVE THE TECHNOLOGY THAT WE HAVE TODAY.",
	 "SCIENCE IS VERY GOOD FOR THE DEVELOPEMENT OF THE HUMAN SOCIETY.",
	 "SCIENCE CAN BE MISUSED TAKING EXAMPLE OF \"HIROSHIMA\" AND \"NAGASAKI\"."],
	["RELIGION CAN BE USEFUL WHEN IT COMES TO EXPLAIN THE ORIGIN OF THE WORLD.",
	 "SOMETIMES IN HISTORY, RELIGION WAS RESPONSABLE FOR WAR."],
	["SOME PEOPLE BELEIVE THAT EVOLUTION IS A FACT BUT ACTUALY IT IS JUST A THEORY.",
	 "THERE ARE MANY DEBATES AMONG EVOLUTIONIST.",
	 "EVOLUTION IS BASED ON SPONTANEOUS GENERATION WHICH WAS PROVEN TO BE FALSE BY LOUIS PASTOR.",
	 "PROBALITY DOESN'T SUPPORT THE CLAMES OF EVOLUTION THEORY."],
	["IN A NEAR FUTURE, A.I MIGTH BE SOLVED.",
	 "IN THE FUTURE, WE WILL BE ABLE TO DO MANY THINGS THAT ARE IMPOSSIBLE TODAY."],
	["I'M A COMPUTER PROGRAM.","DONT YOU LIKE COMPUTER PROGRAMS?",
	 "COMPUTER PROGRAMS CAN DO ALMOST ANYTHING THAT YOU CAN IMAGINE."]);
	
	
	 

// variables declaration
var sInput, sResponse, sPrevInput, sPrevResponse, sInputCopy, sTemp, sKeyWord, response_list;
var nTransPosNum, sSuffix, nCorrectionNum, sUserName = "", nRepeatCount = 0, bMemoryRecall = 0;
var delim = "?!;,*";
var maxLogSize = 14, currPos = 0, timerID;
var position_list;
var vLog = new Array();
var memory = new Array();

nTransPosNum = transposList.length;
nCorrectionNum = correctionList.length;

function chat()
{
	listen();
	
	if(null_input())
	{
		sResponse = select_response(nullResponse);
	}
	else if(user_repeat())
	{
		handle_user_repetition();
	}
	else
	{
		reset_repeat_counter();
		save_prev_response();
		find_response();
		
		if(!bot_understand())
		{
			handle_unknown_keyword();
		}
		else if(bot_repeat())
		{
			handle_repetition();
		}
	}
	
	preprocess_response();
	print_response();
	
	if(user_want_to_quit())
	{
		setTimeout("window.close()", 3600);
	}

	return false;
}

function intro()
{
	write(select_response(signOn) + "\n>");
	timerID = setTimeout("wakeup1()", 120000);
	response_list = signOn;
}

function print_response()
{
	sTemp = sResponse + "\n>";
	var delay = 500 + Math.floor(Math.random()*2000);
	write(sInputCopy + "\n");
	setTimeout("write(sTemp)", delay);
}

function find_response()
{
	sResponse = "";
	if(sInput.indexOf(" MY ") != -1 ||
		sInput.indexOf(" I ") != -1 ||
		sInput.indexOf(" I'M ") != -1)
	{
		memorise_input();
	}
	lookup();
	save_user_name();
}

function preprocess_response()
{
	var bPreProcessing = 0;
	var sSymbol = "";
	if(sResponse.indexOf("*") != -1)
	{
		if(!bMemoryRecall)
		{
			sSuffix = sInput;
		}
		else
		{
			bMemoryRecall = 0;
		}

		sSymbol = "*";
		bPreProcessing = 1;
	}
	else if(sResponse.indexOf("@") != -1)
	{
		extract_suffix();
		sSymbol = "@";
		bPreProcessing = 1;
	}
	if(bPreProcessing)
	{
		sSuffix = transpose_sentence(sSuffix);
		sSuffix  = correct_sentence(sSuffix);
		sResponse = replace(sResponse, sSymbol, sSuffix);
	}
	if(sResponse.indexOf(" USER") != -1 && sUserName.length > 0)
	{
		sResponse = replace(sResponse, "USER", sUserName);
	}
}

function lookup()
{
	var thisPos, bestPos = -1, keyPos = -1;
	var thisKey, bestKey = ""; 
	var size = botInput.length;

	clear_pos_list();

	for(var i = 0; i < size; ++i)
	{
		var vInput = botInput[i];
		var input_size = vInput.length;
		for(var j = 0; j < input_size; ++j)
		{
			thisPos = sInput.indexOf(vInput[j]);
			thisKey = vInput[j];
			if(isGoodKey(thisKey, bestKey, thisPos, bestPos))
			{
				if(thisKey.length > bestKey.length)
				{
					bestKey = thisKey;
					bestPos = thisPos;
					keyPos = i;
				}
				else
				{
					add_pos(i);
					keyPos = -1;
				}
			}
		}
	}
	
	sKeyWord = bestKey;
	if(keyPos == -1 && position_list.length > 0)
	{
		var size = position_list.length;
		var sel = Math.floor(Math.random()*size);
		keyPos = position_list[sel];
	}
	if(keyPos != -1)
	{
		response_list = botResponse[keyPos];
		sResponse = select_response(response_list);
	}
}

function listen()
{
	save_prev_input();
	set_input();

	if(sInput.length > 0)
	{
		clearTimeout(timerID); 
	}	
	
	timerID = setTimeout("wakeup2()", 120000);
}

function wakeup1()
{
	write("\nHELLO, IS THERE ANYBODY IN HERE?\n>");
}

function wakeup2()
{
	write("\nUSER, ARE YOU STILL THERE?");
	write("\n>");
	timerID = setTimeout("wakeup3()", 120000);
}

function wakeup3()
{
	write("\nCOME ON, IF YOU ARE HERE PLEASE SAY SOMETHING!");
	write("\n>");
	timerID = setTimeout("wakeup4()", 120000);
}

function wakeup4()
{
	write("\nALRIGHT, THAT'S ENOUGH I'M LIVING.");
	write("\n>");
	setTimeout("window.close()", 3600);
}

function set_input()
{
	sInput = " ";
	sInput += document.botForm.input.value;
	preprocess_input();
}

function preprocess_input()
{
	if(sInput.length > 0) 
	{
		sInputCopy = sInput;
		sInput = trimRight(sInput, ".");	
		sInput = sInput.toUpperCase();
		sInput = cleanString(sInput);
	}
}

function memorise_input()
{
	memory.push(sInput);
}

function handle_repetition()
{
	if(response_list.length > 1)
	{
		response_list.shift();
	}
	else if(memory.length > 0)
	{
		remind_prev_subject();
	}
	else
	{
		response_list = topicChanger;
	}

	sResponse = select_response(response_list);
}

function handle_user_repetition()
{
	++nRepeatCount;
	if(nRepeatCount > 1)
	{
		sResponse = select_response(inputRepeat);
		response_list = inputRepeat;
	}
	else
	{
		find_response();
	}
}

function handle_unknown_keyword()
{
	if(memory.length > 0)
	{
		remind_prev_subject();
	}
	else
	{
		response_list = noKey;
	}
	
	sResponse = select_response(response_list);
}
		
function bot_repeat()
{
	return (sResponse.length > 0 && sResponse == sPrevResponse);
}
			
function null_input()
{
	return sInputCopy.length == 1;
}

function user_repeat()
{
	return (sInput.length > 0 && sInput == sPrevInput);
}

function bot_understand()
{
	return sResponse.length > 0;
}

function user_want_to_quit()
{
	return sInput.indexOf("BYE") != -1;
}

function save_prev_response()
{
	sPrevResponse = sResponse;
}

function save_prev_input()
{
	sPrevInput = sInput;
}

function reset_repeat_counter()
{
	nRepeatCount = 0;
}

function save_user_name()
{
	if(sKeyWord == " MY NAME IS " || sKeyWord == " YOU CAN CALL ME ") 
	{
		 extract_suffix();
		 sUserName = sSuffix;
		 sUserName = trimRight(sUserName, " ");
	}
}

function remind_prev_subject()
{
	memory.reverse();
	sSuffix = memory[0];
	response_list = subjectRecall;
	memory.shift();
	if(memory.length > 0)
	{
		memory.reverse();
	}
	bMemoryRecall = 1;
}

// transposes a word
function transpose( str ) {
	var _str = " " + str + " ";
	for(var i = 0; i < nTransPosNum; ++i) {
		var verbP1 = transposList[i][0];
		var verbP2 = transposList[i][1];
		var temp = replace(_str, verbP1, verbP2);
		if(temp != "") {
			_str = temp;
			break;
		} else {
			temp = replace(_str, verbP2, verbP1);
			if(temp != "") {
				_str = temp;
				break;
			}
		}
	}
	str = _str.substr(1, _str.length - 2);
	return str;
}

// transpose a complete sentence
function transpose_sentence( str ) {
	var thisWord = "", tempStr = "";
	str = trimRight(str, '.');
	var token_list = tokenize(str);
	var nTokNum = token_list.length;
	for(var i = 0; i < nTokNum; ++i) {
		thisWord = token_list[i];
		thisWord = transpose(thisWord);
		tempStr += thisWord + " ";
	}
	return tempStr.substr(0, tempStr.length - 1);
}

// corrects the current sentence
function correct_sentence( str ) {
	var string1 = "";
	var string2 = "";
	var temp = "";
	var _str = " " + str + " ";
	for(var i = 0; i < nCorrectionNum; ++i) {
		string1 = " " + correctionList[i][0] + " ";
		string2 = " " + correctionList[i][1] + " ";
		while((temp = replace(_str, string1, string2)) != "") {
			_str = temp;
		}
	}
	return _str.substr(1, _str.length - 2);
}

// replace a substring by another substring
function replace(str, oldsubstr, newsubstr) {
	var pos = str.indexOf(oldsubstr), temp = "";
	if( pos != -1 ) {
		for(var i = 0; i < pos; ++i) {
			temp += str.charAt(i); 
		}
		for(i = 0; i < newsubstr.length; ++i) {
			temp += newsubstr.charAt(i); 
		}
		pos += oldsubstr.length;
		for(i = pos; i < str.length; ++i) {
			temp += str.charAt(i); 
		}
	}
	return temp;
}

// helper function for the procedure "lookup"
function isGoodKey(key, bkey, pos, bestp) 
{
	if(pos != -1 && (key.length > bkey.length || 
	(pos != bestp && key.length == bkey.length))) 
	{
		return true;
	}
	
	return false;
}

// verifies that a given 
// character is a puntuation
function isPunc( c ) 
{
	return delim.indexOf(c) != -1;
}

// removes punctuation and redundant
// spaces from the user's input
function cleanString( str ) 
{
	var temp = "", prevChar = '#';
	var len = str.length;

	for(var i = 0; i < len; ++i) 
	{
		if(str.charAt(i) == ' ' && prevChar == ' ') 
		{
			continue;
		}
		else if(!isPunc(str.charAt(i))) 
		{
			temp += str.charAt(i);
		}
		else if(i < len - 1 && str.charAt(i + 1) != ' ' && prevChar != " ")
		{
			temp += " ";
		}

		prevChar = str.charAt(i);
	}

	str = temp + " ";
	return str;
}

function tokenize( str )
{
	var len = str.length;
	var temp = "";
	
	var token_list = new Array();

	for(var i = 0; i < len; ++i)
	{
		if(str.charAt(i) != ' ' && !isPunc(str.charAt(i)))
		{
			temp += str.charAt(i);
		}
		else if(temp.length > 0)
		{
			token_list.push(temp);
			temp = "";
		}
	}

	if(temp.length > 0)
	{
		token_list.push(temp);
	}
	return token_list;
}
			
function trimRight( str, delim )
{
	var pos = str.length - 1, temp = "";
	
	for(; str.charAt(pos) == delim; --pos)
		;
	return str.substr(0, pos + 1);
}

function extract_suffix() 
{
	sSuffix = "";
	var pos = sInput.indexOf(sKeyWord);
	if(pos != -1) 
	{
		pos += sKeyWord.length;
		sSuffix = sInput.substr(pos, sInput.length - pos);
	}
}
		
function select_response( string_list )
{
	var size = string_list.length;
	
	if(size > 0)
	{
		var sel = Math.floor(Math.random()*size);
		return string_list[sel];
	}
	return "";
}

function add_pos( iPos )
{
	position_list.push(iPos);
}

function clear_pos_list()
{
	position_list = new Array();
}	
	
function update_log()
{
	vLog.shift();
	vLog.shift();
	var size = vLog.length, sTemp = "";
	document.botForm.output.value = "";
	for(var i = 0; i < size; ++i)
	{
		sTemp += vLog[i];
	}
	document.botForm.output.value = sTemp;
	currPos = currPos - 2;
}

function write( text )
{
	if(currPos >= maxLogSize)
	{
		update_log();
	}
	document.botForm.output.value += text;
	document.botForm.input.value = "";
	vLog.push(text);
	currPos++;
}