
<!-- Begin 
var prevcolor;  //may be not used anymore
var currRecipe = new Object; //mealplan variable
var env_path = '';
var recipelookup = '';
var currtd;             //current td element that a recipe lookup has been clicked for (to allow to refocus and set values when finished with lookup)
var curridvalue = '';   //recipe id value
var currnamevalue = ''; //recipe name value
var current_tab = ''; //currently set tab
var foodcircles = ["apple", "apple_crumble", "apple_juice", "asian", "asian_soup", "asparagus",
"beans", "bread", "bread_pudding", "caviar_sushi", "cereal", "cheesy_toast", "chickpea_salad",
"chips", "chocolate_cake", "chocolate_shavings", "chocolates", "coffee_cake", "dessert", "egg", 
"fresh_strawberries", "garlic", "garlic_toast", "grain", "hot_milk", "ice_cream", "juice", "meat", 
"new_potatoes", "onions", "pizza", "pudding", "roll", "rum_balls", "salad", "sandwiches", 
"sausage_pizza", "spaghetti", "strawberries", "sugared_almonds", "sushi", "toast"];
var handlerFunc = function(t) { alert('john says:' + t.responseText); } ;

function process_intro(option)
{
	if (option == 'skip')
	{
		option2 = 'recipes';
		extra = '&startfilter=true';
		action = 'list';
	}
	else 
	{
		option2 = option;
		extra = '&bypass=1';
		action = 'new';

	}
	set_tab('tab_' + option2);
	newAjax('top_nassles', env_path + '/' + option2 + '/' + action + '?update=top_nassles&return_page=1' + extra);
	document.getElementById('showintro_button_hidden').click();
}


function set_tab(tab)
{
  if (current_tab != '') document.getElementById(current_tab).className = ''
  document.getElementById(tab).className = "current"
  current_tab = tab
  //set_foodcircle()
}


function set_foodcircle()
{
  rndNo = Math.floor(Math.random()* foodcircles.length)
  fc_curr = document.getElementById("food_circle")
  fc_curr.alt = foodcircles[rndNo]
  fc_curr.title = foodcircles[rndNo]
  fc_curr.src = env_path + "/images/food_circles/" + foodcircles[rndNo] + ".jpg"
}

function newAjaxForm(update, url, obj)
{
  return eval(ajaxString(update, url, obj))
}
function newAjax(update, url)
{
  set_foodcircle()
  return eval(ajaxString(update, url))
}
function ajaxString(update, url, obj)
{
  loading = "showLoading()"
  complete = "showComplete()"
  if ((url.indexOf('/recipes/edit') >= 0) || (url.indexOf('/recipes/update') >= 0) || (url.indexOf('/recipes/create') >= 0)) complete = "exec_script('recipe_change_div')"
  if ((url.indexOf('/shoppinglists/edit') >= 0) || (url.indexOf('/shoppinglists/update') >= 0) || (url.indexOf('/shoppinglists/create') >= 0) || (url.indexOf('/shoppinglists/new') >= 0)) complete = "exec_script('shoppinglist_change_div')"
  //if (complete != "showComplete()") alert(complete)

  if (obj) strForm = ", parameters:Form.serialize(obj)"
  else strForm = ""

  return 'new Ajax.Updater(update, url, {asynchronous:true, evalScripts:true, onComplete:function(request){' + complete + '}, onLoading:function(request){' + loading + '}' + strForm +'});'
}

