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

	holdingsAndBalances.js

	Written by		Date 
	Jason Harris	03/29/10
	
	Revised by		Date		Summary of changes
	Lane Roathe		06/17/10	[DE1026] Save and restore table states (for now, just sorted columns)
	Lane Roathe		06/22/10	[DE1411] check window.viewController usage to fix deferred printing
								(Some reports do not have a viewController or attached method)
	Chris Campbell	07/01/10	[S541] Adding ability to click on Other balance descriptions to edit them
	Lane Roathe		07/19/10	[DE1456] save state of collapsable areas (holdings & other balances)
	Mickey Roberson	08/06/10	[DE1445] Added a SetupScroller call to enable scrollability for many holdings
	Mickey Roberson	08/13/10	[DE1429] Removed a check that prevented multisource holding columns form being sortable
	Chris Campbell	08/25/10	[DE1573] Making the acctCol column in the security table clickable (instead of
									the first column, but they happen to be the same) and making the balanceAcctCol column
									(the second column) of the balances table clickable (it was previously the first column).
									The net effect of these changes is that the Description column is now the clickable one
									for holdings, balances, and Other balances (those are 3 different classes of data, and they
									are handled individually).

	Copyright 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 ------------------------- */

function HAndBInit()
{
	$(".setUpForDownload").click(function() {
		if (window.viewController)
			window.viewController.DisplayAccountPropertiesViewForDownload();
		return false;
	});

	$(".connectNow").click(function() {
		if (window.viewController)
			window.viewController.DoDownloadNow();
		return false;
	});
	
	InitHoldingSources();
	InitBalances();
	InitOtherBalances();
	InitWarnings();
	SetupScroller();

	var tables = $("table.holdingCollection");
	for (var i = 0; i < tables.length; ++i)
	{
		var table = $(tables[i]);
		var sortState = "[[0,0]]";
		if( window.viewController && window.viewController.TableState )
			sortState = ( window.viewController.TableState( table[0].className, sortState ) );

		table.tablesorter({
			sortList:	JSON.parse( sortState ),
			cssHeader:	"sortcol", 
			cssAsc:		"sortasc", 
			cssDesc:	"sortdesc",
			cssChildRow:"holdingSource"
						
		});
		if( window.viewController )
			table.bind("sortBeg",function() {
				   window.viewController.SetTableState( this.className, JSON.stringify( this.config.sortList ) );
				   });
	}
	TableSortInit("table.balanceTable");
	TableSortInit("table.userBalances");
}

function AddRowClickHandler(row)
{
	var firstTD = row.find("td.acctCol");
	firstTD.addClass("disclosable");
	
	firstTD.click(function() {
		var parent = $(this).parent("tr");
		var quickenID = parent.attr('quicken_id');
		var objectType = parent.attr('object_type');
		if (window.viewController) {
			if (objectType == "holding")
				window.viewController.EditHoldingObject(quickenID);
		}
		return false;
	});
}

function AddCostBasisClickHandler(row)
{
	var firstTD = row.find("td.costBasisCol.needsReview");
	
	firstTD.click(function() {
		var parent = $(this).parent("tr");
		var quickenID = parent.attr('quicken_id');
		var objectType = parent.attr('object_type');
		if (window.viewController) {
			if (objectType == "holding")
				window.viewController.EditHoldingCostBasis(quickenID);
		}
		return false;
	});
}

function CreateAnchorRow(anchorRow, sourceRows)
{
	sourceRows = $(sourceRows);
	var firstTD = anchorRow.find("td:first");
	var actuatorState = "closed";
	var stateID = firstTD[0].firstChild.textContent;
	if( window.viewController )
		actuatorState = window.viewController.TableState( stateID, actuatorState );

	firstTD.prepend("<span class='actuator closed'></span>");
	var actuator = firstTD.find(".actuator");
	sourceRows.hide();

	actuator.toggle(function() {
		sourceRows.show();
		actuator.removeClass("closed");
		actuator.addClass("opened");
		if( window.viewController )
			window.viewController.SetTableState( stateID, "opened" );
	}, function() {
		sourceRows.hide();
		actuator.removeClass("opened");
		actuator.addClass("closed");
		if( window.viewController )
			window.viewController.SetTableState( stateID, "closed" );
	});

	// must toggle via click if opened, otherwise jquery internal state is not updated (known jquery issue)
	if( actuatorState == "opened" )
		actuator.click();
}

