/**
 * @author Anton Starcev (ast@design.ru)
 * @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
 */

/**
 * Deposit calculator
 * @constructor
 * @extends {vtb24.calculator}
 */
function AutoStandart_Calculator() {
	AutoStandart_Calculator.baseConstructor.call(this);

//	this.MO = 26; // московский округ
	this.MO = 27; // московский округ
	this.SPB = 42; // санкт-петербург

	this.updateTermSlider(this.getArray(1,5));

	this.sheet = new Sheet(); // создание листа
	var Calc = this;
	this.sheet.calculate = function()
	{
		var rate = this.o.rate;
		var commission = this.o.commission;
//		console.log("commission",commission)
		commission = 0; // TODO разовая?
		var monthlyPayment = this.o.monthlyPayment;
		var firstMonth = this.o.firstMonth;

		var sHtml = "";
		var current_loan = this.o.loan;
		var ln = parseInt(Calc.getControlValue("term"))*12;
		var percentsSum = 0;
		for (var i = 0; i < ln; i++)
		{
			var paying_off_cell = (current_loan * rate) / 12; // погашение процентов
			var paying_loan_cell = monthlyPayment - paying_off_cell; // погашение долга

			var number = '<td class="number sheet-number"><span>' + parseInt(i + 1) + '</span></td>';
			var loan = '<td class=""><span>' + n.format(current_loan) + '</span></td>'; // Текущий долг
			var paying_loan = '<td class=""><span>' + n.format(i == 0 ? 0 : /*this.o.annua*/ monthlyPayment - paying_off_cell) + '</span></td>'; // выплата долга
			var paying_off = '<td class=""><span>' + n.format(paying_off_cell) + '</span></td>'; // выплата процентов

			td = '<td class=""><span>0</span></td>';

			var month_payment = '<td class=""><span>' + n.format(i == 0 ? firstMonth + this.o.commission : monthlyPayment) + '</span></td>';

			// <tr></tr>
			sHtml += '<tr>' + number + loan + paying_loan + paying_off + month_payment + '</tr>';

			if (i != 0){
				current_loan -= paying_loan_cell; // уменьшение долга
			}

			percentsSum += paying_off_cell; // складываем проценты
		}
		$('sheet_data').innerHTML = '<table class="data sheet-data" width="100%">' + sHtml + '</table>';
		Calc.writeResult("percent-summ", CalcHelper.WriteIfValIs(percentsSum, Calc.label, "&mdash;"));
	};
	this.calculate();
	this.updateByCity(this.getControlValue("city"));
	var currency = this.getControlValue("currency");
	this.previousCurrency = currency;
	this.updateByCurrency(" " + Currencies[currency].rus, currency, this.getControlValue("car-cost"), this.getControlValue("initial-payment"));
}

AutoStandart_Calculator.inheritFrom(vtb24.calculator);

