
var xtern_tables = new Array();
var xtern_xml = new Array();
var xreq;

var xtern_done = false;
var xtern_callback = false;
var xtern_overlay_init = false;
var xtern_loading_status = false;

function loadXternData() {

	/// set callback function
	if (arguments.length > 0 && arguments[0]) {
		xtern_callback = arguments[0];
	}
	
	if (xternurl && !xtern_done) {
		if (document.getElementsByClassName) {
			xts = document.getElementsByClassName("xtern_select");
			
			if (xts.length > 0) {
				j = 0;
				for (i = 0; i < xts.length; i++) {
					/// which table?
					xt = (new String(xts[i].id)).split("_");
					ok = true;
					
					for (key in xtern_tables) {
						if (xtern_tables[key]['table'] == xt[1]) {
							/// already got it
							ok = false;
							break;
						}
					}
					
					if (ok) {
						xtern_tables[j] = new Array();
						xtern_tables[j]['table'] = xt[1];
						xtern_tables[j]['col'] = xt[2];
						
						/*if (xt[3] && xt[3] != "") {
							xtern_tables[j]['other'] = xt[3];
						}*/
						
						j++;
					}
				}
				
				appendOverlay();
				getNextXML();
			}
		}
	} else {
		/// just do callback
		if (xtern_callback != false) {
			xtern_callback();
		}
	}
}


function dealWithXML() {
	if (xreq && xreq.readyState == 4) {
		if (xreq.status == 200) {
			/// do it
			xtern_xml.push(xreq.responseXML.documentElement.cloneNode(true));
			
			getNextXML();
		}
	} else {
		//alert("XML Problem: "+xreq.status);
	}
}

function getNextXML() {
	//alert("getNextXML() called, xtern_tables.length = "+xtern_tables.length);
	xreq = null;
	xreq = xmlhttp();
	
	xreq.onreadystatechange = function () {
		window.setTimeout('dealWithXML();', 300);
	};
	
	if (xreq && xtern_tables.length > 0) {
		showOverlay();
		while (tt = xtern_tables.pop()) {
			/*if (tt['other']) {
				xurl = xternurl + "?table=" + tt['table'] + "&cols=" + tt['col'].replace(/UNDERSCORE/g, "_") + "," + tt['other'].replace(/UNDERSCORE/g, "_");
			} else {
				xurl = xternurl + "?table=" + tt['table'] + "&cols=" + tt['col'].replace(/UNDERSCORE/g, "_");
			}*/
			xurl = xternurl + "?table=" + tt['table'] + "&cols=" + tt['col'].replace(/UNDERSCORE/g, "_");
			
			xreq.open("GET", xurl, true);
			xreq.send(null);
			
			if (xtern_loading_status) {
				xtern_loading_status.innerHTML = "Table: "+tt['table'];
			}
			
			break;
		}
	} else {
		/// what?
		if (xtern_loading_status) {
			xtern_loading_status.innerHTML = "Finishing...";
		}
		
		/// we're done
		installXML();
	}
}

/// actually make the motherfucking dropdowns
function installXML() {
	//alert('installXML() called, xtern_xml.length = '+xtern_xml.length);
	xtern_done = false;
	
	for (i = 0; i < xtern_xml.length; i++) {
		tn = xtern_xml[i].getElementsByTagName('tablename')[0].firstChild.nodeValue;
		
		if (tn && document.getElementsByClassName) {
			xts = document.getElementsByClassName("xtern_select");
			for (j = 0; j < xts.length; j++) {
				/// which table?
				ppparts = (new String(xts[j].id)).split("_");
				
				xt = ppparts[1];
				xcol = ppparts[2];
				//xcol2 = ppparts[3];
				
				/// ridicuous, I know
				xcol = xcol.replace(/UNDERSCORE/g, "_");
				
				if (tn == xt) {
					/// here we are, do it to it					
					theselects = xts[j].getElementsByTagName('select');
					theitems = xtern_xml[i].getElementsByTagName('item');
					
					for (k = 0; k < theselects.length; k++) {
						
						for (l = 0; l < theitems.length; l++) {							
							/// get the id
							//idlabel = theitems[l].getAttribute("idcol");
							idvalue = -1;
							nodeout = null;
							//nodeaddendum = null;
							params = theitems[l].getElementsByTagName('param');
							for (m = 0; m < params.length; m++) {
								if (params[m].getAttribute("name") == xcol && params[m].firstChild) {
									nodeout = params[m].firstChild.cloneNode(true);
									idvalue = params[m].firstChild.nodeValue;
								}
								
								/*else if (params[m].getAttribute("name") == xcol2 && params[m].firstChild) {
									nodeaddendum = params[m].firstChild.cloneNode(true);
								}*/
							}
							
							if (idvalue != -1 && nodeout != null) {
								opt = document.createElement("option");
								opt.value = idvalue;
								/*if (nodeaddendum == null) {
									opt.appendChild(nodeout);
								} else {
									opt.appendChild(nodeaddendum);
								}*/
								opt.appendChild(nodeout);
								
								/// jam it in!
								theselects[k].appendChild(opt);
							}
							
						}
						
						/// attach event listener
						theselects[k].addEventListener('change', doXternSelect, false);
					}
				}
			}
		}
	}
	
	xtern_done = true;
	hideOverlay();
	
	/// do callback
	if (xtern_callback != false) {
		xtern_callback();
	}
}


