// JavaScript Document

//This JS originally seemed great, but eventually outgrew itself. I need to create something far more modular

//awesomeness with ajax
function createRequestObject() {
     var ro;
     var browser = navigator.appName;
     if(browser == "Microsoft Internet Explorer"){
          ro = new ActiveXObject("Microsoft.XMLHTTP");
     }else{
          ro = new XMLHttpRequest();
     }
     return ro;
}

var http = createRequestObject();

//this is the universal response handling function
function handleQuestions() {
	if(http.readyState == 4 && http.status == 200){
		var response = http.responseText;
		var update = new Array();
		update = response.split('|');
		//alert("our new value: "+ response);

		if(response.indexOf('|') != -1) {
			//create a switch based on update[0];
			switch(update[0]){
					
				case 'fetchCategoriesResponse':
					fetchCategoriesResponse(update);
					break;
					
			}
			
		}
		//the return message was not an array
		else{
			alert("error: "+ response);
		}
	}
}

var timer = "";

function fetchTimeCheck(){
	//first we clear the old timer
	timer = clearTimeout(timer);
	//now we reset it
	timer =setTimeout('fetchCategories();', 1500); // 1.5 seconds
}

function fetchCategories(){
	
	var theInput = document.getElementById("cat_search");
	
	srchString = theInput.value;
	
	if(srchString != ""){
		
		//make it read only and let it know you're puttingit to work.
		theInput.className="ajaxing";
		
		http.open('POST', 'ajaxFunctions.php',true);
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.onreadystatechange = handleQuestions;
		http.send('direction=fetchCategories&srchString='+srchString);
	}
}

function fetchCategoriesResponse(update){

	//fetchCategoriesResponse|true/false|catID|catName|catID|catName....
	if(update[1] == 'true'){
		//get the size of the array
		content = "<ul>\n";
		len = update.length;
		for(i=2;i < len; i += 2){
			content += "<li onclick=\"setCat('"+ update[i] +"')\">"+ update[i+1] +"</li>\n";
		}
		content += "</ul>";
		
		//set the search box back to normal
		var theInput = document.getElementById("cat_search");
		theInput.className="";
		
		//send all that good stuff out
		var statusBox = document.getElementById("cat_search_box");
		statusBox.style.display = "";
		//alert(content);
		statusBox.innerHTML = content;
	}
	else{
		//set the search box back to normal
		var theInput = document.getElementById("cat_search");
		theInput.className="";
	}
}

function setCat(catID){
	
	var theCatBox = document.getElementById("cat_id");
	var inti = 0;
	var len = theCatBox.length;
	while(inti < len){
		if(theCatBox[inti].value == catID){
			theCatBox[inti].selected = true;
			//we found it so lets hide the div
			var statusBox = document.getElementById("cat_search_box");
			statusBox.style.display = "none";
		}
		inti += 1;
	}
	
}
