var xmlHttp
var xmlDoc
var url
var xmlHttpInception

function exec(functionCall){ 

	//reset fields
	document.getElementById("totals_top").innerHTML="";
	//document.getElementById("totals_bottom").innerHTML="";
	
	xmlHttp=GetXmlHttpObject();

	if (xmlHttp==null)
	  {
	  alert ("Your browser does not support AJAX!");
	  return;
	  } 
	var functionVars=functionCall.split(",");
	if (functionVars[0]=="getData"){
		url="getDirectory.php";
		url=url+"?sid="+Math.random();
		xmlHttp.onreadystatechange=findRecentData;
	}else if(functionVars[0]=="loadSummary"){
		url="loadSummary.php";
		url += "?type="+functionVars[1];
		url += "&date="+functionVars[2];
        url += "&sid="+Math.random();
		xmlHttp.onreadystatechange=loadedSummary;
	}

	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}


function loadedInception(){
	if (xmlHttpInception.readyState==4 || xmlHttpInception.readyState=="complete"){
		xmlDocInception=xmlHttpInception.responseXML.documentElement;
		
		var outputTotals="";	
		var totalsXML=xmlDocInception.getElementsByTagName("totals");
		/*
		outputTotals = 'Inception - Total Share Qty' + totalsXML[0].childNodes[0].firstChild.nodeValue + '<br/>';
		outputTotals += 'Inception - Total Value' + totalsXML[0].childNodes[1].firstChild.nodeValue + '<br/>';
		outputTotals += 'Inception - Total Trades' + totalsXML[0].childNodes[2].firstChild.nodeValue + '<br/>';
		
		document.getElementById("tradesBox").innerHTML=totalsXML[0].childNodes[2].firstChild.nodeValue;
		document.getElementById("sharesBox").innerHTML=totalsXML[0].childNodes[0].firstChild.nodeValue;*/
	}
}

