// Synthetix smartAgent V4.17
// This computer source code is Copyright 2001-2008, Synthetix Ltd.

String.prototype.replaces=strReplace;
String.prototype.matches=strMatch;

function imgOn(imgIdx)
{
	for(x=1;x<=imgIdx;x++)
		document["s"+x].src = eval("star_on.src");
}

function imgOff(imgIdx)
{
	for(x=1;x<=imgIdx;x++)
		document["s"+x].src = eval("star_off.src");
}

function strReplace(str,wit)
{
	return this.split(str).join(wit);
}

function strMatch(strM)
{
	return this.indexOf(strM);
}

function trace(val)
{
	if(trace_on==true)
	{
		trace_text+=(val+"<BR>");
		document.getElementById("trace").innerHTML=trace_text;
	}
}

function rating(score)
{
	dataAction("http://www.synthetix.net/submit_rating.php?answer_id="+answer_id+"&rating="+score);
	gotoLabel("link_from_rating");
}

function get_pop_cat(cat)
{
	dataAction("http://www.synthetix.info/smartagent_cat_rss.php?agent_id="+agent_id+"&category="+mastercategory);
}

function set_fav_faq_cat(cat)
{
	poplist="Here are the top questions asked on this topic:<BR><BR>";
	
	fav_array=fav_faq_cat.split("|");
	
	if(fav_array.length>(max_pop_num))
		temp_pop_lgth=max_pop_num
	else
		temp_pop_lgth=fav_array.length;
	
	if(fav_array.length>1)
	{
		for(x=0;x<temp_pop_lgth;x++)
		{
			if(!fav_array[x].match("NOPOP"))
			{
				poplist+="<a href='#' class='faq_option' onClick='clickmode=\"FAQ\";pop_submit(\""+remPunc(fav_array[x])+"\")'>"+fav_array[x]+"</a><BR>";
			}
			else
				temp_pop_lgth++;
		}
	}

	if((faq_visible==true)&&(fav_array.length>1))
	{
		show_faqs(poplist);
	}
}

function set_fav_day_faq()
{
	poplist="Here are the top questions for <b>yesterday</b>:<BR><BR>";
	
	fav_array=fav_faq_yesterday.split("|");
	
	if(fav_array.length>(max_pop_num*2))
		temp_pop_lgth=max_pop_num*2
	else
		temp_pop_lgth=fav_array.length;
	
	if(fav_array.length>1)
	{
		for(x=0;x<temp_pop_lgth;x+=2)
		{
			if(!fav_array[x].match("NOPOP"))
			{
				if(show_qs_categories==true)
					poplist+="<a href='#' class='faq_option' onClick='clickmode=\"FAQ\";pop_submit(\""+remPunc(fav_array[x])+"\")'>"+fav_array[x]+"</a> ["+fav_array[x+1]+"]<BR>"
				else
					poplist+="<a href='#' class='faq_option' onClick='clickmode=\"FAQ\";pop_submit(\""+remPunc(fav_array[x])+"\")'>"+fav_array[x]+"</a><BR>";
			}
			else
				temp_pop_lgth+=2;
		}
	}
	else
		poplist+="No questions were asked yesterday.<BR>";
	poplist+="<BR><img src='images/bullet.gif'>&nbsp;<a href='#' class='faq_option' onClick='set_fav_faq()'>Last 7 days</a>";

	if(faq_visible==true)
	{
		show_faqs(poplist);
	}
}

function set_fav_faq()
{
	poplist="Here are the top questions for <b>the last 7 days</b>:<BR><BR>";
	
	fav_array=fav_faq_lastsevendays.split("|");
	
	if(fav_array.length>(max_pop_num*2))
		temp_pop_lgth=max_pop_num*2
	else
		temp_pop_lgth=fav_array.length;
	
	if(fav_array.length>1)
	{
		for(x=0;x<temp_pop_lgth;x+=2)
		{
			if(!fav_array[x].match("NOPOP"))
			{
				if(show_qs_categories==true)
					poplist+="<a href='#' class='faq_option' onClick='clickmode=\"FAQ\";pop_submit(\""+remPunc(fav_array[x])+"\")'>"+fav_array[x]+"</a> ["+fav_array[x+1]+"]<BR>"
				else
					poplist+="<a href='#' class='faq_option' onClick='clickmode=\"FAQ\";pop_submit(\""+remPunc(fav_array[x])+"\")'>"+fav_array[x]+"</a><BR>";
			}
			else
				temp_pop_lgth+=2;
		}
	}
	else
		poplist+="No questions were asked in the last 7 days.<BR>";
	poplist+="<BR><img src='images/bullet.gif'>&nbsp;<a href='#' class='faq_option' onClick='set_fav_day_faq()'>Yesterday</a>";

	if(faq_visible==true) show_faqs(poplist);
}

function show_popular()
{
	dataAction("http://www.synthetix.info/faqs/"+agent_id+"/fav_faqs.js");
}

function diag_check_faqs(usrInp)
{
	var userA=new Array();
	var matchI=0;
	var patQuMn="";

  log_question=usrInp;
	usrInp=remPunc(usrInp);
	patQu=splitArray(usrInp);
	usrInp=usrInp.toUpperCase();
	usrInp=remSpace(usrInp);
	usrInp=patSub(usrInp,qspelA);
	usrInp=patSub(usrInp,commA);
	patQuMn=simplify(usrInp);
	usrInp=simplify(usrInp);
	userA=splitArray(usrInp);
	result=run_allcat_parse(userA);
	matchI=result[0];
	response=q[matchI][3];
	if(response.charAt(0)=="#")
		matchI=getLabelIndex(response);
	return matchI;
}

function diagnostics()
{
	dcount=0;
	for(x=0;x<q.length;x++)
	{
		if(q[x][4])
		{
			test_result=diag_check_faqs(q[x][4])
			if(test_result!=x)
			{
				if(test_result==0)
				{
					trace("[ERROR]	<font color=red>'"+q[x][4]+"' is adjacent to label <b>"+q[x][1]+"</b> - "+q[x][2]+" but matches to nothing.</font>")
					dcount++;
				}
				else
					{
						if(q[x][3]!="#"+q[test_result][1])
						{
							trace("[OPTIMISE]	'"+q[x][4]+"' is adjacent to label <b>"+q[x][1]+"</b> - "+q[x][2]+" but actually matches to label <b>"+q[test_result][1]+"</b> - "+q[test_result][2]+"");
							dcount++;
						}
					}
			}
		}
	}
	trace("<BR><b>Problems found: </b>"+dcount);
}

function rnd(val)
{
	return Math.round(val*100)/100;
}

function rand(x,y)
{
	return Math.floor(Math.random()*(y-x+1))+x;
}

function text_size(size)
{
	document.getElementById("textbox").style.fontSize=size+'pt';
	document.getElementById("faq_space").style.fontSize=(size-faq_text_smaller_by)+'pt';
}

window.onbeforeunload = function()
{
	age=getElapsedTime(startTime)/60000;
	if(age>60) age=60;
	age=Math.round(age*100)/100;
	send_log(username,"[USER SESSION TERMINATED]","Conversation Duration - ["+age+"] minutes.",9,"close","close","");
}

function record(num)
{
	backA[++backIndex]=num;
	backAanswer[backIndex]="";
}

function go_back()
{
	if(backIndex!=1)
	{
		backIndex--;
		if(backAanswer[backIndex]=="")
		{
			actions(backA[backIndex],true);
			globalOptions=options(backA[backIndex]);
			response=q[backA[backIndex]][3];
			speak(response,backA[backIndex]);
		}
		else
		{
			speak(backAanswer[backIndex],backA[backIndex]);
		}
	}
}

function go_home()
{
	jnyA=new Array();
	goal_index=1;
	goalA=new Array();
	for(x=0;x<=goalNum;x++)
		goalA[x]=false;
	catchall=false;
	run_agent_p3("STARTNEWAGENT");
}

function go_print()
{
	window.open("print.html","print_box","toolbar=yes,location=yes,status=yes,top=100,left=100,width=800,height=600,scrollbars=yes,resizable=yes");
}

function getRemoteData()
{
	recA=new Array();
	fieldA=new Array();
	recA=dataset.split(/\*/);
	q[0]=new Array("t:smartAgent label error","error","[error]","<b>Sorry! We can't carry out that command. Please ask something else!","");
	for(lp=0;lp<recA.length;lp++)
	{
		recA[lp]=recA[lp].replace(/\|\|/g,"|0|");
		qindex=lp+1;
		q[qindex]=new Array();
		q[qindex]=recA[lp].split(/\|/);		
		asA[qindex]=0;
	}
	convertData();
}

function convertData()
{
	qt=new Array();
	tempAnswer=new Array();
	for(a=1;a<=q.length-1;a++)
	{
		if(q[a][4]==undefined) q[a][4]="";
		if(q[a][4]=="0") q[a][4]="";
		
		if(q[a][5]==undefined) q[a][5]="";
		if(q[a][5]=="0") q[a][5]="";
	
		if(q[a][6]==undefined) q[a][6]="";
		if(q[a][6]=="0") q[a][6]="";
		if(q[a][0].match("&pt"))
		{
			tempAnswer=splitArray(q[a][2]);
			jabberwock[a]=tempAnswer;
		}
		else
			{
				if(q[a][2].charAt(0)=="{")
				{
					q[a][2]=q[a][2].replace("{","[");
					q[a][2]=q[a][2].replace("}","]");
					q[a][0]="&kw;"+q[a][0]
				}
				kwArray[a]=splitQueries(q[a][2])
				kwNeg[a]=nA;
			}
			
		if(q[a][2].charAt(0)=="&")  qt[a]="o"; // Option
		if(q[a][0].match(/&pt/,"")) qt[a]="p"; // Pattern
		if(q[a][2].charAt(0)=="[")  qt[a]="q"; // Query
	}
	agentname=getAnswer("agentname");
}

function expression(img)
{
	if(characterOn==true)
	{
		if(img=="neutral")
		{
			imgI=rand(1,neutral_num);
			img="neutral"+imgI;
		}
	
		imgGo=eval(img+".src");
		if((IE)&&(!OPERA))
		{
			saImage.filters.blendTrans.apply();
			document.images.saImage.src=imgGo;
			saImage.filters.blendTrans.play();
		}
		else
			document["saImage"].src=imgGo;
	}
}

