var versionN=6; 
var cupview=false;
var cuptype=0;
var cupviewi=false;
var logstate=0;
var logname="";
var lognamed="";
var logpassw="";
var logpasswd="";
var cupfindm=0;
var lastcindex=null;
var lastcindexm=0;
var mentick=[];
var mencross=[];
var lastTitle="";
var words=[];
var ing =[];
var jumpOnLoad=false;

var cbstrisp=[];
var cbstri=[];
var cbstrlen=0;

var resultspage=1;

var incdrop=[];
var incdropind=0;
var ifindshow=false;

var include=[];
var includeah=[];
var exclude=[];

var activedropid=1;
var drop1active=false;
var drop2active=false;
var drop3active=false;
var locationtimer=null;
var skipid=-1;
var hideResults=true;
var resultTitle=true;
var searchmod=0;
var suggmode=0;

var cupmenu_exp=[];
var suggstring=";";
var sugglarge=false;

var recipecats=["All recipes","Main &amp; Starters","     - Bread","     - Sandwiches",
"     - Salads","     - Soups &amp; Broths","     - Dips",
"     - Sauces","     - Casseroles &amp; Stews","     - Curries",
"     - Kebabs","     - Pasta","     - Pies &amp; Pastries",
"     - Rice Dishes","     - Roasts","     - Stir Fries","Desserts",
"     - Cakes","     - Cookies &amp; Biscuits","     - Ice Cream/Frozen",
"     - Fruit Puddings","     - Other Puddings","     - Candy",
"     - Chocolate","Drink","     - Alcoholic Cocktails",
"            - Shooters",
"            - Long Drinks",
"            - Party/Punch",
"     - Smoothies","            - Fruit Smoothies",
"            - Vegetable Smoothies","     - Juice Mixes",
"            - Fruit Juice Drink",
"            - Vegetable Juice Drink  ",
"     - Dairy Drink &amp; Milk Shake","     - Hot Beverages"];

var recipecathead=["","Main and Starter","Bread","Sandwich",
"Salad","Soup and Broth","Dip",
"Sauce","Casserole and Stew","Curry",
"Kebab","Pasta","Pie and Pastry",
"Rice Dish","Roast","Stir Fry","Dessert",
"Cake","Cookie and Biscuit","Ice Cream n Frozen Dessert",
"Fruit Pudding","Other Pudding","Candy",
"Chocolate","Drink","Alcoholic Cocktail",
"Alcoholic Shooter",
"Alcoholic Long Drink",
"Party Punch Drink",
"Smoothie","Fruit Smoothie",
"Vegetable Smoothie","Juice Drink",
"Fruit Juice Drink",
"Vegetable Juice Drink",
"Dairy Drink and Milk Shake","Hot Beverage"];


var cbCoder=['(',')','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M',
                 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l',
                 'm','n','o','p','q','r','s','t','u','v','w','x','y','z'];


var recipecatid=["","3","40","38","27","28","36","37","29","30","31","32","39","33","34","35","26","19","20","21","22","23","24","25","4","6","7","8","9","5","10","11","12","13","14","15","18"];

var thisPageLocation="";

var searchHelp0="<p>Change any of the above settings to search our recipe database.</p><p>When you start typing in the &#39;must include&#39; or " +
"&#39;must exclude&#39; ingredient boxes you should be presented with a list of ingredients that matches what you type. Ingredients that are grayed out " +
"can not be found in any recipes and so are not selectable.</p><p>The list will match " +
"against several words, for instance, type &#39;o j&#39; and a list will be presented with ingredients such as orange juice in it. When the ingredient" +
" you want is highlighted, press return. Use the arrow keys or mouse to select an item from the list.</p>";

var searchHelp1="<p>Change any of the above settings to search our recipe database.</p><p>We will provide the best recipe matches we can against " +
"the ingredients you have at hand. Click on a &#39;have at hand&#39; ingredient to highlight it, these highlighted ingredients <strong>must</strong> be included " +
"in the recipe search results.</p>" +
"<p>When you start typing in the &#39;I have at hand&#39; or " +
"&#39;must exclude&#39; ingredient boxes you should be presented with a list of ingredients that matches what you type. Ingredients that are grayed out " +
"can not be found in any recipes and so are not selectable.</p><p>The list will match " +
"against several words, for instance, type &#39;o j&#39; and a list will be presented with ingredients such as orange juice in it. When the ingredient" +
" you want is highlighted, press return. Use the arrow keys or mouse to select an item from the list.</p>";



