/* --------------------------- INTUIT CONFIDENTIAL ---------------------------

 spendingTrends.js

 Written by		Date
 Jason Harris	10/19/09

 Revised by		Date		Summary of changes
 Dan Herman		2/5/10		[DE946] Show pointer (hand) cursor when hovering
 over clickable slices of pie charts.
 Lane Roathe		06/22/10	[DE1411] check window.viewController usage to fix deferred printing
 (Some reports do not have a viewController or attached method)
 Lane Roathe		08/12/10	[DE1426] check in deferred printing token when aborting w/o no data
 Mickey Roberson	08/23/10	Added an oldIndex option to sliceHoverIndex to lighten the JS workload
 Chris Campbell	10/01/10	[DE1784] When scrolling the vertical legend, only scroll half the
 visible height so that rows that are cut off at the bottom scroll
 up to be fully visible in the middle instead of scrolling up to
 be cut off at the top.
 Mickey Roberson	10/22/10	[DE1873] Added a negative payee section to the bottom of the payee table.
 This sections shows refunds/inflows
 Added 10 to the heights to account for a possible Returns/Inflow
 row header which has a 10px padding at the top
 Mickey Roberson	12/03/10	[DE1989] Backed out my questionable 10px change for a more limited and integrated
 adjustment where only if there is an Inflow/Outflow header,
 the additional space is accounted for by adding another "row" to the
 calculations.
 Mickey Roberson	12/06/10	[DE1989] Need to report the actual amount to scroll, as not all rows are the same
 height due to text wrapping

 Copyright 2009-2010 Intuit, Inc All rights reserved. Unauthorized
 reproduction is a violation of applicable law. This material contains
 certain confidential and proprietary information and trade secrets of
 Intuit, Inc.

 RESTRICTED RIGHTS LEGEND

 Use, duplication, or disclosure by the Government is subject to
 restrictions as set forth in subdivision (b) (3) (ii) of the Rights in
 Technical Data and Computer Software clause at 52.227-7013.

 Intuit, Inc
 P.O. Box 7850
 Mountain View, CA 94039-7850

 ----------------------------- INTUIT CONFIDENTIAL ------------------------- */

var gSpendingTrendsPrintToken = undefined;
var gHasInflowOutflowHeader;

