var currENum		= 0;
var	processing	= false;
var pathToRoot	= './';


function runMenuItem(menuID, container, title, href) {
	if (!menuID) {
		console.error('Menu ID is blank');
		return false;
	}
	if (!href) href = pathToRoot +'fetches/fetch_page.php?view=menuitem&menu_id='+ menuID +'&json=0';
	
	switch (container) {
		case 'tab':
			var	ContID	= 'tab'+ assignEnum();
			href		+= ((href.indexOf('?') == -1)?'?':'&') +'cont_id='+ ContID;
			createTab (ContID, title, href, true);
		break;
		case 'dialog':
			var	ContID	= 'dialog'+ assignEnum();
			href		+= ((href.indexOf('?') == -1)?'?':'&') +'cont_id='+ DialogID;
			createDialog(ContID, title, href);
		break;
		case 'newwin':
			var	subWinID	= 'window'+ menuID;
			href			+= ((href.indexOf('?') == -1)?'?':'&') +'cont_id='+ subWinID;
			openFullSubWindow(href, subWinID);
		break;
		case 'win':
			window.location.href	= href;
		break;
	}
}

function assignEnum() {
	return currENum++;
}

function drawPage(data, container) {
	if (!container) return false;
	
	//	Load content into TableData container element
	dojo.byId(container).innerHTML	= urldecode(data.html);
	
	dojo.parser.parse(container);
	
	processing	= false;
	hideProgress();
}

function createDataGrid(structure, id) {
	if (!structure) return false;

    // create a new grid:
    var grid = new dojox.grid.DataGrid({
    	id: id,
    	jsId: id,
        clientSort: true,
        loadingMessage: '<div class="PBarLoading">Loading Data...</div>',
        noDataMessage: 'There are no records to display.',
        structure: structure
    },
    document.createElement('div'));
    
    return grid;
}

function loadTable(tableID, tableName, tableHead, linkID, linkRef) {
	if (!tableID && !tableName) return false;
	if (!tableHead) tableHead = tableName;
	
	var	href		= pathToRoot +'fetches/fetch_page.php?json=0&view=table'+ ((tableID) ?'&table_id='+ tableID:'') + ((tableName) ?'&table_name='+ tableName:'') +((linkID)?'&link_id='+ linkID + '&link_ref='+ linkRef:'');
	var	closable	= true;
	var	tabName		= ((tableID) ? tableID : tableName) + 'Tab';
	var cp			= createTab(tabName, tableHead, href, closable);

	return cp;
}


function loadTableData(DataGridID, TableID, searchText) {
	if (!DataGridID || !TableID) return false;
	
	dijDataGrid	= dijit.byId(DataGridID);
	if (dijDataGrid) {
		if (dijDataGrid.store) dijDataGrid.store.close();
		var	store	= new dojo.data.ItemFileReadStore({url: pathToRoot +'fetches/fetch_table_data.php?option=VIEW&table_id='+ TableID +((searchText)?'&search='+ searchText:'')});
		
		store.fetch({
			query: {id: '*'},
			gridID: DataGridID,
			isSearch: (searchText != ''),
			onComplete: function (items, request) {
				updateGridBottom(request.gridID, request.store, request.isSearch);
			},
			onError: function(){alert('An Error Occurred');}
		});
		
		dijDataGrid.setStore(store);
	}
}

function updateGridBottom(DataGridID, gridStore, isSearch) {
	if (!DataGridID || !gridStore)  return false;
	
	html		= '';
	html		+= gridStore._arrayOfAllItems.length +' Record' + ((gridStore._arrayOfAllItems.length > 1)?'s':'');
	if (isSearch) html += ' (Filtered)';
	
	bottID		= DataGridID.replace('TableData', 'Bottom');
	elBott		= dojo.byId(bottID);
	if (elBott) elBott.innerHTML	= html;
}

function onTableRowClick(cell) {

}


