  var devflag=false;
  // var fullpath="http://pie.usna.edu/";
  var fullpath="";
  var searched="";
  var regexpmatch=false;
  var tamecardspace=false;
  var tamecardnull=false;
String.prototype.trim = function()
{
  // Use a regular expression to normalize the string
  var s = this.replace (/\s+/g, " ");
  return s.replace(/(^\s+)|(\s+$)/g, "");
}
String.prototype.normalize = function()
{
  // Use a regular expression to normalize the string
  var s = this.trim().toLowerCase();
  s = s.replace(/~/g, " ~ ");
  s = s.replace(/~\s+(-*){/g, " ~$1{");
  s = s.replace(/\+/g, " + ");
  s = s.replace(/\[/g, " [");
  s = s.replace(/}/g, "} ");
  s = s.replace(/\s+/g, " ");
  s = s.replace(/-\s+/g, "-");
  s = s.replace(/\s+{/g, "{");
  s = s.replace(/}{/g, "&");
  s = s.replace(/\s+-{/g, "-{");
  s = s.replace(/\s+-\[/g, "-[");
  s = s.replace(/\s+\]/g, "]");
  s = s.trim();
  s = s.replace(/[^a-z'_\*\-\+~ ,#\[\]\{\}\?\d&@]/g, "");
  return  s;
}
   var fused = new Object();
   fused["ain't"]="ai n't"; fused["aren't"]="are n't"; fused["can't"]="can n't"; fused["cannot"]="can not"; fused["couldn't"]="could n't"; fused["d'you"]="d' you"; fused["didn't"]="did n't"; fused["doesn't"]="does n't"; fused["don't"]="do n't"; fused["dont"]="do nt"; fused["dunno"]="du n no"; fused["gonna"]="gon na"; fused["gotta"]="got ta"; fused["hadn't"]="had n't"; fused["hasn't"]="has n't"; fused["haven't"]="have n't"; fused["he's"]="he 's"; fused["innit"]="in n it"; fused["isn't"]="is n't"; fused["shan't"]="sha n't"; fused["she's"]="she 's"; fused["that's "]="that 's"; fused["there's"]="there 's"; fused["they've"]="they 've"; fused["tis"]="t is"; fused["wanna"]="wan na"; fused["wasn't"]="was n't"; fused["weren't"]="were n't"; fused["we've"]="we 've"; fused["won't"]="wo n't"; fused["wouldn't"]="would n't";
   var mwus="#'s,abit,agooddeal,agreatdeal,ala,alacarte,alittle,alittlebit,alot,apriori,accordingto,adhoc,adlib,adjacentto,aheadof,allatonce,allbut,allofasudden,allright,allthesame,alongwith,anawfullot,andsoforth,andsoon,anylonger,anythingbut,apartfrom,asagainst,asbetween,asfor,asfrom,asif,asitwere,aslongas,asof,asopposedto,asregards,assoonas,asthough,asto,asusual,aswellas,asyet,asidefrom,atall,atbest,atfirst,atlarge,atlast,atleast,atlength,atlonglast,atmost,atonce,atpresent,atrandom,atworst,awayfrom,becauseof,bonafide,brandnew,butfor,byandlarge,byfar,bymeansof,bynomeans,bynow,byreasonof,bywayof,consideringthat,contraryto,defacto,dependingon,dueto,eachother,enmasse,enroute,ensuite,etal,evenif,evenso,eventhough,evenwhen,everso,everysooften,exparte,exceptfor,exceptthat,farfrom,fedup,followup,forcertain,forever,forexample,forfearof,forgood,forinstance,forlong,foronce,forsure,forthemostpart,forthetimebeing,fromnowon,fromtimetotime,giventhat,grandprix,guardianadlitem,halfway,inaccordwith,inaccordancewith,inaddition,inadditionto,inaidof,inanswerto,inassociationwith,inbetween,inbrief,incase,incaseof,inchargeof,inco-operationwith,incommon,incommonwith,incomparisonwith,inconjunctionwith,inconnectionwith,inconsultationwith,incontactwith,indefenceof,indefianceof,inexcessof,infavourof,infrontof,infull,ingeneral,inkeepingwith,inlieuof,inlightof,inlinewith,inneedof,inorder,inpart,inparticular,inplaceof,inpossessionof,inprivate,inproportionto,inpublic,inpursuitof,inreceiptof,inregardto,inrelationto,inreplyto,inrespectof,inresponseto,inreturnfor,insearchof,inshort,insitu,insofaras,inspiteof,insupportof,intermsof,inthat,inthelightof,inthemain,intouchwith,invain,inviewof,invitro,invivo,insideout,insofaras,insteadof,interalia,intolinewith,irrespectiveof,justabout,kindof,kungfu,lessthan,letalone,morethan,nearto,nearerto,nearestto,nextto,nodoubt,nolonger,nomatterhow,nomatterwhat,noone,noneother,nonetheless,nowthat,ofcourse,offof,oldfashioned,onaccountof,onbehalfof,onboard,onthepartof,onto,ontopof,onceagain,onceandforall,oncemore,oneanother,otherthan,outof,outofdate,outoftouchwith,outsideof,overhere,overthere,owingto,perannum,percapita,percent,perse,pertainingto,postmortem,primafacie,priorto,providedthat,providingthat,pursuantto,raisond'etre,ratherthan,relativeto,savefor,seeingthat,sinnfein,soas,socalled,solongas,somuchas,sothat,sortof,statusquo,straightaway,subjectto,subsequentto,suchas,suchthat,thanksto,thatis,thatistosay,timeandagain,timeandagain,toandfro,ultravires,underway,upfront,upto,uptodate,upuntil,upsidedown,upwardsof,viceversa,welloff,whetherornot,withaviewto,withreferenceto,withregardto,withrespectto,".split(',');
   var mwu=new Object();
   var ml = mwus.length -2;
   for (var i=0; i< ml; i++)
   { mwu[mwus[i]]=true;}
   mwus=null;
   var sp=' ';

function writefield(targ, field, val)
{
  targ.write("<input type='hidden' name='" + field + "' value=\"" + val + "\">\n");
}

function defuse(gram)
{
  var grams = gram.split(" ");
  for (var i=0; i<grams.length; i++)
  {
    if (fused[grams[i]])
    {
      grams[i] = fused[grams[i]];
    }
  }
  return grams.join(" ");
}
function checkSearched(thisgram)
{
  if (searched.indexOf("|" + thisgram + "|") == -1)
  {
    searched += thisgram + "|";
    return true;
  }
  else
  {
    return false;
  }   
}
function goWild(gram)
{
  var save;
  if (gram.indexOf("~") > -1)
  {  var thisgram="";
    var grams = gram.split(" ");
    var gl = grams.length - 1;
    for (var z=gl; z>=0; z--)
    {
      if (grams[z].trim().slice(0,1)=="~")
      {
        save=grams[z];
        grams[z]="";
        thisgram = grams.join(" ").trim();
        if (checkSearched(thisgram))
        {
          spawnSearch(thisgram);
          goWild(thisgram);
        }
        grams[z]=save;
      }
    }
  }
}

function wildwordSearch(gram)
{ 
    var tmp, i = gram.indexOf("[");
    if (i > -1)
    {
        var ar = gram.split("[");
        for (i = 1; i < ar.length; i++)
        {
        tmp = ar[i].split("]");
        tmp[0] = tmp[0].replace(/\s+/g, ",");
      ar[i] = tmp.join("]");
    }
      gram = ar.join("[");
    }
    spawnSearch(gram);
    searched="|" + gram+ "|";
    goWild(gram);
  }
  
function tamecard(gram)
{ 
  var res="", toomany;
  var findhyph= new RegExp();
  findhyph=/\w+(-\w+)+/g;
  matched=true;
  j=0;
  while (matched!=null)
  {
    matched = findhyph.exec(gram);
    if (matched!=null)
    { 
      res+="\n\n" + ++j + " " + RegExp.lastIndex + "\n" + RegExp.lastMatch;
      lm = RegExp.lastMatch;
      lc = RegExp.leftContext; 
      rc = RegExp.rightContext; 
      if (tamecardspace)
      {
        res = lc + lm.replace(/-/g," ") + rc;
        toomany = res.split(" ");
        if (toomany.length<7 && checkSearched(res)) {spawnSearch(res)};
      }
      if (tamecardnull)
      {
        res = lc + lm.replace(/-/g,"") + rc;
        if (checkSearched(res)) {spawnSearch(res)};
      }
    }
  }
}

function setValue(id, val)
{  
   var el=document.getElementById(id) || document.getElementsByName(id)[0];
   el.value=val;        
}
function readValue(id)
{  
   try
   { var el=document.getElementById(id).value; }
   catch (e)
   { el=document.getElementsByName(id)[0].value; }
   return el;        
}

function spawnSearch(gram)
{ 
  if (tamecardnull || tamecardspace)
  {
    tamecard(gram);
  }
  if (!devflag)
  {
    var pat="", keep1="", keep2="", sp=' ', extra="";
    gram = gram.trim();
    var words=gram.split(sp);
    var p, j, tmp, num = words.length;
    var exw=new Array(num);
    var exp=new Array(num);
    var tabflag = (document.location.href.indexOf("Tab.")>0) ? "Tab" : "";
    var target=fullpath + 'bexplorengrams' + tabflag + '.php';
    var title="&quot;" + gram + "&quot; - Simple Search in the BNC";
    var wn = window.open("", "", "scrollbars=1,dependent=1,location=0,menubar=1,resizable=1,toolbar=0,directories=0");
    while (!wn) { }
    var doc=wn.document;
    doc.open();
    doc.write("<HTML><HEAD><TITLE>" + title + "</TITLE></HEAD>");
    doc.write("<BODY style='background-color:#ECECEC;color:#000080;font-family:tahoma, verdana, arial, helvetica'><p style='font-size:xx-small;' align='center'><a href='index.html'>&quot;Phrases in English&quot; Home</a><span style='margin-left:1em;margin-right:1em;'>|</span><a href='javascript:window.close();' title='Close this window'>Close</a></p>");
    // Double quotes for values as they may contain apostrophes
    // Double quotes for values as they may contain apostrophes
    // Mar 05 -- support tabbed output
    doc.write('<form id="frmsimplesearch" action="' + target + '" method="post">');
    writefield(doc,'order', 'desc');
    writefield(doc,'showtable', 'ON');
    writefield(doc,'startwith', 1);
    writefield(doc,'showmax', readValue('showmax'));
    writefield(doc,'max', '');
    writefield(doc,'min', readValue('min'));
    if (!tabflag || !document.getElementById("nopos").checked)
    {
      writefield(doc,'showpos', 'ON');
    }    
    if (regexpmatch)
    {
      writefield(doc,'searchtype', 'reTab');
      writefield(doc,'minn', readValue('minn'));
      writefield(doc,'maxn', readValue('maxn'));
      writefield(doc,'regex', gram); 
      pat = gram.replace(/\\\/\?\*/g, "");    
      extra = " -- regular expression searches can take a minute or longer";
      alert(pat);
    } 
    else
    {
      writefield(doc,'searchtype', 'simple' + tabflag);
      writefield(doc,'num', num);
    }
    
    for (i=0; i<num; i++)
    {
      if (words[i]!="~" && words[i]!="+")
      { 
        // exclude?
        if (words[i].slice(0,1)=="-")
        {
          writefield(doc,'excludeword' + (i + 1), "ON");
          words[i] = words[i].slice(1);
          keep1 = "NOT ";
        }
        // POS?
        p = words[i].indexOf("{");
          if (p > -1)
          {  
            tmp = words[i].slice(p+1, -1);
          j = tmp.indexOf("}");  // in case of multiple {}{}
            if (j > -1)
          { tmp=tmp.slice(0,j);}
            tmp = tmp.toUpperCase();
            tmp = tmp.replace(/&/g, " ");
            writefield(doc,'matchpos' + (i + 1), tmp);
            keep2 = tmp;
            if (words[i].slice(p-1,p)=="-")
            {
              writefield(doc,'excludepos' + (i + 1), "ON");
              p--
              keep2="NOT "+keep2;
            }
            words[i] = words[i].slice(0,p)
          }
          tmp = words[i].replace(/\[|\]/g, "");
          tmp = tmp.replace(/,/g, " ");
          tmp = tmp.replace(/\d+/g, "#");
          pat += keep1 + tmp + sp + keep2 + sp;
          if (tmp != "+" && tmp !="~")
          { 
            writefield(doc,'matchword' + (i + 1), tmp);
          }
        }
      }
      
      pat = pat.trim();
      writefield(doc,'filename', pat);  // Tab only
      pat="<p style='text-size:large;font-weight:bold;'>Your search for &quot;" + pat.trim() + "&quot; has been submitted<br>     please be patient...</p>";
      doc.write(pat);
      doc.write("</FORM></BODY></HTML>");
      doc.close();
      doc.getElementById('frmsimplesearch').submit();
    }
    else
    {
      alert("Searching for: " + gram);
    }
}

function getmwu(gram)
{    
  var sp=' ';
  var dst='', src, cmp, i, j;
  src = gram.split(sp);
  var sl = src.length;
  for (i=0; i<sl; i++)
  {
    cmp=src.slice(i, i + 4);
    j = cmp.length;
    while (!mwu[cmp.join('')] && j > 1)
  { cmp.pop(); j--; }
    dst += cmp.join('_') + sp;
    i = i + j - 1;
  }
  return dst.trim();
}

function checkform()
{
  var msg="";
  var find = document.getElementById("find");
  var gram = find.value;
  if (!regexpmatch)
  {
    gram=gram.normalize();
    gram = getmwu(gram);
    gram = defuse(gram);
    s = gram.split(" ");
    // Only works when mwu and fused have been treated
    if (s.length > 8)
    {
      msg=' - Please enter a maximum of 8 "words".\n';
    }
  }
  find.value=gram.trim();
  if (gram.length < 1)
  {
    msg=" - Please enter a string to match.\n";
  }
  if (msg.length > 0)
  {
    alert("Your query has errors:\n" + msg);
  }
  else
  {
    searched="";  // reset
    if (regexpmatch)
    {
      spawnSearch(gram);   
    }
    else
    {
      wildwordSearch(gram);
    }
  }
}

function showhide(what, flag)
{
  if (flag)
  {
    what.style.display=""
  }
  else
  {
    what.style.display="none"
  }
}

function toggleDiv(divid, src)
{ var what=document.getElementById(divid).style;
  var state=(what.display=="none")?"":"none";
  what.display=state;
  if (src)
  {
    state=(state)?"Show":"Hide";
    src.innerHTML=state+src.innerHTML.slice(src.innerHTML.indexOf(" "));
  }
}

function addPOS(val)
{
  if (val)
  {
  val = "{" + val + "}";
    var search = document.getElementById("find");
    //IE 
    if (search.value.indexOf("|") > -1)
    {
      search.value = search.value.replace(/\|/g,val);
    }
    else if (document.selection) 
    {
      search.focus();
      sel = document.selection.createRange();
      sel.text = val;
    }
    else
    {
      search.value += val;
    }
  }
}
function submitter(ev)
{
  ev=ev||event;
  if (ev.keyCode==13)
  {
    checkform();
  }
}
function startpage()
{
  if (top.location != location) {top.location.href = location.href;}
  // add event handler for query field
  document.getElementsByName("find")[0].onkeypress=submitter;
}
function addPOS()
{
  var pos=document.getElementById("POS");
  var val = pos.options[pos.selectedIndex].value
  if (val)
  {
    val = "{" + val + "}";
    var find=document.getElementById("find");
    
    //IE 
    if (find.value.indexOf("|") > -1)
    {
      find.value = find.value.replace(/\|/g,val);
    }
    else if (document.selection) 
    {
      find.focus();
      sel = document.selection.createRange();
      sel.text = val;
    }
    else
    {
      find.value += val;
    }
  }
}

function explainRegEx(src)
{
  var texts= new Array('Hide Explanation','Explain Regular Expressions');
  if (src.value==texts[0])
  {
     src.value=texts[1];
     document.getElementById("regexnotes").style.display='none';
     return false;
  }
     src.value=texts[0];
     var div = document.getElementById("regexnotes");
     div.style.display='';
     if (div.childNodes.length>10)
     {  // text already fetched
       return false;
     }
    var httpRequest;
    if (window.XMLHttpRequest) 
    { // Mozilla, Safari, ...
        httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) 
    { // IE
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    httpRequest.open("GET", "regexnotes.txt", true);
    httpRequest.send(null);
    // register callback function to process feedback asynchronously
    httpRequest.onreadystatechange = function() { showNotes(httpRequest); };
}

function showNotes(httpRequest)
{
  if (httpRequest.readyState == 4) 
  {
    if (true || httpRequest.status == 200)
    {
      document.getElementById("regexnotes").innerHTML=httpRequest.responseText;
    }
    httpRequest=null;
  }
}

