// DEAR chart SCRIPT

// variables

var SelectedColumn=0; // holds selected column 
var ChartType="Pie"; // holds selected chart type
var ChartMax=-1; // 0= no limit, >0 limit # data points, -1 = limit to color array size -1
var ChartMode="R"; // R= regular, P=Portfolio, D= Dashboard
var Debugging=false; // do/not provide alerts from dalert function
var ChartsInitialized=false; // have we initialized the chart(s) yet?
var wd="100%"; // dashboard mode chart width
var ht=screen.height*.2; // dashboard mode chart height
var chtIndex=0; // current array index;
var cht = new Array(); // holds  charts
var tbl = new Array;  // holds  tables
var ChartLocs = new Array(); // urls for loading the charts in dashboard
var Titles=new Array(); // holds titles
var AnalysisTables = new Array(); // holds tables for charts
var ChartContext=new Array(); // holds chart objects
var ActiveSegment=new Array();
var chartBtns; // holds chart open close buttons...
var SelectedColumn=new Array(); // hold selected column
var displaymode=new Array(); // hold of display mode 1 for show 0 for hide
var DEARCharts; // holds div if mode="R" or "P"
var xhttp; // holds either XMLHttpRequest or XMLHTTP object - depending on browser
var svgurl="../../reports/scripts/svg/chart/chart.svg"; // holds url to the svg file
var childdlgurl="../../reports/scripts/svg/chart/ChildOpen.html"; // holds url to the child dialog file
var forceChildData=false;

//
// Initializer function  caleed by first chart button click or onload of dashboard
//

function InitializeCharting() {

	if(Debugging) { alert ('dearchart.js.InitializeCharting')};
	
	// figure out chart url
	bsavelocal = false; //saved complete to local.
	
	if(window.location.protocol=="file:") {
			var metacount=document.getElementsByTagName("META").length
			for(idx=0;idx<metacount;idx++) {
				if ( document.getElementsByTagName("META")[idx].getAttribute("name")=="GENERATOR") {
					svgurl=document.getElementById("chartimg").href; 
					childdlgurl= document.getElementById("childopen").href;
					bsavelocal = true;
				}
			}
			if (bsavelocal == false) {
				svgurl="../../reports/scripts/svg/chart/chart.svg";
				childdlgurl="../../reports/scripts/svg/chart/ChildOpen.html";
				if(window.location.pathname.indexOf("ExpandedChart")>=0) {
					svgurl="../../reports/scripts/svg/chart/chart.svg";
					childdlgurl="../../reports/scripts/svg/chart/ChildOpen.html";
				}
			}
	}
	//else {
		
		
		//svgurl=window.location.protocol + "//" + window.location.host+window.location.pathname
		//svgurl=svgurl.substr(0,svgurl.lastIndexOf("/"))+"../../reports/scripts/svg/chart.svg";
		//alert(svgurl);
	//}
	
	//svgurl="./scripts/svg/chart.svg";
	// see what our chart mode is...
		// find all maindata tables
		
		var nds=document.all;
		var tb;
		var idx;
		var tbls=document.getElementsByTagName("TABLE");
		var mdts=new Array;
		var divs=new Array();
		var chttbls=new Array();
		chartBtns = new Array();
		
		for(tb =0;tb< tbls.length;tb++) {
			if(tbls[tb].getAttribute("id")=="maindata") mdts[mdts.length]=tbls[tb];
			else if(tbls[tb].getAttribute("id").indexOf("chart") >= 0) chttbls[chttbls.length]=tbls[tb];
			//else alert(tbls[tb].getAttribute("id")+ String(tbls[tb].getAttribute("id").indexOf("chart")))
		}
		//alert("Found " + chttbls.length +" of " + tbls.length)
		tbls=document.getElementsByTagName("DIV");
		for(tb =0;tb< tbls.length;tb++) divs[divs.length]=tbls[tb];
		if(mdts.length==0) {
			// initialize for dashboard mode
			ChartMode="D"
			
			chtIndex=0
			var chartcount=document.getElementsByTagName("chart").length
			
			
				for(idx=0;idx<chartcount;idx++) {
					SetupChartData(
						idx,
						document.getElementsByTagName("chart")[idx].getAttribute("url"), 
						document.all.namedItem("chart"+(idx+1)+"data"),
						document.all.namedItem("chart"+(idx+1)),
						document.getElementsByTagName("chart")[idx].getAttribute("type"),
						document.getElementsByTagName("chart")[idx].getAttribute("column"),
						document.getElementsByTagName("chart")[idx].getAttribute("display"))
					if(document.getElementsByTagName("chart")[idx].getAttribute("url")=="")
					{
						//alert("Setting table for chart " + document.getElementsByTagName("chart")[idx].getAttribute("table"))
						var chtid=document.getElementsByTagName("chart")[idx].getAttribute("table")
						for(tb=0;tb<chttbls.length;tb++) if(chttbls[tb].getAttribute("id") == chtid) {
							//alert("found " + chtid)
							AnalysisTables[idx]=chttbls[tb];
						}


					}
				}			
				LoadOneChart();
				
					
				
				
				

		}
		else if(mdts.length > 1) {
			// initialize for Portfolio/Panel mode
			ChartMode="P"
			// find divs and tables for each main data table
			var cx=document.getElementsByTagName("TD")
			for(tb=0;tb<cx.length;tb++) try {
				if(new String(cx[tb].getAttribute("onclick")).indexOf("LoadGraph") > 0 ) {
					chartBtns[chartBtns.length]=cx[tb].uniqueID;	
					// find accompanying div...
					var theDiv;
					for(idx=0;idx<divs.length;idx++) if(divs[idx].sourceIndex > cx[tb].sourceIndex) {
						theDiv=divs[idx];			
						break;
					}
					var theTbl;
					// find accompanying table...
					for(idx=0;idx<mdts.length;idx++) if(mdts[idx].sourceIndex > cx[tb].sourceIndex) {
						theTbl=mdts[idx];			
						break;
					}
					SetupChartData(chartBtns.length-1,null, theTbl,theDiv,ChartType,0)
				}
			}
			catch(e) {} finally {}
			
		}
		else {
			// initialize for Regular mode
			// find first div that has an id of 'DEARCharts'
			
			for(tb =0;tb< divs.length;tb++) if(divs[tb].id='DEARCharts') { DEARCharts=divs[tb]; break;}
			
			
		}
		ChartsInitialized=true;
	// initialize chart arrays
	
}


