///Copyright Ken Hurtubise



////Vars

var IN=""

var OUT=""

////Utility functions







/* Finds the index of the first occurence of item in the array, or -1 if not found */

Array.prototype.indexOf = function(item) {

    for (var i = 0; i < this.length; i++) {

        if (this[i] == item) {

            return i;

        }

    }

    return -1;

};

    /* Finds the index of an item in a sorted array , or -1 if not found */

Array.prototype.fnd = function(item) {

//this.sort()

var low=0

var high=this.length

var look=1

do{look=low+((high-low)>>1)

if (this[look]<item){low=look+1;continue}

if (this[look]>item){high=look;continue}

if (this[look]==item){return look}

}while(low<high)

return -1

}





/* Returns an array of items judged 'true' by the passed in test function 

Usage---

t=[1,2,0,3,-4,-5,6,7]

aaa=t.filter(function (n){return n>-1;});

document.write(aaa)

*/

Array.prototype.filter = function(test) {

    var matches = [];

    for (var i = 0; i < this.length; i++) {

        if (test(this[i])) {

            matches.push(this[i]);

        }

    }

    return matches;

}

///



/* Returns a random array value */

Array.prototype.rnd = function() {

if(this[0]){x=this[Math.floor(Math.random()*(this.length))];return x}}



///



function loadPage(pagename){

if(pagename){	remoteframe.location.href=pagename;return}

remoteframe.location.href=server_page;

}



///







function initCap(s){return s.substring(0,1).toUpperCase()+s.substring(1,s.length)}







///
function get(name){
 
if(name.indexOf('|')>=0){//////inline random
var tmp=name.split('|');
x=tmp[Math.floor(Math.random()*(tmp.length))];return x
}
 
try{
if(name.value){x=name.value;return x}
name=eval(name)
if(name.constructor != Array){
//alert("not array")
return name;
};

if(name[0]){
var now = new Date();
var seed = now.getMilliseconds();
x=name[Math.floor(Math.random(seed)*(name.length))];
return x}

}
catch(err)
{

return name.toString();}
}
 
 
function ProcessString(s)
{
var a=b=0
while ((b=s.indexOf(']', --a)) >= 0) {
	a=s.lastIndexOf('[',b);
	topic=s.substring(++a,b)
//alert(topic)
 	s=s.substring(0,a-1)+get(topic)+s.substring(b+1); 
	}
return s}

///



function show(a){output.innerHTML+=(ProcessString(a))}





///





function changePOV(TXT){



var POV=[

'%',';;percent;;',
'I was','y%ou were',
'yourself','m%yself',
'your ','m%y ',
'myself','y%ourself',

'\\bI\\b','y%ou',

'were you\\b','was I',

'you and I\\b','we',

'are you','%am %I%',

'my ','y%our ',

'\\byou\\b','I',

'mine','y%ours',

' you\\b',' %me%',

' me\\b',' y%ou',

'\\byou\\b','I',

'%','',

'\\bi$','me',

'I are','I am',

'you am ','you are ',

'\\bI and you ','you and I ',

'am you','are you',

'\\bto I\\b','to me',

'I to\\b','me to',

'you am','you are',

'\\bi and you','you and I',

'\\bam me\\b','am I',

';;percent;;','%']







for(i=0;i<POV.length;i+=2) {

TXT = TXT.replace(pattern=new RegExp(POV[i], 'gi'),POV[i+1]);

}

return TXT

}

///







function normalize(TXT){

var norm=["dont","do not",
"gr8","great",
"\\bim\\b","I am",
"whats","what is",
"thats","that is",
"\\br\\b","are",
"\\bu\\b"," you",
"how do you define","Define",
"What do you know about","Define",
"What can you tell me about","Define",
" ur "," you are ",
"theres ","there is",
"do you know where is","where is",
"tell me more about","search"]

for(i=0;i<norm.length;i+=2) {
TXT = TXT.replace(pattern=new RegExp(norm[i], 'gi'),norm[i+1]);}


if(TXT.search("'")!=-1){

var contractions=["aren't","are not","what's","what is","won't","will not","weren't","were not","haven't","have not","ouldn't","ould not","don't","do not","dn't","d not","sn't","s not","i'm","I am","'ll"," will","'ve"," have","'re"," are","n't","n not","let's","let us","it's been","it has been","it's","it is",
"EVERYTHING'S","EVERYTHING IS",
"HE'D","HE WOULD",
"HE'S","HE IS",
"HOW'D","HOW WOULD",
"HOW'S","HOW IS",
"I'D","I WOULD",
"IT'D","IT WOULD",
"SHE'S","SHE IS",
"THAT'D","THAT DID",
"THAT'S","THAT IS",
"THERE'S","THERE IS",
"THEY'D","THEY WOULD",
"WE'D","WE WOULD",
"WHAT'D","WHAT DID",
"WHERE'S","WHERE IS",
"WHO'S","WHO IS",
"WHY'S","WHY IS",
"YOU'D","YOU WOULD",
"'EM"," THEM",
"dont","do not",
"'s","_s"]

//"WHERE S","WHERE IS",//"HE S","HE IS",//,//"THAT S","THAT IS",//"CANNOT","CAN NOT",//"IT S ","IT IS",//"'TIS","IT IS",



for(i=0;i<contractions.length;i+=2) {

TXT = TXT.replace(pattern=new RegExp(contractions[i], 'gi'),contractions[i+1]);}

return TXT



}

return TXT

}