function loadedSummary(){
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		var xmlDocCsv=xmlHttp.responseXML.documentElement;
		//error checking for null, errro reespone, or summary response
		if(xmlDocCsv==null){
			document.getElementById("summary").innerHTML = "Could not load data";
		}else if(xmlDocCsv.getElementsByTagName('error').length!=0){
			tmp=xmlDocCsv.getElementsByTagName('error');
			document.getElementById("summary").innerHTML = tmp[0].firstChild.nodeValue;
		}else if(xmlDocCsv.getElementsByTagName('summary').length!=0){
			//print column titles (not curently read from php but the feature is there)
			outputTable = '<table width="550" style="margin-top:25px; border-bottom:1px solid #7E8B7A" border="0" cellpadding="0" cellspacing="0" id="summaryTable">'+
			'<tr><td id="leftCell" class="topRow">Symbol</td>'+
			'<td id="leftCell" class="topRow">Security Name</td>'+
			'<td id="dailySummaryCell" width="60px" class="topRow">Share Volume</td>'+
			'<td id="dailySummaryCell" class="topRow">Dollar Value</td>'+
			'<td id="dailySummaryCell" width="20px" class="topRow">Trades</td></tr>';
			
			
			tradesXML=xmlDocCsv.getElementsByTagName('trade');
			for (i=0;i<tradesXML.length;i++)
			  {
				var securitySymbol=tradesXML[i].childNodes[0].firstChild.nodeValue;
				var securityName= URLDecode(tradesXML[i].childNodes[1].firstChild.nodeValue);
				var shareQty=tradesXML[i].childNodes[2].firstChild.nodeValue;
				var dollarValue=tradesXML[i].childNodes[3].firstChild.nodeValue;
				var trades=tradesXML[i].childNodes[4].firstChild.nodeValue;
				outputTable +='<tr text-transform:uppercase;>'+
				'<td id="leftCell">'+securitySymbol+'</td>'+
				'<td id="leftCell">'+securityName+'</td>'+
				'<td id="dailySummaryCell">'+shareQty+'</td>'+
				'<td id="dailySummaryCell">'+dollarValue+'</td>'+
				'<td id="dailySummaryCell">'+trades+'</td>'+
				'</tr>';
				
			  }
			
			/*numTrades=xmlDocCsv.childNodes[0].childNodes.length-1;
			for(i=0; i<numTrades; i++){
				var securitySymbol=xmlDocCsv.childNodes[0].childNodes[i].childNodes[0].firstChild.nodeValue;
				var securityName= URLDecode(xmlDocCsv.childNodes[0].childNodes[i].childNodes[1].firstChild.nodeValue);
				var shareQty=xmlDocCsv.childNodes[0].childNodes[i].childNodes[2].firstChild.nodeValue;
				var dollarValue=xmlDocCsv.childNodes[0].childNodes[i].childNodes[3].firstChild.nodeValue;
				var trades=xmlDocCsv.childNodes[0].childNodes[i].childNodes[4].firstChild.nodeValue;
				outputTable +='<tr><td>'+securitySymbol+'</td><td>'+securityName+'</td><td>'+shareQty+'</td><td>'+dollarValue+'</td><td>'+trades+'</td></tr>';
			}
			*/
			outputTable +='</table>';
			
			/*outputTotals = 'Total Share Qty' + xmlDocCsv.childNodes[0].childNodes[numTrades].childNodes[0].firstChild.nodeValue + '<br/>';
			outputTotals += 'Total Value' + xmlDocCsv.childNodes[0].childNodes[numTrades].childNodes[1].firstChild.nodeValue + '<br/>';
			outputTotals += 'Total Trades' + xmlDocCsv.childNodes[0].childNodes[numTrades].childNodes[2].firstChild.nodeValue + '<br/>';
			*/
			document.getElementById("summary").innerHTML=outputTable;
			
			//display totals
			totalsXML=xmlDocCsv.getElementsByTagName('totals');
			
			outputTotals = '<table width="220" border="1px" rules="all" style=" border-collapse:collapse;border:1px solid #7E8B7A;"><tr><td>Total Share Volume</td><td align="right">' + totalsXML[0].childNodes[0].firstChild.nodeValue + '</td></tr>';
			outputTotals += '<tr><td>Total Dollar Value </td><td align="right">' + totalsXML[0].childNodes[1].firstChild.nodeValue + '</td></tr>';
			outputTotals += '<tr><td>Total Trades </td><td align="right">' + totalsXML[0].childNodes[2].firstChild.nodeValue + '</td></tr>';
			outputTotals += '</table>';
			
			
			document.getElementById("totals_top").innerHTML=outputTotals;
			//document.getElementById("totals_bottom").innerHTML=outputTotals;
			
			alternateRowColours("summaryTable");
			document.getElementById("sortLink").setAttribute("href","javascript:init(document.getElementById('summaryTable'));");
			document.getElementById("entireSummaryLink").removeAttribute("href");
			document.getElementById("entireSummary").style.backgroundColor="#6DB13F";
			document.getElementById("sorters").style.backgroundColor="#4F504E";
			
			//alert(entireSummary);
			if(entireSummary==false){
				init(document.getElementById('summaryTable'));
			}else{
				
			}
		}
	}
}

function alternateRowColours(tableId){
	var table = document.getElementById(tableId);  
   	var rows = table.getElementsByTagName("tr");  
   	for(i = 1; i < rows.length; i++){          
 	//manipulate rows
    	if(i % 2 == 0){
     		rows[i].className="light";
     	}else{
			rows[i].className="dark";
    	}      
  	} 
}

function URLDecode(psEncodeString)
{
  // Create a regular expression to search all +s in the string
  var lsRegExp = /\+/g;
  // Return the decoded string
  return unescape(String(psEncodeString).replace(lsRegExp, " "));
}