AutoStandart_Calculator.prototype.calculate = function(evt) {
	var current = this.getCurrentControl(evt);
	var currency = this.getControlValue('currency');
	var label = ' ' + Currencies[currency].rus;
	var city = this.getControlValue('city');

	var cityType = (city == this.MO || city == this.SPB ? 1 : 2); // Москва или "Регионы"
	var autoType = this.getControlValue('auto-type');

	var autoProducer = this.getControlValue('auto-producer');
	var hasInsurance = this.getControlValue('has-insurance');
	var insuranceSize = this.getControlValue('insurance-size');
	var initialPayment = this.getControlValue('initial-payment');
	var carCost = this.getControlValue('car-cost');


	this.setCarCostRange(cityType, autoType, autoProducer, hasInsurance);

	switch (current) {
		case "city":
			this.updateByCity(city);
			break;
		case 'currency':
			this.updateByCurrency(label, currency, carCost, initialPayment);
			this.setTermRange(currency, autoProducer, autoType);
			break;
		case 'has-insurance':
			this.updateByInsurance(hasInsurance);
			break;
		case "auto-type":
			this.setTermRange(currency, autoProducer, autoType);
			this.updateByAutoType(autoType);
			break;
		case "auto-producer":
			this.setTermRange(currency, autoProducer, autoType);
			this.updateByAutoProducer(autoProducer);
			break;
		case "insurance-size":
			this.updateByInsuranceSize(insuranceSize);
			break;
		case "initial-payment":
//			this.updateByInitialPayment(initialPayment, city);
			break;
	}

	var term = this.getControlValue('term');

	/*?*/
	initialPayment = this.getControlValue('initial-payment');
	carCost = this.getControlValue('car-cost');
	
	// hasInsurance - не insurance, отоношение
	// Выбор той или иной ставки зависит от условия ПВ от и до 20% от СА.
//	console.log("initialPayment %s, carCost %s", initialPayment, carCost);
	var percents = initialPayment/(carCost/100);
	var key = null;
	if(percents < 20){
		key = 1;
	}
	else if(20 <= percents){
		key = 2;
	}
	//console.log("percents",percents,"key",key);

	//var rate = this.getRate(currency, term, city, autoProducer, autoType, key);
	var rate = this.getRate(currency, term, city, autoProducer, autoType, hasInsurance);
	
	 console.log('!!!!! ' + rate + 'currency %s, term %s, city %s, autoProducer %s, autoType %s, hasInsurance %s', currency, term, city, autoProducer, autoType, hasInsurance);

	var commission = this.getCommission(city, hasInsurance);
	this.setInitialPaymentLimit(cityType, autoType, autoProducer, hasInsurance);

	var emptyResult = "&mdash;";
	var loanSumm = this.getLoanSumm(cityType, autoType, autoProducer, hasInsurance);

	var monthlyPayment = this.getMonthlyPayment(term, loanSumm, rate);

//	var firstMonth = commission + (loanSumm * CalcHelper.ParseFloat(rate)/100/12);
	var firstMonth = (loanSumm * CalcHelper.ParseFloat(rate)/100/12);

	this.writeResult('loan-size', CalcHelper.WriteIfValIs(loanSumm, label, emptyResult));
	this.writeResult('rate', CalcHelper.WriteIfValIs(rate, '%', emptyResult));
	this.writeResult('commission', CalcHelper.WriteIfValIs(commission, label, emptyResult));
	this.writeResult('per-month', CalcHelper.WriteIfValIs(monthlyPayment, label, emptyResult));
	this.writeResult("first-month", CalcHelper.WriteIfValIs(firstMonth+commission, label, emptyResult));

	if (this.sheet)
	{
		this.label = label;
		this.sheet.print({
			loan: loanSumm,
			rate:  CalcHelper.ParseFloat(rate)/100,
			commission: commission,
			monthlyPayment: monthlyPayment,
			firstMonth: firstMonth
		});
	}

};

/**
 * Пересчитывает в новую валюту.
 * @param currency Текущая валюта.
 * @param value Значение.
 */
AutoStandart_Calculator.prototype.convertToCurrency = function(value) {
	var result = null;
	if(this.previousCurrency == 1) result = value / usd;         // rub
	if(this.previousCurrency == 2) result = value;               // usd
	if(this.previousCurrency == 3) result = value / (usd / eur); // eur
	result = this.convertCurrency( Math.round(result) );
	return Math.round(result);
};

/**
 * Устанавливает лимит (от и до) первоначального взноса на слайдере.
 * @param cityType
 * @param autoType
 * @param autoProducer
 * @param hasInsurance
 */
