/* 
	This library contains the functionality for updating the graphs, data table, and dials on
	every data page.
*/

// Store the general utility functions in variable gen
var gen = new generalUtils();

// Run this function when the pages loads to fill data table and update graph options
function initPage(){
	if(true){
		updateDials(false);
		changeStats(graph_dir,graph_type);
	}
}

// Called when the buttons under the graph are clicked to update the graph type
function updateGraphType(obj,index){
	var userDefined = $('userDefinedDate');
	// Verify dates if this is a user defined plot
	if((userDefined.visible() && gen.verifyDates('startDate','endDate')) || !userDefined.visible()){
		// First check to see if this is a new plot
		if(!Element.hasClassName(obj,"optionButtonSelected") && !Element.hasClassName(obj,"bottomButtonCurrent")){
			// Check to see if this is an option tab or a main tab.  Change the tab properties
			// depending on which has been selected.  Regardless, take the title of the option
			// tab and convet it to the values needed for the graph.
			var isOptionTab = obj.parentNode.id == "bottomGraphQueries" ? false : true;
			
			// If this is a main tab do the following	
			if(!isOptionTab){
				// Change the main bottom tabs
				gen.changeTabs(obj,"bottomButton","bottomButtonCurrent");
				
				// get a list of option lists
				var optionList = document.getElementsByClassName("optionListItem","bottomWrapper");
				
				for(var i = 0; i < optionList.length; i++){
					if(i === index){
						optionList[i].setStyle({display: "block"});
						var graphOptions = optionList[i].getElementsByClassName("optionButtonSelected");
						var dir = graphOptions[0].id.split('0')[0];
						var type = graphOptions[0].id.split('0')[1];
					}else{
						optionList[i].setStyle({display: "none"});
					}
				}
				
				// Call functions to change the graph and data table information
				changeStats(dir,type);
		
			// If it is an option tab, do the following
			}else{
				// Get the directory and data type from the id of the option tab
				var dir = obj.id.split('0')[0];
				var type = obj.id.split('0')[1];
				
				// Get the currently selected element and deselect it
				gen.changeTabs(obj,"optionButton","optionButtonSelected");
			}
			// Always change the graph at this point
			swapGraph(dir,type,graph_time);
			
			// Set global variables for next graph request
			graph_dir = dir;
			graph_type = type;
		}
	}
	
}

// Used to update the time frame of the current graph
function updateGraphTime(time,obj){
	// Only update the plot if the time changes
	if (time != graph_time) {
		// Update the tabs to reflect the current time range
		gen.changeTabs(obj,"topButton","topButtonCurrent");
		swapGraph(graph_dir,graph_type,time);
		graph_time = time;
	}else{
		// Hide the custom plotting features if shown
		var userDefined = $('userDefinedDate');
		if(userDefined.visible()){
			// Update the tabs to reflect the current time range
			gen.changeTabs(obj,"topButton","topButtonCurrent");
			userDefined.hide();
		}
							   
	}
}

// Function to change the graph based on a directory, grahp type, and data range
function swapGraph(dir,type,time) {
	// If the custom div is showing but the user has chosen another set time frame, hide it
	if (time != 'custom' && type == graph_type){
		if ($('userDefinedDate').visible()){
			$('userDefinedDate').hide();
		}
	}
	
	var graph = $('graph'); // graph object (div)

	graph.style.filter = "alpha(opacity=10)"; // IE
	graph.style.opacity = 0.1; // Opera/Firefox

	// If it's not a custom graph, just get the standard type, otherwise pass the start and end dates in
	var pathToGraphs = '../../../../sentalis-framework/lib/phplib/packages/'+dir+'/graphs/'+type+'.php';
	var graphData = '?client='+client+'&project='+project+'&range='+time+'&dataEnd='+dataEnd+'&dataStart='+dataStart+'&dummy=' + new Date().getTime();
	if (time == 'custom') {
		graphData += "&startDate=" + gen.startDate + "&endDate=" + gen.endDate;
	}
	
	// Set the src attribute of the graph image to the new graph
	graph.setAttribute('src',pathToGraphs+graphData);
	
	// Once the new image loads, change the opacity to 100%		
	graph.onload = function () {
		// Instantly fade in the graph.  This was originally done with effects, but the 
		// browser cpu usage would sky rocket.
		graph.style.filter = "alpha(opacity=100)"; // IE
		graph.style.opacity = 1.0; // Opera/Firefox
	};

} 

