var actypescount = 0;
var actypes = new Array();
var acidents = new Array();
var instructors = new Array();

var enable_tlog = 0;

var booking_data = new Array();
var headers = new Array();
var starth = 8.0;
var endh = 21.5;
var parth = 2;
var displaytab = 1;

var search = false;
var searchstr = "";
var searchdisplayed = false;

var tabnames = new Array();
var numtabs = 0;
var num_rows = new Array();
var num_cols = new Array();

String.prototype.pad = function(l, s, t){
	return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
		+ 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
		+ this + s.substr(0, l - t) : this;
};

function tlog(a)
{
	if ((enable_tlog == 1) && (document.forms.f)) {
		document.forms.f.t.value = document.forms.f.t.value + '\n' + a;
	}
}

function gfoformSubmit() {
	hideId('disclaimer');
	hideGraphicTables();
	showId('loading');
	document.forms.gfoform.submit();
	return false;
}

function graphicChecked() {
	if (document.forms.gfoform.graphic.checked) {
		document.getElementById('graphicOptions').style.display='';
		document.forms.gfoform.todaybutton.disabled = false;
		document.forms.gfoform.prevbutton.disabled = false;
		document.forms.gfoform.nextbutton.disabled = false;
	} else {
		document.forms.gfoform.todaybutton.disabled = true;
		document.forms.gfoform.prevbutton.disabled = true;
		document.forms.gfoform.nextbutton.disabled = true;
		document.getElementById('graphicOptions').style.display='none';
	}
}


function dayOffsetDelta(d) {
	var a = parseInt(document.forms.gfoform.dayoffset.value);
	if (d == 0) { a = 0; } else { a = a+d; }
	document.forms.gfoform.dayoffset.value = a;
}

function hideId(a) {
	if (document.getElementById(a)) {
		document.getElementById(a).style.display='none';
	}
}

function showId(a) {
	if (document.getElementById(a)) {
		document.getElementById(a).style.display='';
	}
}

function uF(a) {
	document.forms.result.found.value = a;
}

function setDisplayTab(tabnum) {
	var table;
	var tabname;

	displaytab = tabnum;
	for(var i=0;i<numtabs;i++)
	{
		if (i != tabnum) 
		{
			// tlog("setDisplayTab("+tabnum+") HIDE "+tabnames[i]);
			table = document.getElementById(tabnames[i]);
			table.style.display='none';
		}
	}

	// tlog("setDisplayTab("+tabnum+") SHOW "+tabnames[tabnum]);
	table = document.getElementById(tabnames[tabnum]);
	table.style.display='';
	if(typeof Set_Cookie == 'function') {
		Set_Cookie('proifrdisplaytab', tabnum, 30);
	} 

}

function hideGraphicTables()
{
	var table;
	var tabnum = 0;
	var tabname;

	while (tabnum < numtabs) {
		tabname = tabnames[tabnum];
		hideId(tabname);
		tabnum++;
	}
	hideId("dTableSwitchTab");
}

function resetGraphicTables()
{
	var table;
	var tabnum = 0;
	var tabname;

	while (tabnum < numtabs) {
		tabname = tabnames[tabnum];
		var Parent = document.getElementById(tabname);
		while(Parent.hasChildNodes())
		{
			Parent.removeChild(Parent.firstChild);
		}
		Parent.parentNode.removeChild(Parent);
		num_rows[tabnum] = 0;
		num_cols[tabnum] = 0;
		tabnum++;
	}
}

function createGraphicTables()
{
	// Number of tables is number of aircraft types + 1 for instructors
	// We first do the aircrafts, in the end, we do instructors
	var numtables = actypes.length;
	var i = 0;
	for(i=0;i<numtables;i++) {
		// tlog("createGraphicTable("+i+", "+actypes[i]+")");
		createGraphicTable(i, actypes[i]);
	}

	// tlog("createGraphicTable("+numtables+", Instructor)");
	createGraphicTable(numtables, "Instructor");

	numtabs = numtables+1;
}

