var http_requests = new Array(5);

function xmlRequest(idx) {

	http_requests[idx] = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_requests[idx] = new XMLHttpRequest();
			if (http_requests[idx].overrideMimeType) {
				http_requests[idx].overrideMimeType('text/xml');
			}
		} else if (window.ActiveXObject) { // IE
		try {
			http_requests[idx] = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_requests[idx] = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_requests[idx]) {
		alert('Cannot create an XMLHTTP instance ('+idx+')!');
		return false;
	} else {
		return true;	
	}
}

function getAccountInfo(e) {
	if(e.selectedIndex == 0) {
		document.f.company_id.value = '';
		document.f.user_id.value = '';
		document.f.name.value = '';
		document.f.email.value = '';
		document.f.pass.value = '';
		document.f.phone.value = '';
		document.f.fax.value = '';
		document.f.company_name.value = '';
		document.f.address.value = '';
		document.f.address2.value = '';
		document.f.city.value = '';
		document.f.state.value = '';
		document.f.zip.value = '';
	}
	else {
		getAccountList(e.options[e.selectedIndex].value);
	}
}
function getAccountList(code) {
	if(xmlRequest(0)) {
		http_requests[0].onreadystatechange = gotAccountList;
		http_requests[0].open('POST', "Company.php", true);
		http_requests[0].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

		var pInfo = "mode=xmlhttp&customer_code=" + code;

		http_requests[0].send(pInfo);
	}
}
function gotAccountList() {
	if (http_requests[0].readyState == 4) {
		if (http_requests[0].status == 200) {

			try {
				x = new ActiveXObject("Microsoft.XMLDOM");
				x.async = false;
				x.loadXML(http_requests[0].responseText);
			} catch (e) {
			//alert(http_requests[0].responseText);
				x = http_requests[0].responseXML;
			}

			accounts = x.getElementsByTagName('account');
//			alert(accounts.length);

			if(accounts.length == 1) {
				//alert(accounts.item(0).tagName);
				//alert(accounts.item(0).childNodes.length);

				user_id = 0;
				company_id = 0;

				nodes = accounts.item(0).childNodes;
				for(i=0; i<nodes.length; i++) {
					//alert(nodes.item(i).tagName);
					if(nodes.item(i).tagName == 'company_id') company_id = nodes.item(i).firstChild.nodeValue;
					if(nodes.item(i).tagName == 'user_id') user_id = nodes.item(i).firstChild.nodeValue;
				}

//				alert('company_id: ' + company_id);
//				alert('user_id: ' + user_id);

				getAccountDetail(company_id, user_id, true);
			}
			if(accounts.length > 1) {

				s = "";
				for(i=0; i<accounts.length; i++) {
					nodes = accounts.item(i).childNodes;

					uid = 0;
					cid = 0;
					name = "";
					cname = "";
					for(j=0; j<nodes.length; j++) {
						//alert(nodes.item(i).tagName);

						if(nodes.item(j).tagName == 'company_id') cid = nodes.item(j).firstChild.nodeValue;
						if(nodes.item(j).tagName == 'company_name') cname = nodes.item(j).firstChild.nodeValue;
						if(nodes.item(j).tagName == 'user_id') uid = nodes.item(j).firstChild.nodeValue;
						if(nodes.item(j).tagName == 'name') name = nodes.item(j).firstChild.nodeValue;
					}
					s += '<a href="javascript:getAccountDetail(' + cid + ',' + uid + ',true)">' + name + ', ' + cname + '</a><br>';
				}

				//alert(s);
				document.getElementById("accountList").innerHTML = s;
				document.getElementById("accountList").style.cssText = "display:block";
			}

		} else {
			alert('There was a problem with the request.');
		}
	}
}
function getAccountDetail(company_id, user_id, getDetailFlag) {

	if(getDetailFlag) {
		document.f.company_id.value = company_id;
		document.f.user_id.value = user_id;
		document.getElementById("accountList").style.cssText = "display:none";

		if(xmlRequest(0)) {
			http_requests[0].onreadystatechange = gotCompanyDetail;
			http_requests[0].open('POST', "Company.php", true);
			http_requests[0].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	
			var pInfo = "mode=xmlhttp&id=" + company_id;
	
			http_requests[0].send(pInfo);
		}
	
		if(xmlRequest(1)) {
			http_requests[1].onreadystatechange = gotUserDetail;
			http_requests[1].open('POST', "User.php", true);
			http_requests[1].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	
			var pInfo = "mode=xmlhttp&id=" + user_id;
	
			http_requests[1].send(pInfo);
		}
	}

	if(xmlRequest(2)) {
		http_requests[2].onreadystatechange = function () {
			if (http_requests[2].readyState == 4) {
				if (http_requests[2].status == 200) {
		
					try {
						x = new ActiveXObject("Microsoft.XMLDOM");
						x.async = false;
						x.loadXML(http_requests[2].responseText);
					} catch (e) {
					//alert(http_requests[2].responseText);
						x = http_requests[2].responseXML;
					}
		
					savePickupAddrs = x;

					prevAddr = document.f.pickup_previous_address;
					for(i=0; i<prevAddr.length; i++) prevAddr.options[i] = null;
					prevAddr.length = 0;
					prevAddr.options[0] = new Option("New","0",false,false);

					addresses = x.getElementsByTagName('previous_address');
					for(i=0; i<addresses.length; i++) {
						nodes = addresses.item(i).childNodes;
	
						s = '';
						name = "";
						address = "";
						address2 = "";
						city = "";
						state = "";
						zip = "";
						for(j=0; j<nodes.length; j++) {
							if(nodes.item(j).tagName == 'company_name') name = getNodeValue(nodes.item(j));
							if(nodes.item(j).tagName == 'address') address = getNodeValue(nodes.item(j));
							if(nodes.item(j).tagName == 'address2') address2 = getNodeValue(nodes.item(j));
							if(nodes.item(j).tagName == 'city') city = getNodeValue(nodes.item(j));
							if(nodes.item(j).tagName == 'state') state = getNodeValue(nodes.item(j));
							if(nodes.item(j).tagName == 'zip') zip = getNodeValue(nodes.item(j));
						}
	 
						s += name + ', ' + address + ', ';
						if(address2 != '') s += address2 + ', ';
						s += city + ', ' + state + ', ' + zip;
						//alert(s);


						prevAddr.options[prevAddr.length] = new Option(s,'',false,false);
					}
				
				} else {
					alert('There was a problem with the request.');
				}
			}
		};

		http_requests[2].open('POST', "PickupClass.php", true);
		http_requests[2].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

		var pInfo = "mode=xmlhttp&address_type=pickup&company_id=" + company_id;

		http_requests[2].send(pInfo);
	}

	if(xmlRequest(3)) {
		http_requests[3].onreadystatechange = function () {
			if (http_requests[3].readyState == 4) {
				if (http_requests[3].status == 200) {
		
					try {
						x = new ActiveXObject("Microsoft.XMLDOM");
						x.async = false;
						x.loadXML(http_requests[3].responseText);
					} catch (e) {
					//alert(http_requests[3].responseText);
						x = http_requests[3].responseXML;
					}
		
					saveDeliveryAddrs = x;

					prevAddr = document.f.delivery_previous_address;
					for(i=0; i<prevAddr.length; i++) prevAddr.options[i] = null;
					prevAddr.length = 0;
					prevAddr.options[0] = new Option("New","0",false,false);

					addresses = x.getElementsByTagName('previous_address');
					for(i=0; i<addresses.length; i++) {
						nodes = addresses.item(i).childNodes;
	
						s = '';
						name = "";
						address = "";
						address2 = "";
						city = "";
						state = "";
						zip = "";
						for(j=0; j<nodes.length; j++) {
							if(nodes.item(j).tagName == 'company_name') name = getNodeValue(nodes.item(j));
							if(nodes.item(j).tagName == 'address') address = getNodeValue(nodes.item(j));
							if(nodes.item(j).tagName == 'address2') address2 = getNodeValue(nodes.item(j));
							if(nodes.item(j).tagName == 'city') city = getNodeValue(nodes.item(j));
							if(nodes.item(j).tagName == 'state') state = getNodeValue(nodes.item(j));
							if(nodes.item(j).tagName == 'zip') zip = getNodeValue(nodes.item(j));
						}
	 
						s += name + ', ' + address + ', ';
						if(address2 != '') s += address2 + ', ';
						s += city + ', ' + state + ', ' + zip;
						//alert(s);


						prevAddr.options[prevAddr.length] = new Option(s,'',false,false);
					}
				
				} else {
					alert('There was a problem with the request.');
				}
			}
		};

		http_requests[3].open('POST', "PickupClass.php", true);
		http_requests[3].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

		var pInfo = "mode=xmlhttp&address_type=delivery&company_id=" + company_id;

		http_requests[3].send(pInfo);
	}
}