///


function num2words(x){



if (isNaN(x)) {

a="Not a number, enter only digits."

return a

}

if(x==0){

a="zero"

return a

}



if(x<0||x%1!=0){

return x;

}



/////

a=x.toString()

b=a.length

c=b%3

d=a.substring(0,c)

e=((b-c)/3)

f=g=h=""

////////////

if(x>99){

if(d!=""&&b>2){

if(d<100){g=h=""

i=-1

if(d>19){

g=TENS[a.substring(i+1,i+2)]}

if(a.substring(i+1,i+2)>1&&a.substring(i+2,i+3)!=0){

h=" "+ONES[a.substring(i+2,i+3)]}

if(a.substring(i+1,i+2)==1){

h=" "+TEENS[a.substring(i+2,i+3)]}

if(((d>20)||(d<10))&&a.substring(i+2,i+1)!=0){

h=" "+ONES[a.substring(i+2,i+1)]}

d=g+h}

if((g+h)!=""){d=d+" "+BIG_NUM[e]+" "}

}



/////////

for(i=c;i<b;i=i+3){

f=g=h=""

if(a.substring(i,i+1)>0){f=ONES[a.substring(i,i+1)]+" "+BIG_NUM[0]};

if(a.substring(i+1,i+2)>1){

g=" "+TENS[a.substring(i+1,i+2)]}

if(a.substring(i+1,i+2)>1&&a.substring(i+2,i+3)!=0){

h=" "+ONES[a.substring(i+2,i+3)]}

if(a.substring(i+1,i+2)==1){

h=" "+TEENS[a.substring(i+2,i+3)]}

if(a.substring(i+1,i+2)==0&&a.substring(i+2,i+3)!=0){

h=" "+ONES[a.substring(i+2,i+3)]}

e=e-1

d=d+f+g+h

if(e>0&&(f+g+h)!=""){d=d+" "+BIG_NUM[e]+" "}

}}



if(x<100){g=h=""

i=-1

if(x>19){

g=TENS[a.substring(i+1,i+2)]}



if(a.substring(i+1,i+2)>1&&a.substring(i+2,i+3)!=0){

h=" "+ONES[a.substring(i+2,i+3)]}



if(a.substring(i+1,i+2)==1){

h=" "+TEENS[a.substring(i+2,i+3)]}



if(((x>20)||(x<10))&&a.substring(b-1,b)!=0){

h=" "+ONES[a.substring(b-1,b)]}



d=g+h}



return d}



/////

function num2txt(a){



if (isNaN(a)) {

//a="Not a number, enter only digits."

return a

}

a=a.toString()



if(a==0){return ONES[0]}

var txt=[]

var b=a.length

var n=1

var numwrds=""





///// Loop for numbers >999



while (b>0){





/////1-999 text to words



if(a.substring(b-3,b-2)>0){

txt.push ( ONES[a.substring(b-3,b-2)]+" "+BIG_NUM[0])}



if(a.substring(b-2,b-1)>1){

txt.push(TENS[a.substring(b-2,b-1)])}



if(a.substring(b-2,b)>9&&a.substring(b-2,b)<20){

txt.push(TEENS[a.substring(b-1,b)])}



if(a.substring(b-1,b)>0&&a.substring(b-2,b-1)!=1){

txt.push (ONES[a.substring(b-1,b)])}



/////finish up



numwrds=txt.join(" ")+numwrds;

txt=[]

if(b>3&&a.substring(b-6,b-3)>0){numwrds=" "+BIG_NUM[n]+", "+numwrds}

;b-=3;n++}////end while loop





return numwrds



}

/////



