/**
	AJAX functions:
*/



/**
	ImportNodeIE
  
  Final version, replaces importNode for IE for most cases.

	Implements importNode for IE.  Not needed for standards-compliant browsers
	From http://dhtmlkitchen.com/news/?permalink=811FD9713AEB64EC5FD183BF0ED39B29.txt
	also helpful:
	http://www.codingforums.com/showthread.php?t=66401
	
	This is a hack to import a node, usually from an XMLHttpRequest().responseXML;
	This creates a temporary div and puts the serialized xml of the node into it, then returns
	the new div's child node.

	The problem with <tr>s is that you can't change innerHTML for <table>s or <tr>s.  

	TODO: add other special cases as the come up.
	
	@param oNode	- original node, usually incoming.
	@param bDeep	- boolean - do deep compy?
	@returns		- new copy of oNode now part of document.
*/
function importNodeIE (oNode, bDeep) {
	var nodeHTML = oNode.xml||oNode.outerHTML;
	if(!nodeHTML) throw "importNodeIE: nodeHTML is null or undefined";
	if(typeof bDeep == "undefined") throw "importNodeIE: not enough arguments";

	//TR tags are a special case, can't use innerHTML directly.
	if (oNode.tagName == 'tr') {
		var tmpNode = document.createElement("table");
		var tmpTR = document.createElement("tr");
		tmpNode.appendChild(tmpTR);
		//loop through all cells.
		c = oNode.firstChild; 
		while (c) { 
			var d = document.createElement(c.tagName);
   			d.innerHTML = c.xml;
   			tmpTR.appendChild(d);
   			c = c.nextSibling; 
		}
	 	return tmpTR;
	//Almost everything else can be put in a div's innerHTML.
	} else {
		var tmpNode = document.createElement("div");
		tmpNode.innerHTML = nodeHTML;
		return tmpNode.firstChild.cloneNode(bDeep);
	}
}



/**
	Wrapper function to create a request

	@param	reqType		GET or POST
	@param	url			Url to call
	@param	asynch		true for asynch, false for synchronous. 
*/
function httpRequest(reqType, url, asynch) {
	// Mozilla: detect XMLHttpRequest 
	if (window.XMLHttpRequest) {
		request = new XMLHttpRequest();
	// IE:  detect XMLHTTP 	
	} else if (window.ActiveXObject) {
		request = new ActiveXObject("Microsoft.XMLHTTP");
		if (!request) {
			request = new ActiveXObject("Msxml2.XMLHTTP");
		}
	} else {
		alert("No AJAX for you!");
	}
	if (request) {
		request.onreadystatechange=handleResponse;
		request.open("GET", url, true);
		
    //this makes sure we treat response as XML whether or not sent correctly
		if (request.overrideMimeType) {
    	request.overrideMimeType('text/xml');
		}

    request.send(null);
	}
}

function handleResponse() {
	//alert("handled! readystate="+request.readyState+" status="+request.status);

	//var old_cell_1 = document.getElementById("item_search_1");
	//old_cell_1.innerHTML = 'Searching...';

	if (request.readyState == 4) {
    //clearTimeout(timeoutId);
    	if (request.status == 200) {
      		//Implement document object in DOM
	      	//var xmlReturnVal = request.responseText;
	      	var xmlReturnVal = request.responseXML;

				//alert (xmlReturnVal.xml + "inner "+xmlReturnVal.innerHTML );
            
            if (xmlReturnVal) {
            
       			//var new_row = xmlReturnVal.getElementsByTagName("tr")[0].cloneNode(true);
       			
                
                
                var new_row = xmlReturnVal.getElementsByTagName("tr")[0];
					var old_row = document.getElementById("item_search");
					var container = old_row.parentNode; //the table 
					var next_row = old_row.nextSibling;
                var cur_count = parseInt(document.getElementById("i").value);
			
    			//With IE, can't just appendNode ro replace node from responseXML
    			//  basically, IE thinks it's a different document but doesn't support importNode.  
    			//  explained at http://neo.dzygn.com/archive/id/56
    			//  and http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/4b2c75d68dff5243/8ba8b50050b40f69
			
    			//Standard Method:
    			if (document.importNode) {
    				//alert('import!');
                    document.importNode(new_row, true);
    				
                    //replace the next row with another add item form
                    var copy_row = old_row.cloneNode(true);
 
                    //find the "i" field and update it
                    //TODO: using exact children is easy to break, look into making it
                    //more robust
                    copy_row.childNodes[1].childNodes[0].value = cur_count+1;
                    //copy_row.childNodes[1].style.opacity = 0;
                    copy_row.childNodes[3].childNodes[1].style.opacity = 0;
                    copy_row.childNodes[3].childNodes[3].style.opacity = 0;


                    
                    container.replaceChild(copy_row, next_row);
                    
                    //put the results where the add item form used to be.
                    container.replaceChild(new_row, old_row);
    				//container.appendChild(new_row);

                    //hide:
                    //opacity('item_search', 100, 0, 500);
                    opacity('input_text', 0, 100, 1000);
                    opacity('item_search_button', 0, 100, 1000);

    			// Hack for IE:
    			} else {
    				//alert('fake import!');
    				var imported = importNodeIE(new_row, true);

                    var copy_row = old_row.cloneNode(true);
						copy_row.style.opacity = 0;

                    //find the "i" field and update it
                    copy_row.childNodes[0].childNodes[0].value = cur_count+1;
                    copy_row.childNodes[1].childNodes[0].style.opacity = 0;
                    copy_row.childNodes[1].childNodes[1].style.opacity = 0;

                    //alert(copy_row.childNodes[1].innerHTML);
                    
                    //put the results where the add item form used to be.
    				container.replaceChild(imported, old_row);

                    //replace the next row with another add item form
                    container.replaceChild(copy_row, next_row);
						
                    //hide:
                    //opacity('item_search', 100, 0, 500);
                    opacity('input_text', 0, 100, 1000);
                    opacity('item_search_button', 0, 100, 1000);
                    
                    
                    //shiftOpacity('item_search', 1000);
						
                    //replaceNode is an IE-only ext., because replaceChild seems to have problems.
                    //old_row.replaceNode(imported);
    				
                    //container.appendChild(imported);				
    			}

                setup_events();  //need to do this to reapply functions

				} else {
					//p.innerHTML = '<td colspan="2">No foods found!</td>';
				}            
     	} else {
				//p.innerHTML = '<td colspan="2">No foods found!</td>';
    	}
  	}
}