AutoStandart_Calculator.prototype.setInitialPaymentLimit = function(cityType, autoType, autoProducer, hasInsurance) {
	var maxValue = this.getInitialPaymentMax();
	var initial_payment_cf = this.getControl("initial-payment");
	var carCost = this.getControlValue('car-cost');

	var minValue = csinitial_payment_range.getValue(0, cityType, autoType, autoProducer, hasInsurance);
//	console.log("initial payment min", minValue)
	if (minValue == 'FUNC') {
		var city = this.getControlValue('city');
		var value = ( this.MO == city || this.SPB == city ? 10000 : 15000 );
//		if (this.convertCurrency(10000) < carCost && carCost < this.convertCurrency(50000)) {
//			minValue = 0;
//		}
//		else {
//			minValue = carCost * 0.20; // %
//		}
	}
	else {
//		minValue = carCost * minValue / 100; // %
	}
	
//	minValue = carCost * 0.20; // % // @ast 18 dec 2008
	if(carCost < maxValue){
		maxValue = carCost;
	}
	if(this.getControlValue("has-insurance") == 2){ // если нет страховки
		//console.log("maxValue",maxValue, this.getParam(city))
		maxValue -= this.getParam(city);
	}
	if (maxValue < 0) {
		maxValue = 0;
	}

	initial_payment_cf.setRange(minValue * carCost / 100, maxValue); // TODO
};

AutoStandart_Calculator.prototype.updateByCurrency = function(label, currency, carCost, initialPayment) {
	var carCostControl = this.getControl("car-cost");
	var initialPaymentControl = this.getControl("initial-payment");
	carCostControl.setLabel(label);
	initialPaymentControl.setLabel(label);

	carCostControl.setValue(this.convertToCurrency(carCost));
	initialPaymentControl.setValue(this.convertToCurrency(initialPayment));

	this.previousCurrency = currency;
};

AutoStandart_Calculator.prototype.updateByAutoProducer = function(autoProducer) {
	var input1 = $("auto-type1"); // Новый
	var input2 = $("auto-type2"); // Подержанный
	// для значения "Отечественный" пункт "Поддержанный" становится неактивным.
	if(autoProducer == 1){
		input2.disabled = false;
	}
	else if(autoProducer == 2){
		input2.disabled = true;
		input1.checked = true;
	}
};

AutoStandart_Calculator.prototype.updateTermSlider = function(values) {
	var term_cf = this.getControl("term");
	var slider=term_cf.getSlider();
	Common.Class.add(term_cf.ptr.parentNode, 'fixed-term');
	slider.setLabels(values);

	this._createFixedTermControl(values);
};

AutoStandart_Calculator.prototype.updateByInsuranceSize = function(insuranceSize) {
	var value = parseInt(insuranceSize);
	var errorState = "error";
	var insuranceInput = $("insurance-size");
	if(value == 0){
		Common.Class.add(insuranceInput, errorState);
	}else{
		Common.Class.remove(insuranceInput, errorState);
	}
};

AutoStandart_Calculator.prototype._createFixedTermControl=function(values){
	var term_cf=this.getControl('term');
	var previous = term_cf.ptr.parentNode.getElementsByTagName("select")[0];
	if(previous){
		term_cf.ptr.parentNode.removeChild(previous); // удаляем предыдущий
	}
	
	var control=als.createElement('select', 'with-slider');
	control.name='term-fixed';
	for(var i=0; i<values.length; i++){
		control.options[control.options.length]=new Option(values[i], values[i]);
	}

	term_cf.ptr.parentNode.insertBefore(control, term_cf.ptr);
	var old_cb=term_cf.getCallback();

	term_cf.setCallback(function(obj){
		old_cb(obj);
		var val=obj.getValue();
		for(var i=0; i<control.options.length; i++){
			if(control.options[i].value == val){
				control.options[i].selected=true;
				break;
			}
		}
	});

	Common.Event.add(control, 'change', function(evt){term_cf.setValue(this.value);});
};
/**
 * Дисейбливание отечественных авто.
 * @param city
 */