function loadYear(year)
{
	document.getElementById("colMonth").innerHTML = "";
	document.getElementById("colDay").innerHTML = "";
	
	yearId="year_"+year;
	
	//remove bgcolor from all year elemnts
	//for(i=0;i<xmlDoc.childNodes.length -1;i++)
	//{
		//yrId = "year_"+i;
		//document.getElementById(yearId).style.backgroundColor = '';
//	}

//	document.getElementById(yearId).style.backgroundColor="#6DB13F";
	displayMonths(year);
	
	yearName = xmlDoc.childNodes[year].getAttribute("name");
	//load the yearly summary.
	//yearly summary is based on 31 dec of that year 
	//dayString = yearName+'12'+'31';
	
	//yearly summary based on most recent data available for that year
	totalMonths=xmlDoc.childNodes[year].childNodes.length-1;
	monthName=xmlDoc.childNodes[year].childNodes[totalMonths].getAttribute("name");
	
	totalDays=xmlDoc.childNodes[year].childNodes[totalMonths].childNodes.length-1;
	dayName=xmlDoc.childNodes[year].childNodes[totalMonths].childNodes[totalDays].getAttribute("name");
	
	dayString=yearName+monthName+dayName;
	displayDayString=dayName+" "+MonthText(monthName)+" "+yearName;
	//load the daily summary.
	document.getElementById("summaryType").innerHTML = "Yearly Summary: "+yearName+" Most Recent Data: "+displayDayString;
	document.getElementById("summaryType").innerHTML = "Yearly Summary:&nbsp;";
	document.getElementById("summaryDate").innerHTML = yearName;

	var month = parseInt(monthName) - 1;
	//loadMonth(year, month);
	params="loadMonth," + year + "," + month;
	exec(params);
}

function loadMonth(year,month)
{
	document.getElementById("colDay").innerHTML = "";
	monthId="month_"+month;
	//if(year >= 1)
	//{
		for(i=0;i<xmlDoc.childNodes[year].childNodes.length;i++){
			mId="cell_month_"+i;
			document.getElementById(mId).style.backgroundColor='';	
		}
	//}
	
	cellMonthId="cell_"+monthId;
	document.getElementById(cellMonthId).style.backgroundColor="#6DB13F";
	displayDays(year,month);
	
	//load the monthly summary.
	//monthly summary
	yearName=xmlDoc.childNodes[year].getAttribute("name");
	monthName=xmlDoc.childNodes[year].childNodes[month].getAttribute("name");
	//most recent day of most recent month
	numDays=xmlDoc.childNodes[year].childNodes[month].childNodes.length-1;
	dayName=xmlDoc.childNodes[year].childNodes[month].childNodes[numDays].getAttribute("name");
	
	//last day of that month NOT most recent day of month 
	//stripMonth=monthName.replace("0","");
	//dayName=daysInMonth(stripMonth,yearName);
	
	
	dayString = yearName + monthName + dayName;
	displayDayString=dayName+" "+MonthText(monthName)+" "+yearName;
	//load the daily summary.
	document.getElementById("summaryType").innerHTML="Monthly Summary "+MonthText(monthName)+" Most Recent Data: - "+displayDayString;
	document.getElementById("summaryType").innerHTML="Monthly Summary:&nbsp;";
	document.getElementById("summaryDate").innerHTML=MonthText(monthName);

	var dayArray = [];

	for(i = 0; i < numDays + 1; i++)
	{
		dayArray[i] = xmlDoc.childNodes[year].childNodes[month].childNodes[i].getAttribute("name");
	}
	//alert(displayDayArray);
	//alert(dayName);
	//loadDay(year, month, (dayArray.length - 1));
	params="loadSummary,month,"+dayString;
	exec(params);
}

function loadDay(year,month,day){
	
	dayId="day_"+day;
	for(i=0;i<xmlDoc.childNodes[year].childNodes[month].childNodes.length;i++){
		dId="day_"+i;
		document.getElementById(dId).style.backgroundColor='';	
	}
	document.getElementById(dayId).style.backgroundColor="#6DB13F";
	
	yearName=xmlDoc.childNodes[year].getAttribute("name");
	monthName=xmlDoc.childNodes[year].childNodes[month].getAttribute("name");
	dayName=xmlDoc.childNodes[year].childNodes[month].childNodes[day].getAttribute("name");
	
	dayString=yearName+monthName+dayName;
	displayDayString=dayName+" "+MonthText(monthName).substring(0,3)+" "+yearName;
	//load the daily summary.
	<!--document.getElementById("summaryType").innerHTML="Daily Summary "+ displayDayString;-->
	document.getElementById("summaryType").innerHTML="Daily Summary:&nbsp;";
	document.getElementById("summaryDate").innerHTML=displayDayString;
	
	params="loadSummary,day,"+dayString;
	exec(params);
}

