// JavaScript Document
// AJAX functions RMK

// Handles fetching data from PHP
function requestDynData(domObjectName, fileName, targetBox, selValue) {
	var selValue = (selValue == null) ? "" : selValue; // selValue is optional
	var elements = document.getElementsByName(domObjectName);
	sId = null;
	// if elements have values
	if(elements[0].value.length > 0){
		sId=elements[0].value;
	}
	// Do HTTP request
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open("get", fileName+"?id=" + sId, true);
	// set the floorSel box's contents while loading
	var box1 = document.getElementsByName(targetBox);
//alert(targetBox);
	box1[0].length = 0;
	box1[0].options[0] = new Option('Loading...','');
	//
//alert(domObjectName+"\n"+fileName+"\n"+targetBox);	
	oXmlHttp.onreadystatechange = function () {
	    if (oXmlHttp.readyState == 4) {
	        if (oXmlHttp.status == 200) {
				// output
	            displayCustomerInfo(oXmlHttp.responseText, targetBox, selValue);
	        } else {
				// output
	            displayCustomerInfo("An error occurred: " + oXmlHttp.statusText, targetBox);
	        }
	    }
	};
	oXmlHttp.send(null);
}

// called by requestFloors. Converts a JSON string back into an object.
function displayCustomerInfo(string, targetBox, selValue){
	var selValue = (selValue == null) ? "" : selValue; // selValue is optional
	// reset select box's contents
	var box = document.getElementsByName(targetBox);
	box[0].length = 0;
	box[0].options[0] = new Option('Select One..','');	
	if(string.length > 0){	
		var oCarInfo = new Object();
		oCarInfo = JSON.parse(string);
		// populate floorSel select box
		for(var n=0; n<oCarInfo.length; n++){
		// DEBUG inspect(element);
	
		if(oCarInfo[n].name){
			var name = oCarInfo[n].name;
		}
		if(oCarInfo[n].indent){
			var name = "--".repeat(oCarInfo[n].indent)+oCarInfo[n].name; // add  &nbsp; in front n times for indent
		}
			
			var id = oCarInfo[n].id;
			// add option to select box. myunescape() resides in functions_javascript.js
			box[0].options[box[0].length] = new Option(myunescape(name),id);
			// set option as selected
			// DEBUG alert(box[0].options[box[0].length-1].value +' :: '+ selValue);
			if(selValue.length >0 && box[0].options[box[0].length-1].value == selValue){
				box[0].options[box[0].length-1].selected = true;
			}
		}
	}
}