//show progress of ajax calls
function showLoading() 
{
	document.getElementById("screen_progress").innerHTML = "&nbsp;&nbsp;WORKING ...&nbsp;&nbsp;";
	document.getElementById("screen_msg").innerHTML = "";
}
function showComplete() 
{ 
   document.getElementById("screen_progress").innerHTML = "";
   setFocus();
   //alert(name)
   if (document.getElementById("hidden_msg")) 
   {
     hiddenmsg = document.getElementById("hidden_msg");
     document.getElementById("screen_msg").innerHTML = hiddenmsg.innerHTML;
     new Effect.Opacity('screen_msg', { duration: 2.0, transition: Effect.Transitions.linear, from: 1.0, to: 0.15 });
     hiddenmsg.innerHTML = "";
   }

   //if (name!='pickanotherlist' && document.getElementById("tmp_msg"))
   //{
   //  new Effect.Opacity('tmp_msg', { duration: 2.0, transition: Effect.Transitions.linear, from: 1.0, to: 0.15 });
   //}
}

function showScreenMsg(currmsg)
{
    document.getElementById("screen_msg").innerHTML = currmsg;
    new Effect.Opacity('screen_msg', { duration: 0.7, transition: Effect.Transitions.linear, from: 1.0, to: 0 });
}

function set_env_path(the_path)
{
  env_path = the_path
//  recipelookup = 'new Ajax.Updater(\'AJAXID\', \'' + env_path + '/recipes/lookforrecipe?parentpartial=globals%2Fmealplanrecipe&amp;return_recipe_id=RRIVAL&amp;update=AJAXESCID&amp;return_recipe_name=RRNVAL&amp;return_name=RECIPEVAL&amp;return_page=1&startfilter=true\', {asynchronous:true, evalScripts:true, onComplete:function(request){showComplete()}, onLoading:function(request){showLoading()}});'
  recipelookup = 'new Ajax.Updater(\'AJAXID\', \'' + env_path + '/recipes/lookforrecipe?parentpartial=globals%2Fmealplanrecipe&return_recipe_id=RRIVAL&update=AJAXESCID&return_recipe_name=RRNVAL&return_name=RECIPEVAL&return_page=1&startfilter=true\', {asynchronous:true, evalScripts:true, onComplete:function(request){showComplete()}, onLoading:function(request){showLoading()}});'
}


function setdivclass(divname, divclass) 
{ 
  document.getElementById(divname).className = divclass
}


function setRecipeID(e) {
  idname = e.name.replace('recipe_name', 'recipe_id')
  the_id = document.getElementById(idname)
  the_id.value = ""
}

function hiddendiet(n)
{//maybe able to replace this with toggle javascript - used to select diet in mealplan
if (n == 0) return true 
else return false
}



//mealplanner functions
function rChanged(pref) {
  prefid = pref + '[recipe_id]'
  prefname = pref + '[recipe_name]'
  newRID = document.getElementById(prefid).value
  newRNAME = document.getElementById(prefname).value
  oldRID = currRecipe[prefid] 
  oldRNAME = currRecipe[prefname] 
  if ((newRID != oldRID) || (newRNAME != oldRNAME))
  {
    //alert('Current [' + oldRID + ']\n[' + oldRNAME + ']\n\nNew  [' + newRID + ']\n[' + newRNAME + ']')
    maintChanged(document.getElementById(prefname), 'mp_save_button')
  }
  return false
}

