// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// Written by: Andrew Krause (http://www.ajkrause.net)

function showMarket ()
{
	document.getElementById("page_market").style.display = 'inline';
	document.getElementById("page_daily").style.display = 'none';
	document.getElementById("page_total").style.display = 'none';
	
	document.getElementById("menu_market").className = 'menu_on';
	document.getElementById("menu_daily").className = 'menu_off';
	document.getElementById("menu_total").className = 'menu_off';
}

function showDaily ()
{
	document.getElementById("page_market").style.display = 'none';
	document.getElementById("page_daily").style.display = 'inline';
	document.getElementById("page_total").style.display = 'none';
	
	document.getElementById("menu_market").className = 'menu_off';
	document.getElementById("menu_daily").className = 'menu_on';
	document.getElementById("menu_total").className = 'menu_off';
}

function showTotal ()
{
	document.getElementById("page_market").style.display = 'none';
	document.getElementById("page_daily").style.display = 'none';
	document.getElementById("page_total").style.display = 'inline';
	
	document.getElementById("menu_market").className = 'menu_off';
	document.getElementById("menu_daily").className = 'menu_off';
	document.getElementById("menu_total").className = 'menu_on';
}

function printNumber (number, prefix, precision)
{
	var whole, frac;

	var out = (number < 0.0) ? "-" + prefix : prefix;	
	var numstr = Math.abs (number) + "";
	var decimal = numstr.search(/\./);
	
	if (decimal >= 0) {
		whole = numstr.substr (0, decimal);
		frac = numstr.substr (decimal+1, numstr.length-decimal);
	} else {
		whole = numstr;
		frac = "00";
	}
	
	if (whole.length > 3)
		whole = whole.substr (0, whole.length-3) + "," + whole.substr (whole.length-3, 3);
	
	if (frac.length > precision) {
		frac = frac.substr (0, precision);
	} else if (frac.length < precision) {
		for (i = frac.length; i < precision; i++)
			frac = frac + "0";
	}
	
	out += whole + "." + frac;
	return out;
}

function printDate (num)
{
	if (num < 10)
		return "0"+num;
	else
		return num;
}

function delHolding (num)
{
	var answer = confirm ("Do you really want to delete the holding '" 
		+ positions[num].Symbol + "'?");
	
	if (answer) {
		location.href = "delete.php?id=" + num;
	}
}

function editHolding (num)
{
	showWindow('editform');
	
	document.getElementById("editid").innerHTML
		= "<input type=\"hidden\" name=\"id\" value=\"" + num + "\">";
	document.getElementById("epos").value = positions[num].Name;
	document.getElementById("esym").value = positions[num].Symbol;
	document.getElementById("eshare").value = positions[num].Shares;
	document.getElementById("ecb").value = positions[num].CostBasis;
	document.getElementById("ediv").value = positions[num].Dividends;
}

