var current = new Object();
	current.period = new Object();
	current.rate = new Object();
	current.cost = new Object();
	current.pay = new Object();
	current.first = new Object();
	current.first.rub = new Object();
	current.first.percent = new Object();
var complectation = new Object();
	complectation.id = '';
	complectation.price = new Object();
	complectation.option = new Array();
var program = new Object();
	program.id = '';
	program.first  = new Object();
	program.first.rub  = new Object();
	program.first.percent  = new Object();
	program.cost = new Object();
	program.period = new Object();
	program.rate = new Array();
var credit = new Object();
var period = new Object();
	period.list = ['12','24','36','48','60','72','84'];
var infa;
$(function(){
	var original_href = $('#content .top_link').attr('href');
	$('#content .top_link').click(function(){
		var href = original_href;
			href = href + '&auto=' + $('#auto').find(':selected').text();
			href = href + '&complectation=' + $('#complectation').find(':selected').text();
			href = href + '&cost=' + $('#cost').val();
			href = href + '&program=' + $('#program').find(':selected').text();
			href = href + '&rub=' + $('#rub').val();
			href = href + '&percent=' + $('#percent').val();
			href = href + '&period=' + $('#period').find(':selected').text();
			href = href + '&rate=' + $('#rate').val();
			href = href + '&pay=' + $('#pay').val();
		$(this).attr('href',href);
	});
	$('#auto').change(function(){
		$('#label_first').show();
		$('#calc .calc_result, #label_detail, .after_program').hide();
		var code = $(this).val();
		var name = $(this).find(':selected').text();
		$('#complectation option, #program option, #period option').remove();
		$('#complectation, #program, #period').append('<option></option>');
		$('#rub, #percent, #cost, #rate, #pay').val('');
		if(code!='0'){
			$('#complectation option, #program option, #period option').remove();
			$('#complectation, #program, #period').append('<option></option>');
			$('#rub, #percent, #cost, #rate, #pay').val('');
			$.ajax({
				'url'		: '/ajax/complectation.php',
				'data'		: 'code='+code+'&name='+name,
				'success'	: function(infa){
								complectation.id = '';
								program.id = '';
								current.period = '';
								$('#complectation').removeAttr('readonly').html('<option></option>'+infa);
							  }
			})
		}
	});

	complectation.update = function(){
		var id = parseInt($(this).val());
		var change = true;
		if(id == complectation.id)
			change = false;
		if(change){
			$('#label_first').show();
			$('#calc .calc_result, #label_detail, .after_program').hide();
			$('#program option, #period option').remove();
			$('#program, #period').append('<option></option>');
			$('#rub, #percent, #cost, #rate, #pay').val('');
		}
		var active = '';
		var program_path = 'program.php';
		if(debug){
			active = '&debug';
//			program_path = '_program.php';
		}
		if(id > 0 && change){
			$.ajax({
				'dataType'	: 'json',
				'cache'		: 'false',
				'url'		: '/ajax/'+program_path,
				'data'		: 'id='+id+active,
				'success'	: function(infa){
								program.id = '';
								current.period = '';
								complectation.id = id;
								complectation.price.val = parseFloat(infa['PRICE'].split(' ').join(''));
								complectation.price.html = number_format(complectation.price.val);
								complectation.option = infa.option;
								$('#program option, #period option').remove();
								$('#program, #period').append('<option></option>');
								var options_for_program = '';
								for(i in complectation.option)
									options_for_program = options_for_program + '<option value="'+i+'">'+complectation.option[i]+'</option>';
								$('#program').append(options_for_program).removeAttr('readonly');
								$('#cost').val(complectation.price.html);

							  }
			});
		}
	}
	$('#complectation').live('click', complectation.update);
	$('#complectation').live('keyup', complectation.update);
	program.update = function(){
		var id = parseInt($(this).val());
		var change = true;
		if(id == program.id)
			change = false;
		if(change){
			$('#label_first').show();
			$('#calc .calc_result, #label_detail').hide();
			$('#time option').remove();
			$('#time').append('<option></option>');
			$('#rub, #percent, #rate, #pay').val('');
		}
		if(id>0 && change){
			$.ajax({
				'dataType'	: 'json',
				'cache'		: 'false',
				'url'		: '/ajax/credit_params.php',
				'data'		: 'id='+id,
				'success'	: function(data){
								infa = data;
								program.id 					= id;
								current.period 				= '';
								program.text 				= infa['LEGEND_TEXT'];
								program.url 				= infa['URL'];
								program.type 				= infa['TYPE'];
								program.kia 				= parseFloat(infa['KIA'].split(' ').join(''));
								program.cost.val 			= complectation.price.val; //- program.kia;
								program.cost.html 			= number_format(program.cost.val);
								program.first.percent.val	= parseFloat(infa['FIRST'].split(' ').join(''));
								program.first.rub.val 		= program.cost.val*program.first.percent.val/100;
								program.min 				= parseFloat(infa['MIN'].split(' ').join(''));
								program.diapazone			= false;
								program.first_diapazone		= new Array;
								if (infa.diapazone != ''){
									program.diapazone = true;
									program.first_diapazone		= infa.FIRST.split('/');
									for (j in program.first_diapazone)
										program.first_diapazone[j] = parseFloat(program.first_diapazone[j].split(',').join('.'));
								}
								$('.after_program').hide();
								if(program.min){
									$('#program_min').val(number_format(program.min));
									$('#program_min_tr').show();
								}
								else
									program.min 			= 0;
								program.max 				= parseFloat(infa['MAX_RUB'].split(' ').join(''));
								if(program.max){
									$('#program_max').val(number_format(program.max));
									$('#program_max_tr').show();
								}
								else
									program.max 			= program.cost.val - program.first.rub.val;
								program.first.rub.val 		= Math.max(parseFloat(infa['FIRST_RUB'].split(' ').join('')) || 0, program.cost.val - program.max);
								program.first.rub.val 		= Math.min(program.first.rub.val, program.cost.val - program.min);
								program.first.percent.val	= Xround(program.first.rub.val*100/program.cost.val);
								program.first.rub.html 		= number_format(program.first.rub.val);
								program.period.max 			= infa['MAX'];
								$('#rub, #percent').removeAttr('readonly');
								$('#percent').val(program.first.percent.val);
								$('#rub').val(program.first.rub.html);
							  	$('#period option').remove();
								program.period.options = '';
								program.rate_diapazone		= new Object;
								var rate_d = new Object;
								for(i in period.list){
									if(period.list[i] <= program.period.max){
										program.period.options = program.period.options + '<option value="'+period.list[i]+'">'+period.list[i]+'</option>';
										program.rate[period.list[i]] = parseFloat(infa['RATE_'+period.list[i]].split(',').join('.'));
										if (program.diapazone){
											program.rate_diapazone[period.list[i]] = infa['RATE_'+period.list[i]].split('/');
											rate_d[period.list[i]] = new Object;
											for (j in program.rate_diapazone[period.list[i]]){
												program.rate_diapazone[period.list[i]][program.first_diapazone[j]] = parseFloat(program.rate_diapazone[period.list[i]][j]);
												rate_d[period.list[i]][program.first_diapazone[j]] = parseFloat(program.rate_diapazone[period.list[i]][j]);
												delete program.rate_diapazone[period.list[i]][j];
											}
										}
									}
								}
								if (program.diapazone) program.rate_diapazone = rate_d;
								if (program.period.max != period.list[0])
									program.period.options = '<option></option>'+program.period.options;
								$('#period').append(program.period.options);
								if(program.period.max == period.list[0])
									if(debug) $('#period').each(period.update);

							  }
			})
		}
	}
	$('#program').live('click', program.update);
	$('#program').live('keyup', program.update);
	period.update = function(){
		var period = parseFloat($(this).val());
		var change = true;
		if(current.period == period)
			change = false;
		if(change)
			$('#rate, #pay').val('');
		if(period>0 && change){
			current.period = period;
			current.rate.val = program.rate[current.period];
			current.rate.back = current.rate.val;
			current.rate.html = current.rate.val+' %';
			if(current.period)
				$('#rate').val(current.rate.html);
			current.first.rub.val = parseFloat($('#rub').val().split(' ').join(''));
			current.first.percent.val = parseFloat($('#percent').val());
			diapazone();
			if(current.first.rub.val > 0 || current.first.percent.val > 0)
				annuity();
		}
	}
	$('#period').live('click', period.update);
	$('#period').live('keyup', period.update);

	$('#rub').keyup(function(){
		current.first.rub.val = parseFloat($(this).val().split(' ').join(''));
		if(current.first.rub.val > 0){
			var input = $(this);
			clearTimeout(current.first.rub.delay);
			current.first.rub.delay = setTimeout(function(){
				if(parseFloat($('#rub').val())>0){
					current.first.rub.val = Math.max(current.first.rub.val, Math.max(program.first.rub.val,program.cost.val - program.max));
					current.first.rub.val = Math.min(current.first.rub.val, Math.max(program.first.rub.val, program.cost.val - program.min));
					current.first.rub.html = number_format(current.first.rub.val);
					current.first.percent.val = Xround(current.first.rub.val*100/program.cost.val);
					$(input).val(current.first.rub.html);
					$('#percent').val(current.first.percent.val);
					diapazone();
					annuity();
				}
			}, 1000);
		}
	})
	$('#percent').keyup(function(){
		current.first.percent.val = parseFloat($(this).val().split(',').join('.'));
		if(current.first.percent.val > 0){
			var input = $(this);
			clearTimeout(current.first.percent.delay);
			current.first.percent.delay = setTimeout(function(){
				if(parseFloat($('#percent').val())>0){
					current.first.percent.val = Math.max(current.first.percent.val, Math.max(program.first.percent.val, (program.cost.val - program.max)/program.cost.val));
					current.first.percent.val = Math.min(current.first.percent.val, Math.max(program.first.percent.val, (program.cost.val - program.min)*100/program.cost.val));
					current.first.rub.val = Xround(current.first.percent.val*program.cost.val/100);
					current.first.rub.html = number_format(current.first.rub.val);
					$(input).val(Xround(current.first.percent.val));
					$('#rub').val(current.first.rub.html);
					diapazone();
					annuity();
				}
			}, 1000);
		}
	});
	function diapazone(){
		if (program.diapazone){
			current.diapazone = new Object;
			//console.log(program.rate_diapazone[12]);
			current.diapazone = program.rate_diapazone[current.period];
			for (j in current.diapazone){
				if (j <= current.first.percent.val)
					current.rate.val = current.diapazone[j];
			}
			current.rate.html = current.rate.val+' %';
			$('#rate').val(current.rate.html);
		}
	}
	function annuity(){
		if(debug){

		}

		if(current.rate.val==0){
			credit.sum = program.cost.val - program.kia - current.first.rub.val;
			current.pay.val = Xround(credit.sum/current.period);
			current.pay.html = number_format(current.pay.val);
		}
		else{
			if(!current.rate.val || !current.period) return;
			credit.p = current.rate.val/100/12;
			credit.over = Math.pow((1+credit.p), current.period - 1);
			credit.annuity = credit.p * credit.over / (credit.over-1);
			credit.sum = program.cost.val - program.kia - current.first.rub.val;
			if (program.id == 22850 | program.id == 22849 | program.id == 22847){
				credit.sum = (program.cost.val - current.first.rub.val)*(1 + 0.02*current.period/12) + program.cost.val*0.063*current.period/12;
			}
		//	console.info(program, credit, current);

			credit.pay = credit.annuity * credit.sum;
			current.pay.val = Xround(credit.pay);
			current.pay.html = number_format(current.pay.val);
		}
		$('#program_legend_text').html(program.text);
		$('#label_first').hide();
		$('#calc .calc_result, #label_detail').show();

	//	if(debug) console.info(current, credit);

		$('#pay').val(current.pay.html);
	}
});
function Xround(number,power){
	if(typeof(power)=='undefined') power = 2;
	var exponent = Math.pow(10,power);
	return Math.round(number*exponent)/exponent;
}
function number_format (number, decimals, dec_point, thousands_sep) {
    var n = number, prec = decimals;
    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ' ' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