function lookforRecipe(pref, rt_name) {

  currRecipe[pref + '[recipe_id]'] = document.getElementById(pref + '[recipe_id]').value
  currRecipe[pref + '[recipe_name]'] = document.getElementById(pref + '[recipe_name]').value
  currtd = pref
  curridvalue = currRecipe[pref + '[recipe_id]'] 
  currnamevalue = currRecipe[pref + '[recipe_name]']

  str = recipelookup.replace('RRIVAL', curridvalue)
  str = str.replace('RRNVAL', encodeURIComponent(currnamevalue).replace(/'/g, "\\\'"))
  str = str.replace(/AJAXID/g, 'top_lookuprecipe_div')
  str = str.replace('AJAXESCID', encodeURIComponent('top_lookuprecipe_div'))
  str = str.replace('RECIPEVAL', rt_name.replace(/'/g, "\\\'"))
  //alert(str)
  //if (document.getElementById("hidden_msg"))	document.getElementById("hidden_msg").innerHTML = "" 
  setdivclass('top_mealplan_div', 'notdisplayed') 
  eval (str)
  setdivclass('top_lookuprecipe_div', 'mealplan') 
  return false;
}
function selectRecipe(rid, rname) {
  curridvalue = rid
  currnamevalue = rname
  endlookforRecipe()
  return false;
}
function endlookforRecipe() {
  setdivclass('top_lookuprecipe_div', 'notdisplayed') 
  document.getElementById(currtd + '[recipe_id]').value = curridvalue 
  document.getElementById(currtd + '[recipe_name]').value = currnamevalue 
  setdivclass('top_mealplan_div', 'mealplan') 
  document.getElementById('top_lookuprecipe_div').innerHTML = '' 
  focusfield = document.getElementById(currtd + '[recipe_name]')
  rChanged(currtd)
  new Effect.Highlight(document.getElementById(currtd + '[recipe_name]'), {duration: 1.0, startcolor: '#000000', backgroundColor: '#ffffff'})
  setTimeout("focusfield.focus()", 250)
  return false;
}



//send email form validation
function validate_send_email(btn) {
  btn.disabled = true
  failed = false
  if (trim(document.getElementById('email_to').value) == "")
  {
    alert('You must enter an Email To!')
    failed = true
  }
  if (!emailCheck (trim(document.getElementById('email_to').value))) failed = true

  if (trim(document.getElementById('email_subject').value) == "")
  {
    alert('You must enter an Email Subject!')
    failed = true
  }
  if (trim(document.getElementById('email_content').value) == "")
  {
    alert('You must enter an Email Content!')
    failed = true
  }

  if (!failed)
  {
    commitbtn = document.getElementById('se_button_hidden')
    commitbtn.click();
  }
  btn.disabled = false;
}


//generic form validation
function validate_it(btn, commit_btn_name, arrObj, arrObjblanksok) {
 btn.disabled = true
 commitbtn = document.getElementById(commit_btn_name)
 currform = commitbtn.parentNode.parentNode
 full_status = 0
 for (obji = 0;obji < arrObj.length; obji++)
 {
  switch (val_common(arrObj[obji], arrObjblanksok[obji], currform)) 
  {
  case 0: 
	break
  case 1: 
	full_status = 1;
	break
  default: 
	return false;
  }
 }

 if (full_status == 0) commitbtn.click();
 else alert('You have errors.  Fields with errors have been marked in red.\n\nYou can get a description of any of the errors by hovering your mouse over the relevant red box.');
}



function val_common(theObj, blanks_ok, theForm) {
//returns 0 = successful, 1: errors, 2: system error
 are_errors = false
 blankline = true //ignore any fields before 1st table column

 for (i = 0;i < theForm.length; i++)
 {
    error_msg = ""
    does_start_with = starts_with(theForm.elements[i].name, theObj.tablename + '[')
    does_end_with = ends_with(theForm.elements[i].name, '[' + theObj.colorder[0] + ']')
    if (does_start_with && does_end_with)
    {
	//current field is the first column in the row
      blankline = chkblankline(theForm, i, theObj.colorder)
    }

    if (does_start_with) //is a table column
    {
      if (!blankline)	//ignore blank lines
      {
	  column_value = trim(theForm.elements[i].value)
	  if (!blanks_ok)
	  {	
	    if (column_value  == "") error_msg = 'This field can\'t be empty.'
	  }
	  if (error_msg == "")
	  {
	    the_index = get_column(theForm.elements[i].name, theObj)
          if ((the_index < 0) || (the_index > (theObj.coldbsize.length - 1)) )
	    {
		alert("System Error: No Valid Column Found");
		return 2;//system error
	    }
	    else
	    {
		//check length restrictions
		if (column_value.length > theObj.coldbsize[the_index]) error_msg = 'This value is too long.  It has ' + column_value.length + ' characters.  The maximum is ' + theObj.coldbsize[the_index] + '.';
            if (error_msg == "")
		{
			switch (the_index)
  			{
			  case 0: 
				if (theObj.divname == 'ings')
				{//ingredients iamount must be numeric
      		  	  if (column_value.match(/^(\d+(\.\d+|)|\.\d+)$/g) == null) error_msg = 'This field must be a  positive number.'
				}
				if (theObj.divname == 'tags') error_msg = used_before(i, theForm, theObj, the_index, column_value, 'tag') 
			  	break;
			  case 2: 
				if (theObj.divname == 'ings') error_msg = used_before(i, theForm, theObj, the_index, column_value, 'tag') 
			  	break;
			}
		}
	    }
	  }
      }
	if (error_msg != "")
	{
		  theForm.elements[i].style.border = '2px solid red'
		  theForm.elements[i].title = error_msg
		  are_errors = true
	}
	else theForm.elements[i].style.border = '1px solid blue'
    }
  }

  if (are_errors) return 1;//errors
  else return 0;//success
}




function used_before(pi, pForm, pObj, pColind, pColval, txt) {
  for (pj = pi - 1; (pj > -1); pj--)
  {
	if (get_column(pForm.elements[pj].name, pObj) == pColind)
   	{
	  if (pColval == trim(pForm.elements[pj].value)) return 'This ' + txt + ' can only be entered once in a recipe.'
	}
  }
  return ""
}
//end generic validation



//attempt to pick out ingredient information from a textarea
function extract_ingredients(ingObj) {

 instr = trim(document.getElementById('tmp_ingredients').value).toLowerCase()
 if (instr == "")
 {
   alert('You haven\'t entered any ingredients')
   return
 } 
 //split text in lines 
 inglines = instr.split('\n')
 linecount = 0
 lineno = new Array()
 for (i=0;i<inglines.length;i++)
 { 
      checkstr = ltrim(inglines[i])
	if (checkstr != "")
 	{
		colval = new Array(3)
      	a_match = checkstr.match(/^(\d+(\.\d+|\s*\/\s*\d+|\s+\d+\s*\/\s*\d+|\s+and\s+\d+\s*\/\s*\d+|)|\.\d+)/g) //match the first number (integer, decimal or fraction)
		a_matchstr = (a_match + '').replace('and','   ') //remove 'and' if of format 3 and 3/4
	      if (a_match == null) a_match = 1;
		else checkstr = ltrim(checkstr.substring(a_matchstr.length));

            b_match = a_matchstr.match(/^\d+\s+\d+\s*\/\s*\d+/g) //check for '5 3/4' type number
            if (b_match == null) eval('colval[0] = ' + a_match)
		else
		{
			b_matchstr = b_match + ''
			num1 = b_matchstr.match(/^\d+/g) //get integer part
			num2 = b_matchstr.match(/\s+\d+\s*\/\s*\d+/g) //get fraction part
			eval('colval[0] = ' + num1 + ' + ' + '(' + num2 + ')')
		}
		
		//match the next bracketed expression plus the next set of non-space characters or just the next set of non-space characters.
      	a_match = checkstr.match(/^(\(.*\)\s*|)\S*/g) 
		if (a_match == "") alert('error: ' + inglines[i])
		else
		{
              	colval[1] = (a_match + '')
			colval[2] = ltrim(checkstr.substring((a_match + '').length))
			lineno[linecount] = colval
			linecount += 1
		}
	}
 }

 outstr = ""
 for (ii=0;ii<lineno.length;ii++) 
 {
   outstr += (ii + 1) + ': -- ' + lineno[ii] + '\n'
   copyRow('ing', ingObj, lineno[ii])
 }
 //alert(outstr) 
}


//function executes javascript which has been stored in a html dom id
function exec_script(idname) {
  cmds = document.getElementById(idname).value
  cmds = cmds.replace(/"/g, '&quot;')
  eval(cmds)
  showComplete()
}


//  End -->
