/*
* Site Calculator
* @Author: Alexander Gavazov
* @Site: www.studio.bg
*/


var Calculator = function(componentsPrices, articlesQuantity, calculateRows) {
	this.componentsPrices = componentsPrices;
	this.articlesQuantity = articlesQuantity;
	this.calculateRows = calculateRows;

	this.wrapper = $('CalculatorWrapper');
	this.monthExpense = $('month_expense');
	this.monthIncome = $('month_income');
	this.monthTotalIncome = $('month_total_income');

	this.otherExpenses = $$('#other_expenses input');

	this.costPrices = {};

	this.setBehaviour();
}

Calculator.prototype.setBehaviour = function() {
	this.wrapper.select('input[type="text"]').each(function(node) {
		node.first_value = node.value;

		node.observe('focus', function(node) {
			if (node.value <= 0) {
				node.value = '';
			}
		}.curry(node));

		node.observe('blur', function(node) {
			if (node.value <= 0) {
				node.value = node.first_value;
			}
		}.curry(node));

		node.observe('keyup', function(node) {
			node.value = node.value.replace(/,/gi, '.');
			node.value = node.value.replace(/ /gi, '');
			node.value = node.value.replace(/[^0-9.]/gi, '');

			if (!isNaN(parseFloat(node.value))) {
				this.reCalculate();
			}
		}.bind(this, node));
	}.bind(this));

	this.wrapper.select('select').each(function(node) {
		node.observe('change', this.reCalculate.bind(this));
	}.bind(this));
}

Calculator.prototype.reCalculate = function() {
	var expenses = 0;
	var income = 0;

	for (i in this.calculateRows) {
		var id = this.calculateRows[i];

		var oneRecipes = parseFloat($('one_recipes_' + id).value.replace(/[^0-9.]/gi, ''));
		var dayRecipes = parseFloat($('day_recipes_' + id).value.replace(/[^0-9.]/gi, ''));
		var NArticles = $$('#articles_' + id + ' select');
		var NTotalPrice = $$('#total_price_' + id)[0];

		var oneProductPrice = 0;
		NArticles.each(function(node) {
			if (node.value > 0) {
				oneProductPrice = oneProductPrice + (this.componentsPrices[node.value] * (this.articlesQuantity[node.name] / 1000))
			}
		}.bind(this));

		var sebestoinost = oneProductPrice * dayRecipes;

		NTotalPrice.update(this.round(sebestoinost * 30));

		expenses = expenses + sebestoinost;

		if (oneRecipes && dayRecipes) {
			income = income + (oneRecipes * dayRecipes);
		}
	}

	expenses = expenses * 30;
	income = income * 30;

	this.otherExpenses.each(function(node) {
		expenses = expenses + parseFloat(node.value);
	});

	expenses = this.round(expenses);
	income = this.round(income);

	this.monthExpense.update(expenses);
	this.monthIncome.update(income);
	this.monthTotalIncome.update(income - expenses);
}

Calculator.prototype.round = function(val, precision) {
	myVal = val + ' ';
	myVal = myVal.split('.');

	if (!precision) {
		var precision = 2;
	}

	if (!myVal[1]) {
		return val;
	} else {
		return parseFloat(myVal[0] + '.' + myVal[1].substr(0, precision));
	}
}