function SpendingTrendsInit(title, summary, noLabels) {
	var gSpendingTrendsPrintToken = CreateDeferredPrintingToken();

	var titleDiv = $(".spendingTrendsTitle");
	if (titleDiv.length) {
		title = titleDiv[0].innerHTML;
		titleDiv.hide();
	}
	
	SpendingTrendsDateSelectorInit();

	var spendingTrendsKey = $('.spendingTrendsKey');
	if (!spendingTrendsKey.length) CheckInDeferredPrintingToken(gSpendingTrendsPrintToken);

	spendingTrendsKey.hide();

	var spendingTrendsHeader = $('#stepACont h2');
	spendingTrendsHeader.click(function() {
		if (window.viewController)
			window.viewController.showCategoryExplorer();
	});

	var spendingTrendsBillReminder = $('#stepBCont h2');
	spendingTrendsBillReminder.click(function() {
		if (window.viewController)
			window.viewController.NavigateToBillReminder();
	});

	var spendingTrendsBudget = $('#stepCCont h2');
	spendingTrendsBudget.click(function() {
		if (window.viewController)
			window.viewController.DisplayBudgetWithQuickenID($('.currentBudget').attr('id'));
	});

	var tableHolder = $('#tableHolder');
	var tableParent = tableHolder.parent();
	tableHolder.replaceWith("<table class='spendingTrendsTable' cellspacing='0' cellpadding='0' border='0'></table>");
	var spendingTrendsTable = tableParent.find(".spendingTrendsTable");
	if (title)
		spendingTrendsTable.append("<thead><tr><th colspan='3' class='graphTitle'>" + title + "</th></tr></thead>");

	function Click() {
		SpendingTrendsLegendClicked(this);
	}

	var plotData = [];
	var colorComponents = ['#40BF75', '#7783FF', '#D689FB', '#FF9C4E', '#1CA8DD', '#FF74A2', '#4EDFE1', '#EAFD6A', '#5578C3', '#B6C647', '#FF556C', '#F6D76B', '#40BF75', '#7783FF', '#D689FB', '#FF9C4E', '#1CA8DD', '#FF74A2', '#4EDFE1', '#EAFD6A', '#5578C3', '#B6C647', '#FF556C', '#F6D76B', '#40BF75', '#7783FF', '#D689FB', '#FF9C4E', '#1CA8DD', '#FF74A2', '#4EDFE1', '#EAFD6A', '#5578C3', '#B6C647', '#FF556C', '#F6D76B', '#40BF75', '#7783FF', '#D689FB', '#FF9C4E', '#1CA8DD', '#FF74A2'];
	var payees = spendingTrendsKey.find(".payee");

	for (var i = 0; i < payees.length; ++i) {
		var category = $(payees[i]).find(".category:first")[0].innerText;
        if (category && category.length > 21) {
            category = category.substring(0, 21) +'...';
        }
		var rawAmount = $(payees[i]).find(".rawAmount:first")[0].innerHTML;
		var numberOfTxn = $(payees[i]).find(".numberOfTxn:first")[0].innerHTML;
        var quickenID = $(payees[i]).find(".quickenID:first")[0].innerHTML;
		var percentage = $(payees[i]).find(".percentage:first")[0].innerHTML;
		var amountElement = $(payees[i]).find(".amount:first")[0];
		var amount = amountElement.innerHTML;
		var amountClass = amountElement.className;
		var entry = {name: category, y: parseInt(rawAmount * 100) / 100, numberOfTxn: numberOfTxn, amount: amount};
        if(window.viewController &&
           category == window.viewController.CategoryInternalNameForUncategorized() &&
           numberOfTxn &&
           parseInt(numberOfTxn) > 0)
        {
            //show the uncategorized link for overview
            var uncategorizedLink = $('.stepAUncategorized');
            uncategorizedLink.text(numberOfTxn + ' uncategorized transactions');
            
            //update the uncategorizedTotal for category exploror
            $('#uncategorizedTrnx').text(numberOfTxn + ' Uncategorized');
            $('#uncategorizedTotal').text('totaling ' + amount);
            
            uncategorizedLink.click(function() {
            if (window.viewController)
                window.viewController.ExploreCategoryWithQuickenIDs(window.viewController.QuickenIDForCategoryInternalNameForUncategorized() + 'c');
            });
            
            $('#uncategorizedTrnx').click(function() {
            if (window.viewController)
                window.viewController.ExploreCategoryWithQuickenIDs(window.viewController.QuickenIDForCategoryInternalNameForUncategorized() + 'c');
            });
        }
        plotData.push(entry);
        
        if($('.moneySpent')[0]){
            $('#spendingTotal').text($('.moneySpent')[0].innerHTML);
        }
                
        if($('.dateRange')[0]){
            $('#spendingFilter').text($('.dateRange')[0].innerHTML);
        }

		spendingTrendsTable.append('<tr></tr>');
		tr = spendingTrendsTable.find("tr:last");

		category = $('<div/>').text(category).html();
		tr.append('<td class="categoryCol"><span class="swatch" style="background-color:' + colorComponents[i] + ';"></span><span class="pieLegendLabel">' + category + '</span></td>');
		tr.append('<td class="' + amountClass + '">' + amount + '</td>');
		tr.append('<td class="percentCol">' + percentage + '</td>');
	}

	var allCells = spendingTrendsTable.find("td");
	allCells.mousedown(Click);

	payees = spendingTrendsKey.find(".negativePayee");
	gHasInflowOutflowHeader = (payees.length > 0);

	if (gHasInflowOutflowHeader) {
		spendingTrendsTable.append('<tr></tr>');
		var tr = spendingTrendsTable.find("tr:last");

		// The title of the separting header depends on the type of graph (expense/income)
		if (spendingTrendsKey.attr('id') == 'expense')
			tr.append('<td colspan=3 class="inflowRow inflowHeader">Returns/Inflows</td>');
		else
			tr.append('<td colspan=3 class="inflowRow inflowHeader">Expenses/Outflows</td>');


		for (i = 0; i < payees.length; ++i) {
			category = $(payees[i]).find(".category:first")[0].innerText;

			percentage = $(payees[i]).find(".percentage:first")[0].innerHTML;
			amountElement = $(payees[i]).find(".amount:first")[0];
			amount = amountElement.innerHTML;
			amountClass = amountElement.className;

			spendingTrendsTable.append('<tr></tr>');
			tr = spendingTrendsTable.find("tr:last");

			category = $('<div/>').text(category).html();
			tr.append('<td class="categoryCol inflowRow"><span class="emptySwatch"></span>' + category + '</span></td>');
			tr.append('<td class="inflowRow ' + amountClass + '">' + amount + '</td>');
			tr.append('<td class="percentCol inflowRow">' + percentage + '</td>');
		}
	}


	if (summary && summary.length) {
		spendingTrendsTable.append('<tr></tr>');
		tr = spendingTrendsTable.find("tr:last");

		tr.append('<td class="summary" colspan="3">' + summary + '</td>');
	}

    //draw the charts on the overview page
    CreatePieChart(colorComponents, plotData, noLabels? true:false);
	if (window.viewController && typeof sliderInit == 'function'){//these two charts are not available for category explorer page
		//Backend returns a json string, use eval to convert it to object
		var spendingOverTimeData = eval("(" + window.viewController.GetSpendingOverTime() + ")");
		CreateColumnChart(spendingOverTimeData["valueOverTime"],'spendingOvertimeChart');

		var netIncomeData = eval("(" + window.viewController.GetNetIncomeOverTime() + ")");
		CreateColumnChart(netIncomeData["valueOverTime"],'netIncomeChart');
	}
	
    if(typeof sliderInit == 'function'){//this function is not available for category explorer page
        $('.slider_container').hover(function(){
            $('.slider_container').addClass('slider_container_hover');
        },function(){
            $('.slider_container').removeClass('slider_container_hover');
        });
        setTimeout(function() {sliderInit("slider");},200);
    }
}

