showCalculation = false;
$(document).ready(function(){
	
	//public facing calculator
	
	/*$('#btnPrintCalculatorOutput').bind('click', function(e) {
		e.preventDefault();
		//$('#taxpurchasecalculator').printElement({printMode:'popup'});
	});*/
	
	$('#btnEmailCalculatorOutput').bind('click', function(e) {
		e.preventDefault();
		$('#email_tax_purchase_form').show();
		$('#taxPurchaseEmail').val('')
		$('#taxPurchaseEmail').focus();
	});
	
	
	$('#linkCloseEmailContainer').bind('click', function(e) {
		e.preventDefault();
		$('#taxPurchaseCalculatorErrorMessage').hide();
		$('#email_tax_purchase_form').hide();
	});
	
	$('#submitPurchaseEmailRequest').bind('click', function(e) {
		e.preventDefault();
		$('#taxPurchaseCalculatorErrorMessage').hide();
		//check email 
		var chrEmailAddress = $('#taxPurchaseEmail').val();
		
		if (emailCheck(chrEmailAddress)) {
			$('#email_tax_purchase_form').hide();
			var numRequestCount = parseInt($('.rowSavings').size());
			chrQS = '&email=' + chrEmailAddress;
			chrQS = chrQS + '&requestCount=' + numRequestCount;
			for (i=1;i<=numRequestCount;i++) {
				$('table#tax_purchase tr[id=row_'+ i + '] td').each(function(index){
					if (index <= 3) {
						chrQS = chrQS + '&row_' + eval(i) + '_col_' + eval(index+1) + '=' + $(this).text();
					}
				});
			}
			var chrPaymentFooter = $('#paymentFooter').html();
			chrQS = chrQS + '&paymentFooter=' + chrPaymentFooter;
			//alert(chrQS);
			//return true;
			doAjaxCall({
				fuseAction:'emailPublicTaxPurchaseRequest',
				blnSupressQ:false,
				callBack:'confirmEmailPublicTaxPurchaseRequest',
				data:chrQS
				});
		} else {
			chrErrorMessage = "Please enter a valid email address";
			$('#taxPurchaseCalculatorErrorMessage .taxCalculatorErrorMessage').text(chrErrorMessage);
			$('#taxPurchaseCalculatorErrorMessage').show();
		}
		
	});
	
	$('.taxPurchaseCalculator').bind('click', function(e) {
		e.preventDefault();
		$('.overlay').show();
		$('#taxpurchasecalculatorContainer').show();
		$('#taxpurchasecalculator').show();
		$('body').css('overflow','hidden');
		$('#inside_flash').hide();	
		clearTaxPurchaseCalculator();
	});
	
	$('.tax_purchase_btn_next_step').bind('click', function(e) {
		e.preventDefault();
		$('#taxPurchaseCalculatorErrorMessage').hide();
		$('#email_tax_purchase_form').hide();
		calculateSavings();
	});
	
	$('.tax_purchase_btn_login_to_purchase').bind('click', function(e) {
		e.preventDefault();
		$('#taxPurchaseCalculatorErrorMessage').hide();
		$('#email_tax_purchase_form').hide();
		$('#taxpurchasecalculator .resultsTable').hide();
		$('#paymentFooter').html('');
		$('#taxpurchasecalculator .loginAddPanel').hide();
		$('#taxpurchasecalculator .loginPanel').show();
		$('#login_tax_purchase_form').show();
		$('.tax_purchase_btn_login_to_purchase2').bind('click', function(e) {
			e.preventDefault();
			var chrUsername = $('#login_tax_purchase_form #username').val();
			var chrPassword = $('#login_tax_purchase_form #password').val();
			doAjaxCall({fuseAction:'doPreLoginTest',blnSupressQ:false,callBack:'showTaxPurchaseLoginResult',data:{'username':chrUsername,'password':chrPassword}});	
		});
		$('#login_tax_purchase_form #username').focus();
	});
	
	/*
	$('#taxpurchasecalculator .modal_close').bind('click', function(e) {
		e.preventDefault();
		$('#taxpurchasecalculatorContainer').hide();
		//closeModalCalculator('taxpurchasecalculator');
		//$('#paymentFooter').html('');
	});
	
	*/
	$('.tax_purchase_btn_add_another').bind('click', function(e) {
		e.preventDefault();
		$('#taxPurchaseCalculatorErrorMessage').hide();
		$('#email_tax_purchase_form').hide();
		buildAddAnotherFormPublic(0);
	});
	
	/*
	$('#btn_login_purchase').bind('click', function(e) {
		e.preventDefault();
		//showModal("Disabled at the moment",'closeButton');
		//return true;
		growModalCalculator(240,'taxpurchasecalculator');
		$('#taxpurchasecalculator #results').hide();
		$('#taxpurchasecalculator #login_add').hide();
		$('#taxpurchasecalculator #login_modal').show();
		$('#taxpurchasecalculator #login_purchase').show();
		$('#taxpurchasecalculator .modal_note').hide();
	});
	
	$('#btn_login_modal_purchase').bind('click', function(e) {
		e.preventDefault();
		var chrUsername = $('#taxpurchasecalculator #login_modal #username').val();
		var chrPassword = $('#taxpurchasecalculator #login_modal #password').val();
		doAjaxCall({fuseAction:'doPreLoginTest',blnSupressQ:false,callBack:'showTaxPurchaseLoginResult',data:{'username':chrUsername,'password':chrPassword}});	
	});
	*/
	var blnShowCalculatorByDefault = parseInt($('#blnShowCalculatorByDefault').size());
	var blnShowEmptyCalculatorByDefault = parseInt($('#blnShowEmptyCalculatorByDefault').size());
	
	if(blnShowCalculatorByDefault) {
		//numAdditionalHeight = 30 * parseInt($('.rowSavings').size());
		$('.overlay').show();
		$('.purchaseFeesForm').hide();
		$('.resultsTable').show();
		$('#taxpurchasecalculator .submitPanel').hide();
		$('#taxpurchasecalculator .loginAddPanel').show();
		$('#taxpurchasecalculatorContainer').show();
		$('#taxpurchasecalculator').show();
		$('.pencilEdit').click(function(e){
			e.preventDefault();
			$('#taxPurchaseCalculatorErrorMessage').hide();
			$('#email_tax_purchase_form').hide();
			numRequest = parseInt($.ListLast($(this).parent().parent().attr('id'),'_'));
			buildAddAnotherFormPublic(numRequest);
		});
	}
	
	if (blnShowEmptyCalculatorByDefault) {
		$('.overlay').show();
		$('#taxpurchasecalculatorContainer').show();
		$('#taxpurchasecalculator').show();
		$('body').css('overflow','hidden');
		$('#inside_flash').hide();	
		clearTaxPurchaseCalculator();
	}
		
});