function initTable ()
{
	var edit = "<img src=\"img/edit.gif\" border=0 alt='Edit' width=14 height=14 style=\"vertical-align:top\">";
	var noedit = "<img src=\"img/edit_no.gif\" border=0 alt='No Edit' width=14 height=14 style=\"vertical-align:top\">";
	var del = "<img src=\"img/delete.gif\" border=0 alt='Delete' width=15 height=15 style=\"vertical-align:top\">";
	var nodel = "<img src=\"img/delete_no.gif\" border=0 alt='No Delete' width=15 height=15 style=\"vertical-align:top\">";
	var quote = "<img src=\"img/quote.gif\" border=0 alt='Quote' width=12 height=14 style=\"vertical-align:top\">";
	
	
	// Initialize the market table
	var html = "<table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" class=\"holdings\">\n";
	
	for (var i = 0; i < positions.length; i++) {
		html += "<tr><td class=\"holding_id\">" +positions[i].Symbol+ "</td>\n";
		html += "<td class=\"holding_price\" id=\"market" +i+ "\">$0.000</td>\n";
		html += "<td class=\"holding_change_good\" id=\"mchange" +i+ "\" NOWRAP>+$0.00 (+0.00%)</td>\n";
		html += "<td class=\"holding_buttons\" NOWRAP>\n";
		html += "<a href=\"javascript:popUp('" + positions[i].Symbol +
				"',true)\">" + quote + "</a> <a href=\"javascript:editHolding('" +
				i+ "')\">" + edit + "</a> <a href=\"javascript:delHolding('" +
				i+ "')\">" + del + "</a>\n";
		html += "</td></tr><tr>\n";
		html += "<td colspan=\"2\" class=\"holding_name\" NOWRAP>" +positions[i].Name+ "</td>\n";
		html += "<td class=\"holding_info\" NOWRAP>" +printNumber (positions[i].Shares, "", 3);
		html += " Shares</td><td class=\"holding_empty\">-</td></tr>\n";
	}

	html += "</table>\n";
	
	document.getElementById("page_market").innerHTML = html;
	
	
	// Initialize the daily table
	html = "<table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" class=\"holdings\">\n";
	
	for (var i = 0; i < positions.length; i++) {
		html += "<tr><td class=\"holding_id\">" +positions[i].Symbol+ "</td>\n";
		html += "<td class=\"holding_price\" id=\"daily" +i+ "\">$0.000</td>\n";
		html += "<td class=\"holding_change_good\" id=\"dchange" +i+ "\" NOWRAP>+$0.00 (+0.00%)</td>\n";
		html += "<td class=\"holding_buttons\" NOWRAP>\n";
		html += "<a href=\"javascript:popUp('" + positions[i].Symbol +
				"',true)\">" + quote + "</a> <a href=\"javascript:editHolding('" +
				i+ "')\">" + edit + "</a> <a href=\"javascript:delHolding('" +
				i+ "')\">" + del + "</a>\n";
		html += "</td></tr><tr>\n";
		html += "<td colspan=\"2\" class=\"holding_name\" NOWRAP>" +positions[i].Name+ "</td>\n";
		html += "<td class=\"holding_info\" NOWRAP>" +printNumber (positions[i].Shares, "", 3);
		html += " Shares</td><td class=\"holding_empty\">-</td></tr>\n";
	}

	html += "<tr><td class=\"daily_total_id\"></td>\n";
	html += "<td class=\"daily_total_price\" id=\"dtotal\">$0.00</td>\n";
    html += "<td class=\"daily_total_change_good\" id=\"dchange\" NOWRAP>+$0.00 (+0.00%)</td>\n";
    html += "<td class=\"holding_empty\">-</td></tr></table>\n";
	
	document.getElementById("page_daily").innerHTML = html;
	
	
	// Initialize the total table
	html = "<table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" class=\"holdings\">\n";
	
	for (var i = 0; i < positions.length; i++) {
		html += "<tr><td class=\"holding_id\">" +positions[i].Symbol+ "</td>\n";
		html += "<td class=\"holding_price\" id=\"total" +i+ "\">$0.000</td>\n";
		html += "<td class=\"holding_change_good\" id=\"tchange" +i+ "\"NOWRAP>+$0.00 (+0.00%)</td>\n";
		html += "<td class=\"holding_buttons\" NOWRAP>\n";
		html += "<a href=\"javascript:popUp('" + positions[i].Symbol +
				"',true)\">" + quote + "</a> <a href=\"javascript:editHolding('" +
				i+ "')\">" + edit + "</a> <a href=\"javascript:delHolding('" +
				i+ "')\">" + del + "</a>\n";
		html += "</td></tr><tr>\n";
		html += "<td colspan=\"2\" class=\"holding_name\" NOWRAP>" +positions[i].Name+ "</td>\n";
		html += "<td class=\"holding_info\" NOWRAP>" +printNumber (positions[i].Dividends, "$", 2);
		html += " Dividends</td><td class=\"holding_empty\">-</td></tr>\n";
	}

    html += "<tr><td class=\"holding_id\"></td>\n";
    html += "<td class=\"holding_price\" id=\"total\">$0.00</td>\n";
    html += "<td class=\"holding_change_good\" id=\"tchange\" NOWRAP>+$0.00 (+0.00%)</td>\n";
    html += "<td class=\"total_empty\">-</td></tr><tr><td class=\"holding_name\" colspan=\"2\"></td>\n";
    html += "<td class=\"holding_info\" id=\"tinfo\"><b>Dividends:</b> $0.00<br><b>Reserves:</b> $0.00</td>\n";
    html += "<td class=\"holding_empty\">-</td></tr></table>\n";
	
	document.getElementById("page_total").innerHTML = html;
}

function goodStr (price, pct, dec, item, type)
{
	if (type == 0)
		item.className = 'holding_change_good';
	else
		item.className = 'daily_total_change_good';
	
	return printNumber (price, "+$", dec) + " (" + printNumber (pct, "+", 2) + "%)";
}

function badStr (price, pct, dec, item, type)
{
	if (type == 0)
		item.className = 'holding_change_bad';
	else
		item.className = 'daily_total_change_bad';
	
	return printNumber (price, "$", dec) + " (" + printNumber (pct, "", 2) + "%)";
}