function InitHoldingSources()
{
	var rows = $(".holdingCollection tr");
	var anchorRow = undefined;
	var sourceRows = undefined;
	for (var i = 0; i < rows.length; ++i)
	{
		var row = $(rows[i]);
		if (undefined == anchorRow)
		{
			if (i > 0)
			{
				if (row.hasClass("holdingSource"))
				{
					anchorRow = $(rows[i-1]);
					sourceRows = new Array(row.get(0));
				}
				else
				{
					AddRowClickHandler(row);
					AddCostBasisClickHandler(row);
				}
			}
		}
		else
		{
			if (row.hasClass("holding"))
			{
				CreateAnchorRow(anchorRow, sourceRows);
				AddRowClickHandler(row);
				AddCostBasisClickHandler(row);
				anchorRow = undefined;
				sourceRows = undefined;
			}
			else
				sourceRows.push(row.get(0));
		}
	}
	
	if (undefined != anchorRow)
		CreateAnchorRow(anchorRow, sourceRows);
}

function InitBalances()
{
	var rows = $(".balanceTable tbody tr");
	var firstCols = rows.find("td.balanceAcctCol");
	firstCols.click(function() {
		var parent = $(this).parent("tr");
		var objectType = parent.attr('object_type');
		if (window.viewController) {
			window.viewController.EditBalance(objectType);
		}
		return false;
	});
}

function InitOtherBalances()
{
	var otherBalances = $(".userPortfolioBalances");
	if (otherBalances.length)
	{
		var tableHeader = otherBalances.find(".tableHeader");

		var actuatorState = "closed";
		var stateElement = tableHeader[0].firstChild;
		var stateID = stateElement.textContent;
		if( window.viewController )
			actuatorState = window.viewController.TableState( stateID, actuatorState );

		tableHeader.prepend("<span class='actuator closed'></span>");
		var actuator = otherBalances.find(".actuator");
		var userBalanceTable = otherBalances.find("#userBalanceTable");
		userBalanceTable.hide();
		
		otherBalances.addClass("disclosable");
		var actuators = actuator.add(otherBalances);

		actuators.toggle(function() {
			userBalanceTable.show();
			actuator.removeClass("closed");
			actuator.addClass("opened");
			if( window.viewController )
				window.viewController.SetTableState( stateID, "opened" );
		}, function() {
			userBalanceTable.hide();
			actuator.removeClass("opened");
			actuator.addClass("closed");
			if( window.viewController )
				window.viewController.SetTableState( stateID, "closed" );
		});

		// must toggle via click if opened, otherwise jquery internal state is not updated (known jquery issue)
		if( actuatorState == "opened" )
			actuator.click();

       var rows = userBalanceTable.find("tbody tr");
        var firstCols = rows.find("td.userBalanceDescriptionCol");
        firstCols.click(function() {
            var parent = $(this).parent("tr");
            var quickenID = parent.attr('quicken_id');
            var objectType = parent.attr('object_type');
            if (window.viewController) {
                if (objectType == "userBalance")
                    window.viewController.EditInvestmentBalanceObject(quickenID);
            }
            return false;
        });
	}
}

function InitWarnings()
{
	var warnTimer;
	$("a.warningIcon,a.pencilIcon").hover(function() {
		var that = this;
		warnTimer = setTimeout(function(){
			$(that).siblings(".warningBox").fadeIn("fast");
		},200);
	},	function() {
			var that = this;
			clearWarnTimer();
			$(that).siblings(".warningBox").fadeOut("fast");
		});
	function clearWarnTimer() {
		clearTimeout(warnTimer);
	}
}