function gotCompanyDetail() {
//alert("0:"+http_requests[0].readyState);
	if (http_requests[0].readyState == 4) {
		if (http_requests[0].status == 200) {

			try {
				x = new ActiveXObject("Microsoft.XMLDOM");
				x.async = false;
				x.loadXML(http_requests[0].responseText);
			} catch (e) {
			//alert(http_requests[0].responseText);
				x = http_requests[0].responseXML;
			}

			document.f.company_name.value = findNodeValue(x,"name");
			document.f.address.value = findNodeValue(x,"address");
			document.f.address2.value = findNodeValue(x,"address2");
			document.f.city.value = findNodeValue(x,"city");
			document.f.state.value = findNodeValue(x,"state");
			document.f.zip.value = findNodeValue(x,"zip");
			document.f.fax.value = findNodeValue(x,"fax");
			document.f.phone.value = findNodeValue(x,"phone");

		} else {
			alert('There was a problem with the request.');
		}
	}
}
function gotUserDetail() {
//alert("1:"+http_requests[1].readyState);
	if (http_requests[1].readyState == 4) {
		if (http_requests[1].status == 200) {

			try {
				x = new ActiveXObject("Microsoft.XMLDOM");
				x.async = false;
				x.loadXML(http_requests[1].responseText);
			} catch (e) {
			//alert(http_requests[1].responseText);
				x = http_requests[1].responseXML;
			}

			document.f.name.value = findNodeValue(x,"name");
			document.f.email.value = findNodeValue(x,"username");

		} else {
			alert('There was a problem with the request.');
		}
	}
}
function gotPickupAddresses() {
alert("2:"+http_requests[2].readyState);
	if (http_requests[2].readyState == 4) {
		if (http_requests[2].status == 200) {

			try {
				x = new ActiveXObject("Microsoft.XMLDOM");
				x.async = false;
				x.loadXML(http_requests[2].responseText);
			} catch (e) {
			alert(http_requests[2].responseText);
				x = http_requests[2].responseXML;
			}

		
		} else {
			alert('There was a problem with the request.');
		}
	}
	
}