function doTableSearch(DataGridID, TableID, searchText) {
	if (!DataGridID || !TableID) return false;
	
	loadTableData(DataGridID, TableID, searchText);
}


function createTab (id, title, href, closable) {
	if (!title) console.error('A title for the tab has not been assigned');
	if (!id || !title || !href) return false;
	
	var cp	= dijit.byId(id);
	if (!cp) {
		showProgress();
		
		//	Create New Tab
		cp = new dijit.layout.ContentPane({
			id: id,
			title: title,
			style: 'padding: 0',
			closable: closable,
			href: href,
			onLoad: hideProgress,
			onClose: function () {
				//TabCont.removeChild(this);
				this.destroyDescendants();
				return true;
			},
			onDownloadError: function () {
				hideProgress();
				elError	= document.createElement('div');
				dojo.addClass(elError, 'Error');
				elError.innerHTML	= 'Unable to load the contents';
				this.node.appendChild(elError);
			}
		});
	    TabCont.addChild(cp);
	}
	
	if (cp) TabCont.selectChild(cp);
	
	return cp;
}


function createDialog(id, title, href) {
	if (!id) return false;
	
	//	Destroy Dialog Box if it already exists
	var	dialogBox	= dijit.byId(id);
	if (dialogBox) {
		dialogBox.hide();
	}
	
	showProgress();
	
	//	Open new dialog box
	dialogBox	= new dijit.Dialog({
		id: id,
		jsId: id,
		title: title,
		preload: true,
		parseOnLoad: true,
		href: href,
	});
	dialogBox.startup();
	
	dojo.connect(dialogBox, 'onLoad', dialogBox.show);
	dojo.connect(dialogBox, 'onLoad', 'hideProgress');
	dojo.connect(dialogBox, 'hide', function () {this.destroyRecursive(); return false;});
	
	return dialogBox;
}


function formatDate(strDate) {
	var	date	= parseMySQLDate(strDate);
	
	str	= new String();
	str	+= monthNames[date.getMonth()].substring(0,3);
	str	+= ' ';
	str	+= date.getDate();
	str	+= ', ';
	str	+= (date.getFullYear());
	
	return str;
}


function formatTime(strTime) {
	var	date	= parseMySQLTime(strTime);
	
	var	hour	= date.getHours();
	var ampm	= 'am';
	if (hour > 12) {
		hour	-= 12;
		ampm	= 'pm';
	}
	
	str	= new String();
	str += hour.toString();
	str	+= ':';
	if (date.getMinutes() < 10) str += '0';
	str	+= date.getMinutes();
	str += ampm;
	
	return str;
}


function formatDateTime(strDateTime) {
	var	date	= parseMySQLDateTime(strDateTime);
	
	str	= new String();
	str	+= monthNames[date.getMonth()].substring(0,3);
	str	+= ' ';
	str	+= date.getDate();
	str	+= ', ';
	str	+= (date.getFullYear());
	str += ' ';
	if (date.getHours() > 12) str += (date.getHours() - 12); else str += date.getHours();
	str	+= ':';
	if (date.getMinutes() < 10) str	+= '0';
	str	+= date.getMinutes();
	str	+= ':';
	if (date.getSeconds() < 10) str	+= '0';
	str	+= date.getSeconds();
	if (date.getHours() > 12) str += 'pm'; else str += 'am';
	
	return str;
}


function formatEdit(id) {
	var	tableName	= id.split(rowMarker);
	id				= tableName[1];
	tableName		= tableName[0];
	
	return "<div class=\"RowOpt Edit\" onclick=\"editRecord('"+ tableName +"', '"+ id +"');\" title=\"Edit this Record\"><img class=\"IconIBase IconEdit\" /></div>";		
}