function browserHeight()
{
  if (typeof(window.innerHeight)=='number')
    return window.innerHeight;
  if (document.documentElement && document.documentElement.clientHeight)
    return document.documentElement.clientHeight;
  if (document.body && document.body.clientHeight)
    return document.body.clientHeight;
  return 400;
}
function scrollY()
{
  if (typeof( window.pageYOffset)=='number' )
    return window.pageYOffset;
  if (document.body && document.body.scrollTop)
    return document.body.scrollTop;
  if (document.documentElement && document.documentElement.scrollTop)
    return document.documentElement.scrollTop;
  return 0;
}

function saveCS()
{
  if (cuptype==1)
    return "<td colspan='2' class='pl55'>" +
"<input type='button' id='cubsave' class='dynam' value='Save (Local)' onClick='javascript:saveCupboard()' />" +
"<input type='button' id='cubreset' class='dynam' value='Reset Cupboard' onClick='javascript:setCheckBoxesFromSaved()' />" +
"<input type='button' value='Create Account' onClick='javascript:createaccount(0)' /></td>";
    return "<td colspan='2' class='pl55'>" +
"<input type='button' id='cubsave' class='dynam' value='Save Cupboard' onClick='javascript:saveCupboard()' />" +
"<input type='button' id='cubreset' class='dynam' value='Reset Cupboard' onClick='javascript:setCheckBoxesFromSaved()' /></td>";
}

function getCookie(cname)
{
  if (document.cookie.length>0)
  {
    var i1=document.cookie.indexOf(cname + "=");
    if (i1>=0)
    {
      i1=i1 + cname.length+1;
      var i2=document.cookie.indexOf(";",i1);
      if (i2==-1) i2=document.cookie.length;
      return document.cookie.substring(i1,i2);
    }
  }
  return null;
}

function setCookie(cname,value,exdays)
{
  var cdate=new Date();
  cdate.setDate(cdate.getDate()+exdays);
  document.cookie=cname+ "=" + value + ";expires=" + cdate.toUTCString() + "; path=/";
}

function setSessionCookie(cname,value)
{
  document.cookie=cname+ "=" + value + "; path=/";
}


//ord gives the bit position for each ingredient
function initIngredients ()
{
  createIngList (ig);
}