function SpendingTrendsLegendClicked(element) {
	var tr = element.parentElement;
	var index = $(".spendingTrendsTable tbody tr").get().indexOf(tr);
	SpendingTrendsSliceClicked(index);
}


function SpendingTrendsSliceClicked(index) {
	var spendingTrendsKey = $('.spendingTrendsKey');
	var payee = $(spendingTrendsKey.find(".payee")[index]);
	var quickenID = payee.find(".quickenID:first")[0].innerHTML;

	if (window.viewController)
		window.viewController.ExploreCategoryWithQuickenIDs(quickenID);
}

function SpendingTrendsUncategorizedLinkClicked() {
	if (window.viewController)
		window.viewController.ExploreCategoryWithQuickenIDs(window.viewController.CategoryInternalNameForUncategorized());
}

function SpendingTrendsDateSelectorInit() {
	var timeFrameSelector = $("#timeFrameSelect");
	if (timeFrameSelector.length) {
		timeFrameSelector.change(function() {
			var dateRange = $(this).val();
			if( window.viewController )
				window.viewController.SelectSpendingTrendsDateRange(dateRange);
		});
	}
}

function CreatePieChart(colorComponents, plotData, noLabels) {
	$(function() {
		Highcharts.setOptions({
			colors: colorComponents,
			chart      : {
				style			   :{
					fontFamily: '"HelveticaNeue", "Helvetica Neue", Calibri, sans-serif'
				}
			}
		});
		// Radialize the colors
		Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, function(color) {
			return {
				radialGradient: { cx: 0.5, cy: 0.5, r: 0.7 },
				stops         : [
					[0, color],
					[1, Highcharts.Color(color).brighten(-0.1).get('rgb')] // darken
				]
			};
		});

		// Build the chart
		$('#spendingTrendsPlot').highcharts({
			chart      : {
				plotBackgroundColor: null,
				plotBorderWidth    : null,
				plotShadow         : false,
				alignTicks         : false,
				backgroundColor    : 'rgba(0,0,0,0)'
			},
			title      : {
				text: ''
			},
			tooltip    : {
				headerFormat: '<span style="color: #333; display: block; text-align: center;margin: 10px 0;">{point.key}</span>',
				shadow: {
					width: 5,
					opacity: 0.05,
					offsetX: 0,
					offsetY: 1
				},
				useHTML     : true
			},
			plotOptions: {
				pie: {
					cursor     : 'pointer',
					innerSize  : '35%',
					borderColor: '',
					dataLabels : {
						enabled       : noLabels? false: true,
						distance      : 10,
						color         : '#707070',
						connectorColor: '#707070',
                        softConnector: false,
						style         : {
							textTransform: 'capitalize',
							fontSize: '13px'
                        }
                    }
				}
			},
			credits    : {
				enabled: false
			},
			series     : [
				{
					type   : 'pie',
					data   : plotData,
					tooltip: {
						pointFormat  : '<div style="font-size: 17px;display: block; text-align: center;color: #333; margin-bottom: 10px;">{point.amount} ({point.percentage:.0f}%)</div>'
							+ ' <div style="font-size: 13px;color: #707070;">{point.numberOfTxn} Transactions & Splits</div>',
						valueDecimals: 0
					},
					point  : {
						events: {
							click: function(event) {
								SpendingTrendsSliceClicked(getSliceIndex(plotData, this.name));
							}
						}
					}
				}
			]
		});
	});
}