function updateQuotes (timeout)
{
	var xmlHttp = new XMLHttpRequest();
	
	xmlHttp.onreadystatechange=function()
	{
		if (xmlHttp.readyState == 4)
		{
			// Initialize totals
			var dividends = 0.0;
			var total = reserve;
			var daytotal = 0.0;
			var totalchange = 0.0;
			var totalcb = 0.0;
		
			// Results = "price|change\nprice|change..."
			var quotes = xmlHttp.responseText.split("\n");
			
			// Foreach quote, update its contents
			for (var i = 0; i < quotes.length; i++) {
				if (quotes[i] == "|")
					break;
			
				var result = quotes[i].split("|");
				
				// Update the market numbers
				var idMarket = document.getElementById("market"+i);
				idMarket.innerHTML = printNumber (result[0], "$", 3);
				
				var idMChange = document.getElementById("mchange"+i);
				if (result[1] >= 0)
					idMChange.innerHTML 
						= goodStr (result[1], result[1]/result[0]*100, 3, idMChange, 0);
				else
					idMChange.innerHTML 
						= badStr (result[1], result[1]/result[0]*100, 3, idMChange, 0);
				
				// Update the daily numbers
				var idDaily = document.getElementById("daily"+i);
				var newPrice = result[0]*positions[i].Shares;
				idDaily.innerHTML = printNumber (result[0]*positions[i].Shares, "$", 2);
				
				var idDChange = document.getElementById("dchange"+i);
				if (result[1] >= 0)
					idDChange.innerHTML = goodStr (result[1]*positions[i].Shares,
						result[1]/result[0]*100, 2, idDChange, 0);
				else
					idDChange.innerHTML = badStr (result[1]*positions[i].Shares,
						result[1]/result[0]*100, 2, idDChange, 0);
				
				// Update the total numbers
				var idTotal = document.getElementById("total"+i);
				idTotal.innerHTML = printNumber (newPrice, "$", 2);
				
				var idTChange = document.getElementById("tchange"+i);
				var priceChange = newPrice - positions[i].CostBasis;
				if (priceChange >= 0)
					idTChange.innerHTML = goodStr (priceChange,
						priceChange/positions[i].CostBasis*100, 2, idTChange, 0);
				else
					idTChange.innerHTML = badStr (priceChange,
						priceChange/positions[i].CostBasis*100, 2, idTChange, 0);
				
				dividends += positions[i].Dividends;
				total += newPrice;
				daytotal += result[1]*positions[i].Shares;
				totalchange += priceChange;
				totalcb += positions[i].CostBasis;
			}
			
			var idDTotal = document.getElementById("dtotal");
			idDTotal.innerHTML = printNumber (total, "$", 2);
			
			var idDChange = document.getElementById("dchange");
			if (daytotal >= 0)
				idDChange.innerHTML = goodStr (daytotal,
					daytotal/(total-daytotal)*100, 2, idDChange, 1);
			else
				idDChange.innerHTML = badStr (daytotal,
					daytotal/(total-daytotal)*100, 2, idDChange, 1);
			
			var idTotal = document.getElementById("total");
			idTotal.innerHTML = printNumber (total, "$", 2);
			
			var idTChange = document.getElementById("tchange");
			//var tchange = total - costbasis;
			if (totalchange >= 0)
				idTChange.innerHTML = goodStr (totalchange,
					totalchange/totalcb*100, 2, idTChange, 0);
			else
				idTChange.innerHTML = badStr (totalchange,
					totalchange/totalcb*100, 2, idTChange, 0);
			
			var idTInfo = document.getElementById("tinfo");
			idTInfo.innerHTML = "<b>Dividends:</b> " +printNumber (dividends, "$", 2)+
				"<br><b>Reserves:</b> " +printNumber (reserve, "$", 2);
			
			var now = new Date();
			var datestr = "Updated at ";
			
			if (now.getHours() >= 12)
				datestr += printDate (now.getHours()-12) +":"+
					printDate (now.getMinutes()) +":"+
					printDate (now.getSeconds()) +" PM";
			else
				datestr += printDate (now.getHours()) +":"+
					printDate (now.getMinutes()) +":"+
					printDate (now.getSeconds()) +" AM";
			
			document.getElementById("update").innerHTML = datestr;
		}
	}
	
	var url;
	if (positions.length == 0) {
		url = "quotes.php";
	} else {
		var url = "quotes.php?symbols=" + positions[0].Symbol;
		for (var i = 1; i < positions.length; i++) {
			url += "," + positions[i].Symbol;
		}
	}
	
	xmlHttp.open ("GET", url, true);
	xmlHttp.send (null);

	if (refreshrate > 0 && timeout) {
		update_timeout = setTimeout ("updateQuotes(true)", refreshrate * 1000);
	}
}