function createIngList (wg)
{
  var addSpace=false;
  var index=0;
  var wx=0;
  for (var i=0; i<wg.length; i++)
  {
    var sp=0;
    var end=wg[i].length;
    ing[index]=[]; wx=0; ing[index][wx]="";
    while (sp<end)
    {
      var i1=wg[i].charCodeAt(sp);
      if (i1>92) i1-=41; else i1-=40;
      sp++;
      if (i1==84) 
      {
        if (addSpace) {wx++; ing[index][wx]="";}
        ing[index][wx] += wg[i].charAt(sp++);
        addSpace=true;
        continue;
      }
      if (i1==85) 
      {
        index++; addSpace=false;
        if (sp<end-1) {ing[index] = []; wx=0; ing[index][wx]="";}
        continue;
      }
      var i2=wg[i].charCodeAt(sp);
      if (i2>92) i2-=41; else i2-=40;
      sp++;
      var wi= (i1*86)+i2;
      if (addSpace) {wx++; ing[index][wx]="";}
      ing[index][wx]+=words[wi].replace(/&#39;/g, "'");
      addSpace=true;
    }
  }
}

function loadWordData (allWords)
{
  var index=0;
  for (var i=0; i<allWords.length; i++)
  {
    var sp=0;
    var end=allWords[i].length;
    while (sp<end)
    {
      words[index]="";
      for (var a=0; a<allWords[i].charCodeAt(sp)-65; a++) {words[index]+=words[index-1].charAt(a); }
      sp++;
      while (true)
      {
        if (allWords[i].charAt(sp)==':') {sp++; index++; break;}
        else if ((allWords[i].charAt(sp)>='A') && (allWords[i].charAt(sp)<='Z')) {words[index]+= String.fromCharCode(allWords[i].charCodeAt(sp)+32);  sp++; index++; break;}
        words[index]+=allWords[i].charAt(sp++);
      }
    }
  }
//document.write("<br>" + "number of words stored = " + words.length + ".<br>");
//for (var i=0; i<words.length; i++) document.write(words[i] + "<br>");
}

function dropkeyup (e, id)
{
   var key = (window.event) ? event.keyCode : e.keyCode;
   if (id==1)
   {
     if (drop2active) cleardrop(2,false);
     if (drop3active) cleardrop(3,false);
   }
   else if (id==2)
   {
     if (drop1active) cleardrop(1,false);
     if (drop3active) cleardrop(3,false);
   }
   else if (id==3)
   {
     if (drop1active) cleardrop(1,false);
     if (drop2active) cleardrop(2,false);
   }
   activedropid=id;
   if (key==13)
   {
     if (ifindshow && (incdropind>=0) && (incdropind<incdrop.length))
     {
       find(id,incdrop[incdropind]);
       return;
     }
   }
   if (key==27) {dropblur(id); return;} 
   if ((key==38) || (key==40)) return;
   ingredtext(id);
}

function dropkeydown (e,id)
{
   if (id==1)
   {
     if (drop2active) cleardrop(2,false);
     if (drop3active) cleardrop(3,false);
   }
   else if (id==2)
   {
     if (drop1active) cleardrop(1,false);
     if (drop3active) cleardrop(3,false);
   }
   else if (id==3)
   {
     if (drop1active) cleardrop(1,false);
     if (drop2active) cleardrop(2,false);
   }
   activedropid=id;
   if (ifindshow==false) ingredtext(id);
   else
   {
     var key = (window.event) ? event.keyCode : e.keyCode;
     if (key==27) {dropblur(); return;} 
     if (key==38) 
     {
       if (incdropind==0) {}//dropmousein(id,incdrop.length-1);
       else dropmousein(id,incdropind-1);
       return;
     }
     if (key==40) 
     {
       if (incdropind==incdrop.length-1) {}//dropmousein(id,0);
       else dropmousein(id,incdropind+1);
       return;
     }
   }
}

function ingredtext (id)
{
  if (id==1)
  {
    if (drop2active) cleardrop(2,false);
    if (drop3active) cleardrop(3,false);
    drop1active=true;
  }
  else if (id==2)
  {
    if (drop1active) cleardrop(1,false);
    if (drop3active) cleardrop(3,false);
    drop2active=true;
  }
  else if (id==3)
  {
    if (drop1active) cleardrop(1,false);
    if (drop2active) cleardrop(2,false);
    drop3active=true;
  }
  ifindshow=true;
  incdrop=[];
  var allincdrop=[]; var aid=0;
  var newhtml="<table class='ingdrop'>";
  var otxt;
  if (id==1) otxt = document.incf.inc.value.toLowerCase();
  else if (id==2) otxt = document.excf.exc.value.toLowerCase();
  else otxt = document.cubf.find.value.toLowerCase();
  var txt="";
  var c;
  var state=0;
  var i=0;
  var numw=1;
  while (i<otxt.length)
  {
    c= otxt.charAt(i);
    if ((c>='a' && c<='z') || (c=='\''))
    {
      if (state==1) {txt += ' ' + c; numw++;} 
      else txt += c;
      state=2;
    }  
    else if (c>='0' && c<='9')
    {
      if (state==2) {txt += ' ' + c; numw++;}
      else txt += c;
      state=1;
    }
//    else if (c=='-')
//    {
//      txt += ' - '; numw++;
//      state=0;
//    }
    else
    {
      if (state!=0) {txt+=' '; numw++;}
      state=0;
    }
    i++;
  }
  if (state==0) {txt=txt.substring(0,txt.length-1); numw--;} //trim space off end
  
  var idnum=0;
  var lsize=0;
  var sci=1;
  var fc=txt.charAt(0);
  var lastaddid=-1;
  if (txt.length>0)
  {
    mainfor:for (var i=0; i<ing.length; i++)
    {
      for (var woff=0; woff<=(ing[i].length-numw); woff++)
      {
       var wind=woff;
       if (ing[i][wind].charAt(0)==fc)
       {
        sci=1; var succ=true;
        checkloop:for (var sct=1; sct<txt.length; sct++) //match reset of text
        {
          var c=txt.charAt(sct);
          if (c==' ')
					{
						wind++; sci=-1;
						if (wind>=ing[i].length) {succ=false; break checkloop;}
						else if ((ing[i][wind]=='-') || (ing[i][wind]=='/')) wind++;
					}
          else if (sci>=ing[i][wind].length) {succ=false; break checkloop;}
          else if (c!=ing[i][wind].charAt(sci)) {succ=false; break checkloop;}
          sci++;
        }
        
        if (succ) for (ii=0; ii<allincdrop.length; ii++) if (ingid[allincdrop[ii]]==ingid[i]) {succ=false; break;}
        if (succ)
        { 
          allincdrop[aid++]=i;
          lastaddid=ingid[i];
          lsize++;
          var found=false;
          if (id!=3)
          {
            for (var ii=0; ii<include.length; ii++) if (ingid[i]==ingid[include[ii]]) {found=true; break;}
            if (!found)
              for (var ii=0; ii<exclude.length; ii++) if (ingid[i]==ingid[exclude[ii]]) {found=true; break;}
          }
          if (!found)
          {
            if (i<zp)
            {
              incdrop[idnum]=i;
              newhtml += "<tr><td id=\"drp" + id + "i" + idnum + "\" class=\"ingdropi\" onMouseOver=\"dropmousein(" + id + "," + idnum 
                    + ")\" ><a onFocus=\"canceldropblur()\" href=\"javascript:find(" + id + "," + i + ");\">&nbsp;";
              var thising="";
              for (var wx=0; wx<ing[i].length; wx++) newhtml+= ing[i][wx].replace(/'/g, "&#39;") + " ";
              newhtml += "</a></td></tr>";
              idnum++;
            }
            else 
            {
              newhtml += "<tr><td class=\"ingdropz\">&nbsp;";
              for (var wx=0; wx<ing[i].length; wx++) newhtml+= ing[i][wx].replace(/'/g, "&#39;") + " ";
              newhtml +=  "</td></tr>";
            }
          }
          else
          {
            newhtml += "<tr><td class=\"ingdropd\">&nbsp;";
            for (var wx=0; wx<ing[i].length; wx++) newhtml+= ing[i][wx].replace(/'/g, "&#39;") + " ";
            newhtml +=  "</td></tr>";
          }
          if (lsize>=15) break mainfor;
        }
      }
     }
    }
  }
  if (incdropind>=idnum) {incdropind=idnum-1; if (incdropind<0) incdropind=0;}
  document.getElementById("ingdrop" + id).innerHTML=newhtml + "</table>";
  if (incdrop.length>0) dropmousein(id,incdropind);
}

function dropmousein (id, idnum)
{
  document.getElementById("drp" + id + "i" + incdropind).className="ingdropi";
  incdropind=idnum;
  document.getElementById("drp" + id + "i" + incdropind).className="ingdropa";
}

function cleardrop (id, cleartxt)
{
  if (id==1) drop1active=false;
  else if (id==2) drop2active=false;
  else if (id==3) drop3active=false;
  
  document.getElementById("ingdrop" + id).innerHTML="";
  ifindshow=false;
  
  if (cleartxt)
  {
    if (id==1) document.incf.inc.value="";
    else if (id==2) document.excf.exc.value="";
    else document.cubf.find.value="";
  }
}

function dropblur (id)
{
  droptimer=window.setTimeout("cleardrop(" + id + ",false);",150);  
}

function canceldropblur () //used to ensure when a menu item is clicked, the blur event doesn't clear table before menu is activated
{
  if (droptimer) 
  {
    window.clearTimeout(droptimer);
    droptimer=null;
  }
}

function dropfocus (id)
{
  activedropid=id;
  ingredtext(id);  
}

function removei(id, index)
{
  var temp=[];
  var ind=0;
  if (id==1)
  {
    var tempah=[];
    for (var i=0; i<index; i++) {temp[ind]=include[i]; tempah[ind++]=includeah[i];}
    for (var i=index+1; i<include.length; i++) {temp[ind]=include[i]; tempah[ind++]=includeah[i];}
    include=temp; includeah=tempah;
  }
  else
  {
    for (var i=0; i<index; i++) temp[ind++]=exclude[i];
    for (var i=index+1; i<exclude.length; i++) temp[ind++]=exclude[i];
    exclude=temp;
  }
  displayIncludeList(id);
  updateHashLocation(1);
}

function displayIncludeList(id)
{
   var resmi=false;
   var newhtml="<table class='ingredbox'>";
   if (id==1) todisplay=include; else todisplay=exclude;
   for (var i=0; i<todisplay.length; i++) 
   {
     if ((searchmod==1) && (id==1))
     {
       if (!includeah[i]) newhtml+= "<tr><td class='delbut'><a href='javascript:removei(" + id + "," + i + ");'>X</a></td><td>&nbsp;<a class='athand' href='javascript:athandchange(" + i + ")'>" +  getIngName(todisplay[i]).replace(/'/g, "&#39;") + "</a></td></tr>";
       else {resmi=true; newhtml+= "<tr><td class='delbut'><a href='javascript:removei(" + id + "," + i + ");'>X</a></td><td>&nbsp;<a class='athandh' href='javascript:athandchange(" + i + ")'>" +  getIngName(todisplay[i]).replace(/'/g, "&#39;") + "</a></td></tr>";}
     }
     else newhtml+= "<tr><td class='delbut'><a href='javascript:removei(" + id + "," + i + ");'>X</a></td><td>&nbsp;" +  getIngName(todisplay[i]).replace(/'/g, "&#39;") + "</td></tr>";
   }
   if (resmi)  newhtml+= "<tr><td></td><td>&nbsp;<a class='brwnbld' href='javascript:unhighlight()'>un-highlight all ingredients</a></td></tr>";
   document.getElementById("ingredients" + id).innerHTML=newhtml + "</table>";

   if (id==2)
   {
     var allhtml="ingredients containing: ";
     for (var xx=0; xx<algt.length; xx++) 
     {
       var fndall=false;
       for (var yy=0; yy<exclude.length; yy++) if (exclude[yy]==algt[xx]) {fndall=true; break;}
       if (!fndall) allhtml+="<span class='sameline'>&nbsp;<a class='blckbld' href='javascript:find(2," + algt[xx] + ")'>"+getIngName(algt[xx]).replace(/'/g, "&#39;").substring(11) + "</a>&nbsp;</span> ";
     }
     document.getElementById("allergens").innerHTML=allhtml;
   }

}

function unhighlight()
{
  for (var i=0; i<include.length; i++) includeah[i]=false;
  displayIncludeList(1);
  updateHashLocation(1);
}

function find(id, index)
{
   incdropind=0;
   cleardrop(id,true);
   if (id==3)
   {
     var allI=-1;
     for (var i=0; i<algt.length; i++) if (algt[i]==index) allI=i;
     if (allI<0) openAllMenuForIng(ingid[index]);
     if ((lastcindex!=null) && (cupmenu_exp[lastcindexm]==1))
     {
       if (lastcindex.className.indexOf("norm">=0)) lastcindex.className="cbnorm";
       else lastcindex.className="cbuline";
     }
     //add - cupboard/diet list scroll to ingredient
     if (allI<0)
     {
       var cn=document.getElementById("cbing" + ingid[index]);
       if (cn!=null)
       {
         if (cn.className.indexOf("norm">=0)) cn.className="cbnormh";
         else cn.className="cbulineh";
         lastcindex=cn;
         scrollToIDadv ("cbing" + ingid[index],0);
       }
     }
     else
     {
       lastcindex=null; lastcindexm=0;
       if (cupfindm==1) cupgexc(allI,false);
       if (cupfindm==2) cupgexc(allI,true);
     }
   }
   else
   {
     if (id==1) {include[include.length]=index; includeah[include.length]=false;}
     else exclude[exclude.length]=index;
     displayIncludeList(id);
     updateHashLocation(1);
   }
}

function athandchange(index)
{
  includeah[index]=!includeah[index];
  displayIncludeList(1);
  updateHashLocation(1);
}

function searchmode(mode,updateH)
{
  searchmod=mode;
  if (mode==0) 
  {
    for (var i=0; i<includeah.length; i++) includeah[i]=false;
    document.getElementById("smode").innerHTML="<span class='hlight'>Normal</span> / <a class='mchange' href='javascript:searchmode(1,true)'>By Ingredients At Hand</a>";
    document.getElementById("incheader").innerHTML="<strong>Must Include:</strong>";
    document.getElementById("ingheader").innerHTML="";
    document.getElementById("titlehead").innerHTML="(best match)";
    document.getElementById("emphasis").className="hide";
    document.getElementById("searchhelptd").innerHTML=searchHelp0;
  }
  else
  {
    document.getElementById("smode").innerHTML="<a class='mchange' href='javascript:searchmode(0,true)'>Normal</a> / <span class='hlight'>By Ingredients At Hand</span>";
    document.getElementById("incheader").innerHTML="<strong>I Have at Hand:</strong>";
    document.getElementById("ingheader").innerHTML="Highlighted &#39;have at hand&#39; ingredients <strong>must</strong> be included in the recipe. Click on items to toggle highlight.";
    document.getElementById("titlehead").innerHTML="(match all) ";
    document.getElementById("emphasis").className="show";
    document.getElementById("searchhelptd").innerHTML=searchHelp1;

//<span id='incheader'><strong>Must Include:</strong><span>
  }
  if (updateH) 
  {
    displayIncludeList(1);
    updateHashLocation(1);
  }
}