function displayYears()
{
	numYears		= xmlDoc.childNodes.length;
	var yearArray	= [];

	for(i=0; i<numYears; i++)
	{
		yearArray[i]= xmlDoc.childNodes[i].getAttribute("name");
	}

	displayYearArray = yearArray.reverse();
	//loop thru array which is crossbrowser apparently
	var yearOutput	 = "";
	yearOutput		+= "<table>";

	for(i=0; i<displayYearArray.length ; i++)
	{
		yearOutput += "<tr><td><a id=\"year_"+(displayYearArray.length-i-1)+"\" href=\"javascript:loadYear('"+(displayYearArray.length-i-1)+"');\">" + displayYearArray[i] + "</a></td></tr>";
		break;
	}

	yearOutput += "</table>";
	//document.getElementById("colYear").innerHTML = yearOutput;
}

function displayMonths(year){
	//displayMonth
	numMonths=xmlDoc.childNodes[year].childNodes.length;
	var monthArray=[];
	for(i=0; i<numMonths; i++){
		monthArray[i]= xmlDoc.childNodes[year].childNodes[i].getAttribute("name");
	}
	
	displayMonthArray=monthArray.reverse();
	//loop thru array which is crossbrowser apparently
	var monthOutput="";

	monthOutput += "<table>";
	
	//if(year >= 1)
	//{
		for(i=0; i<displayMonthArray.length; i++){
			monthOutput += "<tr><td id=\"cell_month_"+(displayMonthArray.length-i-1)+"\" width=\"100%\" ><a id=\"month_"+(displayMonthArray.length-i-1)+"\" href=\"javascript:loadMonth('"+year+"','"+(displayMonthArray.length-i-1)+"');\">" + MonthText(xmlDoc.childNodes[year].childNodes[(displayMonthArray.length-i-1)].getAttribute("name")).substring(0,3) + "</a></td></tr>";
			
			//"<li>" + MonthText(monthArray[i]) + "</li>";
		}
	//} else
	//{
		//monthOutput += "<tr><td id=\"cell_month_"+(displayMonthArray.length-1)+"\" width=\"100%\" ><a id=\"month_"+(displayMonthArray.length-1)+"\" href=\"javascript:loadMonth('"+year+"','"+(displayMonthArray.length-1)+"');\">" + MonthText(xmlDoc.childNodes[year].childNodes[(displayMonthArray.length-1)].getAttribute("name")).substring(0,3) + "</a></td></tr>";
	//}

	monthOutput += "</table>";
	document.getElementById("colMonth").innerHTML = monthOutput;
	
}

function displayDays(year,month){
	//display Days
	numDays = xmlDoc.childNodes[year].childNodes[month].childNodes.length;
	var dayArray=[];
	for(i=0; i<numDays; i++){
		dayArray[i]= xmlDoc.childNodes[year].childNodes[month].childNodes[i].getAttribute("name");
	}
	
	dayArray.sort();
	displayDayArray=dayArray.reverse();
	//loop thru array which is crossbrowser apparently
	var dayOutput="";

	dayOutput += "<table id=\"days_col\">";
	for(i=0; i<displayDayArray.length; i++){
		var dayView=displayDayArray[i] + "&nbsp;"+MonthText(xmlDoc.childNodes[year].childNodes[month].getAttribute("name")).substring(0,3)+"&nbsp;"+xmlDoc.childNodes[year].getAttribute("name");
		dayOutput += "<tr><td><a id=\"day_"+(displayDayArray.length-i-1)+"\" href=\"javascript:loadDay('"+year+"','"+month+"','"+(displayDayArray.length-i-1)+"');\">" + dayView + "</a></td></tr>";
	}
	dayOutput += "</table>";
	document.getElementById("colDay").innerHTML = dayOutput;
	
	/*
	//for sorting days
	var oSortDaysCol; // Our tableSorter Object
	orderDays(document.getElementById('days_col'));
	
	function orderDays(oElem)// oElem is the target table of the document; our tableSorter will deal with this table
	{
		oSortDaysCol = new MB_TableSorter(oElem,0);// 1 means "omit 1st row (headers)"
		oSortDaysCol.setSortFuncs([1]);// 1- case insensitive sorting , 4-numeric 
		oSortDaysCol.sortOn(0);
		oSortDaysCol.updateTblCellsTxt(document.getElementById('days_col'));

	}
	

	//end for sorting days
	*/
}