function confirmEmailPublicTaxPurchaseRequest() {
	$.timeout(function() { $('#emailRequestConfirmation').fadeIn('slow',function() {$.timeout(function() { $('#emailRequestConfirmation').fadeOut('slow')}, 3000);}); }, 500);
}


function clearTaxPurchaseCalculator() {
	$('div.error').hide();
	$('#taxPurchaseCalculatorErrorMessage').hide();
	$('#email_tax_purchase_form').hide();
	$('.purchaseFeesForm').show();
	$('#taxpurchasecalculator .resultsTable').hide();
	$('#login_tax_purchase_form').hide();
	$('#login_tax_purchase_form #username').val("");
	$('#login_tax_purchase_form #password').val("");
	$('.tax_purchase_btn_remove_line').hide();
	$('#taxpurchasecalculator .submitPanel').show();
	$('#taxpurchasecalculator .loginAddPanel').hide();
	$('#taxpurchasecalculator .loginPanel').hide();
	$('#requestAmount_1').val('');
	$('#calculateFromDateDay_1').val('');
	$('#calculateFromDateMonth_1').val('');
	$('#calculateFromDateYear_1').val('');
	$('#renderRequestValuesContainer').empty();
	$('#renderResults').empty();
	$('#paymentFooter').html('');
	$('#requestAmount_1').focus();
	$('#negativeSavingsMessage').hide();
}

