/*
 =============================
Ingredients
 =============================
*/

/*
This section will rectrieve a list of matching ingredients.
We return the top five matching ingredients.
These are generated by functions/matchingredient.php
*/
var httpObject = null;

// Get the HTTP Object
function getHTTPObject(){
    if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
    else if (window.XMLHttpRequest) return new XMLHttpRequest();
    else {
        alert("Your browser does not support AJAX.");
        return null;
    }
}

// Change the value of the outputText field
function setOutput(){
    if(httpObject.readyState == 4){
        document.getElementById("IngridList").innerHTML=httpObject.responseText;
    }
}

// Implement business logic
function doWork(){
   httpObject = getHTTPObject();

    if (httpObject != null) {
	httpObject.open("GET", "funcldr.php?func=ingred_match&inputText=" + document.getElementById('ingredient').value + "&i=" + document.getElementById('IngrId').value, true);
	httpObject.send(null);
	httpObject.onreadystatechange = setOutput;
    }
}

//Clear ingredient id if the value changes as user types
function ClearIngrId(){
    document.getElementById('IngrId').value = -1;
}


/*
This section is for the 2 drop downs.
One has a set list of measurement categories.
The second is a changing list depending on selected category
*/
//fuction to return the xml http object
function getXMLHTTP() { 
  var xmlhttp=false;
  try{
    xmlhttp=new XMLHttpRequest();
  }
  catch(e)	{
    try{
      xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e){
      try{
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch(e1){
	xmlhttp=false;
      }
    }
  }
  return xmlhttp;
}

//This function is called to load a specific page into a dv
//strURL is the url to be outputted
//outDiv is where it will output the content
//Most commonly I've used it for the measurment drop down
function dropLDR(strURL,outDiv) {
  var req = getXMLHTTP();

  if (req) {
    req.onreadystatechange = function() {
    if (req.readyState == 4) {
      // only if "OK"
      if (req.status == 200) {
	document.getElementById(outDiv).innerHTML=req.responseText;
      } else {
	alert("There was a problem while using XMLHTTP:\n" + req.statusText);
      }
    }
    }
    req.open("GET", strURL, true);
    req.send(null);
  }
}
function dropLDR2(strURL,outDiv) {
  var req = getXMLHTTP();
  var obj=document.getElementById(outDiv);
  var pipes= '';
	if (req) {
		req.onreadystatechange = function() {
		if (req.readyState == 4) {
		  // only if "OK"
		  if (req.status == 200) {
			pipes=req.responseText;
		//alert( pipes);
			var prezar = pipes.split("|");//split response text
		
			obj.length = 1;//clear existing itesm
				
			obj.length = prezar.length;
			//alert(obj.length);
				alert 
			for (o=1; o < prezar.length; o++)
			{
					obj[o].text = prezar[o];
					obj[o].value = prezar[o];
					//alert (prezar[o]);
			  }

		  } else {
			alert("There was a problem while using XMLHTTP:\n" + req.statusText);
		  }
		}
	}
    req.open("GET", strURL, true);
    req.send(null);
  }
}
//Replace text in the text box and put the id in a hidden field when a user selects a match from ingredients list
function putIngr(strIngr,Id) {
    document.getElementById('ingredient').value = strIngr;	//Replace the textbox
    document.getElementById('IngrId').value = Id;		//Put in the id
	document.getElementById('note').focus();
    doWork();							//Recheck to see if there are any more matching
}

//After they add an ingredient clear the form
function clearIngrid() {
    document.getElementById('amount').value='';
    document.getElementById('ingredient').value='';
    document.getElementById("myform_errorloc").innerHTML='';
    document.getElementById("IngridList").innerHTML='';
	document.getElementById('note').value='';
    document.getElementById('measurement_group').selectedIndex=0;
     document.getElementById('measurement').length = 1;
   document.getElementById('amount').focus();
}

//Ajax send ingredient and get a list of the current ones
function sendRequest(strURL) {
    var meas 			= document.myform.measurement.options[document.myform.measurement.selectedIndex].value;
    var amt 			= document.myform.amount.value;
    var ingrd 			= document.myform.ingredient.value;
    var measurement_group 	= document.myform.measurement_group.options[document.myform.measurement_group.selectedIndex].value;
    var id 			= document.myform.id.value;
    var ingrdId 		= document.myform.IngrId.value;
    var note 			= document.myform.note.value;
    var pod 			= 'amount=' + amt + '&ingredient=' + ingrd + '&measurement=' + meas +  '&measurement_group=' + measurement_group + '&id=' + id + '&IngrId=' + ingrdId + '&note=' + note;
   // alert (pod);
    $.post(strURL, pod,
	function(txt) {
	    $("div#"+"divCurIngrd").html(txt);
	    //alert(txt);
	}
    );
}

/*
  =============================
Categories
 =============================
*/
//Copy category ids into a hidden field
function copyCat() {
    var names='',ids='',curname='';

//get normal ones
    for (var i=0; i < document.catform.cat.length; i++) {
       if (document.catform.cat[i].checked) {
	    curname=document.catform.cat[i].id;

	    names = names  + curname.replace("_", "/").replace("|", " ") + ", ";
	    ids= ids  + document.getElementById('hdn_'+curname).value+ ",";
	  //   ids= ids  + document.getElementById(curname).value+ ",";
	}
    }
    
//Get all alergies
    for (var i=0; i < document.catform.cat_al.length; i++) {
       if (document.catform.cat_al[i].checked) {
	    curname=document.catform.cat_al[i].id;

	    names = names  + curname + ", ";
	   // ids= ids  + document.getElementById(curname).value+ ",";
	    ids= ids  + document.getElementById('hdn_'+curname).value+ ",";
	}
    }

names =str_replace("__", ",",names);
names =str_replace("_", "/",names);
names =str_replace(".", " ",names);
names =str_replace(":", ")",names);
names =str_replace("--", "(",names);

    document.getElementById("CatList").innerHTML="<h4>Categories</h4>" + names.slice(0, -2);
    document.getElementById('catIds').value = ids.slice(0, -1);
//alert (names.slice(0, -2));
//alert (ids.slice(0, -1));
}

    function str_replace(search, replace, subject) {  
        // Replaces all occurrences of search in haystack with replace    
        //   
        // version: 812.1017  
        // discuss at: http://phpjs.org/functions/str_replace  
      
        // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)  
        // +   improved by: Gabriel Paderni  
       // +   improved by: Philip Peterson  
       // +   improved by: Simon Willison (http://simonwillison.net)  
       // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)  
       // +   bugfixed by: Anton Ongson  
       // +      input by: Onno Marsman  
       // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)  
       // +    tweaked by: Onno Marsman  
       // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');  
       // *     returns 1: 'Kevin.van.Zonneveld'  
       // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');  
       // *     returns 2: 'hemmo, mars'  
       var f = search, r = replace, s = subject;  
       var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;  
     
       while (j = 0, i--) {  
           if (s[i]) {  
               while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};  
           }  
       };  
     
       return sa ? s : s[0];  
  }



