// JavaScript Document
function calculate()
{
	var tax_year = $('#taxyear').val();
	var list_price = to_num($('#listprice').val());
	var extras = to_num($('#extras').val());
	var capital_contribution = to_num($('#cont_costs').val());		
	var private_amount = to_num($('#private_amount').val());
	var fuel_type = $('#fuel_type').val();						
	var co2_emission = to_num($('#co2_emissions').val());					
	var engine_capacity = $('#engine_capacity').val();			
	var reg_date = $('#date_registered').val();				
	var private_amount = to_amount($('#private_amount').val());		
	var pay_employer = $("input[name='employer_pays']:checked").val();	
	var yearVal = 12; // this would be used to reset based on the year to calulate co2 %	
	var rate = $('#tax_rate').val();
	var total_value = 0;
	var start_dd = to_num($('#start_dd').val());
	var start_mm = to_num($('#start_mm').val());
	var start_yy = to_num($('#start_yy').val());
	var end_dd = to_num($('#end_dd').val());
	var end_mm = to_num($('#end_mm').val());
	var end_yy = to_num($('#end_yy').val());
	var whole_year = $("input[name='all_year']:checked").val();
	var unavl_days = to_num($("input[name='unavl_days']").val());
	var un_period = $("input[name='un_period']:checked").val();
	
	//Taxable Rate
	var tax_rate;
	//Car Benefit
	var car_benefit;	
	// Fuel Benefit
	var fuel_benefit;	
	// Total Benefit
	var total_benefit;
	
	var form = document.car_calc;
	
	var res = true;
	var date_msg = new Array();
	var message = "<p><span class='ui-icon ui-icon-alert' style='float: left; margin-right: .3em;'></span>Please check the following errors:-<ul>";
	
	
	if(tax_year == 0)
	{
		message += "<li> Please select a tax year.</li>";
		res = false;
	}
	if(list_price == 0)
	{
		message += "<li> Please provide list price of the car</li>";
		res = false;
	}
	if(list_price > 80000)
	{
		message +="<li> Your car value can only be upto 80,000</li>";
		res = false;
	}
	if(reg_date == "")
	{
		message += "<li> Please select the registration date</li>";
		res = false;
	}
	if(fuel_type == "")
	{
		message += "<li> Please select the fuel type</li>";
		res = false;
	}
	
	if(reg_date == "Pre98" && $('#no_co2:checked').val() == null){
		message += "<li> Before 1998 there was only pre-defined catogeries for engine<br />   sizes so please tick the box and select an engine size</li>";
		res = false;
	}
	if(co2_emission == 0 && $('#no_co2:checked').val() == null)
	{
		message += "<li> Please provide the CO2 Emission value</li>";
		res = false;		
	}
	if(co2_emission >254 && $('#no_co2:checked').val() == null)
	{
		message += "<li> Your emissions cannot exceed 254 g/Km</li>";
		res = false;		
	}
	if(engine_capacity == "" && $('#no_co2').attr('checked'))
	{
		message += "<li> Please choose the Engine Capacity</li>";
		res = false;				
	}
	if(whole_year == null || whole_year == undefined){
		message += "<li> Please select if the car was available for the whole tax year</li>";
		res = false;
	}
	if(whole_year == "no")
	{
		
		// check the start is ok..
		date_msg = is_date_ok(start_dd,start_mm,start_yy,tax_year);
		if(date_msg[0] == true)
		{
			// then check the end part of the date. 
		   date_msg = is_date_ok(end_dd,end_mm,end_yy,tax_year);
		   if(date_msg[0] == false)
		   {
			   message += date_msg[1];
			   res = false;
		   }
		}
		else
		{
			message += date_msg[1];
			res = false;
		}
		if(un_period == null || un_period == undefined){
		message += "<li> Please select whether the car was anavailable for more than 30 days.</li>";
		res = false;
		}
		if((unavl_days<30) && (un_period == "yes")){
		message += "<li> You can only claim for any period that the car was unavailable for 30 or more consecutive days.</li>";
		res = false;	
		}
	}
	
	message += "</ul></p>";
	if(res == false)
	{
		$('#dialog').html(message);
		$('#dialog').dialog('open');
		return false;
	}
	else
	{
		//If CO2 value was not entered, set to zero
		if(co2_emission == 0 || $("#no_co2").is(":checked") || fuel_type == "E") co2_emission = 0;
		//If Capital Contribution value was not entered, set to zero or > than 5000, default to 5000.
		if (capital_contribution == '') capital_contribution = 0;
		else if(capital_contribution > 5000) captial_contribution = 5000;
		//If Extras value was not entered, set to zero
		if (extras == '')extras = 0;
		
		
		// calculate total taxable value of the car:	
		list_price += extras;
		total_value = list_price - capital_contribution;
		// check if total taxable value is greater than 80k if so, make it to max accepted value. 
		if(total_value > 80,000) total_value = 80,000;
		// calculating the appropriate % 		
		if(reg_date == "Post98" && co2_emission > 0)
		{
			
			if (co2_emission != 0){							
				//Ensure CO2 value within defined range
				switch(tax_year){
					case '2011':
									if(co2_emission < 76)
									{
										tax_rate = 5;
										break;
									}
									else if(co2_emission < 121)
									{
										tax_rate = 10;
										break;
									}
									else if(co2_emission < 135)
									{
										tax_rate = 15;
										break;
									}
									else{
										var bot_co2 = 134;
										var top_co2 = 254;
										tax_rate = 14;
										if(co2_emission > 250){co2_emission = 250}
										for(var i=bot_co2; i<=top_co2; i+=5){
											tax_rate++;
											if(i>=co2_emission){
												break;
											}
										}
									}									
					case '2010':
					case '2009':	
									if(co2_emission < 121)
									{
										co2_emission = 110;
									}
									if (co2_emission > 120 && co2_emission < 135) 
									{
										co2_emission=135;									
									}
									if (co2_emission>235) 
									{
										co2_emission=235;
									}
									yearVal = 12;
									break;
					case '2008':	
					case '2007':	
					case '2006':	
									if (co2_emission<140) 
									{
										co2_emission=140 ;
									}
									if (co2_emission>240) 
									{
										co2_emission=240;
									}
									yearVal = 13;
									break;
					case '2005':
									if (co2_emission<145) 
									{
										co2_emission=145 ;
									}
									if (co2_emission>245) 
									{
										co2Emission=245;
									}
									yearVal = 14;
									break;
					case '2004':
									if (co2_emission<155) 
									{
										co2_emission=155 ;
									}
									if (co2_emission>255) 
									{
										co2_emission=255;
									}
									yearVal = 16;
									break;
				}
				
				//Calculate tax_rate value
				switch(tax_year){
					case '2011':  // as of 2011 the tax rates change						
						tax_rate = tax_rate;
						break;
					default:
						tax_rate = Math.floor(co2_emission/5) - yearVal;	
						break;
				}
				// Adjust tax_rate based on fuel types
				if (co2_emission != 0) 
				{				
					switch(fuel_type)
					{
						case 'D':
							//If Diesel, increase tax_rate percentage by 3
							tax_rate = tax_rate + 3;
							break;
						case 'H':							
							if(tax_year >2006)tax_rate = tax_rate - 3;
							else tax_rate = tax_rate - 2;
							break;
						case 'E85':
							if(tax_year>2009)tax_rate = tax_rate - 2;
							break;
					}
					//make sure that tax_rate is in the allowed range
					/*if (tax_rate<10) tax_rate=15; */
					if (tax_rate>35){
						tax_rate=35;
					}
				}		
			}		
			
		}
		else if(reg_date == "Post98" && co2_emission == 0){			
			if (engine_capacity == "1") { tax_rate=15; }
			if(tax_year >= 2011){
				if (engine_capacity == "2") { tax_rate=25; }	
				if (engine_capacity == "3" || engine_capacity == "4") { tax_rate=35; }
			}
			else{
				if (engine_capacity == "2") { tax_rate=22; }	
				if (engine_capacity == "3" || engine_capacity == "4") { tax_rate=32; }
			}
				
			if(fuel_type == "E" && tax_year >= 2011){
				tax_rate = 0;
			}
			else if(fuel_type == "E" && tax_year < 2011)
			{
				tax_rate = 9;
			}
			else if(fuel_type == "H")
			{
				tax_rate = tax_rate - 3;
			}
			//alert("tax rate with fixed engine size (post 98): "+tax_rate);
		}
		else if(reg_date == "Pre98" && co2_emission == 0)
		{
			if (engine_capacity == "1") { tax_rate=15; }
	
			if (engine_capacity == "2") { tax_rate=22; }
	
			if (engine_capacity == "3" || engine_capacity == "4") { tax_rate=32; }		
	
			if(fuel_type == "E")
			{
				tax_rate = 15;
			}
			//alert("tax rate with fixed engine size (pre 98): "+tax_rate);					
		}	
	
	
		// calculate the results:
		
		tax_rate = tax_rate/100;
		car_benefit = Math.floor(total_value * tax_rate);
		car_benefit = car_benefit - private_amount;
		// check whether the car was available whole year, if not do the calc for the available period.
		if(whole_year == "no")
		{
			// calculate the total days that the car was unavailable
			// need to minus month by 1 because in javascript the month is calculated from 0-11 not 1-12
			var standard_day = 1000*60*60*24;
			var start_date = new Date(start_yy,(start_mm-1),start_dd);
			var end_date = new Date(end_yy,(end_mm-1),end_dd);		
			var total_days = Math.ceil((end_date.getTime() - start_date.getTime())/standard_day);			
			if(unavl_days == "" || unavl_days == 0) unavl_days = 0;
			total_days += Math.round(unavl_days);
			total_days = 365 - total_days;
			car_benefit = car_benefit - Math.ceil((car_benefit * (total_days/365)));
		}
		
		
		
		// if employer pays for the priave use for fuel , then calculate it.
		if(pay_employer == "yes")
		{
			if(tax_year >= 2011)
			{
				fuel_benefit = Math.ceil(18000 * tax_rate);
			}
			else if(tax_year >= 2009)
			{
				fuel_benefit = Math.ceil(16900 * tax_rate);
			}
			else
			{
				fuel_benefit = Math.ceil(14400 * tax_rate);
			}
			if(whole_year == "no")
			{
				fuel_benefit = fuel_benefit - Math.ceil(fuel_benefit*(total_days/365));
			}
		}
		else
		{
			fuel_benefit = 0;
		}
		$('#car_benefit').html(to_amount(car_benefit));
		$('#fuel_benefit').html(to_amount(fuel_benefit));
		$('#cb_per').html(to_amount(car_benefit*rate));
		$('#fb_per').html(to_amount(fuel_benefit*rate));
		//$('#tr_per').html(to_amount(tax_rate*100));
		$('#result_area').show('slow');
	}
} // function ends here.. 