AutoStandart_Calculator.prototype.updateByCity = function(city) {
	var input1 = $("auto-producer1"); // Иностранный
	var input2 = $("auto-producer2"); // Отечественный
//	if(city == this.MO || city == this.SPB){
	if(city == this.MO){
		input2.disabled = true;
		input2.checked = false;
		input1.checked = true;
	}
	else if(city != this.MO){ input2.disabled = false; }

};

AutoStandart_Calculator.prototype.setTermRange = function(currency, autoProducer, autoType) {
	var termMax = csterm_limit.getValue(0, currency, autoProducer, autoType, this.MAX);
	var termMin = csterm_limit.getValue(0, currency, autoProducer, autoType, this.MIN);

	var term_cf = this.getControl('term');

//	console.log("setTermRange from %s to %s by key currency(%s) and autoProducer(%s) and autoType(%s)", termMin, termMax, currency, autoProducer, autoType);
	term_cf.setRange(termMin, termMax);
	this.updateTermSlider(this.getArray(termMin, termMax)); // TODO
};

AutoStandart_Calculator.prototype.getArray = function(min, max){
	var arr = [];
	for(var i = min; i <= max; i++){
		arr.push(i);
	}
	return arr;
};

AutoStandart_Calculator.prototype.updateByAutoType = function(autoType) {
	var input1 = $("auto-producer1"); // Иностранный
	var input2 = $("auto-producer2"); // Отечественный
//	if(autoType == 1){ // новый
		var city = this.getControlValue("city");
//		if(city != this.MO){
//			input2.disabled = false;
//		}
//	}
//	else if(autoType == 2){ // подержаный
//		input2.disabled = true;
//		input2.checked = false;
//		input1.checked = true;
//	}

	if(city == this.MO || autoType == 2){
		input1.checked = true;
		input2.disabled = true;
	}
	else{
		input2.disabled = false;
	}
};
/**
 * Обновляет по страховке, дисейблит "страховку" если надо.
 * @param hasInsurance
 */
AutoStandart_Calculator.prototype.updateByInsurance = function(hasInsurance) {
	var insurance_size_cf = this.getControl("insurance-size");
	if(hasInsurance == 1){ // true
		insurance_size_cf.enable();
	}
	else if(hasInsurance == 2){ // false
		insurance_size_cf.disable();
	}
};
AutoStandart_Calculator.prototype.getRate = function(currency, term, city, autoProducer, autoType, hasInsurance) {
	var rate = csrate.getValue(0, currency, term, city, autoProducer, autoType, hasInsurance);
//	var rate = csrate.getValue(0, currency, term, city, autoProducer, autoType, 2); // теперь одна
//	console.log(currency, term, city, autoProducer, autoType, 2)
//	console.log("rate is",rate)
	return rate;
};
AutoStandart_Calculator.prototype.getCommission = function(city, hasInsurance) {
	var commission = cscommission.getValue(0, city, hasInsurance);
//	var commission = cscommission.getValue(0, city, 2); // теперь похожу ко всему относиться
	return this.convertCurrencySpec(commission); // спец изменение ВТБ24.
};
/**
 * Устанавливает диапазон цены на слайдере.
 * @param cityType
 * @param autoType
 * @param autoProducer
 * @param hasInsurance
 */
AutoStandart_Calculator.prototype.setCarCostRange = function(cityType, autoType, autoProducer, hasInsurance) {
	var car_cost_cf = this.getControl('car-cost');
//	var currency = this.getControlValue("currency");
	var city = this.getControlValue("city");
	
	var minValue = cscar_cost_from.getValue(0, cityType, autoType, autoProducer, hasInsurance);
//	var minValue = cscar_cost_from.getValue(0, city, autoType, autoProducer, 1);
//	console.log("car cost range min", city, autoType, autoProducer, hasInsurance);
	car_cost_cf.setRange(this.convertCurrency(minValue), this.convertCurrency(1000000)); // TODO сделать maxValue
//	console.log("car cost range min",minValue);

	var progs=cscar_cost_progressive.get(1); // <car-cost-progressive> <currency> ...
	
	for(var i = 0; i < progs.length; i++){
		car_cost_cf.addCustomRange(
			parseFloat( progs[i].getLabel() )
			, parseFloat( this.convertCurrency(progs[i].getValue()) )
			);
	}
};
/**
 * Возвращает максимум первоначального взноса.
 */
