// Loan Amount Calculator
// Head script
// copyright Stephen Chapman, 25th February 2005
// you may copy this calculator provided that you retain the copyright notice

$(document).ready(function(){
	$('<a class="yes_loan" href="javascript:void(0)" title="Yes, I wish to apply now"><strong class="txt-xlarge">Yes</strong><br/>I wish to<br/>apply now</a>').insertBefore('.confirmation');
				   
	$('<a class="contact-span-link" href="javascript:void(0)" title="">Yes<\/a>').insertBefore('.confirmation .yesno .pass-calc');
	
	
	
	
	
	$.get('/loans/ajax/mini-tools', function(data) {
	  		$('#resourcer-box div.loan-actions').html(data.replace('{CALCTYPE}', 'resourcer'));
                        $('#responder-box div.loan-actions').html(data.replace('{CALCTYPE}', 'responder'));
                        $('#reloader-box div.loan-actions').html(data.replace('{CALCTYPE}', 'reloader'));
	   		$('div.loan-actions ul').show();
	   
	   
	   
	   	/*  SETUP THE TOOL BARS  */
	      	$('.loan-infoBox').hide();
			$('.existing-member .confirmation').hide();
		
			$('.contact-span').hide();
		
			$('div.loan-container').removeClass('loan-active');
		
		
		
			$('.yes_loan').click(function (){
				if($(this).parent().children('.confirmation').is(':visible') == false){
					$(this).parent().children('.confirmation').slideDown(250);
					$(this).addClass('hover');
				}
				else{
					$(this).parent().children('.confirmation').slideUp(250);
					$(this).removeClass('hover');
				}
		
			});
			
		
			$('div.loan-container  .loan-title').click(function(){
		
				openInfoBox($(this).parent(), 'info');
		
				return false;
			});
			
			
			$('.loan-title .loan-actions .information a').click(function(){
				openInfoBox($(this).parent().parent().parent().parent().parent(), 'info');
		
				return false;
			});
			
			
			$('.loan-title .loan-actions .apply a').click(function(){
				openInfoBox($(this).parent().parent().parent().parent().parent(), 'existing-member');
				return false;
			});
		
		
			$('div.loan-container  .loan-title').mouseover(function(){
				if($(this).parent().children('.info').is(':visible') === true || $(this).parent().children('.existing-member').is(':visible') === true)
					return false;
		
				$(this).parent().addClass('loan-active');
			});
		
		
			$('div.loan-container  .loan-title').mouseout(function(){
		
				if($(this).parent().children('.info').is(':visible') === true || $(this).parent().children('.existing-member').is(':visible') === true)
					return false;
		
		
				$(this).parent().removeClass('loan-active');
			});
		
			$('div.loan-container  a.contact-span-link').click(function(){
		
		
				if( $(this).parent().parent().children('.contact-span').is(':visible') ){
					$(this).parent().parent().children('.contact-span').slideUp(250);
					$(this).removeClass('hover');
				}
				else{
					$(this).parent().parent().children('.contact-span').slideDown(250);
					$(this).addClass('hover');
				}
			});
		
		
			//$('a.no-join-now').attr('href', 'javascript:void(0)')
			$('a.pass-calc').click(function(){
				var type = $(this).parent().parent().parent().parent().attr('id')
		
				//check if they went the yes route
				if(type == '')
					type = $(this).parent().parent().parent().parent().parent().parent().attr('id')
		
				var calc_type = '';
				if(type == 'resourcer-box'){
					calc_type = 'calculate-resourcer'
				}
				else if(type == 'responder-box'){
					calc_type = 'calculate-responder'
				}
				else{
					calc_type = 'calculate-reloader'
				}
		
				//use the a tag's own href to submit data
				$('#' + calc_type + ' form').attr('action', $(this).attr('href') ).submit();
		
				return false;
			})
			
			
			
			setup_calc();
	});
	 


						   
						   
 
	

    function openInfoBox(obj, class_var){
        var to_analyze = obj;

        $('.confirmation').hide();
        $('.contact-span').hide();
        $('.yes_loan').removeClass('hover');
        $('div.loan-container  a.contact-span-link').removeClass('hover');

        $('.loan-infoBox[class!='+class_var+']:visible').not(to_analyze.children('.loan-infoBox.'+class_var+'')).slideUp(250);
        $('div.loan-container').not(to_analyze.children('.loan-infoBox.'+class_var+'')).removeClass('loan-active');

        if(to_analyze.children('.loan-infoBox.'+class_var+'').is(':visible') === true)
        {
            to_analyze.removeClass('loan-active');
            to_analyze.children('.loan-infoBox.'+class_var+'').slideUp(250);
        }
        else
        {
            to_analyze.children('.loan-infoBox.'+class_var+'').slideDown(250);
            to_analyze.addClass('loan-active');
        }

        return false;
    }

    $('.loan-infoBox a.close').click(function(){
        $(this).parent()
        .slideUp(250);
		
        $(this)	.parent()
        .parent()
        .removeClass('loan-active');
        return false;
    });
	
	
	
	
	function setup_calc(){
		$.get('/loans/ajax/calculator', function(data) {
	  		$('body').append(data);
		
			
			
			 
		
		
		
			$('.calculatorform .apply-online a').click(function(){
				var calc_type = $(this).parent().parent().parent().parent().parent().attr('id');
		
				closeTB();
		
				var parent_box = '';
				if(calc_type == 'calculate-resourcer'){
					parent_box = 'resourcer-box'
				}
				else if(calc_type == 'calculate-responder'){
					parent_box = 'responder-box'
				}
				else{
					parent_box = 'reloader-box'
				}
		
				if( ! $('#' + parent_box + " .existing-member").is(':visible') ){
					openInfoBox($('#' + parent_box), 'existing-member');
				}
			  
				return false;
			})
		
		
			/* REINITIALISES THICKBOX */
			$('.thickbox').unbind("click");
			tb_init('.thickbox');

		
			//preset values
		
			var resourcer_int_rate = '8';
			var responder_int_rate = '12.7';
			var reloader_int_rate = '12.7';
		
			$('.calculatorform input#amount').val('')
			$('.calculatorform input#repayment_period').val('')
			$('#resourcer-calculator .calculatorform div#interest_rate').html(resourcer_int_rate + '%')
		
			$('#responder-calculator .calculatorform div#interest_rate').html(responder_int_rate + '%')
		
			$('#reloader-calculator .calculatorform div#interest_rate').html(reloader_int_rate + '%')
		
		
				
			$('.calculatorform .calculate-loan').click(function(){
				var calc_type = $(this).parent().parent().parent().parent().parent().parent().parent().attr('id');
		
		
		
				//get to form level
				var form = $(this).parent().parent().parent().parent().parent();
		
				//retrieve needed form values
				//alert($(form).children('#amount').value())
				
				var amount = $('#'+calc_type+' input#amount').val();
				var repayment_period = $('#'+calc_type+' input#repayment_period').val();
				
				
				amount = amount.replace(/[^0-9.\.]+/g,'');
				repayment_period = repayment_period.replace(/[^0-9.\.]+/g,'');
				
				
				//check all are numeric. If not, set errors and halt processing
				var errors = false;
				var errors_loc = form.parent().parent().children('#errors');
				//clear existing errors
				errors_loc.html('');
				errors_loc.hide();
				
				if(isNaN(amount) || amount != parseFloat(amount)){
					errors = true;
					errors_loc.append('<li>The amount must be a valid number</li>')
				//set the error into the ul
				}
				
				if(isNaN(repayment_period) || repayment_period != parseFloat(repayment_period)){
					errors = true;
					errors_loc.append('<li>The repayment period must be a valid number</li>')
				
				//set the error into the ul
				}
				
		
				if(parseFloat(amount) <= 0 || parseFloat(repayment_period) <= 0){
					errors = true;
					errors_loc.append('<li>None of the fields can be equal to or below 0</li>')
				//set the error into the ul
				}
		
				if(errors === true)
				{
					//display the errors
					errors_loc.show();
					return false;
				}
				
				
				//time for more precise error checks
				var min_amount = 0;
				var max_amount = 0;
				var interest_rate = 0;
				if(calc_type == 'calculate-resourcer')
				{
					interest_rate = resourcer_int_rate;
					min_amount = 2000;
					max_amount = 20000;
		
		
					if(repayment_period > 36 && repayment_period <= 60)
					{
						min_amount = 3000;
					}
		
		
					if(repayment_period > 60)
					{
						errors = true;
						errors_loc.append('<li>The maximum payment period is 60 months</li>')
					}
		
					//first check if it's below the most minimal amount' and above the 36 month threshold
					if(amount < 2000 && repayment_period > 36){
						errors = true;
						errors_loc.append('<li>Minimum amount allowed is between &pound;2,000and &pound;2,999 for a repayment period of 36 months</li>')
					}
					else if(amount < 2000){
						errors = true;
						errors_loc.append('<li>Minimum loan amount required is &pound;2,000 on this loan type. Please visit the Responder or Reloader loan calculator for loan between &pound;100 and &pound;12,000</li>')
					}
					//now check if it's below the set minimum'
					else if(amount < min_amount){
						errors = true;
						errors_loc.append('<li>Maximum repayment period is 36 months for a loan this size</li>')
					}
					else if(max_amount < amount)
					{
						errors = true;
						errors_loc.append('<li>Maximum amount allowed is &pound;'+max_amount+'</li>')
					}
		
				}
				else if(calc_type == 'calculate-responder')
				{
					interest_rate = responder_int_rate;
					min_amount = 100;
					max_amount = 12000;
		
					if(repayment_period > 36 && repayment_period <= 60)
					{
						min_amount = 3000;
					}
		
		
					if(repayment_period > 60)
					{
						errors = true;
						errors_loc.append('<li>The maximum payment period is 60 months</li>')
					}
		
					//first check if it's below the most minimal amount' and above the 36 month threshold
					if(amount < 100 && repayment_period > 36){
						errors = true;
						errors_loc.append('<li>Minimum amount allowed is between &pound;100and &pound;2,999 for a repayment period of 36 months</li>')
					}
					else if(amount < 100){
						errors = true;
						errors_loc.append('<li>Minimum loan amount required is &pound;100 on this loan type.</li>')
					}
					//now check if it's below the set minimum'
					else if(amount < min_amount){
						errors = true;
						errors_loc.append('<li>Maximum repayment period is 36 months for a loan this size</li>')
					}
					else if(max_amount < amount)
					{
						errors = true;
						errors_loc.append('<li>Maximum amount allowed is &pound;'+max_amount+' on this loan type. Please see the Resourcer loan calculator for loans between &pound;12,001 and &pound;20,000</li>')
					}
		
				}
				else if(calc_type == 'calculate-reloader')
				{
		
					interest_rate = reloader_int_rate;
					if(repayment_period == 36)
					{
						min_amount = 500;
						max_amount = 5000;
					}
					else
					{
						errors = true;
						errors_loc.append('<li>The ONLY payment period is 36 months</li>')
					}
		
		
					if(amount < min_amount){
						errors = true;
						errors_loc.append('<li>Minimum loan amount required is &pound;500 on this loan type.</li>')
					}
					else if(max_amount < amount)
					{
						errors = true;
						errors_loc.append('<li>Maximum amount allowed is &pound;'+max_amount+' on this loan type</li>')
					}
					else if(amount % 500 !== 0){
						errors = true;
						errors_loc.append('<li>The amount for a reloader loan must be in &pound;500 blocks</li>')
					}
				}
				else
				{
					errors = true;
					errors_loc.append('<li>Loan type coud not be clarified. Please Refresh the page and try again</li>')
				}
		
				
				if(errors === true)
				{
					//display the errors
					errors_loc.show();
					return false;
				}
				
					
		
		
			  
		
		
				//work out loan
				var tmp1     = Math.pow( 1 + ((interest_rate / 100) / 12), repayment_period);
				var payment      = number_format(((amount * tmp1) * ((interest_rate / 100) / 12)) / --tmp1, 1, '.', '');
			  
		
				//alert(   amount * ( ((interest_rate/100) / 365.25) * (365.25 / payment_frequency) )     )
		
				//amount per payment
				$('#'+calc_type+' input#repayment').val(number_format(payment, 2));
				
				//total to pay back
				var payback = payment*((repayment_period/12) * 12)
				$('#'+calc_type+' input#total_paid').val( (number_format(payback, 2)) )
				
				//amount of interest
				var total_interest = payback - amount;
				$('#'+calc_type+' input#total_interest').val( number_format(total_interest, 2) )
				return false;
			});
		});
	
	}
	
    /*
		CALCULATE FORM
	*/
 

	
//temp = temp.replace(/[^0-9.\.]+/g,'');
	
	
});


function number_format(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
        var k = Math.pow(10, prec);
        return '' + Math.round(n * k) / k;
    };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}


function closeTB()
{

    //$('.calculatorform').each(function() {
      //  $(this).find('input#amount').val('');
    //})

    //$('.calculatorform').each(function() {
      //  $(this).find('input#repayment_period').val('');
    //})

    $('.loan-calculator').each(function() {
        $(this).find('#errors').html('');
    })

    tb_remove();
    return false;
}