function createGraphicTable(tabnum, tabname)
{
	var row, col, txt;

	// get the reference for the body
	var documentbody = document.getElementsByTagName("body")[0];

	var table = document.createElement("table");
	var thead = document.createElement("thead");
	var tfoot = document.createElement("tfoot");
	var tbody = document.createElement("tbody");

	table.style.overflow = "auto";
	thead.style.height = "0px";
	tfoot.style.height = "0px";

	table.appendChild(thead);
	table.appendChild(tfoot);
	table.appendChild(tbody);

	documentbody.appendChild(table);

	var headerlist = new Array();
	if (tabnum == actypescount) {
		headerlist = instructors.slice(0);
	}
	else {
		headerlist = acidents[tabnum].slice(0);
	}

	tabnames[tabnum] = "table_" + tabname;
	table.id = tabnames[tabnum];

	table.style.display = "none";
	table.style.border = "2px solid black";
	table.style.emptyCells = "show";
	table.style.borderCollapse = "collapse";
	table.style.padding = "0px";
	table.style.margin = "0px";

	
	// We want at least 9 columns for a uniform display
	var cols = headerlist.length;
	while (cols < 9) {
		headerlist[cols++] = " ";
	}
	num_cols[tabnum] = headerlist.length;
	// tlog("tabnum = "+tabnum+", table.id = "+table.id+", cols = "+num_cols[tabnum]+")");

	row = document.createElement("TR");
	col = document.createElement("TH");
	col.className = 'ac';
	col.style.cursor = 'default';
	txt = document.createTextNode("");
	col.appendChild(txt);
	row.appendChild(col);

	for(var i=0; i<num_cols[tabnum]; i++) {
		col = document.createElement("TH");
		col.className = 'ac';
		col.style.cursor = 'default';
		t = headerlist[i];
		t = t.pad(7," ",2);
		txt = document.createTextNode(t);
		col.appendChild(txt);
		row.appendChild(col);
	}

	col = document.createElement("TH");
	col.className = 'ac';
	col.style.cursor = 'default';
	txt = document.createTextNode("");
	col.appendChild(txt);
	row.appendChild(col);

	thead.appendChild(row);

	var h = 0;
	var m = 0;

	num_rows[tabnum] = 0;
	for(var i=starth; i<=endh; i++) {
		for(var j=0; j<parth; j++) {
			row = document.createElement("TR");
			row.onmouseover = function() { this.style.background='#66aaff'; this.style.color='white'; }
			row.onmouseout = function() { this.style.background=''; this.style.color=''; }

			col = document.createElement("TD");
			col.className = 'dt';
			col.style.cursor = 'default';
			col.style.whiteSpace="pre";
			h = i; h = h+''; while (h.length < 2) { h = '0'+h; }
			m = j*(60/parth); m = m+''; while (m.length < 2) { m = '0'+m; }
			txt = document.createTextNode(h+':'+m);
			col.appendChild(txt);
			row.appendChild(col);

			for(var k=0; k<num_cols[tabnum]; k++) {
				col = document.createElement("TD");
				col.className = 'bkempty';
				col.style.cursor = 'default';
				col.style.width = '7em';
				col.style.whiteSpace="pre";
				t = ' ';
				t = t.pad(7," ",2);
				txt = document.createTextNode(t);
				col.appendChild(txt);
				row.appendChild(col);
			}

			col = document.createElement("TD");
			col.className = 'dt';
			col.style.cursor = 'default';
			col.style.whiteSpace="pre";
			h = i; h = h+''; while (h.length < 2) { h = '0'+h; }
			m = j*(60/parth); m = m+''; while (m.length < 2) { m = '0'+m; }
			txt = document.createTextNode(h+':'+m);
			col.appendChild(txt);
			row.appendChild(col);

			tbody.appendChild(row);
			num_rows[tabnum]++;
		}
	}
}

