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

	taxSchedule.js

	Written by		Date 
	Dan Herman		08/26/10
	
	Revised by		Date		Summary of changes
	Lane Roathe		09/17/10	[DE1703] get summarize state from report filters on init so returning to view doesn't reset to loaded state

	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 SummarizeByDidChange(selectElement) {
	var newValue = selectElement.value;
	var data = {};
	if (window.viewController)
	{
		window.viewController.SummarizeByModeDidChange(newValue);
	}
}

function SummarizeByFromString(newValue) {
	var data = {};
	if (window.viewController)
	{
		// GetRealizedGainLoss( bool mergeAccounts, bool mergePositions );
		data =  eval("(" + window.viewController.GetRealizedGainLoss(true, false) + ")");
 		this.createScheduleD(data);
	}
}

function createScheduleD(rawData){
	var rows = rawData['realizedGainLoss'];

    $('.scheduleDTable').each(function() {
                  
        // The closest currency label above dictates the currency of the table
        var previousCurrency = $(this).parent().prevAll('.currencyID:first');
        var tableCurrency;
                              
        // No currency labels means all data is the same currency
        if (previousCurrency.length == 0) {
            if (rows.length > 0) {
                tableCurrency = rows[0]['accountCurrencyCode'];
            }
                              
        // Otherwise get the currency code inside parentheses
        } else {
            // Assuming currency display pattern - Currency (CurrencyCode) i.e. - US Dollar (USD)
            // If different pattern, tableCurrency will be undefined and table will not show
            
            var matchArray = previousCurrency[0].innerHTML.match(/\((.*)\)/);
            if (matchArray != null && matchArray.length == 2) {
                tableCurrency = matchArray[1]
            }
        }
                              
	    var account = '';
	    var longTermAccountName ='';
	    var shortTermAccountName ='';
	    var unknownAccountName ='';
	    var longTermTable = '<tr class="tableTitle collapsibleHeader topHeader longTermTable"><td class="longTermTableTitle" colspan="4">Long-term Capital Gains</td><td class="longTermTableProcessds processds"></td><td class="longTermTableCost costBasis"></td><td class="longTermTableGainLoss gainLoss last"></td></tr>';
	    var shortTermTable = '<tr class="tableTitle collapsibleHeader topHeader shortTermTable"><td class="shortTermTableTitle" colspan="4">Short-term Capital Gains</td><td class="shortTermTableProcessds processds"></td><td class="shortTermTableCost costBasis"></td><td class="shortTermTableGainLoss gainLoss last"></td></tr>';
	    var unknownDataTable = '<tr class="tableTitle collapsibleHeader topHeader unknownDataTable"><td class="unknownDataTableTitle" colspan="4">Unknown acquisition data</td><td class="unknownDataTableProcessds processds"></td><td class="unknownDataTableCost costBasis"></td><td class="unknownDataTableGainLoss gainLoss last"></td></tr>';

        var containsSomeData = false;
	    for(var i = 0; i < rows.length; i++){
		    var data = rawData['realizedGainLoss'][i];
		    var columns = data['holdingLots'];
                              
            // Check if correct currency for table
            if (data['accountCurrencyCode'] != tableCurrency) {
                continue;
            } else {
                containsSomeData = true;
            }
                              
	    	for (var j = 0; j < columns.length; j++){//create data per account
                if (columns[j]['term'] != 'LONG' && columns[j]['term'] != 'SHORT') {
				    if(data['accountName'] != unknownAccountName){//accountName doesn't exist in the table
					    unknownAccountName = data['accountName'];
					    unknownDataTable += '<tr class="collapsibleHeader unknownDataTitle unknownDataTable"><td class="accountTitle" colspan="7" id="unknown' + data['accountName'] + '">' +  data['accountName'] + " (" + data['securityType'] + ')</td></tr>';
				    }
				    unknownDataTable += '<tr class="unknownDataItem">';
				    unknownDataTable += '<td class="security" id="security_'+data['tickerSymbol']+'">' + (data['tickerSymbol'] ? data['tickerSymbol'] : data['securityName']) + '</td>';
				    unknownDataTable += '<td class="shares" id="shares_'+data['tickerSymbol']+'">' +  columns[j]['units'] + '</td>';
				    unknownDataTable += '<td class="dateAcquired" id="dateAcquired_'+data['tickerSymbol']+'">' + '<span>unknown</span>' + '</td>';
				    unknownDataTable += '<td class="dateSold" id="dateSold_'+data['tickerSymbol']+'">' + dateFormatter(columns[j]['sellDate'].slice(0,10)) + '</td>';
				    unknownDataTable += '<td class="processds' + (columns[j]['netProceeds'] < 0 ? " netNegative" : "")+'" id="proceeds_'+data['tickerSybol']+'">' +  formatMoney(columns[j]['netProceeds']) + '</td>';
				    unknownDataTable += '<td class="costBasis" id="costBasis_'+data['tickerSymbol']+'">' + '<span>unknown</span>' + '</td>';
				    unknownDataTable += '<td class="gainLoss last" id="gainLoss_'+data['tickerSymbol']+'">' +  formatMoney(columns[j]['netProceeds']) + '</td>';
				    unknownDataTable += '</tr>';
			    }else{
				    if(columns[j]['term'] == 'LONG'){
					    if(data['accountName'] != longTermAccountName){//accountName doesn't exist in the table
						    longTermAccountName = data['accountName'];
						    longTermTable += '<tr class="collapsibleHeader longTermTitle longTermTable"><td class="accountTitle" colspan="7" id="longTermAccount_'+data['accountName']+'">' +  data['accountName'] + " (" + data['securityType'] + ')</td></tr>';
					    }
					    longTermTable += '<tr class="longTermItem">';
					    longTermTable += '<td class="security" id="security_'+data['tickerSymbol']+'">' + (data['tickerSymbol'] ? data['tickerSymbol'] : data['securityName']) + '</td>';
					    longTermTable += '<td class="shares" id="shares_'+data['tickerSymbol']+'">' +  columns[j]['units'] + '</td>';
					    longTermTable += '<td class="dateAcquired" id="dateAcquired_'+data['tickerSymbol']+'">' + dateFormatter(columns[j]['purchaseDate'].slice(0,10)) + '</td>';
					    longTermTable += '<td class="dateSold" id="dateSold_'+data['tickerSymbol']+'">' +  dateFormatter(columns[j]['sellDate'].slice(0,10)) + '</td>';
					    longTermTable += '<td class="processds' + (columns[j]['netProceeds'] < 0 ? " netNegative" : "")+'" id="proceeds_'+data['tickerSymbol']+'">' +  formatMoney(columns[j]['netProceeds']) + '</td>';
					    longTermTable += '<td class="costBasis' + (columns[j]['costBasis'] < 0 ? " netNegative" : "")+'" id="costBasis_'+data['tickerSymbol']+'">' +  formatMoney(columns[j]['costBasis']) + '</td>';
					    longTermTable += '<td class="gainLoss last' + (columns[j]['priceGainLoss'] < 0 ? " netNegative" : "")+'" id="gainLoss_'+data['tickerSymbol']+'">' +  formatMoney(columns[j]['priceGainLoss']) + '</td>';
					    longTermTable += '</tr>';
				    }else if(columns[j]['term'] == 'SHORT'){
					    if(data['accountName'] != shortTermAccountName) {//accountName doesn't exist in the table
						    shortTermAccountName = data['accountName'];
						    shortTermTable += '<tr class="collapsibleHeader shortTermTitle shortTermTable"><td class="accountTitle" colspan="7" id="shortTermAccount_'+data['accountName']+'">' +  data['accountName'] + " (" + data['securityType'] + ')</td></tr>';
					    }
					    shortTermTable += '<tr class="shortTermItem">';
					    shortTermTable += '<td class="security" id="security_'+data['tickerSymbol']+'">' +  (data['tickerSymbol'] ? data['tickerSymbol'] : data['securityName']) + '</td>';
					    shortTermTable += '<td class="shares" id="shares_'+data['tickerSymbol']+'">' +  columns[j]['units'] + '</td>';
					    shortTermTable += '<td class="dateAcquired" id="dateAcquired_'+data['tickerSymbol']+'">' +  dateFormatter(columns[j]['purchaseDate'].slice(0,10)) + '</td>';
					    shortTermTable += '<td class="dateSold" id="dateSold_'+data['tickerSymbol']+'">' +  dateFormatter(columns[j]['sellDate'].slice(0,10)) + '</td>';
					    shortTermTable += '<td class="processds' + (columns[j]['netProceeds'] < 0 ? " netNegative" : "")+'" id="proceeds_'+data['tickerSymbol']+'">' +  formatMoney(columns[j]['netProceeds']) + '</td>';
					    shortTermTable += '<td class="costBasis' + (columns[j]['costBasis'] < 0 ? " netNegative" : "")+'" id="costBasis_'+data['tickerSymbol']+'">' +  formatMoney(columns[j]['costBasis']) + '</td>';
					    shortTermTable += '<td class="gainLoss last' + (columns[j]['priceGainLoss'] < 0 ? " netNegative" : "")+'" id="gainLoss_'+data['tickerSymbol']+'">' +  formatMoney(columns[j]['priceGainLoss']) + '</td>';
					    shortTermTable += '</tr>';
				    }
			    }
		    }//end of the j loop
	    }//end of the i loop
	    if(shortTermTable.indexOf('shortTermItem') > -1){
		    account += shortTermTable + '<tr><td class="tableWhiteSpace" colspan="8"> space</td></tr>';
	    }
	    if(longTermTable.indexOf('longTermItem') > -1){
		    account += longTermTable + '<tr><td class="tableWhiteSpace" colspan="8"> space</td></tr>';
	    }
	    if(unknownDataTable.indexOf('unknownDataItem') > -1){
		    account += unknownDataTable + '<tr><td class="tableWhiteSpace" colspan="8"> space</td></tr>';
	    }
    
    
        var x = window.document.getElementById("innerWrapperZeroDataCategory");
        if(x)
            x.parentNode.removeChild(x);
    
	    $(this).append(account);
    
	    //schedule D total
        $('.longTermTableCost',this).text(calculateTotal($('tr.longTermItem td.costBasis',this)));
        $('.longTermTableGainLoss',this).text(calculateTotal($('tr.longTermItem td.gainLoss',this)));
        $('.shortTermTableProcessds',this).text(calculateTotal($('tr.shortTermItem td.processds',this)));
        $('.shortTermTableCost',this).text(calculateTotal($('tr.shortTermItem td.costBasis',this)));
        $('.shortTermTableGainLoss',this).text(calculateTotal($('tr.shortTermItem td.gainLoss',this)));
        $('.unknownDataTableProcessds',this).text(calculateTotal($('tr.unknownDataItem td.processds',this)));
        $('.unknownDataTableCost',this).text(calculateTotal($('tr.unknownDataItem td.costBasis',this)));
        $('.unknownDataTableGainLoss',this).text(calculateTotal($('tr.unknownDataItem td.gainLoss',this)));
                              
        if (containsSomeData) {
            $(this).parent().removeClass('hide');
        }
    });

    
    
	//schedule D arrow direction
	$(".scheduleDHeader").click(function() {
		$(this).toggleClass("opened").toggleClass("closed");
	});
	//event listener
	var oneHeader = $(".collapsibleHeader");
	oneHeader.each(function() {
		$(this).click(function(e) {
			if($(this).hasClass('topHeader')){//hide the account title
				if($(this).hasClass('longTermTable')){
					if($('.longTermTitle',this).hasClass('hide')){
						$('.longTermTitle',this).removeClass('hide');
						$('.longTermItem',this).removeClass('hide');
					}else{
						$('.longTermTitle',this).addClass('hide');
						$('.longTermItem',this).addClass('hide');
					}
				}else if($(this).hasClass('shortTermTable')){
					if($('.shortTermTitle',this).hasClass('hide')){
						$('.shortTermTitle',this).removeClass('hide');
						$('.shortTermItem',this).removeClass('hide');
					}else{
						$('.shortTermTitle',this).addClass('hide');
						$('.shortTermItem',this).addClass('hide');
					}
				}else{
					if($('.unknownDataTitle',this).hasClass('hide')){
						$('.unknownDataTitle',this).removeClass('hide');
						$('.unknownDataItem',this).removeClass('hide');
					}else{
						$('.unknownDataTitle',this).addClass('hide');
						$('.unknownDataItem',this).addClass('hide');
					}
				}
			}else{
				$(this).nextUntil('tr.collapsibleHeader').toggleClass('hide');
			}
		});
	});
}

function calculateTotal(fields){
	var sum = 0;
	fields.each(function() {
		sum += Number(this.innerHTML.replace("$","").replace(/,/g,''));
	});
	return formatMoney(sum);
}

function dateFormatter(date){
	var dateParts = date.split(/-/);
	var d = new Date(dateParts[0],parseInt( dateParts[1], 10) -1,dateParts[2]);
	return dateParts[1] + "/" + dateParts[2] + "/" + dateParts[0];
}
function formatMoney(number){
	var dot = ".",
		comma = ",",
		sign = number < 0 ? "-$" : "$",
		absValue = parseInt(number = Math.abs(+number || 0)).toString(),
		numOfComma = (numOfComma = absValue.length) > 3 ? numOfComma % 3 : 0;
	return sign + (numOfComma ? absValue.substr(0, numOfComma) + comma : "") + absValue.substr(numOfComma).replace(/(\d{3})(?=\d)/g, "$1" + comma)+ dot + Math.abs(number - absValue).toFixed(2).slice(2);
}
