
///
/// GRID FUNCTIONS
///

/// variables
//var perPage = 15;
var _timer;
var _query = new Array();

var heightPad = 8;
var viewbutton;
var viewimage;
var editbutton;
var editimage;
var searchbutton;
var searchimage;
var af;
var whereyouat = new Array();

var maxRowH = 200;
//var color_checked = "#C8C8FF";
var color_checked = "#DDDDFF";
var color_odd = "#FFFFDD";
var color_edit = "#FFFFEE";
var color_even = "#FFFFFF";


var theidcol = false;

/// set it all up
function init() {
	// quit if this function has already been called
	if (arguments.callee.done) return;

	// flag this function so we don't do the same thing twice
	arguments.callee.done = true;

	// kill the timer
	if (_timer) clearInterval(_timer);
	
	/// do up the query string.
	loc = new String(location.href);
	//q = loc.replace(/\?([^\s])+$/, "$1");
	q = loc.replace(/^([^\s])+\?/, "$1");
	if (q) {
		qa = q.split("&");
		for (i = 0; i < qa.length; i++) {
			qqq = qa[i].split("=");
			if (qqq[0] && qqq[1]) {
				_query[qqq[0]] = decodeURIComponent(qqq[1]);
			}
		}
	}
	
	/// build view/edit buttons
	viewbutton = document.createElement('a');
	viewbutton.setAttribute('href', '#');
	viewbutton.setAttribute('onclick', 'doView(this.getAttribute("rel"));');
	viewimage = document.createElement('img');
	viewimage.setAttribute('src', new String(baseurl+"x/images/view00.gif"));
	viewimage.setAttribute('width', 30);
	viewimage.setAttribute('height', 30);
	viewbutton.appendChild(viewimage);

	editbutton = document.createElement('a');
	editbutton.setAttribute('href', '#');
	editbutton.setAttribute('onclick', 'doEdit(this.getAttribute("rel"));');
	//editbutton.addEventListener('click', doEdit, false);
	editimage = document.createElement('img');
	editimage.setAttribute('src', new String(baseurl+"x/images/edit00.gif"));
	editimage.setAttribute('width', 30);
	editimage.setAttribute('height', 30);
	editbutton.appendChild(editimage);
	
	searchbutton = document.createElement('a');
	searchbutton.setAttribute('href', '#');
	searchbutton.setAttribute('onclick', 'doInlineSearch();');
	searchimage = document.createElement('img');
	searchimage.setAttribute('src', new String(baseurl+"x/images/search00.gif"));
	searchimage.setAttribute('width', 30);
	searchimage.setAttribute('height', 30);
	searchbutton.appendChild(searchimage);
	
	/// build form for checkbox
	cbli = document.createElement('li');
	cbli.setAttribute('class', 'tcell_checkbox');
	cbli.style.width = "80px";
	//cbli.style.height = "65px";
	cbli.style.height = "auto";
	cbli.style.minHeight = "65px";
	
	cbform = document.createElement('form');
	cbform.setAttribute('method', 'get');
	cbform.setAttribute('action', new String(wdpbaseurl));
	cb = document.createElement('input');
	cb.setAttribute('type', 'checkbox');
	cb.setAttribute('class', 'checky');
	
	/// and now, the real shit.
	var tdivs = document.getElementsByTagName("div");
	for (i = 0; i < tdivs.length; i++) {
		if (tdivs[i].getAttribute("class") == "trow" || tdivs[i].getAttribute("class") == "theader") {
			maxRowH = tdivs[i].offsetHeight;
			
			/// count data cells, divide width and max-width accordingly
			cells = tdivs[i].getElementsByTagName("li");
			if (cells.length > 0) {
				
				if (tdivs[i].getAttribute('class') == 'trow') {
					/// get the id
					pp = new String(cells[0].parentNode.id);
					
					if (pp != "XXX") {
						idname = (new String(pp)).replace(/^id_([0-9]*)/, "");
						idvalue = (new String(pp)).replace(/^id_/, "").replace(new RegExp(idname+"$"), "");
						
						if (theidcol == false && idname) {
							theidcol = idname;
						}
						
						theview = viewbutton.cloneNode(true);
						theedit = editbutton.cloneNode(true);
						thecbf = cbform.cloneNode(true);
						thecb = cb.cloneNode(true);
						thecbli = cbli.cloneNode(true);
						
						theview.setAttribute("rel", pp);
						theedit.setAttribute("rel", pp);
						thecbf.setAttribute("id", "cbform"+idvalue);
						thecb.setAttribute("name", "cb");
						thecb.setAttribute("value", idvalue);
						if (!(i % 2)) {
							thecb.setAttribute("onclick", "doCheckBox(this, 'odd');"); /// why can't I use addEventListener() ?!?!?
						} else {
							thecb.setAttribute("onclick", "doCheckBox(this, 'even');"); /// why can't I use addEventListener() ?!?!?
						}
						
						thecbf.appendChild(thecb);
						thecbli.appendChild(thecbf);
						
						/// attach images to the checkbox cell
						//thecbli.appendChild(document.createElement('br'));
						thecbli.appendChild(theview.cloneNode(true));
						thecbli.appendChild(theedit.cloneNode(true));
						
						/// attach checkbox before first cell
						cells[0].parentNode.insertBefore(thecbli, cells[0]);
					}
				} else if (tdivs[i].getAttribute('class') == 'theader') {
					thli = document.createElement('li');
					thli.setAttribute('class', 'theadercell');
					thli.style.width = "80px";
					thsel = document.createElement('span');
					thsel.setAttribute('class', 'colheader_inert');
					thsel.setAttribute('id', 'ch_selectboxlabel');
					thtext = document.createTextNode("[select]");
					thsel.appendChild(thtext);
					thli.appendChild(thsel);
					
					/// attach header cell
					trows = tdivs[i].getElementsByTagName('ul');
					
					for (j = 0; j < trows.length; j++) {
						trows[j].insertBefore(thli, trows[j].firstChild);
					}
				}
				
				for (j = 0; j < cells.length; j++) {
					//cells[j].style.width = (Math.round(100 / cells.length) - 1)+"%";
					//cells[j].style.maxWidth = cells[j].style.width;

					if (j > 0) {
						cells[j].style.width = (Math.round(790 / cells.length) - 1)+"px";
					}
					
					/// how tall are we after resize?
					maxRowH = (maxRowH < cells[j].offsetHeight) ? cells[j].offsetHeight : maxRowH;
					//cells[j].style.height = maxRowH+"px";
				}
				
			}
			
			/// darken every other row
			if (!(i % 2) && tdivs[i].getAttribute("class") == "trow") {
				tdivs[i].style.backgroundColor = color_odd;
			}
			
			/// adjust height
			tdivs[i].style.height = (maxRowH+3)+"px";
			
		}
	} /// end tdivs loop
	

	
	/// bind box to all data
	if (document.getElementsByClassName && document.addEventListener) {
		thedata = document.getElementsByClassName("datum");
		
		for (i = 0; i < thedata.length; i++) {
			thedata[i].addEventListener('click', doViewFor, false);
			thedata[i].addEventListener('mouseover', datumOn, false);
			thedata[i].addEventListener('mouseout', datumOff, false);
		}
		
		theblanks = document.getElementsByClassName("datumblank");
		
		for (i = 0; i < theblanks.length; i++) {
			theblanks[i].addEventListener('click', doViewFor, false);
			theblanks[i].addEventListener('mouseover', datumOn, false);
			theblanks[i].addEventListener('mouseout', datumOff, false);
		}
		
		/// bind sort functions for column headers
		theheaders = document.getElementsByClassName("colheader");
		
		for (i = 0; i < theheaders.length; i++) {
			theheaders[i].addEventListener('click', resortWithColumn, false);
			theheaders[i].addEventListener('mouseover', datumOn, false);
			theheaders[i].addEventListener('mouseout', datumOff, false);
		}
	}
	
	/// configure 'where' bits
	whereyouat['gridcurrentrep'] = "currentrep = 1";
	whereyouat['gridperformances_future'] = "date > now()";
	
	/// set the search and nav forms
	if (layout) {
		sc = document.getElementById("searchcategory");
		
		for (i = 0; i < sc.options.length; i++) {
			if (encodeURIComponent(sc.options[i].value) == layout) {
				sc.selectedIndex = i;
				break;
			}
		}
		
		navvies = document.getElementsByClassName("cnavoption");
		for (i = 0; i < navvies.length; i++) {
			if (navvies[i].id == layout) {
				navvies[i].selected = true;
				break;
			}
		}
	}
	
	/// irritatingly, we have to set 'andor' here and not at the server
	if (document.getElementById) {
		ao = document.getElementById('andor');
		
		if (_query['andor']) {
			andor = _query['_andor'].toLowerCase();
			
			if (andor == "and") {
				ao.options[0].selected = true;
			} else if (andor == "or") {
				ao.options[1].selected = true;
			}
		} else {
			ao.options[0].selected = true;			
		}
	}
	
	/// test that ass!
	//alert("init() called.");
	
	if (loadXternData && _query['_layout'] && (_query['_layout'].match(/\_edit$/i))) {
		/// load external dropdown XML
		loadXternData();
		
		/// and while we're at it, wash the fucking windows
		if (document.getElementById) {
			var tc = document.getElementsByClassName("tablecontainer");
			tcrows = tc[0].getElementsByTagName("tr");
			
			for (i = 0; i < tcrows.length; i++) {
				if ((i % 2)) {
					teedees = tcrows[i].getElementsByTagName("td");
					for (j = 0; j < teedees.length; j++) {
						teedees[j].style.backgroundColor = color_edit;
					}
				}
			}
		} /// end window washing
		
		
	}
	
	
}