function gotDefaultDeliveryAddressList() {
//alert("3:"+http_requests[3].readyState);
	if (http_requests[3].readyState == 4) {
		if (http_requests[3].status == 200) {

			try {
				x = new ActiveXObject("Microsoft.XMLDOM");
				x.async = false;
				x.loadXML(http_requests[3].responseText);
			} catch (e) {
			alert(http_requests[3].responseText);
				x = http_requests[3].responseXML;
			}

		
		} else {
			alert('There was a problem with the request.');
		}
	}
	
}
function pickupAddress(){
	x = savePickupAddrs;
	idx = document.f.pickup_previous_address.selectedIndex;

	if(idx == 0) {
		document.f.pickup_company_name.value = '';
		document.f.pickup_address.value = '';
		document.f.pickup_address2.value = '';
		document.f.pickup_city.value = '';
		document.f.pickup_state.value = '';
		document.f.pickup_zip.value = '';
	}
	else {
		idx = idx - 1;
		addresses = x.getElementsByTagName('previous_address');
		if(idx <= addresses.length) {
			nodes = addresses.item(idx).childNodes;
			for(j=0; j<nodes.length; j++) {
				if(nodes.item(j).tagName == 'company_name') document.f.pickup_company_name.value = getNodeValue(nodes.item(j));
				if(nodes.item(j).tagName == 'address') document.f.pickup_address.value = getNodeValue(nodes.item(j));
				if(nodes.item(j).tagName == 'address2') document.f.pickup_address2.value = getNodeValue(nodes.item(j));
				if(nodes.item(j).tagName == 'city') document.f.pickup_city.value = getNodeValue(nodes.item(j));
				if(nodes.item(j).tagName == 'state') document.f.pickup_state.value = getNodeValue(nodes.item(j));
				if(nodes.item(j).tagName == 'zip') document.f.pickup_zip.value = getNodeValue(nodes.item(j));
			}
		}
	}
}
function deliveryAddress(){
	x = saveDeliveryAddrs;
	idx = document.f.delivery_previous_address.selectedIndex;

	if(idx == 0) {
		document.f.delivery_company_name.value = '';
		document.f.delivery_address.value = '';
		document.f.delivery_address2.value = '';
		document.f.delivery_city.value = '';
		document.f.delivery_state.value = '';
		document.f.delivery_zip.value = '';
	}
	else {
		idx = idx - 1;
		addresses = x.getElementsByTagName('previous_address');
		if(idx <= addresses.length) {
			nodes = addresses.item(idx).childNodes;
			for(j=0; j<nodes.length; j++) {
				if(nodes.item(j).tagName == 'company_name') document.f.delivery_company_name.value = getNodeValue(nodes.item(j));
				if(nodes.item(j).tagName == 'address') document.f.delivery_address.value = getNodeValue(nodes.item(j));
				if(nodes.item(j).tagName == 'address2') document.f.delivery_address2.value = getNodeValue(nodes.item(j));
				if(nodes.item(j).tagName == 'city') document.f.delivery_city.value = getNodeValue(nodes.item(j));
				if(nodes.item(j).tagName == 'state') document.f.delivery_state.value = getNodeValue(nodes.item(j));
				if(nodes.item(j).tagName == 'zip') document.f.delivery_zip.value = getNodeValue(nodes.item(j));
			}
		}
	}
}