AutoStandart_Calculator.prototype.getInitialPaymentMax = function() {
	var city = this.getControlValue("city");
//	var param = (city == this.MO || city == this.SPB ? this.convertCurrency(4000) : this.convertCurrency(3000));
	var param = this.getParam(city);
	var value = this.getControlValue("car-cost") - param; // 4000 или 3000 в зависимости от Москва (не Москва)
	return this.convertCurrency(value);
};
/**
 * Получить "параметр" из логики, х/з как назвать.
 */
AutoStandart_Calculator.prototype.getParam = function(city){
	return (city == this.MO ? this.convertCurrency(4000) : this.convertCurrency(3000));
};
/**
 * Получить сумму кредита, в зависимости от "зашитой" здесь функции.
 */
AutoStandart_Calculator.prototype.getLoanSumm = function(cityType, autoType, autoProducer, hasInsurance) {
	var carCost = this.getControlValue('car-cost');
	var insurance = this.getControlValue('insurance-size'); // %
	var initialPayment = this.getControlValue('initial-payment');

	var variant = csloan_summ.getValue(0, cityType, autoType, autoProducer, hasInsurance);;
	var value = null;

	/**
	 * VARIANT_1 ... _n - прописанные в XML функции.
	 */
	switch(variant){
		case "VARIANT_1":
			var insurancePercents = parseInt(insurance) / 100 * carCost;
			value = carCost + insurancePercents - initialPayment;
			break;
		case "VARIANT_2":
			value = carCost - initialPayment; 
			break;
	}
	return value;
};
/**
 * Вычислить месячный платеж.
 * @param term
 * @param loan
 * @param rate
 */
AutoStandart_Calculator.prototype.getMonthlyPayment = function(term, loan, rate) {
//A = P * (1+P)N / ((1+P)N-1), где
//
//A — коэффициент аннуитета;
//P — процентная ставка выраженная в сотых долях в расчете на период. Например, для случая 12 процентов годовых и ежемесячного платежа это составит 0.12/12 = 0.01;
//N — число периодов погашения кредита.
	
//	var rateParsed = new String(rate);
	var rateParsed = CalcHelper.ParseFloat(rate);
	rate = rateParsed / 100 / 12;
	term = term * 12;

//	var value = loan * ( rate * Math.pow(1 + rate, term) / ( Math.pow(1 + rate, term) - 1 ) );
	var value = (loan * rate) / ( 1 - Math.pow(1 + rate, 1 - term) );
	return value;
};
/**
 * Конвертит из "универсальной" валюты в остальные.
 * @param value
 */
AutoStandart_Calculator.prototype.convertCurrency = function(value) {
	var currency = this.getControlValue('currency');
	return Currencies[currency].convert(value);
};
/**
 * Странное пресчет 1 доллар = 1 евро = 30 рублей для коммисий
 * @param value
 */
AutoStandart_Calculator.prototype.convertCurrencySpec = function(value) {
	var currency = this.getControlValue('currency');
	return Currencies[currency].convertSpec(value);
};
/**
 *
 * @param evt
 */
AutoStandart_Calculator.prototype.OnReady = function(evt) {

};
/**
 * Перебитая функция слайдера.
 */
vtb24.slider.prototype.drawLimit = function() {
	if (this.hasLimit())
		this._drawItem(this.controls.limit, this.params.limitMin, this.params.limitMax - this.params.limitMin); // item, pos, size
	else
		this._drawItem(this.controls.limit, this.params.limitMin, 1);
};