function updateGraphicTable(tabnum) {
	var row, col, txt;
	var booking, ident, stud, inst, acnum;
	var isout, isin;
	var st, hr, r, c;
	var bk, bkcolor;
	var h = 0;
	var m = 0;
	var startstr, endstr, title;

	// tlog("updateGraphicTable("+tabnames[tabnum]+")");
	var table = document.getElementById(tabnames[tabnum]);

	var headerlist = new Array();
	if (tabnum == actypescount) {
		headerlist = instructors.slice(0);
	}
	else {
		headerlist = acidents[tabnum].slice(0);
	}

	var numbook = booking_data[0][tabnum].length;
	// tlog('Start bookings for '+numbook+' entries');

	for(var i=0; i<numbook; i++) {
		booking = booking_data[0][tabnum][i];
		// tlog(booking);

		// If we are searching, then we display only the matching bookings
		// and ignore all others
		if (search && (booking.indexOf(searchstr) < 0)) {
			continue;
		}

		bparts = booking.split('#');
		if (bparts.length != 9) { tlog('Incorrect parts'); continue; }

		ident = bparts[0];
		st = parseFloat(bparts[1]);
		hr = parseFloat(bparts[2]);
		stud = bparts[3];
		inst = bparts[4];
		isout = bparts[5];
		isin = bparts[6];
		bkc = bparts[7];
		bkt = bparts[8];

		r = 0; 
		c = 0;
		bk = 0;
		bkcolor = "#f0f0f0";


		if (bkc.length == 6) {
			bk = 1;
			bkcolor = "#"+bkc;
		}

		// if (stud.indexOf("DISP") === 0) { bk = 3; bkcolor = "#808080"; }
		// if (stud.indexOf(ident) === 0) { bk = 3; bkcolor = "#808080"; }


		// tlog(ident+'#'+st+'#'+hr+'#'+stud+'#'+inst);

		startstr = Math.floor(st);
		if (startstr.length < 2) { startstr = "0"+startstr; }
		startstr = startstr + ":" + ((st-Math.floor(st))*60);
		if (startstr.length < 5) { startstr = startstr + "0"; }

		endstr = Math.floor(st+hr);
		if (endstr.length < 2) { endstr = "0"+endstr; }
		endstr = endstr + ":" + (((st+hr) - Math.floor(st+hr))*60);
		if (endstr.length < 5) { endstr = endstr + "0"; }

		title = startstr+" - "+endstr+" "+ident+" "+inst+" "+stud+" "+bkt;

		if (st < starth) { hr = hr - (starth - st); st = starth; }
		if (hr < 1) { continue; }
		if ((st+hr) > endh) { hr = (endh-starth); }

		r = (Math.floor(st) - Math.floor(starth))*parth + (st - Math.floor(st))*parth + 1;
		// tlog('ROW='+r);
		if (r < 1) {
			hr = hr+r+1;
			r = 1;
		}

		for(j=0;j<num_cols[tabnum];j++) {
			if (headerlist[j] == ident) {
				c = j+1;
				break;
			}
		}
		// tlog('COL='+c);

		if ((r>0) && (c>0)) {
			if ((search == true) && (searchdisplayed == false)) {
				searchdisplayed = true;
				// alert("SEARCH RESULTS - FOUND IN TAB "+tabnum);
				setDisplayTab(tabnum);
			}
			// tlog('HTML='+table.rows[r].cells[c].innerHTML);
			table.rows[r].cells[c].innerHTML=stud;
			table.rows[r].cells[c].setAttribute('className', 'bknew');
			table.rows[r].cells[c].className='bknew';
			table.rows[r].cells[c].title = title;
			if (bk>0) { table.rows[r].cells[c].style.backgroundColor=bkcolor; }
			hr = hr*parth;
			// tlog('HR='+hr);
			for(k=1;k<hr;k++) {
				if ((r+k) > num_rows[tabnum]) {
					// tlog('UNABLE MID ROW '+(r+k));
					break;
				}
				if (k == 1) {
					table.rows[r+k].cells[c].innerHTML=inst;
				}
				table.rows[r+k].cells[c].setAttribute('className', 'bk');
				table.rows[r+k].cells[c].className='bk';
				table.rows[r+k].cells[c].title = title;
				if (bk>0) { table.rows[r+k].cells[c].style.backgroundColor=bkcolor; }
			}
			if ((r+hr) < num_rows[tabnum]) {
				table.rows[r+hr-1].cells[c].setAttribute('className', 'bklast');
				table.rows[r+hr-1].cells[c].className='bklast';
				table.rows[r+hr-1].cells[c].title=title;
				if (bk>0) { table.rows[r+hr-1].cells[c].style.backgroundColor=bkcolor; }
			}
			else {
				table.rows[num_rows[tabnum]].cells[c].setAttribute('className', 'bklast');
				table.rows[num_rows[tabnum]].cells[c].className='bklast';
				table.rows[num_rows[tabnum]].cells[c].title=title;
				if (bk>0) { table.rows[num_rows[tabnum]].cells[c].style.backgroundColor=bkcolor; }
				// tlog('UNABLE END ROW '+(r+hr));
			}
		}
	}

}

function searchGraphicTable()
{
	var sstr = document.forms.gfoform.search.value;
	sstr = sstr.replace(/^\s+|\s+$/g,"");
	if (sstr.length > 0) {
		searchdisplayed = false;
		search = true;
		searchstr = sstr;
	}
	else {
		searchdisplayed = false;
		search = false;
		searchstr = "";
	}

	resetGraphicTables();
	createGraphicTables();
	for(var i=0;i<numtabs; i++) {
		updateGraphicTable(i);
	}

	if (searchdisplayed == false) {
		searchdisplayed = true;
		// alert("SEARCH RESULTS - DEFAULT TAB 0");
		setDisplayTab(0);
	}

	search = false;
	searchstr = "";
}