function showTaxPurchaseLoginResult(blnOK) {
	if(blnOK == "false") {
		var chrErrorMessage = "The details that you entered are incorrect, please try again";
		$('#taxPurchaseCalculatorErrorMessage .taxCalculatorErrorMessage').text(chrErrorMessage);
		$('#taxPurchaseCalculatorErrorMessage').show();
	} else {
		var numRequestCount = parseInt($('.rowSavings').size());
		$('#calc_tax_purchase #requestCount').val(numRequestCount);
		var chrHiddenFormValues = "";
		$('.rowDate').each(function(index){
			numDate = $.ListLast($(this).attr('id'),'_');
			chrHiddenFormValues = chrHiddenFormValues + "<input name='calculateFromDate_" + eval(index+1) +"' type='hidden' value='" + numDate + "'  style='display:none'/>";
		});
		$('.rowAmount').each(function(index){
			numAmount = parseInt($(this).text().replace(/[^0-9]/g, ""));
			chrHiddenFormValues = chrHiddenFormValues + "<input name='requestAmount_" + eval(index+1) +"' type='hidden' value='" + numAmount + "'  style='display:none'/>";
		});
		$('#calc_tax_purchase #renderRequestValuesContainer').append(chrHiddenFormValues);
		modalTimerFormSubmit('#calc_tax_purchase',2000);
	}
}

function checkCalcDate(dateValue){
	var dayfield=dateValue.split("/")[0];
	var monthfield=dateValue.split("/")[1];
	var yearfield=dateValue.split("/")[2];
	var dayobj = new Date(yearfield, monthfield-1, dayfield);
	if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
	{
		return false;
	}
	else
	{
		return true;
	}
}

function calculateSavings() {
	
	var loggedIn = parseInt($('#loggedIn').text());
	var loginCode = $('#loginCode').text();
	var blnError = false;
	
	var requestAmount_1 = $('.purchaseFeesForm #requestAmount_1').val();
	var calculateFromDateDay_1 = $('.purchaseFeesForm #calculateFromDateDay_1').val();
	var calculateFromDateMonth_1 = $('.purchaseFeesForm #calculateFromDateMonth_1').val();
	var calculateFromDateYear_1 = $('.purchaseFeesForm #calculateFromDateYear_1').val();
	var calculateFromDate_1 = calculateFromDateDay_1 + "/" + calculateFromDateMonth_1 + "/" + calculateFromDateYear_1;
	if (!$.Len(requestAmount_1) || requestAmount_1 == '$' || !$.Len(calculateFromDateDay_1) || !$.Len(calculateFromDateMonth_1) || !$.Len(calculateFromDateYear_1)) {
			blnError = true;
	} else {
		if (!checkCalcDate(calculateFromDate_1)) {
			var blnDateError = true;
		}
	}
	if (blnError || blnDateError) {
		if (blnError) {
			chrErrorMessage = "Please note that all fields need to be completed before continuing.";
		} else {
			chrErrorMessage = "The date selected is not valid, please select again.";
		}
		$('#taxPurchaseCalculatorErrorMessage .taxCalculatorErrorMessage').text(chrErrorMessage);
		$('#taxPurchaseCalculatorErrorMessage').show();
	} else {
		//check that the date entered is acceptable
		var chrEarliestPurchaseDate = getJSDate($('#earliestPurchaseDate').val());
		var chrCalculateToDate = getJSDate($('#calculateToDate').val());
		var chrCalculateFromDate = getJSDate(calculateFromDate_1);
		if (chrCalculateFromDate < chrEarliestPurchaseDate) {
			chrErrorMessage = "Please ensure tax dates are after " + $('#earliestPurchaseDate').val() + ". If you require tax earlier than this date then please call us on 0800 829 888."; 
			$('#taxPurchaseCalculatorErrorMessage .taxCalculatorErrorMessage').text(chrErrorMessage);
			$('#taxPurchaseCalculatorErrorMessage').show();
		} else {
			if (chrCalculateFromDate < chrEarliestPurchaseDate) {
			} else {	
				if (chrCalculateToDate < chrCalculateFromDate) {
					chrErrorMessage = "Please select a past tax date as TaxPURCHASEs cannot be organised for future dates";
					$('#taxPurchaseCalculatorErrorMessage .taxCalculatorErrorMessage').text(chrErrorMessage);
					$('#taxPurchaseCalculatorErrorMessage').show();
				} else {
					if (!parseInt($('#numRequest').val())) {
						var numRequest = $('.pencilEdit').size() + 1;
					} else {
						var numRequest = parseInt($('#numRequest').val());
					}
					var calculateFromDateFormatted = escape(calculateFromDateYear_1 + "-" + calculateFromDateMonth_1 + "-" + calculateFromDateDay_1 + " 00:00:00.0");
					chrQS = '&requestCount=1';
					chrQS = chrQS + '&requestAmount_1=' + requestAmount_1;
					chrQS = chrQS + '&calculateFromDate_1=' + calculateFromDateFormatted;
					chrQS = chrQS + '&numRequest=' + numRequest;
					doAjaxCall({
						fuseAction:'getTaxPurchaseResultsPublic',
						blnSupressQ:false,
						callBack:'buildTaxPurchaseResultsPublic',
						callBackArg: {
								'numRequest':numRequest
								},
						data:chrQS
						});
				}
			}
		}
	}
}

