$(document).ready( function() {

$('#totalassets').numeric();
$('#totalliabilities').numeric();
$('#purchaseprice').numeric();
$('#saleprice').numeric();
$('#assetcost').numeric();
$('#amount').numeric();
$('#apr').numeric();
$('#term').numeric();
$('#gain').numeric();
$('#profit').numeric();

$('#loancalc').submit( function() {
	var $amount = $('#amount').val();
	var $term = $('#term').val();
	var $period = $('#period').val();
	var $apr = $('#apr').val();
	var $factor = ($apr / 1200);
	
	var $monthlypayment = ($factor*Math.pow((1+$factor),$term*$period) / (Math.pow((1+$factor),$term*$period)-1) * $amount);
	var $totalcharge = ($monthlypayment*$term*$period - $amount);
	var $repayment = ($monthlypayment*$term*$period);
	
	$('#monthlypayment').html("&pound;" + formatNumber($monthlypayment.toFixed(2)));
	$('#totalcharge').html("&pound;" + formatNumber($totalcharge.toFixed(2)));
	$('#repayment').html("&pound;" + formatNumber($repayment.toFixed(2)));
	
	return false;
});


$('#loansechdulecalc').submit( function() {

	$('#warningmessage span').html('');
	
	//check fields
	if($('#amount').val() == "" || $('#term').val() == "" || $('#apr').val() == "" || $('#startmon').val() == ""){
		var errormsg = "All fields must be filled in!";
		$('#warningmessage span').html(errormsg);
		return false;
	}

	var $amount = $('#amount').val();
	var $term = $('#term').val();
	var $period = $('#period').val();
	var $apr = $('#apr').val();
	var $factor = ($apr / 1200);
	var $startmon = $('#startmon').val();
	var $startyear = $('#startyear').val();
	
	var $monthlypayment = ($factor*Math.pow((1+$factor),$term*$period) / (Math.pow((1+$factor),$term*$period)-1) * $amount);
	var $totalinterest = ($monthlypayment*$term*$period - $amount);
	var $totalpayable = ($monthlypayment*$term*$period);
	var $monthlyrate = ($apr / 12);
	var $numberofpayments = ($term * $period);
	
	$('#monthlypayment').html(formatNumber("&pound;" + $monthlypayment.toFixed(2)));
	$('#totalinterest').html("&pound;" + formatNumber($totalinterest.toFixed(2)));
	$('#totalpayable').html("&pound;" + formatNumber($totalpayable.toFixed(2)));
	$('#monthlyrate').html(formatNumber($monthlyrate.toFixed(2)) + "%");
	$('#numberofpayments').html($numberofpayments);
	
	$.ajax({
	  url: "/wp-content/themes/which/calculate.php",
	  data: "startmon=" + $startmon + "&startyear=" + $startyear + "&rate=" + $monthlyrate + "&amount=" + $amount + "&term=" + $term + "&period=" + $period + "&payment=" + ($monthlypayment).toFixed(2),
	  type: 'post',
	  success: function(response){
	    $('#scheduleresults').html(response);
	  }
	});
	
	return false;
});

	
// The capital gains tax calculator
$('#capitalgainscalc').submit( function() {
	
	$('#warningmessage span').html('');
	
	//check fields
	if($('#gain').val() == "" || $('#profit').val() == ""){
		var errormsg = "All fields must be filled in!";
		$('#warningmessage span').html(errormsg);
		return false;
	}

	var gain = $('#gain').val();
	var profit = $('#profit').val();

	var profit_calc = (getCorpTaxCeiling(profit) - profit); ////console.log('starting point:'+profit_calc);
	var profit_tax = (profit_calc * getCorpTaxRate(profit_calc)); ////console.log('profit tax:'+profit_tax);

	var gain_total = (gain+profit);
	var total=0.00;





		//band 1
		
		prev = 0;

		if (profit<=300000){
		
		var rate = ((300000 - parseInt(profit)) - parseInt(gain) );console.log('rate1:'+rate);	

		if (profit < 0) {
			profit = (profit* -1);
			var rate = ((0 - parseInt(profit)) + parseInt(gain) );console.log('rate1:'+rate);
			
			if (rate<0){
				total = total + (rate*0.00);
			}else{
			if ((gain>=0) && (gain<=300000)){
				total = total + (rate*0.20);
			}
			if ((gain>=300000) && (gain<=1500000)){
				total = total + (rate*0.275);
			}
			if (gain>1500000){
				total = total + (rate*0.26);
			}
			}
		}else{

		


		if (rate>0){
			var val =   parseInt(gain);
			if (val<=300000){
			total=total+ (val * getCorpTaxRate(val)); //console.log('band1 total:'+total);
			}else{
				var newval = (300000-parseInt(profit));
				if (newval>0){
					total=total+ (newval * getCorpTaxRate(newval)); //console.log('band1 total:'+total);
					prev = (parseInt(gain)-parseInt(newval));
				}else{
					prev = parseInt(gain);
				}
			}
		}else{
			prev= (parseInt(profit) + parseInt(gain) - 300000); 
			
			if (prev<0){
			
			}else{
			var part =   ((300000 - parseInt(profit)) * 0.20) ;
			if (part>=60000){
				var total= total + 60000;
			}else{
				var total= total + part;
			}
			}
		}
		}
		
//console.log('Subtotal: '+total);
//console.log('Carry over: '+prev);

		if (prev < 1200000) {
			prev_tax = (parseInt(prev) * 0.275);
			

		}else{
			var bandX = (parseInt(prev) - 1200000);
			if (bandX>0){
			prev_tax =  ( (parseInt(prev) - 1200000) * 0.26); //console.log('26:'+prev_tax);
			var ans =  (1200000 * 0.275); //console.log('27.5:'+ans);
				prev_tax = prev_tax +ans
			}else{
			prev_tax = 0;
			}
			
		}


		var total = total + parseInt(prev_tax);
		
		}









		//band 2
		
		prev = 0;

		if ( (profit>300000) && (profit<=1500000) ){
		
		var rate = ((1500000 - parseInt(profit)) - parseInt(gain) );//console.log('rate2:'+rate);
		if (rate>0){
			var val =   parseInt(gain);
			if (val<=300000){
			total=total+ (val * getCorpTaxRate(val)); //console.log('band1 total:'+total);
			}else{
				var newval = (1500000-parseInt(profit));
				if (newval>0){
					total=total+ (newval * getCorpTaxRate(newval)); //console.log('band2 total:'+total);
					prev = (parseInt(gain)-parseInt(newval));
				}else{
					prev = parseInt(gain);
				}
			}
		}else{
			prev= (parseInt(profit) + parseInt(gain) - 1500000);
			var total= total +   ((1500000 - parseInt(profit)) * 0.275) ;
			
		}
		
		
//console.log('Subtotal: '+total);
//console.log('Carry over: '+prev);
		
		
			prev_tax = (parseInt(prev) * 0.26);
				var total = total + parseInt(prev_tax);
		


	
		
		}


		//band 3
		if ( (profit>1500000) ){
		
			total = (parseInt(gain) * 0.26);

		}





















	



	//console.log(total);

		
	
	$('#liability').html("&pound;" + formatNumber(total.toFixed(2)));
	
	return false;
	
});

$('#taxrate').change( function() {
	 if($(this).val() == '28') { 
	 	$('#annualallowance').val('5300');
	 } else { 
	 	$('#annualallowance').val('10600');
	 }
});

// The Stamp Duty tax calculator
$('#stampdutycalc').submit( function() {
	
	$('#warningmessage span').html('');
	$('#percentagepaid').html('');
	
	//check fields
	if($('#purchaseprice').val() == ""){
		var errormsg = "You must enter a purchase price!";
		$('#warningmessage span').html(errormsg);
		return false;
	}
	
	var $duty = 0;
	var $price = $('#purchaseprice').val();
	var $proptype = $('#type').val();

	$price=Math.round($price*100)/100;

		if ($price <= 125000) { $duty = 0; $percent = 0; }
		if ($price > 125000 && $price <= 250000) { $duty = $price * 0.01; $percent = 1; }
		if ($price > 250000 && $price <= 500000) { $duty = $price * 0.03; $percent = 3; }
		if ($price > 500000) { $duty = $price * 0.04; $percent = 4; }
	
	if($proptype == "residential"){
		if ($price > 1000000) { $duty = $price * 0.05; $percent = 5; }
	}

	$('#payableduty').html("&pound;" + formatNumber($duty));
	if($percent > 0){
		$('#percentagepaid').html("This is based on a " + $percent + "% Stamp Duty Land Tax rate.");
	} else {
		$('#percentagepaid').html("Stamp Duty Land Tax is not applicable on this amount.");
	}
	
	return false;
});

// The Inheritance Tax calculator
$('#ihtcalc').submit( function() {

	//check fields.
	
	if($('#totalassets').val() == "" || $('#totalliabilities').val() == ""){
		var errormsg = "You must fill in all fields!";
		$('#warningmessage span').html(errormsg);
		return false;
	}
	
	$('#message').html('');
	
	var $singleAllowance = 325000;
	var $marriedAllowance = 650000;
	var $IHTBill = 0;
	var $msg = "";
	var $totalAssets = $('#totalassets').val();
	var $totalLiabilities = $('#totalliabilities').val();
	var $estateValue = ($totalAssets - $totalLiabilities);
	var $IHTAllowance = 0;
	
	if($('#status').val() == "married"){
		$IHTAllowance = $marriedAllowance;
	} else {
		$IHTAllowance = $singleAllowance;
	}
	
	$taxable = ($estateValue - $IHTAllowance);
	
	if($taxable <= 0) {
		$('#taxableamount').html("&pound;" + "0.00");
		$('#ihtbill').html("&pound;" + "0.00");
		$msg = "From the information you have provided, you are not liable for Inheritance Tax. However, this calculator is for guidance only.";
	} else {
		$('#taxableamount').html("&pound;" + formatNumber($taxable));
		$IHTBill = ($taxable * 0.4);
		$('#ihtbill').html(formatNumber("&pound;" + $IHTBill));
		$msg = "From the information you have provided, your estimated tax liabilty is <strong>&pound;" + formatNumber($IHTBill) + "</strong>. However, this calculator is only for guidance.";
	}
	
	$('#taxfreeallowance').html("&pound;" + formatNumber($IHTAllowance));
	$('#valueofestate').html("&pound;" + formatNumber($estateValue));
	
	if($msg != ""){
		$('#message').html($msg);
	}
	
	return false;	
});

});

//number formatting and percentage calculation functions.
function formatNumber(num) {
	num += '';
	var splitMe = num.split('.');
	part1 = splitMe[0];
	part2 = splitMe.length > 1 ? '.' + splitMe[1] : '';
	var filter = /(\d+)(\d{3})/;
	while (filter.test(part1)) {
		part1 = part1.replace(filter, '$1' + ',' + '$2');
	}
	return part1 + part2;
}

function calculatePercentage(percentage,amount) {
	var $result = (percentage / 100) * amount;
	return $result;
}

function getCorpTaxRate(input){
	if (input==undefined){return 0};
	var rate = 0;
    if ( (input>=0) && (input<=300000) ){
		var rate = 0.20;
	}
    if ( (input>300000) && (input<=1500000) ){
		var rate = 0.275;
	}
    if ( (input>1500000)  ){
		var rate = 0.26;
	}
	return rate;
}

function getCorpTaxCeiling(input){
	if (input==undefined){return 0};
	var rate = 0;
    if ( (input>=0) && (input<=300000) ){
		var rate = 300000;
	}
    if ( (input>300000) && (input<=1500000) ){
		var rate = 1500000;
	}
    if ( (input>1500000)  ){
		var rate = 1500000;
	}
	return rate;
}