function mouse_event_handler(e) {

	e = e ||  window.event;
	var cell = e.srcElement || e.target;

	var tname = (cell.nodeType == 1) ? cell.tagName.toLowerCase() : '';

	while(tname != "table" && tname !="td" && tname != "th"){
	        cell= cell.parentNode || cell.parentElement;
	        tname = cell.tagName.toLowerCase();
	}

	if (tname == "td" || tname == "th") {
	    var newClass;

	    var cellIdx = _getCellIndex(cell);
	    var row = cell.parentNode || cell.parentElement;
	    var rowIdx = _getRowIndex(row);

	    if (cellIdx == 0 && rowIdx == 0) {
	        _clearHighlight();
	    }
	    else if (cellIdx == 0) {
	        _setRow();
	    }
	    else if (rowIdx == 0) {
	        // _setCol();
	    }
	    else {
	        _setRow();
	        // _setCol();
	    }
	}

	function _getTable() {
	    var tbleObj;

	    if (mouse_event_handler.previous.table)
	        return;
	    else {
	        tbleObj = row.parentNode || row.parentElement; //tbody
	        var tn = tbleObj.tagName.toLowerCase();
	        while (tn != "table" && tn != "html") {
	            tbleObj = tbleObj.parentNode || tbleObj.parentElement;
	            tn = tbleObj.tagName.toLowerCase();
	        }
	        mouse_event_handler.previous.table = tbleObj;
	    }
	}//eof _getTable

	function _clearHighlight() {
	    _clearRow();
	    // _clearCol();

	    mouse_event_handler.previous.row = null;
	    mouse_event_handler.previous.cellIdx = null;
	}//eof clearHighlight

	function _clearRow() {
	    if (mouse_event_handler.previous.row) {
	        mouse_event_handler.previous.row.className = "";
	        mouse_event_handler.previous.row.cells[0].className = "";
	    }
	}//eof clearRow

	function _setRow() {
	    _clearRow();
	    if (tname == 'td' || mouse_event_handler.previous.row != row) {
	        row.className = 'hlt';
	        row.cells[0].className = 'hlt';
	        mouse_event_handler.previous.row = row;
	    }
	    else {
	        mouse_event_handler.previous.row = null;
	    }
	}//eof setRow

	function _clearCol() {
	    _getTable();
	    if (mouse_event_handler.previous.cellIdx != null) {
	        var table = mouse_event_handler.previous.table;
	        var cell = mouse_event_handler.previous.cellIdx;
	        for (var i = 0; i < table.rows.length; i++) {
	            table.rows[i].cells[cell].className = '';
	        }
	    }
	}//eof clearCol

	function _setCol () {
	    _clearCol();
	    if (tname == 'td' || mouse_event_handler.previous.cellIdx != cellIdx) {
	        mouse_event_handler.previous.table.rows[0].cells[cellIdx].className = 'hlt';
	        var trs = mouse_event_handler.previous.table.rows;
	        for (var i = 1; i < trs.length; i++) {
	            trs[i].cells[cellIdx].className = 'hlt-col';
	        }
	        mouse_event_handler.previous.cellIdx = cellIdx;
	    }
	    else {
	        mouse_event_handler.previous.cellIdx = null;
	    }
	}//eof setCol

	function _getCellIndex(cell) {
	    var rtrn = cell.cellIndex || 0;

	    if (rtrn == 0) {
	        do{
	            if (cell.nodeType == 1) rtrn++;
	            cell = cell.previousSibling;
	        } while (cell);
	        --rtrn;
	    }
	    return rtrn;
	}//eof getCellIndex

	function _getRowIndex(row) {
	    var rtrn = row.rowIndex || 0;

	    if (rtrn == 0) {
	        do{
	            if (row.nodeType == 1) rtrn++;
	            row = row.previousSibling;
	        } while (row);
	        --rtrn;
	    }
	    return rtrn;
	}//eof getRowIndex

}//eof mouse_event

mouse_event_handler.previous = {cellIdx: null, row: null, table: null};

function addEvent(obj, event_name, fnc) {

	if (typeof obj == "undefined")
	    return;
	else if (obj.attachEvent)
	    obj.attachEvent("on"+event_name, fnc);
	else if (obj.addEventListener) // && !browser.isKHTML)
	    obj.addEventListener(event_name, fnc, false);
	else
	    obj["on" + event_name] = fnc;

}//eof addEvent


function init_table_selector(tableid) 
{
	addEvent(document.getElementById(tableid), "click", mouse_event_handler);
};

window.onunload = function () {
	mouse_event_handler.previous = null;
}