function buildTaxPurchaseResultsPublic(htmlResults,objCallBackArg) {
	numRequestToPlace = parseInt(objCallBackArg.numRequest);
	//does the item being placed exist already, if so replace rather than add
	var blnReplaceFormElement = $('#row_' + numRequestToPlace).size();
	$('.purchaseFeesForm').fadeOut('fast', function() {
		
		if (blnReplaceFormElement) {
			$('#row_' + numRequestToPlace).before(htmlResults).remove(); 
			chrFormBuildType = 'replace';
		} else {
			$('#renderResults').append(htmlResults);
			chrFormBuildType = 'add';
			//$('.resultsTable').show();
		}
		
		//bind to edit icon
		$('.pencilEdit').unbind();
		$('.pencilEdit').click(function(e){
			e.preventDefault();
			$('#taxPurchaseCalculatorErrorMessage').hide();
			$('#email_tax_purchase_form').hide();
			numRequest = parseInt($.ListLast($(this).parent().parent().attr('id'),'_'));
			buildAddAnotherFormPublic(numRequest);
		});
		//work out totals and display
		
		buildSummaryTableTotals(chrFormBuildType);
		
	});
}

function buildSummaryTableTotals(chrFormBuildType) {
	$('#taxPurchaseCalculatorErrorMessage').hide();
	var numAmountTotal = 0;
	var numInterestTotal = 0;
	var numSavingsTotal = 0;
	var numEarlyBirdSaving = 0;
	
	$('#negativeSavingsMessage').hide();
	//sum the totals and also renumber the row identifiers incase a row in the middle of the table has been removed
	$('.rowAmount').each(function(index){
		var	chrRowId = $(this).attr('id');
		var numRow = index+1;
		var numOldRow = parseInt($.ListGetAt($(this).attr('id'),2,'_'));
		if (numRow != numOldRow) {
			//rename the amount cell
			var chrReplaceFromString = "_" + numOldRow + "_";
			var chrReplaceToString = "_" + numRow + "_";
			var chrNewRowId = $.Replace(chrRowId,chrReplaceFromString,chrReplaceToString)
			$(this).attr('id',chrNewRowId)
			//rename the parent row cell
			$(this).parent().attr('id','row_' + numRow);
			var chrOldDateId = $('[id*=date' + chrReplaceFromString + ']').attr('id');
			var chrNewDateId = $.Replace(chrOldDateId,chrReplaceFromString,chrReplaceToString)
			$('[id*=date' + chrReplaceFromString + ']').attr('id',chrNewDateId);
		}
		numAmountTotal = numAmountTotal + parseInt($(this).text().replace(/[^0-9]/g, ""));
	});
	$('.rowInterest').each(function(){
		numInterestTotal = numInterestTotal + parseInt($(this).text().replace(/[^0-9]/g, ""));
	});
	$('.rowSavings').each(function(){
		numSavings = $(this).text().replace(/[^0-9]/g, "");
		if (numSavings != "")
		{
			if ($.Left($(this).text(),1) == "-") {
				numSavingsTotal = numSavingsTotal - parseInt(numSavings);
			} else {
				numSavingsTotal = numSavingsTotal + parseInt(numSavings);
			}
		}
		else
		{
			$('#negativeSavingsMessage').show();
		}
	});
	$('#totalAmount').html("<strong>" + $.DollarFormat(numAmountTotal) + "</strong>");
	$('#totalInterest').html("<strong>" + $.DollarFormat(numInterestTotal) + "</strong>");
	if(numSavingsTotal > 0) { 
		$('#totalSavings').html("<strong>" + $.DollarFormat(numSavingsTotal) + "</strong>");
	}
	else {
		$('#totalSavings').html("<strong>$-</strong>");
	}
	$('#taxpurchasecalculator .resultsTable').fadeIn();
	$('#taxpurchasecalculator .submitPanel').hide();
	$('#taxpurchasecalculator .loginAddPanel').show();
	
	if (chrFormBuildType != "remove") {
		// Early bird saving amount
		numInterestRateTMNZ = $('#interestRateTMNZ').val()/100;
		numEarlyBirdTotal = numInterestTotal - (numAmountTotal * numInterestRateTMNZ * 14/365);
		numEarlyBirdSaving = numInterestRateTMNZ/12 * numAmountTotal;
		var chrPaymentFooter = '<p class="modal_note printable">The cost with TMNZ interest for this TaxPURCHASE is <strong>' + $.DollarFormat(numInterestTotal) + '</strong> payable by <strong>' + $('#paymentDate').val() + '</strong></p>'; 
		// removed trac #733 chrPaymentFooter = chrPaymentFooter + '<p class="modal_note printable">' + $('#taxPurchaseWarning').val() + '</p>';
		if ($.ListGetAt($('#paymentDate').val(),2,'-') != 'Dec' && parseInt($('#daysToPaymentDate').val()) >= 13 ) {
			chrPaymentFooter = chrPaymentFooter + '<h4><strong>Alternative Pricing Options:</strong></h4>';
			chrPaymentFooter = chrPaymentFooter + '<p>Early Bird Payment Option - If you can pay by <strong>' + $('#paymentDateEarlyBird').val() + '</strong>, the cost will be <strong>' + $.DollarFormat(numEarlyBirdTotal) + '.</strong>';
			$('#paymentAmountEarlyBird').val(numEarlyBirdTotal);
		} 
		chrPaymentFooter = chrPaymentFooter + '<p>To make this TaxPURCHASE a month later will cost approximately <strong>' + $.DollarFormat(numEarlyBirdSaving) + ' more</strong>.  For each subsequent month the cost will increase by a similar amount.</p>'
		chrPaymentFooter = chrPaymentFooter + '<p class="modal_note printable"><strong>Please note that the availability of this tax cannot be confirmed until you have filed a purchase request.</strong></p>';
		$('#paymentFooter').html(chrPaymentFooter);
	}
}