function loadInception(year,month,day){
	xmlHttpInception=GetXmlHttpObject();

	if (xmlHttpInception==null)
	  {
	  alert ("Your browser does not support AJAX!");
	  return;
	  } 
	  
	yearName=xmlDoc.childNodes[year].getAttribute("name");
	monthName=xmlDoc.childNodes[year].childNodes[month].getAttribute("name");
	dayName=xmlDoc.childNodes[year].childNodes[month].childNodes[day].getAttribute("name");
	
	dayString=yearName+monthName+dayName;	
	
	url="loadSummary.php";
	url += "?type="+"inception";
	url += "&date="+dayString;
	url += "&sid="+Math.random();
	xmlHttpInception.onreadystatechange=loadedInception;
	
	xmlHttpInception.open("GET",url,true);
	xmlHttpInception.send(null);
	
}
function findRecentData()
{
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{ 
		xmlDoc = xmlHttp.responseXML.documentElement;
		
		//find Most recent
		var year 	= xmlDoc.childNodes.length - 1;
		var month 	= xmlDoc.childNodes[year].childNodes.length-1;
		var day 	= xmlDoc.childNodes[year].childNodes[month].childNodes.length-1;
		
		loadInception(year, month, day);
		displayYears();
		loadYear(year);
		loadMonth(year,month);
		loadDay(year,month, day);
		
		populateQuickLinks(year, month, day);
	}
}



function populateQuickLinks(year,month,day){
	dayLink="javascript:loadYear('"+year+"');"+"javascript:loadMonth('"+year+"','"+month+"');"+"javascript:loadDay('"+year+"','"+month+"','"+day+"');";
	monthLink="javascript:loadYear('"+year+"');"+"javascript:loadMonth('"+year+"','"+month+"');";
	yearLink="javascript:loadYear('"+year+"');"+"javascript:loadMonth('"+year+"','"+month+"');";
	
	document.getElementById("quickLinks").innerHTML="<a id=\"quickLink\" href="+dayLink+">Previous Day</a><br>";
	document.getElementById("quickLinks").innerHTML+="<a id=\"quickLink\" href="+monthLink+">Month to Date</a><br>";
	document.getElementById("quickLinks").innerHTML+="<a id=\"quickLink\" href="+yearLink+">Year to Date</a><br>";
}
	
function MonthText (MonthNumber) {
   var Month = new Array();
       Month["01"]="January";
       Month["02"]="February";
       Month["03"]="March";
       Month["04"]="April";
       Month["05"]="May";
       Month["06"]="June";
       Month["07"]="July";
       Month["08"]="August";
       Month["09"]="September";
       Month["10"]="October";
       Month["11"]="November";
       Month["12"]="December";
return Month[MonthNumber];
}

function daysInMonth(month,year) {
	var m = [31,28,31,30,31,30,31,31,30,31,30,31];
	if (month != 2) return m[month - 1];
	if (year%4 != 0) return m[1];
	if (year%100 == 0 && year%400 != 0) return m[1];
	return m[1] + 1;
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}


function createDocument(){


var aVersions = ["MSXML2.DOMDocument.5.0","MSXML2.DOMDocument.4.0","MSXML2.DOMDocument.3.0",

"MSXML2.DOMDocument","Microsoft.XmlDom"];

if (window.ActiveXObject)

{


for(var i = 0;i<aVersions.length ; i++){


try{


var oXmlDom = new ActiveXObject(aVersions[i]);

//alert("returning .."+i+"  "+oXmlDom);

return oXmlDom;

}catch(oError){


}

}

throw new Error ("MSXML  is not installed ");


}


else if (document.implementation && document.implementation.createDocument)

{

var xmlDoc=document.implementation.createDocument("","",null);

return xmlDoc;

}

else

{

alert ("no");

alert('Your browser cannot handle this script');

}


}