function setField(x,n,f) {
	document.getElementById(f).innerHTML = findNodeValue(x,n);
}
function findNodeValue(x,n) {
	e = x.getElementsByTagName(n);
	return getNodeValue(e.item(0));
}
function getNodeValue(e) {
	v = "";
	if(e.firstChild) v = e.firstChild.nodeValue;
	return v;
}



k = -1;
kmax = 0;
kcur = 0;
indicator = 0;
saveValue = "";
customers = new Array();
submitAllowed = true;

newUserFlag = false;
function setN() {
	newUserFlag = true;
}

function Customer() {
	this.companyId = null;
	this.companyName = null;
	this.customerCode = null;
	this.address = null;
	this.address2 = null;
	this.city = null;
	this.state = null;
	this.zip = null;
	this.phone = null;
	this.fax = null;
	this.userId = null;
	this.userName = null;
	this.email = null;
	this.display = null;
}

function formSubmit() {
	return submitAllowed;
}

function handleBlur(e) {
	if(!e) e = event;

debug("blur "+k+e.keyCode);
	if(k >= 0)
		activate(k);
	else
		hideResponses();
}

function keyup(e) {
	//document.getElementById('responseDiv').innerHTML = document.f.fld.value;
	if(!e) e = event;

	var q = document.f.fld.value;
	if(q == '') {
		hideResponses();
		saveValue = '';
//do we need to cancel that particular update if the box goes to zero?  try aa (wait), bksp bksp...
	}
	else {
		switch(e.keyCode) {
			case 9: // Tab
				if(k >= 0) activate(k);
				break;

			case 13: // CR
				if(k >= 0) activate(k);
				break;    

			case 27: // Esc
				hideResponses();
				break;

			case 38: // Up arrow
				if(kmax > 0) {
					k = k - 1;
					if(k < 0) k = kmax -1;
					highlight(k);
				}
				break;

			case 40: // Down arrow
				if(kmax > 0) {
					k = k + 1;
					if(k >= kmax) k = 0;
					highlight(k);
				}
				break;

			default:
				if(saveValue != q) {
					sendRequest(q);
					saveValue = q;
				}
		}
	}
}

function highlight(knew) {
	if(kcur >= 0) document.getElementById('srow'+kcur).style.backgroundColor = '';
	document.getElementById('srow'+knew).style.backgroundColor = '#d1d1e5';
	kcur = knew;
	k = knew;	
}

function activate(i) {
	document.f.company_name.value = '';
	if(customers[i].companyName != 'New company') document.f.company_name.value = customers[i].companyName;

	document.f.name.value = '';
	if(customers[i].userName != 'New user') document.f.name.value = customers[i].userName;

	document.f.customer_code.value = customers[i].customerCode;

	document.f.company_id.value = customers[i].companyId;
	document.f.user_id.value = customers[i].userId;
	document.f.fld.value = customers[i].companyName + ', ' + customers[i].userName;
	document.f.address.value = customers[i].address;
	document.f.address2.value = customers[i].address2;
	document.f.city.value = customers[i].city;
	document.f.state.value = customers[i].state;
	document.f.zip.value = customers[i].zip;
	document.f.email.value = customers[i].email;
	document.f.phone.value = customers[i].phone;
	document.f.fax.value = customers[i].fax;

	saveValue = customers[i].companyName + ', ' + customers[i].userName;
	hideResponses();

	getAccountDetail(customers[i].companyId,0,false);
}