function is_date_ok(iDate,iMonth,iYear,year)
{
	 var data = new Array();
	 var message = "";
	 var res = true;
	 //checking to ensure the entries are digits
     if (iYear == 0 || iMonth == 0 || iDate == 0 || iYear < 2000 || iMonth < 1 ||
        iMonth > 12 || iDate < 1 || iDate > 31) {
		 data[0] = false;
         data[1] = " - Please put a date in the start/end date boxes\n    in dd/mm/yyyy format\n\n";         
     }	 
	 
	 else
	 {
		 var chkdate = iDate+"/"+iMonth+"/"+iYear; 
		 var datUser = new Date(iYear,iMonth,iDate);
		 data = check_date(chkdate);
		 if(data[0] == true)
		 {
			var datNow = new Date(year,04,05);
			var datLimit = new Date(year - 1,04,06);
			if ((datUser.getTime() - datLimit.getTime()) < 0 || (datUser.getTime() - datNow.getTime()) > 0)
			{
				  data[0] = false;
				  data[1] = " -Start & End dates should be\n\n between 6th April " + (year - 1) + " and 5th April " + year + "\n\n";				  
			}
		 }
	 }
	 return data;
	
}	

/************************************************************************************************************/
/*			Change text boxes depending on values e.g. disabling or appearing and disappearing				*/
/************************************************************************************************************/
$(document).ready(function()
{ 
	$('#taxyear').blur(function(){
		var val = $('#taxyear').val();
		change_highest_tax(val);
	});
	
	$('#no_co2').click(
		function()
		{
			if($('#no_co2').attr('checked'))
			{ 
			  $('#co2_emissions').attr("disabled","disabled");
			  $('#engine_capacity').removeAttr("disabled");
			}
			else
			{
				$('#engine_capacity').attr("disabled","disabled");			
				$('#co2_emissions').removeAttr("disabled");
			}
	});
	
	$("input[name='all_year']").click(
		function()
		{
			//alert("inside the click function: "+ $("input[name='all_year']:checked").val());
			if ($("input[name='all_year']:checked").val() == "no")
				{$("#avl_data").show("slow");}
			else{
				$("#avl_data").hide("fast");
				clear_values('avl_data');
			}
			$(this).blur();
	});
	
	$("input[name='un_period']").click(
		function()
		{
			if ($("input[name='un_period']:checked").val() == "yes")
			$("#unavl_data").show("slow");
			else
			$("#unavl_data").hide("fast");
			clear_values('unavl_data');
			$(this).blur();
	});
	$('#fuel_type').blur(function(){
		
	});
});