function CustomGraph(dir,type) {
	// The data has been validated, plot the custom graph
	if (gen.verifyDates('startDate','endDate')) {
		swapGraph(dir,type,'custom');
		// Set global variables for next graph request
		graph_dir = dir;
		graph_type = type;
		graph_time = 'custom';
	}
	
	return false; // don't allow the form to be submitted ever
}

// Function used to toggle the custom plotting box
function toggleCustom(id,obj){
	var e1 = $(id);

	// Update the tabs
	gen.changeTabs(obj,"topButton","topButtonCurrent");
	
	// If the user defined date box is being hidden, change tab back to the one it was on before
	if(e1.visible() && graph_time != "custom"){
		var time = $('_'+graph_time);
		gen.changeTabs(time,"topButton","topButtonCurrent");			
	}

	// If the export data box is still highlighted, change it back.
	var exportButton = $('buttonExport');
	if(Element.hasClassName(exportButton,'buttonExportSelected')){
		Element.toggleClassName(exportButton,'buttonExport');
		Element.toggleClassName(exportButton,'buttonExportSelected');
	}
		
	e1.toggle();	
}

/******************************** DOWNLOAD DATA **************************************/
function dataDownload(){
	var e = $("exportDataForm");
	var input = document.getElementsByName("range");
	
	var typeValue = e.getInputs('radio','range');
	var range = "2day";
	typeValue.each(function(s,index) { 
		if(typeValue[index].checked){
			range = typeValue[index].value;
		}
	});
	
	if ((range == "custom" && gen.verifyDates('exportStartDate','exportEndDate') || range != "custom")){
		// The data has been validated, Make an asynchronous request for it
		if (confirm("Are you sure you want to export data?")){
			var urlData = "exportData.php?client="+client+"&project="+project+"&range="+range+"&fileInfo="+gen.fileInfo;
			if(range == "custom"){
				urlData += "&dataEnd=" + dataEnd + "&dataStart=" + dataStart + "&startDate=" + gen.startDate + "&endDate=" + gen.endDate;
			}
			
			$("exportWait").style.display = "block";
			
			document.exportDataForm.action = urlData;
			document.exportDataForm.submit();
		}
	}
	return false;	
}


/******************************** STATS/DATA TABLE ************************************/
function changeStats(dir,type){
	if ($('dataTable').visible()){
		$('dataTableImg').show();
		$('dataTable').hide();
	}
	
	// Run this function only if it is a new data type
	var url = "../../../../sentalis-framework/lib/phplib/common/dataTable.php";
	var data = "client="+client+"&project="+project+"&dataDir="+dir+"&dataType="+type;
	
	if (dataEnd === "") {
		data += "&getEnergy=true"; // get the energy on the first call only
	}
	var callback = changeStatsCallback;
	var statsAjax = new Ajax.Request(url,{method: 'post',parameters: data,onComplete: callback});
}

function changeStatsCallback(request){
//	var stat = request.responseText;
//	alert(stat);
	
	var xml = request.responseXML;
		
	// Update the date on the page and the dataEnd variable
	var dataDate = gen.$TAG(xml,"dataDate");
		
	$('lastTimestamp').innerHTML = dataDate;
	
	// Update the fileInfo variable
	gen.fileInfo = gen.$TAG(xml,"fileInfo");
	
	// Store the data End as mm/dd/YYYY
	dataEnd = gen.$TAG(xml,"dataDate2");
	
	// Update the start Date of data variable
	dataStart = gen.$TAG(xml,"startDate");

	// Get all row values and put them on the main form
	$A(xml.getElementsByTagName("row")).each(function(e,i){
		var str = e.firstChild.nodeValue.split(",");
		$("value"+i).innerHTML = gen.getUnicode(str[1]).addCommas();
		$("unit"+i).innerHTML = gen.getUnicode(str[2]);
		$("label"+i).innerHTML = gen.getUnicode(str[0]);
	});
	
	// If this is the first time the page loads, hide the data table until the data is available
	if (!$('dataTable').visible()){
		$('dataTableImg').hide();
		$('dataTable').show();
	}
	
	// Everytime new data is available to the page, update the calendar so it
	// will drop down with the latest month regardless of what it was originally.
	prepcalendar(); // prepare user defined calendar
	
}