///
/// cross-browser XMLHttpRequest
/// adapted from http://www.codepost.org/view/59
function xmlhttp() {
	out = false;
	
	if (!window.XMLHttpRequest) {
		
		var types = [
			'Microsoft.XMLHTTP',
			'MSXML2.XMLHTTP.5.0',
			'MSXML2.XMLHTTP.4.0',
			'MSXML2.XMLHTTP.3.0',
			'MSXML2.XMLHTTP'
		];
		
		for (i = 0; i < types.length; i++) {
			try {
				out = new ActiveXObject(types[i]);
			}
			catch (e) {
				/// nothing
			}
		}
		
		try {
			out = new XMLHttpRequest();
		} catch (e) {
			/// nothing
		}
	} else {
		out = new XMLHttpRequest;
	}
	
	return out;
}

/// function for selectors
function doXternSelect() {
	//alert(this.options[this.selectedIndex].value);
	
	/// add new?
	if (this.options[this.selectedIndex].value == -1) {
		nn = "";
		nn = prompt("Please enter a new value: ", "");
		if (nn != "" && nn != false && nn != null) {
			opt = document.createElement("option");
			opt.value = nn;
			opt.appendChild(document.createTextNode(nn));
			opt.selected = true;
			this.appendChild(opt);
		}
	} else if (this.options[this.selectedIndex].value == "NULL") {
		alert("Please make a valid selection.");
	}
}

/// showOverlay(), hideOverlay()
/// for "loading..." screen
/// some code from lightbox.js
function showOverlay() {
	if (xtern_getPageSize && document.getElementById) {
		/// function is in lightbox.js
		ov = document.getElementById("xtern_overlay");
		xloading = document.getElementById("xtern_loading");
		
		if (ov && xloading && (xtern_overlay_init == false)) {
			pageSizeArray = xtern_getPageSize();
			pageScrollArray = xtern_getPageScroll();
			
			ov.style.height = pageSizeArray[1]+"px";
			ov.style.visibility = "visible";
			
			xloading.style.left = (Math.round(pageSizeArray[2] / 2) - Math.round(xloading.offsetWidth / 2))+"px";
			//xloading.style.top = (Math.round(pageSizeArray[1] / 2) - Math.round(xloading.style.height / 2))+"px";
			xloading.style.top = (pageScrollArray[1] + Math.round(pageSizeArray[3] / 12))+"px";
			xloading.style.visibility = "visible";
			
			xtern_overlay_init = true;
		}
	}
}

function hideOverlay() {
	if (document.getElementById) {
		/// function is in lightbox.js
		ov = document.getElementById("xtern_overlay");
		xloading = document.getElementById("xtern_loading");
		
		if (ov && xloading) {
			ov.style.visibility = "hidden";
			xloading.style.visibility = "hidden";
		}
	}
}

function appendOverlay() {
	ovv = document.createElement('div');
	ovv.setAttribute('id', 'xtern_overlay');
	
	xloading = document.createElement('div');
	xloading.setAttribute('id', 'xtern_loading');
	xloading.setAttribute('zIndex', '2000');
	
	
	loadingimageholder = document.createElement('div');
	loadingimageholder.setAttribute('id', 'xtern_loading_imageholder');
	
	loadingimage = document.createElement('img');
	loadingimage.setAttribute('id', 'xtern_loading_image');
	loadingimage.setAttribute('src', new String(baseurl+"x/images/loading.gif"));
	loadingimage.setAttribute('width', 32);
	loadingimage.setAttribute('height', 32);
	
	loadingmessage = document.createElement('span');
	loadingmessage.setAttribute('id', 'xtern_loading_message');
	loadingmessage.appendChild(document.createTextNode("Loading External Data... "));
	
	xtern_loading_status = document.createElement('span');
	xtern_loading_status.setAttribute('id', 'xtern_loading_status');
	//loadingmessage.appendChild(document.createTextNode("..."));
	
	loadingimageholder.appendChild(loadingimage);
	xloading.appendChild(loadingimageholder);
	xloading.appendChild(document.createElement('br'));
	xloading.appendChild(loadingmessage);
	xloading.appendChild(document.createElement('br'));
	xloading.appendChild(xtern_loading_status);
	
	bodydouble = document.getElementsByTagName('body').item(0);
	bodydouble.appendChild(ovv);
	bodydouble.appendChild(xloading);
}

/// this function also from lightbox.js,
/// which apparently was originally from quirksmode.org
/// and someone named 'pHaez', it would seem
function xtern_getPageSize() {
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth) {	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function xtern_getPageScroll() {

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}