// 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 valule 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(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)
			{
				if(co2_emission > 124)
				{
					co2_emission=Math.floor(co2_emission / 5) * 5;					
				}
				
				//Ensure CO2 value within defined range
				switch(tax_year)
				{
					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
				tax_rate = Math.floor(co2_emission/5) - yearVal;			       		
				// 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; 
				}
				// for 2009/10 year calculation to have tax_value defined as below:
				else if(fuel_type == "P" || fuel_type == "D" || fuel_type == "H" && co2_emission >= 120)
				{
					// should set default tax value for the all possible types for values = 120. 				
				}
		
			}		
			
		}
		else if(reg_date == "Post98" && co2_emission == 0)
		{
			if (engine_capacity == "1") { tax_rate=15; }
	
			if (engine_capacity == "2") { tax_rate=25; }
	
			if (engine_capacity == "3" || engine_capacity == "4") { tax_rate=35; }	
			if(fuel_type == "E")
			{
				tax_rate = 9;
			}
			else if(fuel_type == "H")
			{
				tax_rate = tax_rate - 3;
			}
		}
		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;
			}
			
									
		}	
	
	
		// 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 >= 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()
{ 
	$('#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();
	});
	
});

/************************************************************************************************************/
/*										change tax year drop down box										*/
/************************************************************************************************************/
var year = $('#taxyear').val();
var lists = new Array();

// First set of text and values
lists['2009']    = new Array();
lists['2009'][0] = new Array(
	'20%',
	'40%'
);
lists['2009'][1] = new Array(
	'0.2',
	'0.40'
);

// Second set of text and values
lists['2008']    = new Array();
lists['2008'][0] = new Array(
	'22%',
	'40%'
);
lists['2008'][1] = new Array(
	'0.22',
	'0.4'
);

function changeList( box ) {
	 
	var sel_index = (box.selectedIndex > 2)? 3:2;
	list = lists[box.options[sel_index].value];
	emptyList( box.form.tax_rate );
	fillList( box.form.tax_rate, list );
}
function emptyList( box ) {
	while ( box.options.length ) box.options[0] = null;
}
function fillList( box, arr ) {
	for ( i = 0; i < arr[0].length; i++ ) {
		option = new Option( arr[0][i], arr[1][i] );
		box.options[box.length] = option;
	}
	box.selectedIndex=0;
}

/************************************************************************************************************/
/*										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];
}