function displayResponses(htmlBlock) {
	var d = document.getElementById('responseDiv');
	d.innerHTML = htmlBlock;
	d.style.display = 'block';
	submitAllowed = false;
}

function hideResponses() {
	document.getElementById('responseDiv').style.display = 'none';
	k = -1;
	submitAllowed = true;
}
function debug(s) {
	var div = document.getElementById('debug');
	if(div) div.innerHTML = s + "<br>" + div.innerHTML;
}
	
function sendRequest(q) {
	indicator++;

	if(xmlRequest(4)) {
		http_requests[4].onreadystatechange = updateResponseDiv;
		http_requests[4].open('POST', "theX.php", true);
		http_requests[4].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

		var pInfo = "i=" + indicator + "&q=" + q;
		if(newUserFlag) pInfo = pInfo + "&n=1";

		debug(pInfo);

		http_requests[4].send(pInfo);
	}
}
function updateResponseDiv() {
	if (http_requests[4].readyState == 4) {
		if (http_requests[4].status == 200) {

			// odd thing where div still pops up when field is empty.
			// thinking that a request is coming back still with one letter selected.
			if(document.f.fld.value == "") return;

			try {
				x = new ActiveXObject("Microsoft.XMLDOM");
				x.async = false;
				x.loadXML(http_requests[4].responseText);
			} catch (e) {
			//alert(http_requests[0].responseText);
				x = http_requests[4].responseXML;
			}

			var s = "";
			var customerXML = x.getElementsByTagName('customer');
			customers = new Array();
			for(i=0; i<customerXML.length; i++) {
				nodes = customerXML.item(i).childNodes;

				customers[i] = new Customer();
				for(j=0; j<nodes.length; j++) {
					if(nodes.item(j).tagName == 'companyId') customers[i].companyId = getNodeValue(nodes.item(j));
					if(nodes.item(j).tagName == 'companyName') customers[i].companyName = getNodeValue(nodes.item(j));
					if(nodes.item(j).tagName == 'address') customers[i].address = getNodeValue(nodes.item(j));
					if(nodes.item(j).tagName == 'address2') customers[i].address2 = getNodeValue(nodes.item(j));
					if(nodes.item(j).tagName == 'city') customers[i].city = getNodeValue(nodes.item(j));
					if(nodes.item(j).tagName == 'state') customers[i].state = getNodeValue(nodes.item(j));
					if(nodes.item(j).tagName == 'zip') customers[i].zip = getNodeValue(nodes.item(j));
					if(nodes.item(j).tagName == 'userId') customers[i].userId = getNodeValue(nodes.item(j));
					if(nodes.item(j).tagName == 'userName') customers[i].userName = getNodeValue(nodes.item(j));
					if(nodes.item(j).tagName == 'email') customers[i].email = getNodeValue(nodes.item(j));
					if(nodes.item(j).tagName == 'phone') customers[i].phone = getNodeValue(nodes.item(j));
					if(nodes.item(j).tagName == 'fax') customers[i].fax = getNodeValue(nodes.item(j));
					if(nodes.item(j).tagName == 'customerCode') customers[i].customerCode = getNodeValue(nodes.item(j));
					if(nodes.item(j).tagName == 'display') {
						customers[i].display = getNodeValue(nodes.item(j));
						s = s + '<div id="srow'+i+'" onmouseover="highlight('+i+')" onclick="activate('+i+')">' + getNodeValue(nodes.item(j)) + "</div>";
					}
				}
			}
			k = -1;
			kcur = -1;
			kmax = i;

			displayResponses(s);
		}
		else
			alert('There was a problem with the request.');
	}
}

function changeCompanyUser() {
	document.getElementById('companyUserDiv').style.display = 'none';
	document.getElementById('companyUserEditDiv').style.display = 'block';
	document.f.fld.focus();
}
function cancelCompanyUser() {
	document.getElementById('companyUserDiv').style.display = 'block';
	document.getElementById('companyUserEditDiv').style.display = 'none';
	document.f.fld.blur();
	document.f.user_id.value = 0;
	document.f.company_id.value = 0;
}