function formatDelete(id) {
	var	tableName	= id.split(rowMarker);
	id				= tableName[1];
	tableName		= tableName[0];	
	
	return "<div class=\"RowOpt Delete\" onclick=\"deleteRecord('"+ tableName +"', '"+ id +"');\" title=\"Delete this Record\"><img class=\"IconIBase IconDelete\" /></div>";	
}


function getTableDataEditDelete(rowIndex, item) {
	if (!item) return this.defaultValue;
	
	return item.id[0];
}


function getTableDataDelete(rowIndex, item) {
	if (!item) return this.defaultValue;
	
	return item.id[0];		
}


function addRecord(tableID) {
	
}

function editRecord(tableID, id) {
	if (!tableID) return false;

	var	href		= pathToRoot +'fetches/fetch_page.php?view=data_entry&table_id='+ tableID +'&id='+ id +'&de_action=edit&json=0';
	var dialogBox	= createDialog('dialogEditRecord_'+ tableID +'_'+ id, ' ', href);
	
	return dialogBox;
}

function deleteRecord(tableID, id) {
	
}


function fieldHelp(fieldNumber) {
	processing	= true;
	showProgress();
	
	var xhrArgs = {
    	url: 'fetches/fetch_field_help.php?f='+ fieldNumber,
    	handleAs: 'json',
    	preventCache: true,
    	timeout: 15000,
    	load: function (response, ioArgs) {
			return response;
		},
		error: function (response, ioArgs) {
			alert('Unable to retrieve the help for this field.');
			return response;
		},
		handle: function (response, ioArgs) {
			processing	= false;
			hideProgress();
			
			if (response) {
				if (response.help) showHelp(urldecode(response.help));
				if (response.msg) showMsg(urldecode(response.msg));
				if (response.error) showError(urldecode(response.error));
			}
			
			return response;
		}
	};

	//Call the asynchronous xhrGet
	var deferred = dojo.xhrGet(xhrArgs);
	
	return deferred;
}

function refreshChartData(widgChart, chartID, legendID) {
	if (!widgChart || !chartID) return false;
	
	//	Remove Data Series
	while (widgChart.series[0]) {
		widgChart.removeSeries(widgChart.series[0].name);
	}
	
	//	Fetch New Chart Data
	var	deferred	= fetchChartData(widgChart, chartID);
	
	//	Update Legend (if supplied)
	deferred.addCallback(function () {dijit.byId(legendID).refresh();});
	
	return deferred;
}