function clear_form()
{
	form_buffer=document.agent.input_form.value;
	document.agent.input_form.value="";
	document.agent.input_form.focus();
}

function clear_form_onclick()
{
	if(firstclick==false)
	{
		firstclick=true;
		document.agent.input_form.value="";
		document.agent.input_form.focus();
	}
}

function splitQueries(val)
{
	aA=new Array();
	bA=new Array();
	nA=new Array();
	neg_match=new Array();
	neg_match=val.match(/\(.+\)/);
	if(neg_match)
	{
		val=val.replace(/\(.+\)/,"");
		neg_match[0]=neg_match[0].replace(/\(/,"");
		neg_match[0]=neg_match[0].replace(/\)/,"");
		nA=neg_match[0].split("/");
	}
	aA=val.split("[");
	for(l=1;l<aA.length;l++)
	{
		aA[l]=aA[l].replace(/]/,"");
		bA[l]=aA[l].split("/");
	}
	return bA;
}

function goto_multi_Label(label_val,log_text)
{
	face="neutral";
	label_idx_old=getLabelIndex(label_val);
	label_idx_new=actions(label_idx_old,false);
	while(label_idx_new!=label_idx_old)
	{
		label_idx_old=label_idx_new;
		label_idx_new=actions(label_idx_new,false);
	}
	record(label_idx_new);
	st=q[label_idx_new][3];
	globalOptions=options(label_idx_new);
	speak(st,label_idx_new);

	if(q[label_idx_new][4]!="")
		send_log(username,log_text,st,1,q[label_idx_new][5],q[label_idx_new][6],q[label_idx_new][4])
	else
		send_log(username,log_text,st,1,q[label_idx_new][5],q[label_idx_new][6],"")
}

function gotoLabel(label_val,log_text)
{
	face="neutral";
	label_idx_old=getLabelIndex(label_val);
	label_idx_new=actions(label_idx_old,false);
	while(label_idx_new!=label_idx_old)
	{
		label_idx_old=label_idx_new;
		label_idx_new=actions(label_idx_new,false);
	}
	record(label_idx_new);
	st=q[label_idx_new][3];
	globalOptions=options(label_idx_new);
	speak(st,label_idx_new);

	if(q[label_idx_new][4]!="")
		send_log(username,log_text,st,1,q[label_idx_new][5],q[label_idx_new][6],q[label_idx_new][4])
	else
		send_log(username,log_text,st,1,q[label_idx_new][5],q[label_idx_new][6],"")
}

function getLabel(idx)
{
	return q[idx][1];
}

function getAnswer(label)
{
	labelindex=getLabelIndex(label)
	return q[labelindex][3];
}

function getLabelIndex(label)
{
	lindex=0;
	label=label.replace("#","");
	for(l=1;l<q.length;l++)
		if(q[l][1]==label) lindex=l;
	if(label=="backprev") lindex=secondlastindex;
	return lindex;
}