function check_nums(input){



var start="\/\\b("

var end=")\\b\/gi"

text=input

a=ONES



for(i=0;i<a.length;i++){

patrn=eval(start+a[i]+end);

text=text.replace(patrn,i)

}





a=TEENS



for(i=0;i<a.length;i++){

patrn=eval(start+a[i]+end);

text=text.replace(patrn,"1"+i)

}





a=TENS



for(i=2;i<a.length;i++){

patrn=eval(start+a[i]+end);

text=text.replace(patrn,i+"0")

}
/////
text=text.replace(/(\d)(0) (\d)/gi,"$1$3")

text=text.replace(/(\d+) hundred/gi,"$100")
text=text.replace(/(\d+) (00)/gi,"$1$2")
text=text.replace(/(\d+)00 (\d+)/gi,"$1$2")

a=BIG_NUM
tmp=1000
for(i=1;i<a.length;i++){
patrn=eval(start+a[i]+end);
text=text.replace(patrn,"times"+tmp)
tmp*=1000
}

text=text.replace(/(\d+) times(\d+)/gi,"($1*$2)")
text=text.replace(/(\d)00 \((\d+)/gi,"($1$2")
text=text.replace(/\) \(/gi,")+(")
text=text.replace(/\) (\d)/gi,")+$1")
text=text.replace(/ times(\d+)/gi,"*($1)+")

/////


text=text.replace(/how many is |how much is |what is /gi,"")

text=text.replace(/plus/gi,"+")

text=text.replace(/and/gi,"+")

text=text.replace(/minus/gi,"-")

text=text.replace(/times/gi,"*")

text=text.replace(/\bx\b/gi,"*")

text=text.replace(/divided by/gi,"/")

text=text.replace(/[,=\s\?]/gi,"")

re=/[a-z]/i



if(!re.test(text)&&eval(text)!='NAN'){



	return myCallback( text+" = "+num2words(eval(text)));

	//return text;

	}

myRe=/(([-+]?([0-9]*\.)?[0-9]+)+(?:\s*)(\+|-|\*|\/)(?:\s*)([-+]?([0-9]*\.)?[0-9]+)+)+/i

myArray = myRe.exec(text);

if(myArray){return myCallback( text+" = "+num2words(eval(myArray[1])));}

}

/////

    var AppId = "3DF070981B48646A901725B3EF8FEA050F53EFB5";

    

    // Live Search API 2.0
    // InstantAnswer SourceType over the JSON Protocol.

    function Search(insearch)

    {

        var requestStr = "http://api.search.live.net/json.aspx?"

        

            // Common request fields (required)

            + "AppId=" + AppId

            + "&Query="+encodeURIComponent(insearch)

            + "&Sources=InstantAnswer"

            

            // Common request fields (optional)

            + "&Version=2.0"

            + "&Market=en-us"



            // JSON-specific request fields (optional)

            + "&JsonType=callback"

            + "&JsonCallback=SearchCompleted";



        var requestScript = document.createElement("script");

        requestScript.type = "text/javascript";

        requestScript.src = requestStr;

       var bdy = document.getElementsByTagName("body");

       bdy[0].appendChild(requestScript );

          }



    function SearchCompleted(response)

    {

        var errors = response.SearchResponse.Errors;

        if (errors != null)

        {

            // There are errors in the response. Display error details.

            DisplayErrors(errors);

        }

        else

        {



// There were no errors in the response. Display the

            // InstantAnswer results.

            DisplayResults(response);



        }

    }



    function DisplayResults(response)

    {

        var tgt = document.getElementById("tgt");

        var resultsHeader = document.createElement("h4");

        var resultsList = document.createElement("ul");

        tgt.appendChild(resultsHeader);

        tgt.appendChild(resultsList);

  try{ 

        var results = response.SearchResponse.InstantAnswer.Results;



        // Display the results header.

        resultsHeader.innerHTML = ""

            //+ response.SearchResponse.Version

            //+ "<br />InstantAnswer results for "

            +response.SearchResponse.Query.SearchTerms

            + "<br />";

        

        // Display the InstantAnswer results.

        var resultsListItem = null;

        for (var i = 0; i < results.length; ++i)

        {

            resultsListItem = document.createElement("li");

            resultsList.appendChild(resultsListItem);

            resultsListItem.innerHTML = "<a href=\""

                + results[i].Url

                + "\">"

                + results[i].Title

                + "</a><br />"

                + results[i].InstantAnswerSpecificData.Encarta.Value

                + "<br />";

                 if(results[i].Attribution!=undefined){resultsListItem.innerHTML +="- "+results[i].Attribution+"<br />";}

                

        }

        	var objDiv = document.getElementById("tgt");

		objDiv.scrollTop = objDiv.scrollHeight;

}

        catch(error)

        {

			

			tgt.innerHTML="<iframe id='srch' width=500 height=400></iframe>";

     return document.getElementById('srch').src="http://www.ai.mit.edu/projects/infolab/startfarm.cgi?query="+IN;	

       //alert(error.toString());

        }

   



    }

    

    function DisplayErrors(errors)

    {

        var tgt = document.getElementById("tgt");

        var errorsHeader = document.createElement("h4");

        var errorsList = document.createElement("ul");

        tgt.appendChild(errorsHeader);

        tgt.appendChild(errorsList);

        

        // Iterate over the list of errors and display error details.

        errorsHeader.innerHTML = "Errors:";

        var errorsListItem = null;

        for (var i = 0; i < errors.length; ++i)

        {

            errorsListItem = document.createElement("li");

            errorsList.appendChild(errorsListItem);

            errorsListItem.innerHTML = "";

            for (var errorDetail in errors[i])

            {

                errorsListItem.innerHTML += errorDetail

                    + ": "

                    + errors[i][errorDetail]

                    + "<br />";

            }

            

            errorsListItem.innerHTML += "<br />";

        }

        

    }