/// set body onload handler
/// some of this from: http://dean.edwards.name/weblog/2006/06/again/
/// mozilla?
if (document.addEventListener) {
	document.addEventListener("DOMContentLoaded", init, false);
}


/// safari?
if (/WebKit/i.test(navigator.userAgent)) { // sniff
	var _timer = setInterval(function() {
		if (/loaded|complete/.test(document.readyState)) {
			init(); // call the onload handler
		}
	}, 10);
}


/// getRealX and getRealY adopted from stuff at:
/// http://www.xs4all.nl/~ppk/js/findpos.html
/// ... word to moms.
function getRealX(obj) {
	var ccX = 0;
	if (document.getElementById || document.all) {
		while (obj.offsetParent) {
			ccX += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	} else if (document.layers) {
		ccX += obj.x;
	}
	return ccX;
}

function getRealY(obj) {
	var ccY = 0;
	if (document.getElementById || document.all) {
		while (obj.offsetParent) {
			ccY += obj.offsetTop;
			obj = obj.offsetParent;
		}
	} else if (document.layers) {
		ccY += obj.y;
	}
	return ccY;
}

/// stylize the inner text
function datumOn() {
	this.style.textDecoration = "underline";
	this.style.color = "#FF1919";
	
	document.body.style.cursor = "pointer";
}

function datumOff() {
	this.style.textDecoration = "none";
	
	if (this.getAttribute("class") == "datumblank") {
		this.style.color = "#BBBBBB";
	} else {
		this.style.color = "rgb(29, 39, 63)";
	}
	
	document.body.style.cursor = "default";
}

function doSearch() {
	if (document.getElementById) {
		sf = document.getElementById("searchform");
		wf = document.getElementById("wdpform");
		
		sel = sf.elements["searchcategory"].selectedIndex;
		val = sf.elements["searchcategory"].options[sel].value;
		
		/// we don't care if search text field is empty
		//if (val != -1 && (sf.elements["searchtext"].value != sf.elements["searchtext"].defaultValue)) {
		if (val != -1) {
			/// free to go
			wf.elements["_allSearch"].name = "_allSearch";
			wf.elements["_layout"].name = "_layout";
			wf.elements["_cgifunction"].name = "_cgifunction";
			wf.elements["_pageNum"].name = "_pageNum";
			wf.elements["_perPage"].name = "_perPage";
			wf.elements["_andor"].name = "_andor";
			
			wf.elements["_allSearch"].value = sf.elements["searchtext"].value;
			wf.elements["_layout"].value = val;
			wf.elements["_cgifunction"].value = "search";
			if (parseInt(pageNum) > 0) {
				wf.elements["_pageNum"].value = 1;
			} else {
				wf.elements["_pageNum"].value = 1;
			}
			if (parseInt(perPage) > 0) {
				wf.elements["_perPage"].value = perPage;
			} else {
				wf.elements["_perPage"].value = 15;
			}

			/// include 'where'?
			if (whereyouat[val]) {
				wf.elements["_where"].name = "_where";
				wf.elements["_where"].value = whereyouat[val];
			}
			
			/// and / or
			wf.elements['_andor'].value = sf.elements['andor'].options[sf.elements['andor'].selectedIndex].value;
			//if (wf.elements['_andor'].value.toLowerCase() == "and") {
			//	wf.elements["_allSearch"].value = wf.elements["_allSearch"].value.replace(/\s+/i, " and ");
			//} else if (wf.elements['_andor'].value.toLowerCase() == "or") {
			//	wf.elements["_allSearch"].value = wf.elements["_allSearch"].value.replace(/\s+/i, " or ");
			//}
			
			
			wf.submit();
		} else {
			alert("Please select a category.");
		}
	}
}

/// column resort
function resortWithColumn() {
	//alert("Resort with column \""+this.innerHTML+"\"");
	if (document.getElementById) {
		/// get the id
		//bits = (new String(this.id)).split("_");
		//sorter = new String(bits[1]);
		sorter = (new String(this.id)).replace(/^ch_/, "");
		
		wf = document.getElementById("wdpform");
		
		wf.elements["_allSearch"].name = "_allSearch";
		wf.elements["_layout"].name = "_layout";
		wf.elements["_cgifunction"].name = "_cgifunction";
		wf.elements["_pageNum"].name = "_pageNum";
		wf.elements["_perPage"].name = "_perPage";
		wf.elements["_orderby"].name = "_orderby";
		wf.elements["_where"].name = "_where";
		
		wf.elements["_allSearch"].value = allSearch;
		wf.elements["_layout"].value = layout;
		wf.elements["_cgifunction"].value = cgifunction;
		wf.elements["_pageNum"].value = pageNum;
		wf.elements["_perPage"].value = perPage;
		wf.elements["_orderby"].value = sorter;
		wf.elements["_where"].value = decodeURIComponent(where);
		
		wf.submit();
	}
}


/// goToPage() override from webdata PRO.
function goToPage(whereto) {
	if (orderby == "") {
		location.href = wdpbaseurl + "?_cgifunction=" + cgifunction + "&_layout=" + layout + "&_allSearch=" + allSearch + "&_pageNum=" + whereto + "&_perPage=" + perPage + "&_where=" + where;
	} else {
		location.href = wdpbaseurl + "?_cgifunction=" + cgifunction + "&_layout=" + layout + "&_allSearch=" + allSearch + "&_pageNum=" + whereto + "&_perPage=" + perPage + "&_where=" + where + "&_orderby=" + orderby;
	}
}

/// toggle less important fields
function toggleFields() {
	if (document.getElementById) {
		fff = document.getElementById("lessimportantfields");
		
		if (fff.style.display == "block") {
			fff.style.display = "none";
		} else {
			fff.style.display = "block";
		}
	}
}

/// editThis()
function editThis() {
	newURL = location.href.replace(/\_view/i, "_edit");
	location.href = newURL;
}

/// cnavurl() for browse selects
function cnavurl(formname, selectname) {
	sel = document.forms[formname].elements[selectname].selectedIndex
	val = document.forms[formname].elements[selectname].options[sel].value;
	if (val != -1) {
		location.href = val;
	} else {
		alert("Please make a selection.");
	}
	return true;
}


/// doEdit, doView, et cetera
function doEdit(rel) {
	//alert("doEdit() called");
	/// get the id
	idname = (new String(rel)).replace(/^id_([0-9]*)/, "");
	idvalue = (new String(rel)).replace(/^id_/, "").replace(new RegExp(idname+"$"), "");
	
	if (decodeURIComponent(layout) == "gridperformances_future") {
		newlayout = "gridperformances_all_edit";
	} else if (decodeURIComponent(layout) == "gridcurrentrep") {
		newlayout = "gridalldances_edit";
	} else {
		newlayout = layout + "_edit";
	}
	
	location.href = wdpbaseurl + "?_cgifunction=search&_layout=" + newlayout + "&" + tableName + "." + idname + "=" + idvalue;
}

function doView(rel) {
	//alert("doView() called");
	/// get the id
	idname = (new String(rel)).replace(/^id_([0-9]*)/, "");
	idvalue = (new String(rel)).replace(/^id_/, "").replace(new RegExp(idname+"$"), "");
	
	if (decodeURIComponent(layout) == "gridperformances_future") {
		newlayout = "gridperformances_all_view";
	} else if (decodeURIComponent(layout) == "gridcurrentrep") {
		newlayout = "gridalldances_view";
	} else {
		newlayout = layout + "_view";
	}
	
	location.href = wdpbaseurl + "?_cgifunction=search&_layout=" + newlayout + "&" + tableName + "." + idname + "=" + idvalue;
}

/// replace getBoxFor() to allow clicking on things to go to view page
function doViewFor() {
	doView(new String(this.parentNode.parentNode.id));
}

function doInlineSearch() {
}

function doCheckBox(cb, oddeven) {
	//alert("doCheckBox() called; that.checked = "+cb.checked);
	
	thediv = cb.parentNode.parentNode.parentNode.parentNode;
	theid = parseInt(cb.value);
	
	if (cb.checked) {
		//thediv.style.backgroundColor = "#B9E5FA";
		thediv.style.backgroundColor = color_checked;
	} else {
		if (oddeven == 'odd') {
			thediv.style.backgroundColor = color_odd;
		} else {
			thediv.style.backgroundColor = color_even;
		}
	}
}

function doDeleteStuff() {
	if (confirm("Delete selected items? THERE IS NO UNDO!")) {
		theboxes = document.getElementsByClassName("checky");
		whereout = "";
		thefirst = false;
		
		for (i = 0; i < theboxes.length; i++) {
			if (theboxes[i].checked == true) {
				if (thefirst == false) {
					//whereout += (tableName + "." + theidcol + " = " + theboxes[i].value);
					whereout += new String(theboxes[i].value);
					thefirst = true;
				} else {
					//whereout += (" OR " + tableName + "." + theidcol + " = " + theboxes[i].value);
					whereout += "|" + new String(theboxes[i].value);
				}
			}
		}
		
		if (document.getElementById) {
		
			df = document.getElementById("deleteform");
			
			df.elements["_cgifunction"].name = "_cgifunction";
			df.elements["_tableName"].name = "_tableName";
			df.elements["_selectedList"].name = "_selectedList";
			df.elements["_redirect"].name = "_redirect";
			
			df.elements["_cgifunction"].value = "Delete Only Selected Records";
			df.elements["_tableName"].value = tableName;
			df.elements["_selectedList"].value = whereout;
			df.elements["_redirect"].value = new String(location.href);
			
			//alert("list: "+whereout);
			df.submit();
		
		}

	}
}

function returnToList() {
	if (layout) {
		newlayout = layout.replace(/\_edit$/i, "");
		newlayout = newlayout.replace(/\_view$/i, "");
		navvies = document.getElementsByClassName("cnavoption");
		for (i = 0; i < navvies.length; i++) {
			if (navvies[i].id == newlayout) {
				location.href = navvies[i].value;
				break;
			}
		}
	}
}

function showAddForm() {
	if (document.getElementById) {
		af = document.getElementById("thenewnew");
		if (af) {
			af.style.display = "block";
			af.style.visibility = "visible";
			loadXternData(function () {
				if (window.scrollTo) {
					window.scrollTo(0, (getRealY(af) - 100));
				}
			});
		}
	}
}

function hideAddForm() {
	if (document.getElementById) {
		af = document.getElementById("thenewnew");
		if (af) {
			af.style.display = "none";
			af.style.visibility = "hidden";
			
			if (window.scrollTo) {
				window.scrollTo(0, 0);
			}
			
		}
	}
}

/// create new from data
function createNewFromData() {
	out = false;
	
	if (document.getElementById) {
		tf = document.getElementById('editform');
		if (tf) {
			
		}
	}
}