/************************************************************************************************************/
/*										change tax year drop down box										*/
/************************************************************************************************************/
function change_highest_tax(val){
	var switch_options = "";
	switch(val)
	{
		case '2011': 			
			switch_options = {
				"" : "Please choose a tax year",
				"0.2" : "20%",
				"0.4" : "40%",
				"0.5" : "50%"
			}
			break;
		case '2010':
		case '2009': 
			switch_options = {
				"" : "Please choose a tax year",
				"0.2" : "20%",
				"0.4" : "40%"
			}
			break;
		case '2008': 
			switch_options = {
				"" : "Please choose a tax year",
				"0.22" : "22%",
				"0.4" : "40%"
			}
			break;
		case '2007': 
		case '2006':
		case '2005':
		case '2004':
			switch_options = {
				"" : "Please choose a tax year",
				"0.2" : "20%",
				"0.4" : "40%"
			}
			break;
	}
	if(switch_options != ""){
		$("#tax_rate").removeOption(/./);
		$("#tax_rate").addOption(switch_options, false); // use true if you want to select the added options
	}
}

/************************************************************************************************************/
/*										change text block													*/
/************************************************************************************************************/
var textBlocks = new Array(
'Total no. of days the car was unavailable during any periods of 30 days:',
'If the car was available to you at the beginning and the end of the tax year please enter 06/04/2009 as the start date and 05/04/2010 as the end date and Indicate the number of consecutive days within the period the car was not available to you below',
'If the car was available to you at the beginning and the end of the tax year please enter 06/04/2008 as the start date and 05/04/2009 as the end date and Indicate the number of consecutive days within the period the car was not available to you below',
'If the car was available to you at the beginning and the end of the tax year please enter 06/04/2007 as the start date and 05/04/2008 as the end date and Indicate the number of consecutive days within the period the car was not available to you below',
'If the car was available to you at the beginning and the end of the tax year please enter 06/04/2006 as the start date and 05/04/2007 as the end date and Indicate the number of consecutive days within the period the car was not available to you below',
'If the car was available to you at the beginning and the end of the tax year please enter 06/04/2005 as the start date and 05/04/2006 as the end date and Indicate the number of consecutive days within the period the car was not available to you below',
'If the car was available to you at the beginning and the end of the tax year please enter 06/04/2004 as the start date and 05/04/2005 as the end date and Indicate the number of consecutive days within the period the car was not available to you below',
'If the car was available to you at the beginning and the end of the tax year please enter 06/04/2003 as the start date and 05/04/2004 as the end date and Indicate the number of consecutive days within the period the car was not available to you below');

function changetext(elemid) {
var ind = document.getElementById(elemid).selectedIndex;
document.getElementById("display").innerHTML=textBlocks[ind];
}