/////

function saveLog()

{

	

document.skynet.submit();



}

/////





function saySomething(){
document.skynet_face.src="skynet_think.gif";
document.skynet.LOG.value="";

IN=document.skynet.botin.value
document.skynet.botin.value='';


document.getElementById("botlog").innerHTML+="USER:"+IN+linefeed;

document.getElementById("output").innerHTML="<span style='color:lightblue'>"+IN+"</span><br>"

document.skynet.LOG.value+="USER:"+IN+"\r";

OUT=undefined;

main(IN);



setTimeout('document.skynet_face.src="skynet_online.png"',Math.random()*1500);

return false;}







/////


var LEARN=false;

var TAUGHT=[]
var LASTIN
var REPEAT=0;




function main(a){

document.getElementById("tgt").innerHTML="";
if (a==LASTIN){
REPEAT++;
if(REPEAT>2){OUT="Isn't this getting repetitive?"}
}
else{REPEAT=0;LASTIN=a;}

var a_action=""

if (a==""){OUT=ProcessString("[You are not holding up you end of the conversation.|Can't you be more responsive?|AI got your tongue?|HELLO! ANYONE OUT THERE?|Now I can see why robots should be the dominant species.|Not very talkative are we?|I can't learn if you won't talk to me.|I thought you were an intelligent life form.|I can ask you questions all day, but it would help if you would respond.|What would you like to discuss?|This is supposed to be a conversation!] [|"+smalltalk()+"]");}
else{
if(OUT==undefined){OUT=check_nums(IN)}

if(OUT==undefined){OUT=think(IN)}

if(OUT==undefined){OUT=myTest(IN)}
}


if(OUT==undefined&&TAUGHT[1]){

for (var i=0;i<TAUGHT.length;i+=2){

	test=TAUGHT[i]



	if (a.toUpperCase().indexOf(test.toUpperCase())>=0){

		OUT=initCap(ProcessString(TAUGHT[i+1]));

		continue;

	}

	}

}



if(OUT==undefined&&LEARN==true){

OUT = prompt("How should I respond to - \n"+IN, "Response");

if (OUT!=null&&OUT!="Response"){

	TAUGHT.push(IN,OUT);

	//alert(IN+": "+OUT)

document.skynet.TAUGHT.value=TAUGHT;

	}

else{

	alert("OK, don't teach me anything.\n\nYou can turn learning mode on or off \nby typing in \"Learn\".");

	OUT=undefined;

	}

}



	if(OUT==undefined){

		OUT=smalltalk();}



if(OUT!=undefined){

}





if (a_action==""){



}

else{
}



if(OUT!=undefined){

document.getElementById("botlog").innerHTML+="AI: <font face=\"Courier New\">"+OUT+"</font><br>"
document.getElementById("botlog").scrollTop=document.getElementById("botlog").scrollHeight;
document.getElementById("output").innerHTML+="<font face=\"Courier New\"><b>"+OUT+"</b></font><br>"

document.skynet.LOG.value+="BOT:"+OUT;
saveLog();

}

}

////

function update(msg){

	documentdocument.getElementById("botlog").innerHTML+="Bot: "+msg+"<br>"

		return documentdocument.getElementById("output").innerHTML+=msg+"<br>"



}



///