function CreateColumnChart(plotData,plotID) {
	$(function() {
		var plotDate = [];
		var plotAmount = [];
        if(plotData.length < 7){
            plotDate.push(plotData[0].month);
            var entry = {y: parseInt(plotData[0].rawTotal), txnCount: parseInt(plotData[0].transactionCount), total: plotData[0].total};
			plotAmount.push(entry);
        }
		for (var i = 1; i < plotData.length; i++) {
			plotDate.push(plotData[i].month);
            var entry = {y: parseInt(plotData[i].rawTotal), txnCount: parseInt(plotData[i].transactionCount), total: plotData[i].total};
			plotAmount.push(entry);
		}
        
        $('div.date_range').html(plotDate[0] + " - " + plotDate[plotDate.length - 1]);
		Highcharts.setOptions({
			lang: {
				numericSymbols: null //otherwise by default ['k', 'M', 'G', 'T', 'P', 'E']
			}
		});
		$('#'+plotID).highcharts({
			chart  : {
				type: 'column'
			},
			title  : {
				text: ''
			},
			xAxis  : {
				categories: plotDate,
				labels    : {
					align: 'center'
				}
			},
			yAxis  : {
				reversed: plotID == 'spendingOvertimeChart'? true: false,
				title: {
					text: ''
				}
			},

			legend : {
				enabled: false
			},
			tooltip: {
				headerFormat: '<span style="font-size: 14px;color: #666; display: block; text-align: center;">{point.key}</span>',
				useHTML     : true
			},
			credits: {
				enabled: false
			},
			series : [
				{
					name   : 'Spending Amount',
					color  : '#40BF75',
					negativeColor: '#FF556C',
                    minPointLength: 3,
					tooltip: {
						pointFormat: '<div style="font-size: 22px;display: block; text-align: center;">{point.total}</div><hr/>'
							+ ' <div>{point.txnCount} Transactions & Splits</div>'
					},
					data   : plotAmount,
					point  : {
						events: {
							click: function(event) {
								if (window.viewController){
                                    if(plotID == "spendingOvertimeChart"){
                                        window.viewController.exploreCategoryForSelectedMonth(this.category);
                                    }else{
                                        window.viewController.exploreIncomeCategoryForSelectedMonth(this.category);
                                    }
                                }
							}
						}
					}
				}
			]
		});
	});
}