function send_log(usr,question,ans,correct,mcategory,scategory,faq)
{
	var no_pop="";
	var clicks=0;
	
	if(faq!="") correct=2;
		
	if(clickmode=="results")
	{
		question="[User typed] "+lastanswer+" [then pressed ENTER and chose FAQ] "+question;
		clicks=1;
		clickmode="";
		correct=3;
	}
		
	if((clickmode!="")&&(form_buffer==""))
	{
		question="[Chose "+clickmode+"] "+question;
		clicks=1;
		clickmode="";
	}
	
	if((clickmode=="search result")&&(form_buffer!=""))
	{
		question="[User entered] "+form_buffer+" [but aborted input to choose FAQ] "+question;
		clicks=1;
		clickmode="";
		form_buffer="";
		correct=3;
	}
	
	if(automated_question==true)
	{
		correct=5;
		automated_question=false;
	}
	
	if(designed_question==true)
	{
		correct=6;
		designed_question=false;
	}
	
	if(escalation_question==true)
	{
		correct=4;
		escalation_question=false;
	}
	
	if(unanswered_question==true)
	{
		correct=7;
		unanswered_question=false;
	}

	ans=remove_tags(ans);
	ans=ans.replaces("<BR>"," ");
	ans=ans.replaces("<h>"," ");
	ans=ans.replaces("</h>"," ");
	ans=insert_variables(ans);
	ans=ans.replaces("&pound;","£");
	ans=ans.replaces(" & "," and ");
	ans=remSpace(ans);
	
	if(goaltext!="")
	{
		for(x=0;x<goaltextA.length;x++)
			if(goaltextA[x]==goaltext) goaltext="";
		if(goaltext!="") goaltextA[goaltextA.length++]=goaltext;
	}
	
	if(no_pop_flag==true)
	{
		no_pop_flag=false;
		no_pop="<NOPOP>";
	}
	
	aiddate=new Date();
	answer_id=agent_id+aiddate.getTime()+rand(1,999999);
	
	logval="?agent_id="+agent_id+"&aid="+answer_id+"&username="+usr+"&question="+question+"&answer="+ans+optiontext+"&topic="+mcategory+"&correct="+correct+"&clicks="+clicks+"&sid="+sid+"&type="+agenttype+"&count="+interaction_count+"&cid="+cid+"&faq="+faq+no_pop+"&goal="+goaltext+"&rating=";
	logval=logval.replace(/\#/g,"");

	if((log_mode!=false)&&(question!="")&&(profanity==false)&&(username!="nolog")&&(question!="GETNAME")&&(log_allowed==true))
		dataAction(logurl+logval);

	goaltext="";
	optiontext="";
}

function getCommandArray(comI)
{
	comA=new Array();
	tempA=new Array();
	tempA=q[comI][0].split(";");
	for(l=0;l<tempA.length;l++)
	{
		comA[l]=new Array();
		comA[l]=tempA[l].split(":");
	}
}

function parent_url(urlAdrs)
{
	if(opener && !opener.closed)
	{
		if((log_mode==true)&&(hosted_interface==true))
		{
			if(window.opener.location.href) parentAdrs=window.opener.location.href
		}
		else
			parentAdrs="";
		if(parentAdrs!=urlAdrs)
			window.opener.location.href=urlAdrs;
		getFocus();
	}
	else
		window.open(urlAdrs);
}

function url(urlAdrs)
{
	var newWindow = window.open(urlAdrs, '_blank');
	newWindow.focus();
}

function vr(var_id)
{
	ret_val="";
	for(x=0;x<vrA.length;x++)
	{
		if(vrA[x][0]==var_id)
			ret_val=vrA[x][1];
	}
	return ret_val;
}

function actions(comI,back_pressed)
{
	faq_visible=true;
	log_allowed=true;
	inJny=false;
	getCommandArray(comI);
	for(actL=0;actL<comA.length;actL++)
	{
		arg1 = comA[actL][1];
		arg2 = comA[actL][2];
		arg3 = comA[actL][3];	
		
		switch(comA[actL][0].toUpperCase())
		{
			case "DESIGNATE_AS_QUERY":
				designed_question=true;
			break;
			
			case "DESIGNATE_AS_ESCALATION":
				escalation_question=true;
			break;
			
			case "IF":
				if(arg1.match("=="))
				{
					cdA=arg1.split("==");
					if(cdA[1].match("'"))
					{
						cdA[1]=cdA[1].replaces("'","");
						if(vr(cdA[0])==cdA[1])
							comI=getLabelIndex(arg2);
					}
					else
					{
						if(vr(cdA[0])==vr(cdA[1]))
							comI=getLabelIndex(arg2);
					}
				}
				
				if(arg1.match(">="))
				{
					cdA=arg1.split(">=");
					if(arg2.match(","))
					{
						arg2s=arg2.split(",");
						if(vr(cdA[0])*1 >= cdA[1]*1) // Make integers
							comI=getLabelIndex(arg2s[0]);
						else
							comI=getLabelIndex(arg2s[1]);
					}
					else
					{
						if(vr(cdA[0])>=cdA[0])
							comI=getLabelIndex(arg2);
					}
				}
			break;
			
			case "HIDE_POP":
				pop_allowed=false;
			break;
			
			case "FORMFILL":
				if(hosted_interface==true)
				{
					if(arg3=="passed_value")
					{
						if(opener && !opener.closed) eval("opener.document."+arg1+"."+arg2+".value=passed_value")
					}
					else
					{
						if(opener && !opener.closed) eval("opener.document."+arg1+"."+arg2+".value=answer");
					}
				}
			break;
			
			case "NOPOP":
				no_pop_flag=true;
			break;
			
			case "SURVEY":
				dataAction("http://www.synthetix.net/survey_log.php?agent_id="+agent_id+"&survey_title="+arg1+"&survey_result="+arg2);
			break;
			
			case "DIAGNOSTICS":
				diagnostics();
			break;
			
			case "POPULAR_VIEW":
				show_popular();
			break;

			case "NOFAQ":
				faq_visible=false;
				show_faqs("");
			break;
			
			case "NOLOG":
				log_allowed=false;
			break;
			
			case "START_JNY":
				jnyFnd=false;
				for(x=0;x<jnyA.length;x++)
					if(jnyA[x][0]==arg1) jnyFnd=true;
				if(jnyFnd==false)
					jnyA[jnyA.length]=new Array(arg1,q[comI][1],arg2);
				inJny=true;
			break;
			
			case "RECORD_JNY":
				for(x=0;x<jnyA.length;x++)
					if(jnyA[x][0]==arg1) jnyA[x][1]=q[comI][1];
				inJny=true;
			break;
			
			case "END_JNY":
				jnyT=new Array();
				jnyI=0;
				for(x=0;x<jnyA.length;x++)
					if(jnyA[x][0]!=arg1) jnyT[jnyI++]=jnyA[x];
				jnyA=jnyT;
				inJny=false;
			break;
			
			case "FORM":
					if(arg1=="esc_message")
					{
						document.agent.input_form.value=vr("esc_message")
					}
					else
					{
						document.agent.input_form.value="<"+arg1+">";
						firstclick=false;
					}
			break;
			
			case "CAT":
				setCategory(arg1);
				change_pop_cat=true;
			break;
			
			case "SUBCAT":
				setSubcat(arg1);
			break;
			
			case "U":
				if((arg1=="http")||(arg1=="https")) url(arg1+":"+arg2)
				else
					url(arg1);
			break;
			
			case "EXP":
				face=arg1;
			break;
			
			case "P":
				arg1=arg1.replaces("page_change_url",page_change_url);
				if((arg1=="http")||(arg1=="https"))
					parent_url(arg1+":"+arg2)
				else
					parent_url(arg1);
				page_change=true;
			break;
			
			case "NM":
				username=answer;
			break;
			
			case "METGOAL":
				goalA[arg1]=true;
				if(arg2) goaltext=arg2;
			break;
			
			case "SWEARY":
				profanity=true;
			break;
			
			case "ESCALATE":
				if(username!="nolog") dataAction("http://www.synthetix.net/agentalert.php?id="+agent_id+"&username="+username+"&category="+mastercategory+"&cid="+cid);
			break;
			
			case "ESCALATE_TO_CS":
				if(vr('esc_book')!="")
					dataAction("http://www.synthetix.net/esc_email_v2.php?esc_book="+vr('esc_book')+"&esc_name="+vr('esc_name')+"&esc_email="+vr('esc_email')+"&esc_telno="+vr('esc_telno')+"&esc_message="+vr('esc_message')+"&esc_destination="+vr('esc_dest_email'))
				else
					dataAction("http://www.synthetix.net/esc_email_v2.php?esc_book=Not applicable&esc_name="+vr('esc_name')+"&esc_email="+vr('esc_email')+"&esc_telno="+vr('esc_telno')+"&esc_message="+vr('esc_message')+"&esc_destination="+vr('esc_dest_email'));
				clickmode="";
				if(arg1!="")
					send_log(username,vr('esc_message'),"This query forwarded to Customer Services; "+vr('esc_dest_email'),4,arg1,"","");
				else
					send_log(username,vr('esc_message'),"This query forwarded to Customer Services; "+vr('esc_dest_email'),4,"Long question","","");
			break;
				
			case "VALIDATE":
				answer=answer.replace(",","")
				switch(arg1)
				{
					case "name":
						ptA=new Array("HELLO","HI ","THERE","MY NAME IS","MY NAMES","I AM CALLED","IM CALLED","I AM","IM ","THEY CALL ME");
						nmA=new	Array();
						pt=remPunc(answer);
						pt=remSpace(pt);
						for(loop=0;loop<ptA.length;loop++)
							pt=pt.replaces(ptA[loop],"");
						nmA=splitArray(pt);
						resultA=arg2.split(",");
						if(nmA.length>1)
							comI=getLabelIndex(resultA[1]);
						else
							{
								username=answer;
								saveCookies();
								comI=getLabelIndex(resultA[0]);
							}
					break;
					case "range_loose": // neg numbers don't work
						if(!answer.match(/\D/))
						{
							rangeA=arg2.split(",");
							resultA=arg3.split(",");
							answer=(answer*100)/100;
							if((answer>=rangeA[0])&&(answer<=rangeA[1]))
								comI=getLabelIndex(resultA[0]);
							else
								comI=getLabelIndex(resultA[1]);
						}
						else
							run_agent_p3(answer);
					break;
					case "range_strict":
						rangeA=arg2.split(",");
						resultA=arg3.split(",");
						answer=(answer*100)/100;
						if((answer>=rangeA[0])&&(answer<=rangeA[1]))
							comI=getLabelIndex(resultA[0]);
						else
							comI=getLabelIndex(resultA[1]);
					break;
					case "num":
						resultA=arg2.split(",");
						var numreg=/^\d+$/;
						if(numreg.test(answer)==true)
							comI=getLabelIndex(resultA[0]);
						else
							comI=getLabelIndex(resultA[1]);
					break;
					case "email":
						resultA=arg2.split(",");
						answer=answer.replace(" ","");
						var mailreg=/\S+\@\S+\.\S+/;
						if(mailreg.test(answer)==true)
							comI=getLabelIndex(resultA[0]);
						else
							comI=getLabelIndex(resultA[1]);
					break;
					case "postcode":
						resultA=arg2.split(",");
						answer=answer.replace(" ","");
						answer=answer.toUpperCase();
						var postreg=/([A-PR-UWYZ](([A-HK-Y]{1}[0-9]{1}[ABEHMNPRVWXY0-9]{0,1})|([0-9]{1}[A-HJKSTUW0-9]{0,1}))[0-9]{1}[ABD-HJLNP-UW-Z]{2})|GIR 0AA/;
						if(postreg.test(answer)==true)
							comI=getLabelIndex(resultA[0]);
						else
							comI=getLabelIndex(resultA[1]);
					break;
				}
			break;		
			
			// Variable section.
			// *****************
			
			case "STORE":
				if(back_pressed==false)
				{
					if(arg2)
					{
						switch(arg1)
						{
							case "passed_value":
								var varfound=-1;
								for(x=0;x<vrA.length;x++)
								{
									if(vrA[x][0]==arg1)
										varfound=x;
								}
								if(varfound>-1)
									vrA[varfound][1]=passed_value;
								if(varfound==-1)
									vrA[vrA.length]=new Array(arg2,passed_value)
							break;
							
							default:
								var varfound=-1;
								for(x=0;x<vrA.length;x++)
								{
									if(vrA[x][0]==arg1)
										varfound=x;
								}
								if(varfound>-1)
									vrA[varfound][1]=answer;
									
								if(varfound==-1)
									vrA[vrA.length]=new Array(arg2,arg1);
							break;
							
						}
					}
					else
					{
						switch(arg1)
						{
							case "start_date":
								start_date[0]=document.dateform.day.options.value;
								start_date[1]=document.dateform.month.options.value;
								start_date[2]=document.dateform.year.options.value;
							break;
						
							case "end_date":
								end_date[0]=document.dateform.day.options.value;
								end_date[1]=document.dateform.month.options.value;
								end_date[2]=document.dateform.year.options.value;
							break;

							default:
								var varfound=-1;
								for(x=0;x<vrA.length;x++)
								{
									if(vrA[x][0]==arg1)
										varfound=x;
								}
								if(varfound>-1)
									vrA[varfound][1]=answer;
								if(varfound==-1)
									vrA[vrA.length]=new Array(arg1,answer);
							break;
						}
					}	
				}
			break;
			
			case "EXTERNAL":
				eval(arg1+"();");
			break;
			
		}
	}
	return(comI);
}

function store(vname,vvalue)
{
	var varfound=-1;
	for(x=0;x<vrA.length;x++)
	{
		if(vrA[x][0]==vname)
			varfound=x;
	}
	if(varfound>-1)
		vrA[varfound][1]=vvalue;
	if(varfound==-1)
		vrA[vrA.length]=new Array(vname,vvalue);
}

function options(i)
{
	optiontext="";
	faqlist="";
	dd=false;
	optionlist="<BR><BR><table border=0 cellpadding=0 cellspacing=0>";
	jnysFnd=false;
	if((jnyA.length>0)&&(inJny==false))
	{
		for(x=0;x<jnyA.length;x++)
		{
			optionlist+="<tr><td valign=top><img src='images/back_bullet.gif'>&nbsp;</td><td valign=top><a href='#' class='option' onClick='clickmode=\"option\";click_to(\""+jnyA[x][1]+"\",\"Continue with "+jnyA[x][2]+"\");'>Continue with "+jnyA[x][2]+"</a></td></tr>";
			optiontext+="[LB][JOURNEY] Continue with "+jnyA[x][2];
		}
		jnysFnd=true;
	}
	if(i!=0)
	{
		if((qt[i]!="o")&&(i<q.length-1))
		{
			i++;
			com=command(q[i][2]);
			end=0;
			while((com!="NULL")&&(end==0))
			{
				args=new Array();
				args=q[i][2].split(":");
				if(args[1]) args[1]=args[1].replace("'","&apos;");
				if(args[2]) args[2]=args[2].replace("'","&apos;");
				if(args[3]) args[3]=args[3].replace("'","&apos;");
				
				if(jnysFnd==false)
				{
					switch(com)
					{	
						case "&goal":
							if(dd==true)
							{
								dd=false;
								optionlist+="</select></form></td></tr>";
							}

							if(goal_index>goalNum) goal_index=1;

							x=goal_index;
							goal_found=false;
							while((x<=goalNum)&&(goal_found==false))
							{
								if(goalA[x]==true)
								{
									goal_index++
									x++;
								}
								else
									goal_found=true;
							}
							if(goal_index>goalNum)
							{
								goal_index=1;
								x=goal_index;
								goal_found=false;
								while((x<=goalNum)&&(goal_found==false))
								{
									if(goalA[x]==true)
									{
										goal_index++
										x++;
									}
									else
										goal_found=true;
								}
							}
						
							if(goal_found==true)
							{
								labI=getLabelIndex("goal"+goal_index);
								goal_index++;
								labI++;
								q[labI][2]=q[labI][2].replace("&opt:","");
								optionlist+="<tr><td valign=top><img src='images/bullet.gif'>&nbsp;</td><td><a href='#' class='option' onClick='clickmode=\"goal\";click_to(\""+q[labI][3]+"\",\""+q[labI][2]+"\")'>"+q[labI][2]+"</a></td></tr>";
								optiontext+="[LB][GOAL] "+q[labI][2];
							}
						break;

						case "&opt":
							if(args[1]=="catchall")
							{
								catchall=true;
								catchall_label=q[i][3];
							}
							else
							{
								if(dd==true)
								{
									dd=false;
									optionlist+="</select></form></td></tr>";
								}

								if(args[2])
								{
									arg_desc=args[2].replace("&apos;","'");
									optionlist+="<tr><td valign=center><img src='images/bullet.gif'></td><td width=3></td><td valign=center><a href='#' class='option' onClick='clickmode=\"option\";pass_value_to(\""+args[1]+"<SPLIT>"+q[i][3]+"\",\""+args[2]+"\");'>"+arg_desc+"</a></td></tr>";
									optiontext+="[LB][OPTION] "+arg_desc;
								}
								else
									{
										arg_desc=args[1].replace("&apos;","'");
										optionlist+="<tr><td valign=center><img src='images/bullet.gif'></td><td width=3></td><td valign=center><a href='#' class='option' onClick='clickmode=\"option\";click_to(\""+q[i][3]+"\",\""+args[1]+"\");'>"+arg_desc+"</a></td></tr>";
										optiontext+="[LB][OPTION] "+arg_desc;
									}
							}
						break;
						
						case "&page":
							if(dd==true)
							{
								dd=false;
								optionlist+="</select></form></td></tr>";
							}
							arg_desc=args[3].replaces("&apos;","'");
							optionlist+="<tr><td valign=center><img src='images/bullet.gif'></td><td width=3></td><td valign=center><a href='#' class='option' onClick='page_change_url=\""+args[1]+":"+args[2]+"\";page_change_desc=\""+args[3]+"\";clickmode=\"option\";click_to(\""+q[i][3]+"\",\"Visit "+args[3]+" page\");'>Visit "+arg_desc+" page</a></td></tr>";
							optiontext+="[LB][PARENT URL] "+args[3];
						break;
						
						case "&exit":
							if(dd==true)
							{
								dd=false;
								optionlist+="</select></form>";
							}

							arg_desc=args[1].replace("&apos;","'");
							optionlist+="<tr><td valign=top><img src='images/cancel_bullet.gif'>&nbsp;</td><td valign=top><a href='#' class='option' onClick='clickmode=\"option\";click_to(\""+q[i][3]+"\",\""+args[1]+"\");'>"+arg_desc+"</a></td></tr>";
							optiontext+="[LB][EXIT] "+arg_desc;
						break;
					}
				}
				
				switch(com)
				{	
					case "&back":
						if(dd==true)
						{
							dd=false;
							optionlist+="</select></form></td></tr>";
						}

						optionlist+="<tr><td valign=top><img src='images/back_bullet.gif'>&nbsp;</td><td valign=top><a href='#' class='option' onClick='go_back()'>"+args[1]+"</a></td></tr>";
						optiontext+="[LB][BACK] "+args[1];
					break;

					case "&gopt":
						if(args[1]=="catchall")
						{
							catchall=true;
							catchall_label=q[i][3];
						}
						else
						{
							if(dd==true)
							{
								dd=false;
								optionlist+="</select></form></td></tr>";
							}

							arg_desc=args[2].replace("&apos;","'");
							optionlist+="<tr><td></td><td valign=top><a href='#' class='option' onClick='clickmode=\"option\";click_to(\""+q[i][3]+"\",\""+args[2]+"\");'><img src='images/"+args[1]+"' border=0 alt='"+arg_desc+"'></a></td></tr>";
							optiontext+="[LB][GRAPHICAL OPTION] "+arg_desc;
						}
					break;
					
					case "&date":
						var monthA=new Array("January","February","March","April","May","June","July","August","September","August","September","October","November","December");
						optionlist+="<tr><td valign=top colspan=2><form method='get' name='dateform'>";
						optionlist+="<select class='list' name=day>";
						for(x=1;x<=31;x++)
							optionlist+="<option value='"+x+"'>"+x+"</option>";
						optionlist+="</select>&nbsp;";
						optionlist+="<select class='list' name=month>";
						for(x=0;x<=11;x++)
							optionlist+="<option value='"+monthA[x]+"'>"+monthA[x]+"</option>";
						optionlist+="</select>&nbsp;";
						optionlist+="<select class='list' name=year>";
						for(x=start_year;x<=end_year;x++)
							optionlist+="<option value='"+x+"'>"+x+"</option>";
						optionlist+="</select></form>";
						optionlist+="<tr><td valign=top><img src='images/divider.gif'><img src='images/bullet.gif'></td><td valign=top><a href='#' class='option' onClick='click_to(\""+q[i][3]+"\",\""+args[1]+"\");'>Select this date</a></td></tr>";
						optiontext+="[LB][DATE]";
					break;
					
				case "&mail":
						if(dd==true)
						{
							dd=false;
							optionlist+="</select></form></td></tr>";
						}
						
						if(args[2]) optionlist+="<tr><td valign=top><img src='images/bullet.gif'>&nbsp;</td><td><a href='mailto:"+args[1]+"?subject="+args[2]+"'>E-mail "+args[1]+"</a></td></tr>"
						else
							optionlist+="<tr><td valign=center><img src='images/bullet.gif'></td><td width=3></td><td valign=center><a href='mailto:"+args[1]+"' class='option'>E-mail "+args[1]+"</a></td></tr>";
						optiontext+="[LB][EMAIL] E-mail "+args[1];
					break;
					
					case "&url":
						if(dd==true)
						{
							dd=false;
							optionlist+="</select></form></td></tr>";
						}

						if(args[3])
						{
							optionlist+="<tr><td valign=center><img src='images/bullet.gif'></td><td width=3></td><td valign=center><a target='_blank' href='"+args[1]+":"+args[2]+"' class='option'>"+args[3]+"</a></td></tr>";
							optiontext+="[LB][POPUP URL] "+args[3];
						}
						else
						{
							optionlist+="<tr><td valign=center><img src='images/bullet.gif'></td><td width=3></td><td valign=center><a target='_blank' href='"+args[1]+"' class='option'>"+args[2]+"</a></td></tr>";
							optiontext+="[LB][POPUP URL] "+args[2];
						}
					break;
					
					case "&dd":
						if(args[2])
						{
							if(dd==false)
							{
								optionlist+="<tr><td valign=top colspan=2><form method='get' name='ddform'><select class='list' name=dropdown onChange=\"clickmode='list item';if(this.value!='Select') pass_value_to(this.value,'no_val');\">";
								optionlist+="<option value='Select' id='Select'>-- Select --</option>";
								optionlist+="<option value='"+args[1]+"<SPLIT>"+q[i][3]+"<SPLIT>"+args[2]+"' id='"+q[i][3]+"'>"+args[2]+"</option>";
								dd=true;
							}
							else
								optionlist+="<option value='"+args[1]+"<SPLIT>"+q[i][3]+"<SPLIT>"+args[2]+"' id='"+q[i][3]+"'>"+args[2]+"</option>";
						}
						else
						{
							if(dd==false)
							{
								optionlist+="<tr><td valign=top colspan=2><form method='get' name='ddform'><select class='list' name=dropdown onChange=\"clickmode='list item';if(this.value!='Select') click_to(this.value,'no_val');\">";
								optionlist+="<option value='Select' id='Select'>-- Select --</option>";
								optionlist+="<option value='"+q[i][3]+"<SPLIT>"+args[1]+"' id='"+q[i][3]+"'>"+args[1]+"</option>";
								dd=true;
							}
							else
								optionlist+="<option value='"+q[i][3]+"<SPLIT>"+args[1]+"' id='"+q[i][3]+"'>"+args[1]+"</option>";
						}
					break;
					
					case "&faq":
						switch(args[1])
						{
							case "cat":
								for(x=1;x<q.length;x++)
								{
									if((q[x][4])&&(x!=(i-1))&&(q[x][3].charAt(0)!='#'))
									{
										cat_found=false;
										subcat_found=false;
										getCommandArray(x);
										
										for(actL=0;actL<comA.length;actL++)
										{
											if(args[3])
											{
												if((comA[actL][0].toUpperCase()=="CAT")&&(comA[actL][1].toUpperCase()==args[2].toUpperCase()))
													cat_found=true;
											
												if((comA[actL][0].toUpperCase()=="SUBCAT")&&(comA[actL][1].toUpperCase()==args[3].toUpperCase()))
													subcat_found=true;

												if((cat_found==true)&&(subcat_found==true))
												{
													faqlist+="<a href='#' class='faq_option' onClick='clickmode=\"FAQ\";faq_select(\""+q[x][1]+"\");'>"+q[x][4]+"</a><BR>";
													cat_found=false;
													subcat_found=false;
												}
											}
											else
												{
													if((comA[actL][0].toUpperCase()=="CAT")&&(comA[actL][1].toUpperCase()==args[2].toUpperCase()))
														faqlist+="<a href='#' class='faq_option' onClick='clickmode=\"FAQ\";faq_select(\""+q[x][1]+"\");'>"+q[x][4]+"</a><BR>";
												}
										}
									}
								}
								if(faqlist!="")
									faqlist="Here are some <b>"+args[2]+"</b> FAQs:<BR><BR>"+faqlist;
							break;
					
							case "subcat":
								for(x=1;x<q.length;x++)
								{
									if((q[x][4])&&(x!=(i-1))&&(q[x][3].charAt(0)!='#'))
									{
										getCommandArray(x);
										for(actL=0;actL<comA.length;actL++)
										{
											if((comA[actL][0].toUpperCase()=="SUBCAT")&&(comA[actL][1].toUpperCase()==args[2].toUpperCase()))
												faqlist+="<a href='#' class='faq_option' onClick='clickmode=\"FAQ\";faq_select(\""+q[x][1]+"\");'>"+q[x][4]+"</a><BR>";								
										}
									}
								}	
								if(faqlist!="")
									faqlist="Here are some <b>"+args[2]+"</b> FAQs:<BR><BR>"+faqlist;
							break;
					
							case "pattern":
								search_results=true;
								y=0;
								ks_result_array=new Array();
								for(x=0;x<server_search_results.length;x++)
								{
									ks_result_array[y]=new Array();
									ks_result_array[y][0]=server_search_results[x];
									y++;
								}
								server_search_results=new Array(); // Reset

								// Populate
								
								if(ks_result_array.length>0)
								{
									automated_question=true;
									
									show_faqs("");
									if(ks_result_array.length>max_search_num)
										search_length=max_search_num
									else
										search_length=ks_result_array.length;

									faqlist="";

									if(querylength==1)
									{
										if(search_length==1)
											searchresults="<b>I see you've typed a keyword.</b><BR><BR>This is the closest match to your query that I can answer:"
										else
											searchresults="<b>I see you've typed a keyword.</b><BR><BR>Here are the closest <b>"+search_length+"</b> matches that I can find:";
									}
									else
									{
										if(search_length==1)
											searchresults="<b>This is the closest question I can answer:"
										else
											searchresults="Here are the closest <b>"+search_length+"</b> matches to your query that I can find:";
									}
								}
								
								if(ks_result_array.length==0)
								{
									unanswered_question=true;
									search_length=0;
									if(querylength==1)
									{
										searchresults="<b>You've typed a keyword which I have no information on.</b><BR><BR>Try typing a full question, or ask me something else.";
									}
									else
									{
										searchresults="<b>I can't find any information on that, I'm afraid.</b><BR><BR>Try rephrasing your question, or ask me something else.";
									}
								}

								querylength=0;
								for(x=0;x<search_length;x++)
								{
									search_resultsA=ks_result_array[x][0].split("|")
									dd_truncated_answer=search_resultsA[0];
									if(dd_truncated_answer.length>dd_max_length) dd_truncated_answer=dd_truncated_answer.substr(0,dd_max_length)+"...";
									optionlist+="<tr><td valign=center><img src='images/bullet.gif'></td><td width=3></td><td valign=center><a href='#' class='option' onClick='clickmode=\"results\";faq_select(\""+search_resultsA[1]+"\");'>"+dd_truncated_answer+"</a></td></tr>";
									optiontext+="[LB][OPTION] "+dd_truncated_answer;
								}
								if(search_length>0) optionlist+="<tr><td><BR></td></tr><tr><td valign=center><img src='images/bullet.gif'></td><td width=3></td><td valign=center><a href='#' class='option' onClick='clickmode=\"results\";gotoLabel(\"no_answer\",\"My question is not listed\");'>My question is not listed</a></td></tr>";
							break;
						}
						correct=5; // automated queries
					break;
					
					case "&list":
						switch(args[1])
						{		
							case "cat":
								for(x=1;x<q.length;x++)
								{
									if((q[x][4])&&(x!=(i-1))&&(q[x][3].charAt(0)!='#'))
									{
										getCommandArray(x);
										cat_found=false;
										subcat_found=false;

										for(actL=0;actL<comA.length;actL++)
										{											
											if(args[3])
											{
												if((comA[actL][0].toUpperCase()=="CAT")&&(comA[actL][1].toUpperCase()==args[2].toUpperCase()))
													cat_found=true;
													
												if((comA[actL][0].toUpperCase()=="SUBCAT")&&(comA[actL][1].toUpperCase()==args[3].toUpperCase()))
													subcat_found=true;
													
												if((cat_found==true)&&(subcat_found==true))
												{
													if(dd==false)
													{
														optionlist="<tr><td valign=top colspan=2><BR><BR><form method='get' name='ddform'><select class='list' name=dropdown onChange=\"clickmode='FAQ';if(this.value!='Select') faq_select(this.value);\">";
														optionlist+="<option value='Select' id='Select'>-- Related Questions --</option>";
														optionlist+="<option value='"+q[x][1]+"' id='"+q[x][1]+"'>"+q[x][4]+"</option>";
														dd=true;
													}
													else
														optionlist+="<option value='"+q[x][1]+"' id='"+q[x][1]+"'>"+q[x][4]+"</option>";
													
													cat_found=false;
													subcat_found=false;
												}
											}
											else
												{
													if((comA[actL][0].toUpperCase()=="CAT")&&(comA[actL][1].toUpperCase()==args[2].toUpperCase()))
													{
														if(dd==false)
														{
															optionlist="<tr><td valign=top colspan=2><BR><BR><form method='get' name='ddform'><select class='list' name=dropdown onChange=\"clickmode='FAQ';if(this.value!='Select') faq_select(this.value);\">";
															optionlist+="<option value='Select' id='Select'>-- Related Questions --</option>";
															optionlist+="<option value='"+q[x][1]+"' id='"+q[x][1]+"'>"+q[x][4]+"</option>";
															dd=true;
														}
														else
															optionlist+="<option value='"+q[x][1]+"' id='"+q[x][1]+"'>"+q[x][4]+"</option>";
														
														cat_found=false;
													}
												}
										}											
									}
								}
							break;
					
							case "subcat":
								for(x=1;x<q.length;x++)
								{
									if((q[x][4])&&(x!=(i-1))&&(q[x][3].charAt(0)!='#'))
									{
										getCommandArray(x);
										for(actL=0;actL<comA.length;actL++)
										{
											if((comA[actL][0].toUpperCase()=="SUBCAT")&&(comA[actL][1].toUpperCase()==args[2].toUpperCase()))
											{
												if(dd==false)
												{
													optionlist="<tr><td valign=top colspan=2><BR><form method='get' name='ddform'><select class='list' name=dropdown onChange=\"clickmode='FAQ';if(this.value!='Select') faq_select(this.value);\">";
													optionlist+="<option value='Select' id='Select'>-- Related Questions --</option>";
													optionlist+="<option value='"+q[x][1]+"' id='"+q[x][1]+"'>"+q[x][4]+"</option>";
													dd=true;
												}
												else
													optionlist+="<option value='"+q[x][1]+"' id='"+q[x][1]+"'>"+q[x][4]+"</option>";							
											}
										}
									}
								}	
							break;
						}
					break;
				}							
				i++;
				if(i>=q.length) end=1
				else
					com=command(q[i][2]);
			}
		}
	}
	if(dd==true) optionlist+="</select></form></td></td>";
	optionlist+="</table>";
	if(optionlist=="<BR><BR><table border=0 cellpadding=0 cellspacing=0></table>") optionlist="<BR>";
	return optionlist;
}

function sortNumber(a,b)
{
	return b[1]-a[1];
}

function lock_increment()
{
	clearTimeout(lockTimer);
	if(lock_count<10)
	{
		lock_count++;
		lockTimer=setTimeout("lock_increment()",600);
	}
	else
			http_search_lock=false;
}

function http_search_lock_true()
{
	http_search_lock=true;
	lock_count=0;
	lock_increment();
}

function http_search_lock_false()
{
	clearTimeout(lockTimer);
	http_search_lock=false
}

function show_server_search_results()
{
	destroyScripts();
	http_search_lock_false();
	if(server_search_results.length>0)
	{
		faqlist="Quick search: <b>"+server_search_results.length+"</b> similar questions found<BR><BR>";
		for(x=0;x<server_search_results.length;x++)
		{
			server_search_results[x]=server_search_results[x].replace("&dots;","...");
			search_resultsA=server_search_results[x].split("|");
			faqlist+="<a href='#' class='faq_option' onClick='clear_form();clickmode=\"search result\";search_select(\""+search_resultsA[1]+"\");'>"+search_resultsA[0]+"</a><BR>";
		}
		document.getElementById("faq_space").innerHTML=faqlist;
	}
	if(http_search_queue.length>0)
	{
		http_search_lock_true();
		http_temp=http_search_queue[http_search_queue.length-1];
		http_search_queue=new Array();
		dataAction(http_temp);
	}
}

function quicksearch()
{
	document.getElementById("faq_fadebox").style.visibility="hidden";
	keystring=document.agent.input_form.value;
	if((keystring!="")&&(catchall!=true))
	{
		if(http_search_lock==false)
		{
			http_search_lock_true();
			http_search_queue=new Array();
			dataAction("http://www.smartagent.co.uk/quicksearch/"+agent_id+"/quicksearch.php?query="+keystring+"&max_search_num="+max_search_num+"&rand="+rand(1,9999));
		}
		else
		{
			http_search_queue.push("http://www.smartagent.co.uk/quicksearch/"+agent_id+"/quicksearch.php?query="+keystring+"&max_search_num="+max_search_num+"&rand="+rand(1,9999));
		}
	}	
}

function quicksearch_string(val)
{
	keystring=val;
	if((keystring!="")&&(catchall!=true))
	{
		if(http_search_lock==false)
		{
			http_search_lock_true();
			http_search_queue=new Array();
			dataAction("http://www.smartagent.co.uk/quicksearch/"+agent_id+"/quicksearch.php?query="+keystring+"&max_search_num="+max_search_num+"&rand="+rand(1,9999));
		}
		else
		{
			http_search_queue.push("http://www.smartagent.co.uk/quicksearch/"+agent_id+"/quicksearch.php?query="+keystring+"&max_search_num="+max_search_num+"&rand="+rand(1,9999));
		}
	}	
}

function patSub(sV,wordA)
{
	sV=" "+sV+" ";
	for(l=0;l<wordA.length;l+=2)
		sV=sV.replaces(" "+wordA[l]+" "," "+wordA[l+1]+" ");
	sV=remSpace(sV);
	return sV;
}

function remPunc(sV)
{
	sV=sV.replace(/\&/," AND ");
	sV=sV.replace(/\/|\-/g," ");
	sV=sV.replace(/\?|\.|\(|\)|!|;|,|\'|\%/g,"");
	return sV;
}

function quickRemPunc(sV)
{
	sV=sV.replace(/\?|\.|!|;|,|\'/g,"");
	sV=sV.replace(/\/|\-|/," ");
	return sV;
}

function remSpace(sV)
{
	sV=sV.replace(/\s+/g," ");
	sV=sV.replace(/^\s|\s$/g,"");
	return sV;
}

function splitArray(sV)
{
	wdA=new	Array();
	if(sV!="NULL") wdA=sV.split(" ");
	else
		wdA[0]=sV;
	return wdA;
}

function simplify(sV)
{
	strA=splitArray(sV);
	for(lp=0;lp<strA.length;lp++)
	{
		if(strA[lp].charAt(0)!="#")
		{
			strA[lp]="^"+strA[lp]+"$";
			if(strA[lp].length>6) strA[lp]=strA[lp].replaces("S$","$");
			for(l=0;l<rules.length;l+=2)
			{
				if(strA[lp].matches(rules[l])>=0)
					strA[lp]=strA[lp].replaces(rules[l],rules[l+1]);
			}
		}
	}
	sV=strA[0];
	for(lp=1;lp<strA.length;lp++)
		sV=sV+" "+strA[lp];
	sV=sV.replaces("$","");
	sV=sV.replaces("^","");
	return sV.toUpperCase();
}

function keywordSearch(query)
{
	var resA=new Array();
	var resI=0;
	for(a=1;a<q.length;a++)
	{
		if(q[a][4])
		{
			resA[resI]=new Array();
			resA[resI]=a;
			resA[resI+1]=0;
			for(qSI=0;qSI<query.length;qSI++)
			{
				for(b=1;b<kwArray[a].length;b++)
				{
					for(c=0;c<kwArray[a][b].length;c++)
					{
						if(query[qSI]==kwArray[a][b][c])
						{
							resA[resI+1]++;
						}
					}
				}
			}
			resI+=2;
		}
	}
	return resA;
}

function corpusSearch(query)
{
	var resA=new Array();
	var resI=0;
	for(a=0;a<corpusA.length;a++)
	{
		resA[resI]=new Array();
		resA[resI]=corpusI[a];
		resA[resI+1]=0;
		for(qSI=0;qSI<query.length;qSI++)
			for(b=0;b<corpusA[a].length;b++)
				if(query[qSI]==corpusA[a][b])
				{
					resA[resI+1]++;
					break;
				}
		resI+=2;
	}
	return resA;
}

function PatMch(queryStr,ptStr)
{
	var queryI=0;
	var ptFound=1;
	var ptI=0;
	var queryI=0;
	var bufI=0;
	var ptC=0;

	while((ptI<ptStr.length)&&(ptFound==1))
	{
		if(queryI<queryStr.length)
		{
			if(queryStr[queryI]==ptStr[ptI])
			{
				queryI++;
				ptI++;
				ptFound=1;
				ptC++;
			}
			else
			if(ptStr[ptI]=="&PT")
			{
				buf[bufI]="";
				if(ptStr[ptI+1]!=queryStr[queryI])
				{
					while((ptStr[ptI+1]!=queryStr[queryI])&&(queryI<queryStr.length))
					{
						buf[bufI]+=patQu[queryI]+" ";
						queryI++;
					}
					ptC++;
					ptFound=1;
					ptI++;
					bufI++;
				}
				else
				ptFound=0;
			}
			else
				if(queryStr[queryI]!=ptStr[ptI]) ptFound=0;
		}
		else ptFound=0;
	}
	if(ptFound!=1)
		ptC=0;
	return ptC;
}

function runPatMch(queryStr)
{
	ptResult=0;
	match=-1;
	buf=new	Array();
	for(lp=1;lp<jabberwock.length;lp++)
	{
		if(qt[lp]=="p")
		{
			tempResult=PatMch(queryStr,jabberwock[lp]);
			if(tempResult>ptResult)
			{
				match=lp;
				ptResult=tempResult;
			}
		}
	}
	if(match!=-1)
	{
		tempResult=PatMch(queryStr,jabberwock[match]);
		for(lp=0;lp<buf.length;lp++)
		{
			buf[lp]=patSub(buf[lp],ptSynA);
			buf[lp]=buf[lp].replace(/\#/g,"");
		}
	}
	return match;
}

function parseKeywords(userA,syntaxA)
{
	var matchCount=0;
	var matchFound=true;
	var a=1;
	while((a<syntaxA.length)&&(matchFound==true))
	{
		matchFound=false;
		b=0;
		while((b<syntaxA[a].length))
		{
			for(c=0;c<userA.length;c++)
			{
				if(syntaxA[a][b]==userA[c])
				{
					matchFound=true;
					matchCount++;
				}
			}
			b++;
		}
		a++;
	}
	if(matchFound==true)
		return matchCount;
	else
		return 0;
}

function parseQuestions(userA,syntaxA)
{
	var matchCount=0;
	var matchFound=true;
	var a=1;
	while((a<syntaxA.length)&&(matchFound==true))
	{
		matchFound=false;
		c=0;		
		while(c<userA.length)
		{
			b=0;
			while((b<syntaxA[a].length))
			{
				if(syntaxA[a][b]==userA[c])
				{
					matchFound=true;
					matchCount++;
					break;
				}
				b++;
			}
			c++;
		}
		a++;
	}
	if(matchFound==true)
		return matchCount;
	else
		return 0;
}

function run_option_parse(user_query,catname)
{
	match=0;
	bestMatch=0;
	iterA=new Array();

	for(lp=1;lp<q.length;lp++)
	{
		if(qt[lp]=="q")
		{
			if((catname==q[lp][5])&&(q[lp][6]=="Options"))
			{
				aI=0;
   			negMatch=0;
				while((aI<user_query.length)&&(negMatch==0))
				{
					for(nI=0;nI<kwNeg[lp].length;nI++)
						if(user_query[aI]==kwNeg[lp][nI]) negMatch=1;
					aI++;
				}
				if(negMatch==0)
				{
					newMatch=parseQuestions(user_query,kwArray[lp]);
					if(newMatch>match)
					{
						match=newMatch;
						bestMatch=lp;
					}
				}
			}
		}
	}
	matchA=new Array();
	matchA[0]=bestMatch;
	matchA[1]=match;
	return matchA;
}

function run_category_parse(user_query,catname)
{
	match=0;
	bestMatch=0;
	iterA=new Array();

	for(lp=1;lp<q.length;lp++)
	{
		if(qt[lp]=="q")
		{
			if((catname==q[lp][5])&&(q[lp][6]!="Options"))
			{
				aI=0;
   			negMatch=0;
				while((aI<user_query.length)&&(negMatch==0))
				{
					for(nI=0;nI<kwNeg[lp].length;nI++)
						if(user_query[aI]==kwNeg[lp][nI]) negMatch=1;
					aI++;
				}
				if(negMatch==0)
				{
					newMatch=parseQuestions(user_query,kwArray[lp]);
					if(newMatch>match)
					{
						match=newMatch;
						bestMatch=lp;
					}
				}
			}
		}
	}
	matchA=new Array();
	matchA[0]=bestMatch;
	matchA[1]=match;
	return matchA;
}

function run_nouncat_parse(user_query)
{
	match=0;
	bestMatch=0;
	iterA=new Array();

	for(lp=1;lp<q.length;lp++)
	{
		if(qt[lp]=="q")
		{
			if((q[lp][5]!="")&&(q[lp][6]!="Options"))
			{
				aI=0;
   			negMatch=0;
				while((aI<user_query.length)&&(negMatch==0))
				{
					for(nI=0;nI<kwNeg[lp].length;nI++)
						if(user_query[aI]==kwNeg[lp][nI]) negMatch=1;
					aI++;
				}
				if(negMatch==0)
				{
					newMatch=parseQuestions(user_query,kwArray[lp]);
					if(newMatch>match)
					{
						match=newMatch;
						bestMatch=lp;
					}
				}
			}
		}
	}
	matchA=new Array();
	matchA[0]=bestMatch;
	matchA[1]=match;
	return matchA;
}

function run_allcat_parse(user_query)
{
	match=0;
	bestMatch=0;
	iterA=new Array();

	for(lp=1;lp<q.length;lp++)
	{
		if(qt[lp]=="q")
		{
			if(q[lp][6]!="Options")
			{
				aI=0;
   			negMatch=0;
				while((aI<user_query.length)&&(negMatch==0))
				{
					for(nI=0;nI<kwNeg[lp].length;nI++)
						if(user_query[aI]==kwNeg[lp][nI]) negMatch=1;
					aI++;
				}
				if(negMatch==0)
				{
					newMatch=parseQuestions(user_query,kwArray[lp]);
					if(newMatch>match)
					{
						match=newMatch;
						bestMatch=lp;
					}
				}
			}
		}
	}
	matchA=new Array();
	matchA[0]=bestMatch;
	matchA[1]=match;
	return matchA;
}

function setCategory(tval)
{
	mastercategory=tval;
	subcat="";
	category_changed=1;
	
}

function setSubcat(tval)
{
	subcat=tval;
	category_changed=1;
}

function insert_links(st)
{
	st_tag_strip=new Array("<name>","</name>","<b>","</b>","<br>","<i>","</i>","<h>","</h>","<small>","</small>","<INFO>","</INFO>","<NAME>","</NAME>","<B>","</B>","<BR>","<I>","</I>","<H>","</H>","<SMALL>","</SMALL>","<INFO>","</INFO>");
	
	st_temp=st;
	for(x=0;x<st_tag_strip.length;x++)
		st_temp=st_temp.replaces(st_tag_strip[x],"");

	stage1=st_temp.split("</link>");
	y=0;
	stage2=new Array();
	link_textA=new Array();
	for(x=0;x<stage1.length;x++)
	{
		if(stage1[x].match(">"))
		{
			stage2[y]=stage1[x].split(">");
			link_textA[y]=stage2[y][1];
			y++;
		}
	}
	
	stage3=new Array();
	for(z=0;z<stage2.length;z++)
		stage3[z]=stage2[z][0].split("<");
	
	linkA=new Array();
	for(za=0;za<stage3.length;za++)
	{
		linkA[za]=stage3[za][1].split(" href=")
		linkA[za][2]=link_textA[za];
	}
	
	for(x=0;x<linkA.length;x++)
	{
		switch(linkA[x][0])
		{
			case "link_label":
				old_link="<"+linkA[x][0]+" href="+linkA[x][1]+">"+linkA[x][2]+"</link>";
				new_link="<a href='#' class='inline' onMouseDown=gotoLabel('"+linkA[x][1]+"')>"+linkA[x][2]+"</a>";
				st=st.replace(old_link,new_link);
			break;
			
			case "link_behind":
				old_link="<"+linkA[x][0]+" href="+linkA[x][1]+">"+linkA[x][2]+"</link>";
				new_link="<a href='#' class='inline' onMouseDown=parent_url('"+linkA[x][1]+"')>"+linkA[x][2]+"</a>";
				st=st.replace(old_link,new_link);
			break;
			
			case "link_above":
				old_link="<"+linkA[x][0]+" href="+linkA[x][1]+">"+linkA[x][2]+"</link>";
				new_link="<a target='_new' class='inline' href='"+linkA[x][1]+"'>"+linkA[x][2]+"</a>";
				st=st.replace(old_link,new_link);
			break;
			
			case "link_email":
				old_link="<"+linkA[x][0]+" href="+linkA[x][1]+">"+linkA[x][2]+"</link>";
				new_link="<a href='mailto:"+linkA[x][1]+"' class='inline'>"+linkA[x][2]+"</a>";
				st=st.replace(old_link,new_link);
			break;
		}
	}
	return st;
}

function insert_tags(st)
{
	if(opener && !opener.closed)
		window_text="<info>Look behind me now for further information.</info>"
	else
		window_text="<info>See the page appearing now for further information.</info>";

	spA=new	Array(
	"<behind>",window_text,
	"<info>","<BR><BR><b class='list'>",
	"</info>","</b>",
	"<name>","<h>",
	"</name>","<BR></b><a href='#' class='option' onClick=gotoLabel('changename','');><small>Change Name</small></a><BR><BR>",
	"<h>","<b class='hdng'>",
	"</h>","</b><BR><BR>",
	"&apos;","'",
	"&dots;","..."
	);
	
	for(x=0;x<spA.length;x+=2)
		st=st.replaces(spA[x],spA[x+1]);
	
	return st;
}

function insert_variables(st)
{
	date_time=getSystemDate();
	
	if(temp=username.matches("Anon User")>-1)
		tmp_usr="user"
	else
		tmp_usr=username;
		
	if(log_mode==false)
		logmode=" (Logging Off)"
	else
		logmode="";
	
	spA=new	Array(
	"&answer",answer,
	"&username",tmp_usr,
	"&agentname",agentname,
	"&clientname",clientname,
	"&date",date_time,
	"&passed_value",passed_value,
	"&start_date",start_date[0]+" "+start_date[1]+" "+start_date[2],
	"&end_date",end_date[0]+" "+end_date[1]+" "+end_date[2],
	"&searchresults",searchresults,
	"&p0",buf[0],
	"&p1",buf[1],
	"&p2",buf[2],
	"&log_mode",logmode,
	"&page_change_url",page_change_url,
	"&page_change_desc",page_change_desc,
	"&percent;","%"
	);
	
	// Variables set by knowledge-base; use &varname& in sheet
	// *******************************************************
	
	for(x=0;x<vrA.length;x++)
		st=st.replaces("&"+vrA[x][0]+"&",vrA[x][1]);
	
	// *************************
	
	for(x=0;x<spA.length;x+=2)
		st=st.replaces(spA[x],spA[x+1]);
	
	return st;
}


function faq_setOpacity(obj,opacity)
{
  opacity = (opacity == 100)?99.999:opacity;
  obj.style.filter = "alpha(opacity:"+opacity+")";
  obj.style.KHTMLOpacity = opacity/100;
  obj.style.MozOpacity = opacity/100;
  obj.style.opacity = opacity/100;
}

function faq_makeVisible()
{
	clearTimeout(faq_visTimer);
	faq_setOpacity(faq_fadebox,faq_mvisibility);
	if(faq_mvisibility!=10)
	{
		faq_mvisibility-=10;
		faq_visTimer=setTimeout("faq_makeVisible()",30);
	}
	else
		document.getElementById("faq_fadebox").style.visibility="hidden";
}

function setOpacity(obj,opacity)
{
  opacity = (opacity == 100)?99.999:opacity;
  obj.style.filter = "alpha(opacity:"+opacity+")";
  obj.style.KHTMLOpacity = opacity/100;
  obj.style.MozOpacity = opacity/100;
  obj.style.opacity = opacity/100;
}

function makeVisible()
{
	clearTimeout(visTimer);
	setOpacity(fadebox,mvisibility);
	if(mvisibility!=10)
	{
		mvisibility-=10;
		visTimer=setTimeout("makeVisible()",30);
	}
	else
		document.getElementById("fadebox").style.visibility="hidden";
}

function remove_tags(val)
{
	tagA=new Array(
	"<img src='images/exc.gif'>&nbsp;",
	"<info>",
	"</info>",
	"<name>",
	"</name>",
	"<behind>",
	"<h>",
	"</h>",
	"<b>",
	"</b>"
	);
	for(x=0;x<tagA.length;x++)
		val=val.replaces(tagA[x],"");
	return val;
}

function speak(st,asI)
{
	if(st!="&na")
	{
		secondlastindex=lastindex;
		lastindex=asI;
		if(st.match(/<OR>/))
		{
			displayA=st.split(/<OR>/);
			rand_choice=rand(0,displayA.length-1);
			st=displayA[rand_choice];
		}
		else
			if(st.match(/<THEN>/)&&(asI>0))
			{
				displayA=st.split(/<THEN>/);
				st=displayA[asA[asI]++];
				if(asA[asI]>=displayA.length) asA[asI]=0;
			}
	
		if(answer_heading!="")
		{
			st="<h>"+answer_heading+"</h>"+st;
			answer_heading="";
		}
		else
			if(q[asI][4])
				st="<h>"+q[asI][4]+"</h>"+st;
		
		if(page_change==true)
		{
			st=st+"<behind>";
			page_change=false;
		}
		
		if(change_pop_cat==true)
		{
			change_pop_cat=false;
			get_pop_cat(mastercategory);
		}
		st=insert_variables(clarifier+st);
		st=insert_links(st);
		st=insert_tags(st);
		clarifier="";
		lowcase=st.charAt(0);
		upcase=lowcase.toUpperCase();
		caseExp=new RegExp(lowcase);
		st=st.replace(caseExp,upcase);
		print_format_dialogue=remove_tags(print_format_dialogue);
		print_format_dialogue=insert_variables(print_format_dialogue);
		print_format_dialogue+="<BR><HR><BR><b class='dialogue'>smartAgent said:</b><BR><BR>"+st+"<BR><BR>";
		globAnswer=st;
		message='';
		screenA=st.split(" ");
		expression(face);
		
		if(search_results==true)
		{
			backAanswer[backIndex]=st+globalOptions;
			search_results=false;
		}

		if((faqlist!="")&&(faq_visible==true)) show_faqs(faqlist);

		document.getElementById("fadebox").style.visibility="visible";
		mvisibility=100;
		if((q[asI][4])&&(pop_allowed==true)&&(designed_question==false))
			document.getElementById("textbox").innerHTML=st+globalOptions+rate_text
		else
		{
			document.getElementById("textbox").innerHTML=st+globalOptions;
			pop_allowed=true;
		}
		document.getElementById("textbox").scrollTop = 0;
		makeVisible();
	}
}

function show_faqs(val)
{
	document.getElementById("faq_fadebox").style.visibility="visible";
	faq_mvisibility=100;
	document.getElementById("faq_space").innerHTML=val;
	faq_makeVisible();
}

function loadData(surl)
{
	var script  = document.createElement('script');
	script.src  = surl+'?data='+rand(1,9999);
	script.type = 'text/javascript';
	script      = document.getElementsByTagName('head')[0].appendChild(script);
	_scripts.push(script);
	return script;
}

function destroyScripts()
{
	for(i=0;i<_scripts.length;i++)
		if(_scripts[i].parentNode)
			_scripts[i].parentNode.removeChild(_scripts[i]);
}

function dataAction(durl)
{
	var script  = document.createElement('script');
	script.src  = durl;
	script.type = 'text/javascript';
	script      = document.getElementsByTagName('head')[0].appendChild(script);
	_scripts.push(script);
	
}

function start()
{
	cid=rand(1,9999999);
	document.getElementById("textbox").innerHTML=loadmessage;
	document.getElementById("fadebox").style.visibility="hidden";
	document.agent.input_form.value=default_input_string;
	var datafile=loadData(datafile_url);
}

function init()
{
	print_format_dialogue="";
	destroyScripts();
	interaction_count=0;
	getRemoteData();
	loadCookies();
	logValue="";
	startTime=getElapsedTime(0);

	passed_args = location.search.substring(1,location.search.length);
	passed_args = passed_args.replace(/\%20|\%3C|\%3E/g," ");

	for(x=1;x<=goalNum;x++)
		goalA[x]=false;

	argumentA=passed_args.split('&');
	
	passed_data="";
	passed_label="";

	for(x=0;x<argumentA.length;x++)
	{
		var pairA=argumentA[x].split("=");
		switch(pairA[0])
		{
			case "question":
				passed_data=pairA[1];
			break;
			case "label":
				passed_label=pairA[1];
			break;
			
			case "variable":
				args=pairA[1].split(",");
				var varfound=-1;
				for(x=0;x<vrA.length;x++)
				{
					if(vrA[x][0]==args[1])
					varfound=x;
				}
				if(varfound>-1)
				vrA[varfound][1]=answer;
									
				if(varfound==-1)
				vrA[vrA.length]=new Array(args[0],args[1]);
			break;
		}
	}
	
	if((passed_label=="")&&(get_username==false)&&(passed_data==""))
	{
		if(username=="user") username="Anon User "+rand(1,9999);
		run_agent_p3("STARTNEWAGENT");
	}
	else
	{
		if(passed_label!="")
		{
			if(username=="user") username="Anon User "+rand(1,9999);
			gotoLabel(passed_label);
		}
		else
		{
			if(passed_data=="")
			{
				if((temp=username.matches("Anon User")>-1)||(username=="user"))
					run_agent_p3("GETNAME")
				else
					run_agent_p3("STARTNEWAGENT");
			}
			else
			{
				if(username=="user")
					username="Anon User "+rand(1,9999);
				show_popular();
				document.getElementById("youasked").innerHTML="You said: "+passed_data;
				print_format_dialogue+="<b class='dialogue'>You wrote:</b><BR><BR>"+passed_data+"<BR>";
				run_agent(passed_data);
			}
		}
	}
}

function click_to(ans,select_text)
{
	interaction_count++;
	select_text=select_text.replace("&apos;","'");
	if(select_text!="no_val")
	{
		if(youasked=="on") document.getElementById("youasked").innerHTML="You selected: "+select_text;
		if(youasked=="on") print_format_dialogue+="<b class='dialogue'>You selected:</b><BR><BR>"+select_text+"<BR>";
		gotoLabel(ans,select_text);
	}
	else
	{
		dd_split=ans.split("<SPLIT>");
		if(youasked=="on") document.getElementById("youasked").innerHTML="You selected: "+dd_split[1];
		if(youasked=="on") print_format_dialogue+="<b class='dialogue'>You selected:</b><BR><BR>"+dd_split[1]+"<BR>";
		gotoLabel(dd_split[0],dd_split[1]);
	}
}

function faq_select(ans)
{
	answer_heading="";
	interaction_count++;
	label_idx=getLabelIndex(ans);
	if(q[label_idx][3].charAt(0)=="#")
	{
		answer_heading=q[label_idx][4];
		label_idx=getLabelIndex(q[label_idx][3]);
		ans=q[label_idx][1];
		label_idx=getLabelIndex(ans);
		if(youasked=="on") document.getElementById("youasked").innerHTML="You selected: "+answer_heading;
		if(youasked=="on") print_format_dialogue+="<b class='dialogue'>You selected:</b><BR><BR>"+answer_heading+"<BR>";
		gotoLabel(ans,answer_heading);
	}
	else
	{
		ans=q[label_idx][1];
		label_idx=getLabelIndex(ans);
		if(youasked=="on") document.getElementById("youasked").innerHTML="You selected: "+q[label_idx][4];
		if(youasked=="on") print_format_dialogue+="<b class='dialogue'>You selected:</b><BR><BR>"+q[label_idx][4]+"<BR>";
		gotoLabel(ans,q[label_idx][4]);
	}
}

function multi_select(ans)
{
	answer_heading="";
	interaction_count++;
	label_idx=getLabelIndex(ans);
	if(q[label_idx][3].charAt(0)=="#")
	{
		answer_heading=q[label_idx][4];
		label_idx=getLabelIndex(q[label_idx][3]);
		ans=q[label_idx][1];
		label_idx=getLabelIndex(ans);
		if(youasked=="on") document.getElementById("youasked").innerHTML="You selected: "+q[label_idx][4];
		if(youasked=="on") print_format_dialogue+="<b class='dialogue'>You selected:</b><BR><BR>"+q[label_idx][4]+"<BR>";
		goto_multi_Label(ans,answer_heading);
	}
	else
	{
		ans=q[label_idx][1];
		label_idx=getLabelIndex(ans);
		if(youasked=="on") document.getElementById("youasked").innerHTML="You selected: "+q[label_idx][4];
		if(youasked=="on") print_format_dialogue+="<b class='dialogue'>You selected:</b><BR><BR>"+q[label_idx][4]+"<BR>";
		goto_multi_Label(ans,q[label_idx][4]);
	}
}

function search_select(ans)
{
	answer_heading="";
	interaction_count++;
	label_idx=getLabelIndex(ans);
	if(q[label_idx][3].charAt(0)=="#")
	{
		answer_heading=q[label_idx][4];
		label_idx=getLabelIndex(q[label_idx][3]);
		ans=q[label_idx][1];
		if(youasked=="on") document.getElementById("youasked").innerHTML="You selected: "+answer_heading;
		if(youasked=="on") print_format_dialogue+="<b class='dialogue'>You selected:</b><BR><BR>"+answer_heading+"<BR>";
		gotoLabel(ans,answer_heading);
	}
	else
	{
		ans=q[label_idx][1];
		if(youasked=="on") document.getElementById("youasked").innerHTML="You selected: "+q[label_idx][4];
		if(youasked=="on") print_format_dialogue+="<b class='dialogue'>You selected:</b><BR><BR>"+q[label_idx][4]+"<BR>";
		gotoLabel(ans,q[label_idx][4]);
	}
}

function pass_value_to(val,select_text)
{
	interaction_count++;
	print_format_dialogue+="<b class='dialogue'>You selected:</b><BR><BR>"+select_text+"<BR>";
	dd_split=val.split("<SPLIT>");
	if(select_text!="no_val")
	{
		if(youasked=="on") document.getElementById("youasked").innerHTML="You selected: "+select_text;
		passed_value=dd_split[0];
		gotoLabel(dd_split[1],select_text);
	}
	else
		{
			if(youasked=="on") document.getElementById("youasked").innerHTML="You selected: "+dd_split[2];
			passed_value=dd_split[0];
			gotoLabel(dd_split[1],dd_split[2]);
		}
}

function getFocus()
{
	if(firstclick==true)
	{
		document.agent.input_form.value="";
		document.agent.input_form.focus();
	}
}

function form_submit()
{
	clearTimeout(searchTimer);
	if(http_search_lock==true)
		searchTimer=setTimeout("form_submit()",50)
	else
		process_form();
}

function process_form()
{
	usrInp=document.agent.input_form.value;
	if(youasked=="on")
	{
		if(usrInp.length==0)
		{
			document.getElementById("youasked").innerHTML="You said: nothing";
		}
		else
			{
				document.getElementById("youasked").innerHTML="You said: "+usrInp;
				print_format_dialogue+="<b class='dialogue'>You wrote:</b><BR><BR>"+usrInp+"<BR>";
			}
	}
	press_submit=false;
	getData(usrInp,"keys");
}

function pop_submit(query)
{
	if(youasked=="on") document.getElementById("youasked").innerHTML="You said: "+query;
	if(youasked=="on") print_format_dialogue+="<b class='dialogue'>You wrote:</b><BR><BR>"+query+"<BR>";
	getData(query,"clicks");
}

function getData(ans,inputtype)
{
	face="neutral";
	profanity=false;
	getFocus();
	answer=ans;
	interaction_count++;
	if(catchall==true)
	{
		catchall=false;
		gotoLabel(catchall_label,ans)
	}
	else
		{
			if(escalation_detection==true)
			{
				if(answer_word_count=answer.split(" ").length>escalation_word_limit)
					gotoLabel("escalate_query",answer);
				else
					if((answer!="")&&(answer!=default_input_string))
					{
						if(inputtype=="keys")
							run_agent(answer)
						else
							run_agent_p3(answer);
					}
			}
			else
			{
				if((answer!="")&&(answer!=default_input_string))
				{
					if(inputtype=="keys")
						run_agent(answer)
					else
						run_agent_p3(answer);
				}
			}
		}
}

function command(coms)
{
	command_type="NULL";
	if(coms.match(/^&PT/)!="&PT")
	{
		if(coms.charAt(0)=="&")
		{
			i=0;
			command_type="";
			while(coms.charAt(i)!=":")
			{
				command_type+=coms.charAt(i);
				i++;
			}
		}
	}
	return command_type;
}

function run_agent(usrInp)
{
	global_usrInp=usrInp;
	quicksearch_string(usrInp);
	run_agent_p2();	
}

function run_agent_p2()
{
	if(http_search_lock==true)
	{
		runTimer=setTimeout("run_agent_p2()",50)
	}
	else
		{
			clearTimeout(runTimer);
			destroyScripts();
			http_search_lock_false();
			run_agent_p3(global_usrInp);
		}
}

function run_agent_p3(usrInp)
{
	var userA=new Array();
	var matchI=0;
	var patQuMn="";
	var	correct=0;

  log_question=usrInp;
	usrInp=remPunc(usrInp);
	usrInp=usrInp.toUpperCase();
	usrInp=remSpace(usrInp);
	usrInp=patSub(usrInp,synA);
	patQu=splitArray(usrInp);
	querylength=patQu.length;
	usrInp=patSub(usrInp,qspelA);
	usrInp=patSub(usrInp,commA);
	usrInp=simplify(usrInp);
	patQuMn=usrInp;
	userA=splitArray(usrInp);

	if(mastercategory=="")
	{
		resultA=run_category_parse(userA,"");
		resultB=run_nouncat_parse(userA);
		if(resultA[1]>=resultB[1]) matchI=resultA[0]
		else
			matchI=resultB[0];
	}
	
	if(mastercategory!="")
	{
		resultA=run_option_parse(userA,mastercategory);
		if(resultA[0]==0)
		{
			resultB=run_category_parse(userA,mastercategory);
			resultC=run_category_parse(userA,"");
			resultD=run_allcat_parse(userA);
		
			if(resultB[1]>=resultC[1]) matchI=resultB[0]
			else
				matchI=resultC[0];
			if((resultD[1]>resultB[1])&&(resultD[1]>resultC[1]))
				matchI=resultD[0];
		}
		else
			matchI=resultA[0];
	}

	// Jabberwocky

	if(matchI==0)
	{
		if(server_search_results.length>0)
		{
			matchI=getLabelIndex("pt");
		}
		else
		{
			patMn=splitArray(patQuMn);
			matchI=runPatMch(patMn); 
		}
	}
	else
		correct=1;

	response=q[matchI][3];
	if(response.charAt(0)=="#")
	{
		if(q[matchI][4]) answer_heading=q[matchI][4];
		matchI=getLabelIndex(response);
	}
	matchI_new=actions(matchI,false);
	if(matchI!=matchI_new) actions(matchI_new,false);
	record(matchI_new);
	response=q[matchI_new][3];
	globalOptions=options(matchI_new);
	speak(response,matchI_new);
	lastanswer=answer;
	saveCookies();

	if(q[matchI_new][4]!="")
		send_log(username,log_question,globAnswer,correct,q[matchI_new][5],q[matchI_new][6],q[matchI_new][4]);
	else
		send_log(username,log_question,globAnswer,correct,q[matchI_new][5],q[matchI_new][6],"");
}

function getSystemDate()
{
	var current=new Date();
	var newDate=current.toGMTString();
	newDate=newDate.replace("UTC","");
	return newDate;
}

function getElapsedTime(subtraction)
{
	var current=new Date();
	return current.getTime()-subtraction;
}

function loadCookies()
{
	cookievalue=getCookie("cookievalue");
	if (cookievalue!=null)
	{
		cookieA=cookievalue.split(/@/);
		username=cookieA[0];
		if(cookieA[1]<10) sid=rand(1,9999999);
		else
			sid=cookieA[1];
	}
}

function saveCookies()
{
	if(save_cookies==true)
	{
		var now=new	Date();
		now.setTime(now.getTime()+365*24*60*60*1000);
		cookievalue=username+"@"+sid;
		setCookie("cookievalue",cookievalue,now);
	}
}

function getCookie(name)
{
	var cname=name+"=";
	dc=document.cookie;
	if (dc.length>0)
	{
		begin=dc.indexOf(cname);
		if (begin!=-1)
		{
			begin+=cname.length;
			end=dc.indexOf(";",begin);
			if (end==-1) end=dc.length;
			return unescape(dc.substring(begin,end));
		}
	}
	return null;
}

function setCookie(name,value,expires,path,domain,secure)
{
	document.cookie	= name + "=" + escape(value) +
	((expires == null) ? ""	: "; expires=" + expires.toGMTString())	+
	((path == null)	? "" : "; path=" + path) +
	((domain == null) ? "" : "; domain=" + domain) +
	((secure == null) ? "" : "; secure");
}