/************************************** UPDATE DIALS *****************************************/
function updateDials(pLoad){
	// Run this function only if it is a new data type
	var url = "../../../../sentalis-framework/lib/flashlib/gaugelib/gauge-data.php";
	var data = "client="+client+"&project="+project+"&pageName="+pageName;
	var callback = updateDialsCallback;
	var dialsAjax = new Ajax.Request(url,{method: 'post',parameters: data,onSuccess: callback});
	gen.pLoad = pLoad;
}

function updateDialsCallback(request){
	var reply = request.responseText;
	//alert(reply);
	
	// Store XML data in an object
	var xml = request.responseXML;
	
	// Get all row values and put them on the main form
	$A(xml.getElementsByTagName("leftDial"))[0].firstChild.nodeValue.split(",").each(function(e,i){
		$('left_dial_val'+(i+1)).innerHTML = e.addCommas();	
	});
	
	$A(xml.getElementsByTagName("rightDial"))[0].firstChild.nodeValue.split(",").each(function(e,i){
		$('right_dial_val'+(i+1)).innerHTML = e.addCommas();
	});
	
	if (gen.pLoad) {
		var urlLeft = "dials/"+pageName+"-left.php";
		var urlRight = "dials/"+pageName+"-right.php";
		updateGauge(urlLeft,'left');
		updateGauge(urlRight,'right');
	}
}

function updateGaugeLeftCallback(request){
	var xml = request.responseText;
	//alert(xml);
	setFCNewData('left_dial',xml);
}

function updateGaugeRightCallback(request){
	var xml = request.responseText;
	//alert(xml);
	setFCNewData('right_dial',xml);
}

function updateGauge(url,side){
	// Run this function only if it is a new data type
	var data = "gaugeSide="+side;
	var callback = side == "left" ? updateGaugeLeftCallback : updateGaugeRightCallback;
	var dialsAjax = new Ajax.Request(url,{method: 'post',parameters: data,onSuccess: callback});
}

function setFCNewData(objFlash, strXML)
{
    //This function updates the entire XML data for a chart.
    //Get a reference to the movie
	var FCObject=getObject(objFlash);
    //Set the data
    //Set dataURL to null
    FCObject.SetVariable("_root.dataURL","");
    //Set the flag
    FCObject.SetVariable("_root.isNewData","1");
    //Set the actual data
    FCObject.SetVariable("_root.newData",strXML);
    //Go to the required frame
    FCObject.TGotoLabel('/','JavaScriptHandler');
}

function getObject(objectName) {
    if (navigator.appName.indexOf ("Microsoft") !=-1) {
        return window[objectName]
    } else {
        return document.embeds[objectName];
    }
}

/*********************************  INTERVAL UPDATE **************************************/
function checkDate(){
	// get the last timestamp from the page
	var latestTimestamp = gen.getText($('lastTimestamp'));
	
	// Run this function only if it is a new data type
	var url = "../../../../sentalis-framework/lib/phplib/common/checkDate.php";
	var data = "client="+client+"&project="+project+"&date=" + latestTimestamp;
	var callback = checkDateCallback;
	var dateAjax = new Ajax.Request(url,{method: 'post',parameters: data,onSuccess: callback});
	
}

function checkDateCallback(request){
	//var data = request.responseText;
	//alert(data);

	var xml = request.responseXML;
	
	if(xml === null){
		// do nothing
	}else{
		//alert(xml);
		// Get value that determines if page should be updated.  Only update if 'yes' is returned
		var updatePage = gen.$TAG(xml,"update").split(",");
			
		// If the page is supposed to be updated, based on a comparison of timestamps in the PHP script, update the page
		if (updatePage =='yes'){
			// Update the data table
			changeStats(graph_dir,graph_type);
			
			// If the graph is a 2day plot, force it to update
			swapGraph(graph_dir,graph_type,graph_time);
	
			// Update the dials
			updateDials(true);
		}
	}
}