//Unused but works
function un_check_all_value (form,value,span,check) {
    //<span id='chkall'><a href='#' onclick="un_check_all_value(catform,'Non-Allergenic','chkall',true);">Check All</a></span>

    //Loop through all the objects on the form and check all with a predefined values 		    
	for (var i=0; i<form.elements.length; i++) {
		if (form.elements[i].value==value) {
		    form.elements[i].checked=check;
		}
	    }
	    
	    //Reverse the check
	    if (check) {check=false;text='Uncheck All';}else{check=true;text='Check All';}
	      
	    //Set the link to now uncheck all
	    document.getElementById(span).innerHTML='<a href="#" onclick="un_check_all_value('+form.name+',\''+value+'\',\''+span+'\',' + check + ');">'+text+'</a>';
}

    function un_check_all_name (form,name,span,check) {
	//<span id='chkall2'><a href='#' onclick="un_check_all_name(catform,'cat2()','chkall2',true);">Check All</a></span>

	    //Get an array of objects with 
	    var colle=form.elements[name];

    //Loop through all the objects in that array and check all		    
	for (var i=0; i<colle.length; i++) {
		    colle[i].checked=check;
	    }
	    
	    //Reverse the check
	    if (check) {check=false;text='Uncheck All';}else{check=true;text='Check All';}
	    
	    //Set the link to now uncheck all
	    document.getElementById(span).innerHTML='<a href="#" onclick="un_check_all_name('+form.name+',\''+name+'\',\''+span+'\',' + check + ');">'+text+'</a>';
}





$(function() {
    $('input:checkbox').click(function () { 
	var i='';
	
	$('input:checkbox:checked').each(function() {
	    var test ="hdn_"+this.id;
	    i+=document.getElementById(test).value+",";
	});
	i=i.slice(0,i.length-1);
	$('#catIds').val(i);
    });
});