// 
// set up chart arrays for one chart chart mode =P or D
//
function SetupChartData(chartid,chartURL, chartData,chartDiv,chartType,chartColumn, chartDisplay) { 
	
	if(Debugging) { alert ('dearchart.js.SetupChartData')};
	
	if(ChartMode=="P") AnalysisTables[chartid]=chartData;
	ChartLocs[chartid]=chartURL
	tbl[chartid]=chartData
	cht[chartid]=chartDiv
	ActiveSegment[chartid]=chartType
	SelectedColumn[chartid]=chartColumn
	Titles[chtIndex]="";
	
	if (chartDisplay == null )
		{
			displaymode[chartid]= 1;  //1 for show 
		}
		else {
			displaymode[chartid]= 0;  //0 for hide
		}
	
	
	//Titles[chartid]=chartURL
}

//
// child dialog  functions
//

function ChildChart(chartindex) { // open a drill down or expand a dashboard chart
	if(Debugging) { alert ('dearchart.js.ChildChart')};
	
	window.showModalDialog(childdlgurl,ChartContext[chartindex])
}

function SayStatus(msg) { // show status on dialog
	if(Debugging) { alert ('dearchart.js.SayStatus')};
	
	try { 	document.all.namedItem("statusinfo").innerText=msg; } catch(e) {} finally {}
}

function HandleDrillDown() { // let parent know when we are loaded
	if(Debugging) { alert ('dearchart.js.HandleDrillDown')};
	
		window.opener.setDrillDownGraphDoc(document); 
}


//
// dashboard specific functions
//


function LoadOneChart(){ // load data into a div for a chart
	if(Debugging) { alert ('dearchart.js.LoadOneChart')};
	
// perform set up functions
	if(chtIndex>=ChartLocs.length) {
		SayStatus("")
		return; // stop when all loaded

	}
	if(ChartLocs[chtIndex]!='') {

		//instantiate XmlHttpRequest

		  // Checking if IE-specific document.all collection exists
		  // to see if we are running in IE
		  if (document.all) {
		    xhttp = new ActiveXObject("Msxml2.XMLHTTP");
		   } else {
		  // Mozilla - based browser
		    xhttp = new XMLHttpRequest();
		  }
		  SayStatus("Loading chart " + chtIndex + " from " +ChartLocs[chtIndex])
		  //hook the event handler
		  xhttp.onreadystatechange = HandlerOnReadyStateChange;
		  //prepare the call, http method=GET, false=asynchronous call
		  xhttp.open("GET", ChartLocs[chtIndex], false);
		  //finally send the call
		  xhttp.send();
	}
	else {
		// it is contained in a table in the div already
		try {
		if (displaymode[chtIndex] == 0) {
			cht[chtIndex].innerHTML='<embed name="chart' + chtIndex +'" src="'+svgurl+'" width="' + 0 + '" height="' + 0 + '" type="image/svg+xml">';
			}
		else {
			cht[chtIndex].innerHTML='<embed name="chart' + chtIndex +'" src="'+svgurl+'" width="' + wd+ '" height="' + ht + '" type="image/svg+xml">';
			}
		}
		catch(e) {} finally {}
		
	}
}