function getSliceIndex(data, catName) {
	var index = "";
	for (var i = 0; i < data.length; i++) {
		if (data[i].name == catName) {
			index = i;
		}
	}
	return index;
}

function SpendingTrendsHaveDisplayed() {
	if (undefined != gSpendingTrendsPrintToken)
		CheckInDeferredPrintingToken(gSpendingTrendsPrintToken);
}

var scrolling = false;
var scrollAmount, totalAllowedToScroll, scrollSetAmount;

/**
 setup the scroller for vertical legends

 @author Michael Turnwall
 */
function SetupScroller() {
	var $_trendsTable = $(".spendingTrendsTable");
	var $_tableMask = $("#tableMask");
		/**
		 Finding the number of rows visible tells us how far the table can scroll up
		 This is done by multiplying the number of rows by the table cell height (scrollAmount)
		 then subtracting the answer from the total number of rows.
		 The difference multiplied by the scrollAmount is how many rows the table can scroll which is the same as
		 the amount as the table can scroll up.
		 **/
		scrollAmount = $("td", $_tableMask).outerHeight();
		var totalRows = $("tbody tr", $_trendsTable).length; // find the number of rows to find the total height of all the rows
		scrollSetAmount = Math.ceil((($_tableMask.height()) / scrollAmount) * scrollAmount / 2);

		// Need to report the actual amount to scroll, as not all rows are the same height due to
		// text wrapping
		totalAllowedToScroll = $_trendsTable.height() - $_tableMask.height();
		if (totalAllowedToScroll > 0) {
			$_tableMask.wrap("<div id='legendScroller'></div>");
			var $_legendScroller = $("#legendScroller");
			$_legendScroller.css({height: $_tableMask.height()});
//			$_legendScroller.before("<a id='scrollUp' class='scrollBtn' href='#' rel='1'>scroll up</a>");
//			$_legendScroller.after("<a id='scrollDown' class='scrollBtn' href='#' rel='-1'>scroll up</a>");
//			bindScrollLinks(".scrollBtn", $_trendsTable, true);
		}
}

function bindScrollLinks(selector, scrollingEl, typeOfBind) {
	if (typeOfBind) {
		$(selector).bind("mousedown",function(e) {
			scrolling = true;
			animateScroller(scrollingEl, this.rel);
			return false;
		}).bind("mouseup", function() {
				// scrollingEl.stop();
				scrolling = false;
				return false;
			});
	}
	else {
		$(selector).unbind();
	}
}

/**
 handle the animation for scrolling vertically
 @author Michael Turnwall
 */
var scrollTimer;
function animateScroller(el, dir) {
	// console.log("scrolling ",scrolling);
	clearTimeout(scrollTimer);
	if (el.is(":animated") && scrolling) {
		// console.log("animation");
		scrollTimer = setTimeout(function() {animateScroller(el, dir);}, 200);
		return false;
	}

	if (scrolling) {
		var marginTop = parseInt(el.css("marginTop").replace("px", ""), 10);
		// don't scroll if the new margin top is out of bounds
		if ((marginTop >= 0 && dir == "1") || (Math.abs(marginTop) >= totalAllowedToScroll && dir == "-1")) {
			return false;
		}
		var move = marginTop + (scrollSetAmount * dir);
		el.animate({
			marginTop: move
		}, "fast", function() {
			animateScroller(el, dir);
		});
	}
	else {
		el.stop();
	}
	return false;
}