function fetchChartData(widgChart, chartID, xAxis, yAxis, legendID, tooltip, moveSlice, highlight) {
	if (!widgChart || !chartID) return false;
	
	//	Add loading message to chart
	elLoading	= document.createElement('div');
	dojo.addClass(elLoading, "PBarLoading");
	elLoading.innerHTML	= "Loading...";
	widgChart.node.appendChild(elLoading);
	
	//	Remove Error message div
	elError	= dojo.byId(widgChart.node.id +'Error');
	if (elError) widgChart.node.removeChild(elError);
	
	var xhrArgs = {
    	url: pathToRoot +'fetches/fetch_chart_data.php?chart_id='+ chartID,
    	handleAs: 'json',
    	preventCache: true,
    	timeout: 15000,
    	widgChart: widgChart,
    	legendID: legendID,
    	elLoading: elLoading,
    	load: function (response, ioArgs) {
			widgChart	= ioArgs.args.widgChart;

			
			//	Add axes
			if (xAxis) {
				var	xParams	= {fixLower: "minor", natural: true, htmlLabels: false, stroke: "grey", majorTick: {stroke: "red", length: 4}, minorTick: {stroke: "gray", length: 2}};
				if (response.xLabels) xParams.labels = response.xLabels;
				widgChart.addAxis("x", xParams);
			}
			if (yAxis) widgChart.addAxis("y", {vertical: true, htmlLabels: false, min: 0, stroke: "black", majorTick: {stroke: "red", length: 4}, minorTick: {stroke: "gray", length: 2}});
			
			//	Add Data Series
			if (response.items.length) {
				for (var i = 0; i < response.items.length; i++) {
					if (!response.items[i].options) response.items[i].options = {};
					widgChart.addSeries(response.items[i].name, response.items[i].data, response.items[i].options);
				}
			} else {
				widgChart.addSeries(response.items.name, response.items.data, response.items.options);
			}
			
			//	Add animations if required
			if (moveSlice) var anim_a = new dojox.charting.action2d.MoveSlice(widgChart, "default");
	        if (highlight) var anim_b = new dojox.charting.action2d.Highlight(widgChart, "default");
	        if (tooltip) var anim_c = new dojox.charting.action2d.Tooltip(widgChart, "default");
	        
	        //	Render the Chart
			widgChart.render();
			
			//	Add Axes Titles is required
			if ("xTitle" in response) setAxisTitle(widgChart, "x", response.xTitle, 8);
			if ("yTitle" in response) setAxisTitle(widgChart, "y", response.yTitle, 8);
			
			//	Add Legend if Required
			if (legendID) var Legend = new dojox.charting.widget.Legend({chart: ioArgs.args.widgChart, horizontal: true}, legendID);

			return response;
		},
		error: function (response, ioArgs) {
			console.debug('Chart Error: ', response);
			
			widgChart	= ioArgs.args.widgChart;
			
			//	Add error message
			elError		= document.createElement('div');
			elError.id	= widgChart.node.id +'Error';
			dojo.addClass(elError, 'Error');		
			elError.innerHTML	= 'An error has occurred while loading this chart.';
			widgChart.node.appendChild(elError);
			
			
			return response;
		},
		handle: function (response, ioArgs) {
			//	Remove the loading message
			elLoading	= ioArgs.args.elLoading;
	        elLoading.parentNode.removeChild(elLoading);
			
			return response;
		}
	};

	//Call the asynchronous xhrGet
	var deferred	= dojo.xhrGet(xhrArgs);
	
	return deferred;
}

function setAxisTitle(chart, axisname, title, fontsizept) {
    var axis	= chart.axes[axisname];
    var dim		= chart.dim;
    var offsets	= chart.offsets;
    var ta		= chart.theme.axis;
    var taFont	= "font" in axis.opt ? axis.opt.font : ta.font;
    var x,y,label;
    var rotate	= 0;
    if (axis.vertical) {
        rotate	= 270;
        label	= title;
        y		= dim.height / 2  - offsets.b / 2;
        x		= 0+2*fontsizept;
    } else {
        label	= title;
        x		= dim.width / 2 + offsets.l / 2;
        y		= dim.height - fontsizept / 2;
    }
    var m		= dojox.gfx.matrix;
    var elem	= axis.group.createText({x:x, y:y, text:label, align: "middle"});
    elem.setFont({family: "Arial", size: fontsizept+"pt", weight: "bold"});
    elem.setFill('black');
    elem.setTransform(m.rotategAt(rotate, x,y));
}

function explodeChart(chartID, chartTitle) {
	if (!chartID && !chartTitle) return false;
	
	var	href	= pathToRoot +'fetches/fetch_page.php?view=chart&chart_id='+ chartID +'&json=0';
	
	return createTab('TabChart' +chartID, 'Chart: '+ chartTitle, href, true);
}


function showOptions(dropdownID) {
	if (!dropdownID) return false;
	
	dojo.removeClass(dojo.byId(dropdownID), 'Hid');
}

function hideOptions(dropdownID) {
	if (!dropdownID) return false;
	
	dojo.addClass(dojo.byId(dropdownID), 'Hid');
}

function toggleOptions(dropdownID) {
	if (!dropdownID) return false;
	
	elDropDown	= dojo.byId(dropdownID)
	
	if (dojo.hasClass(elDropDown, 'Hid')) {
		dojo.removeClass(elDropDown, 'Hid');
	} else {
		dojo.addClass(elDropDown, 'Hid');
	}
}