function buildAddAnotherFormPublic(numRequest) {
	$('#numRequest').val(numRequest);
	$('#taxpurchasecalculator .loginAddPanel').hide();
	$('#taxpurchasecalculator .submitPanel').show();
	$('.tax_purchase_btn_remove_line').show();
	//$('#paymentFooter').html('');
	if (!numRequest) {
		$('.tax_purchase_btn_remove_line').unbind();
		$('.tax_purchase_btn_remove_line').click(function(e){
			e.preventDefault();
			$('.purchaseFeesForm').hide();
			buildSummaryTableTotals('remove');
		});
		$('.purchaseFeesForm #requestAmount_1').val('');
		$('.purchaseFeesForm #calculateFromDateDay_1').val('');
		$('.purchaseFeesForm #calculateFromDateMonth_1').val('');
		$('.purchaseFeesForm #calculateFromDateYear_1').val('');
	} else {
		var numRequestAmount = $.ListLast($('[id*=amount_' + numRequest + ']').attr('id'),"_");
		var chrCalculationDate = $.ListLast($('[id*=date_' + numRequest + ']').attr('id'),"_");
		$('.tax_purchase_btn_remove_line').unbind();
		$('.tax_purchase_btn_remove_line').click(function(e){
			e.preventDefault();
			removeLine(numRequest);
		});
		$('.purchaseFeesForm #requestAmount_1').val(numRequestAmount);
		$('.purchaseFeesForm #calculateFromDateDay_1').val($.ListGetAt(chrCalculationDate,1,'-'));
		$('.purchaseFeesForm #calculateFromDateMonth_1').val($.ListGetAt(chrCalculationDate,2,'-'));
		$('.purchaseFeesForm #calculateFromDateYear_1').val($.ListGetAt(chrCalculationDate,3,'-'));
	}
	$('.purchaseFeesForm').fadeIn();
	$('#requestAmount_1').focus();
}

function removeLine(numRequest) {
	$('#row_' + numRequest).remove();
	numRowsLeft = $('.rowSavings').size();
	if (!numRowsLeft) {
		clearTaxPurchaseCalculator();	
	} else {
		$('.purchaseFeesForm').hide();
		buildSummaryTableTotals('remove');
	}
}