function HandlerOnReadyStateChange(){  // handler for ready state change event for xmlhttp - dashboard mode only
	if(Debugging) { alert ('dearchart.js.HandlerOnReadyStateChange')};

// This handler is called 4 times for each
// state change of xmlhttp
// States are: 0 uninitialized
//      1 loading
//      2 loaded
//      3 interactive
//      4 complete
if (xhttp.readyState==4){

    tbl[chtIndex].innerHTML = xhttp.responseBody;

    AnalysisTables[chtIndex]=tbl[chtIndex].all.namedItem("mainData");
    cht[chtIndex].innerHTML='<embed name="chart' + chtIndex +'" src="'+svgurl+'" width="' + wd+ '" height="' + ht + '" type="image/svg+xml">';
		try {
    var RespText=xhttp.responseText;

    var itle=RespText.split("itle>")

		Titles[chtIndex]= itle[1].replace("</t", '').replace("</T","");
		}
		catch(e) {
			try {
	    var RespText=xhttp.responseBody;

	    var itle=RespText.split("itle>")

			Titles[chtIndex]= itle[1].replace("</t", '').replace("</T","");
			}
			catch(e) {Titles[chtIndex]=="";} finally{}
		}
		finally{}

  }

}

//
// Misc helper funcitons
//

function dalert(mess) { // debugging alert

	//if(Debugging) { alert ('dearchart.js.dalert')};
	
	if(Debugging) alert(mess);
}

function getDocument() {
	if(Debugging) { alert ('dearchart.js.getDocument')};
	return document;
}
//
// General Error Reporting Alert
//
var vbcrlf=String.fromCharCode(13,10)
function ErrorAlert(e) {

	if(Debugging) { alert ('dearchart.js.ErrorAlert')};
	
	// e is the error object
	msg="Error in "+ ErrorAlert.caller + ": " + vbcrlf
	msg+="    Error Number: " + e.number +vbcrlf
	msg+="          Description: " + e.description
	alert(msg)
}

//
// Load Graph function - called from chart button click
//


function LoadGraph() { 

	if(Debugging) { alert ('dearchart.js.LoadGraph')};
	
	
	if(!ChartsInitialized) InitializeCharting();
	if(svgurl=="chart.svg") ChartMode="R"
	var GraphsLoaded=false;
	
	
	DEARCharts=document.all.namedItem("DEARCharts")
	
	if(ChartMode=="R") {
		try{
		
		if(DEARCharts.innerHTML!="") {GraphsLoaded=true;}
		
		if(GraphsLoaded) {
			
			if(DEARCharts.style.display=="none") {DEARCharts.style.display="";}
			else {DEARCharts.style.display="none";}
			//DEARCharts.innerHTML="";
			//DEARCharts.width=0;
		}
		else {
			// load graphs

			
			DEARCharts.innerHTML='<embed src="'+svgurl+'" width="100%" height="392.5" type="image/svg+xml">'
		}
		}
		catch(e) {
			
		}
	}
	else if(ChartMode=="P")
	{
		// find the chart to open and set its index into chtIndex
		var e=window.event
		var SrcElement=e.srcElement
		var srcID=SrcElement.uniqueID
		chtIndex=-1;
		for(var idx=0;idx<chartBtns.length;idx++) {
			if(chartBtns[idx]==srcID) {
				chtIndex=idx;
				break
			}
		}
		if(chtIndex>-1) {
			
			DEARCharts=cht[chtIndex];
			
			if(DEARCharts.innerHTML!="") {GraphsLoaded=true;}
			if(GraphsLoaded) {
				if(DEARCharts.style.display=="none") {DEARCharts.style.display="";}
				else {DEARCharts.style.display="none";}
				//DEARCharts.innerHTML="";
				//DEARCharts.width=0;
			}
			else {
				
				// load graphs

				DEARCharts.innerHTML='<embed src="'+svgurl+'" width="100%" height="392.5" type="image/svg+xml">'
			}
		}
		else {
			var msg ="Cannot find info for chart" + srcID + String.fromCharCode(13,10);
			for(idx=0;idx<chartBtns.length;idx++) {
				msg+= chartBtns[idx] + String.fromCharCode(13,10)
			}
			
			alert(msg)
			chtIndex=0;
		}
		
	}

}

function LoadGraphEx() {  
	if(Debugging) { alert ('dearchart.js.LoadGraphEx')};

	InitializeCharting()
	ChartMode="R"
	forceChildData=true;
	LoadGraph()

	
}