function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 

function shiftOpacity(id, millisec) {
    //if an element is invisible, make it visible, else make it ivisible
    if(document.getElementById(id).style.opacity == 0) {
			alert("clear!");
        opacity(id, 0, 100, millisec);
    } else {
        opacity(id, 100, 0, millisec);
    }
} 


/**
  Setup Events
  
  This is how we do unobtrustive Javascript.  The page when first loaded will
  not depend on any Javascript to work;  This function is called at the bottom
  of the page (usually by setup_events.js)
  
  This is a series of functionality checks; if the browser supports the function,
  the code will add functionality to elements on the page.
  
*/

function setup_events() {
	//TODO: Need to have functionality if there's no JS
  //	hide plain text of foods, unhide select lists?

	//Setup basic Javascript behavior, W3C DOM:
	if (document.getElementById) {

		//remove disclaimer:
    
   	//document.getElementById('disclaimer').style.display = "none";;


    //here we sweep through all the rows up to i, adding the update weights function onchange.
    var i = document.getElementById('i').value;
    var j, new_NDB_select, cur_erase_button;
    
    for (j=0; j<i; j++) {
    	//Trying to add onchange after new select list is generated:
       	eval("new_NDB_select = document.getElementById('NDB_No_"+j+"');");
       	if (new_NDB_select) {
       		eval("new_NDB_select.onchange = function() {update_weights("+j+", this.value);};");
       	}
    
    	/*//Add functionality to Erase buttons
       	eval("cur_erase_button = document.getElementById('erase_"+j+"');");
       	if (cur_erase_button) {
       		eval("cur_erase_button.onclick = function() {remove_item("+j+");return false;};");
       	}*/

    	//Add functionality to Erase checkbox
       	eval("cur_erase_check = document.getElementById('erase_"+j+"');");
       	if (cur_erase_check) {
            eval("cur_erase_check.onclick = function() {remove_item("+j+");return false;};");
       	}

    
    }
    
   	//TODO: dynamically create the "add an item" box? 
    	
    
   	// Setup AJAX behavior
   	// TODO:  The IE check might be to weak, might need to look for 
   	// ActiveXObject("Microsoft.XMLHTTP"); and ActiveXObject("Msxml2.XMLHTTP");
   	if (window.XMLHttpRequest || window.ActiveXObject) {
    
   		var input_text = '';
  		var input_text_field = document.getElementById('input_text');
   		input_text = input_text_field.value;
   		var item_search_button = document.getElementById('item_search_button');
      
      	//Add hanlder to search button;
	    	item_search_button.onclick = function() {httpRequest("GET", "food.php?action=search_ajax&input="+document.getElementById('input_text').value+"&i="+i, true);};
    
   	  	//Code to prevent submit on hitting enter in search box
      	// TODO:  implement
  	    //input_text_field.onsubmit = function() {httpRequest("GET", "food.php?action=search_ajax&input="+document.getElementById('input_text').value+"&i="+i, true);return false;};
	     	/*input_text_field.onkeydown = function() {
      								if(window.event) { // IE 
    										keynum = window.event.keyCode
    									} else if(event.which) { // Netscape/Firefox/Opera 
    										keynum = event.which
    									}
                                    if (keynum==13) {
                                    	httpRequest("GET", "food.php?action=search_ajax&input="+document.getElementById('input_text').value+"&i="+i, true);
                                    }
                                   };
    	*/
    //No AJAX:                               
   	} else {
			//Make inline search disappear:
    	var input_text_field = document.getElementById('input_text');
        input_text_field.style.display = "none";
   		var item_search_button = document.getElementById('item_search_button');
        item_search_button.style.display = "none";
    }

    
  //No W3C DOM:  
	} else {
	    	
        //TODO:  find old-fashioned way of doing this
        /*var input_text_field = document.getElementById('input_text');
        input_text_field.style.display = "none";
   		var item_search_button = document.getElementById('item_search_button');
        item_search_button.style.display = "none";
			*/

	}


	window.setTimeout('', 1000);

  //disable validation temporarily:
  //var required = window.document.forms.the_form.required.value;
  //var required_fields = new Array();
  //required_fields = required.split(',');
	//var cur_field;
  //for (i=0; i<required_fields.length; i++) {
  	//cur_field = window.document.getElementById(required_fields[i]);
		//make sure an event handler is added to field.
		//cur_field.onchange = function() {check_required();};
  //}
}



