/**
 * Pricecalc
 */

var pricecalcIds = 0;

function pricecalcGetPrice(element) {
	return jQuery(element).parents(".produkt").find(".pricecalcValue").text();
}

function pricecalcGetTitle(element) {
	return jQuery(element).parents(".produkt").find(".pricecalcTitle").text();
}

function pricecalcGetMva(element) {
	return '25';
}

function stringToNum(num) {
	return num.replace(/,/, '.');
}

function numToString(num) {
	num = '' + num;
	return num.replace(/\./, ',');
}

function custRound(x,places) {
	// Created 1997 by Brian Risk.  http://brianrisk.com
	return (Math.round(x*Math.pow(10,places)))/Math.pow(10,places)
}

jQuery(function() {
	jQuery('.pricecalcOpen').bind("click", function(e) {
		title	= pricecalcGetTitle(this);
		price	= pricecalcGetPrice(this);
		//mva 	= pricecalcGetMva(this);

		/*
		position = new Array();
		position.push(e.pageX);
		position.push(e.pageY);
		*/
		
		pricecalcIds = jQuery('#pricecalcId').val();
		pricecalcIds = parseInt(pricecalcIds) + 1;
		jQuery('#pricecalcId').val(pricecalcIds);
		id = 'pricecalc' + pricecalcIds;
		
		priceCalcDialog = jQuery('pricecalcBlock').html();
		if ((priceCalcDialog == undefined) || 
			(priceCalcDialog.length < 1)) {
			priceCalcDialog = '<form onsubmit="return false;">'
							+ '	<div class="formContainer"><div class="formTittel">Innkjøpspris</div><div class="formVerdi"><input type="text" name="inPrice" disabled="disabled"/></div></div>'
							+ '	<div class="formContainer"><div class="formTittel">Faktor innkjøpspris</div><div class="formVerdi"><input type="text" name="factor"/></div></div>'
							+ '	<div class="formContainer"><div class="formTittel">Prosent til innkjøpspris</div><div class="formVerdi"><input type="text" name="percent"/></div></div>'
							+ '	<div class="formContainer"><div class="formTittel">Fortjeneste</div><div class="formVerdi"><input type="text" name="profit"/></div></div>'
							+ '	<div class="formContainer"><div class="formTittel">Utsalgspris</div><div class="formVerdi"><input type="text" name="outPrice"/></div></div>'
							+ '</form>';
		}

		jPriceCalcDialog = jQuery('<div title="Priskalkulator" />').attr("id", "pricecalcBlock");
		jPriceCalcDialog.append(priceCalcDialog);

		jPriceCalcDialog.find('.pricecalcTitle').text(title);

		jPriceCalcDialog.find('input[name=inPrice]').val(numToString(price));
		jPriceCalcDialog.find('input[name=factor]').val(numToString(1.3));

		jPriceCalcDialog.find('input[type=text]').bind('keypress', function(e) {
			if (e.which == 13) {
				pricecalcProcess(this);
			} else {
				//console.log('press ' + e.which);
			}
		});
		
		pricecalcProcess(jPriceCalcDialog.find('input[name=factor]'));
		
		//{ 'position': position, 'title': title, 'dialogClass': 'pricecalc'});
		options = { 'title': title, 'dialogClass': 'pricecalc'};
		jPriceCalcDialog.dialog(options);
	});
});

function pricecalcProcess(element) {
	form = new PriceCalcElement(element);
	priceCalc = new PriceCalc(form.getInPrice(), form.getPercentage(), form.getFactor(), form.getMva(), form.getProfit(), form.getOutPrice());
	priceCalc.calculateByName(form.name);
	form.setPercentage(priceCalc.percent);
	form.setFactor(priceCalc.factor);
	form.setOutPrice(priceCalc.outPrice);
	form.setProfit(priceCalc.profit);
}

function PriceCalcElement(element)
{
	this.form;
	this.name;
	
	this.setFormElement = function(element)
	{
		element = jQuery(element);
		this.form = element.parents('form');
		this.name = element.attr('name');
		//return this;
	};
	
	this.setFormElement(element);
	
	this.setInPrice = function(value)
	{
		this.form.find('input[name=inPrice]').val(numToString(value));
		return this;
	};
	
	this.getInPrice = function()
	{
		value = this.form.find('input[name=inPrice]').val();
		//console.log('getPercentage ' + value + ' stringToNum ' + stringToNum(value));
		return stringToNum(value);
	};
	
	this.setPercentage = function(value)
	{
		//console.log('setPercentage ' + value + ' numToString ' + numToString(value));
		value = custRound(value, 2);
		this.form.find('input[name=percent]').val(numToString(value));
		return this;
	};
	
	this.getPercentage = function()
	{
		value = this.form.find('input[name=percent]').val();
		if (value == undefined) {
			value = '';
		}
		//console.log('getPercentage ' + value + ' stringToNum ' + stringToNum(value));
		return stringToNum(value);
	};
	
	this.setFactor = function(value)
	{
		//console.log('setFactor ' + value + ' numToString ' + numToString(value));
		value = custRound(value, 3);
		this.form.find('input[name=factor]').val(numToString(value));
		return this;
	};
	
	this.getFactor = function()
	{
		value = this.form.find('input[name=factor]').val();
		if (value == undefined) {
			value = '';
		}
		//console.log('getPercentage ' + value + ' stringToNum ' + stringToNum(value));
		return stringToNum(value);
	};
	
	this.setProfit = function(value)
	{
		//console.log('setProfit ' + value + ' numToString ' + numToString(value));
		value = custRound(value, 2);
		this.form.find('input[name=profit]').val(numToString(value));
		return this;
	};
	
	this.getProfit = function()
	{
		value = this.form.find('input[name=profit]').val();
		if (value == undefined) {
			value = '';
		}
		//console.log('getProfit ' + value + ' stringToNum ' + stringToNum(value));
		return stringToNum(value);
	};
	
	this.setOutPrice = function(value)
	{
		//console.log('setOutPrice ' + value + ' numToString ' + numToString(value));
		value = custRound(value, 2);
		this.form.find('input[name=outPrice]').val(numToString(value));
		return this;
	};
	
	this.getOutPrice = function()
	{
		value = this.form.find('input[name=outPrice]').val();
		if (value == undefined) {
			value = '';
		}
		//console.log('getOutPrice ' + value + ' stringToNum ' + stringToNum(value));
		return stringToNum(value);
	};
	
	this.setMva = function(value)
	{
		//this.form.find('input[name=outPrice]').val(numToString(value));
		return this;
	};
	
	this.getMva = function()
	{
		value = '25';
		/*
		mva = this.form.find('input[name=mva]');
		if ((mva.length > 0) && (mva.val() != '')) {
			value = mva.val();
		}
		*/
		//console.log('getMva ' + value + ' stringToNum ' + stringToNum(value));
		return stringToNum(value);
		//return this.form.find('input[name=outPrice]').val();
	};
}

function PriceCalc(pInPrice, pPercent, pFactor, pMva, pProfit, pOutPrice)
{
	this.inPrice;
	this.percent;
	this.factor;
	this.mva;
	this.profit;
	this.outPrice;
	
	this.setValues = function(pInPrice, pPercent, pFactor, pMva, pProfit, pOutPrice)
	{
		this.inPrice = parseFloat(pInPrice);
		this.percent = parseFloat(pPercent);
		this.factor = parseFloat(pFactor);
		this.mva = parseFloat(pMva);
		this.profit = parseFloat(pProfit);
		this.outPrice = parseFloat(pOutPrice);
	};
	
	this.setValues(pInPrice, pPercent, pFactor, pMva, pProfit, pOutPrice);
	
	this.calculateByName = function(name)
	{
		switch(name) {
			case 'factor':
				return this.calculateFromFactor();
			case 'percent':
				return this.calculateFromPercentage();
			case 'outPrice':
				return this.calculateFromOutPrice();
			case 'profit':
				return this.calculateFromProfit();
			default:
				return false;
		}
	};
	
	this.calculateFromFactor = function()
	{
		this.profit = (this.inPrice * this.factor) - this.inPrice;
		this.percent = (this.factor - 1) * 100;
		this.outPrice = (this.inPrice + this.profit) * percentToFactorPositive(this.mva);
		return this;
	};
	
	this.calculateFromPercentage = function()
	{
		this.factor = percentToFactorPositive(this.percent);
		this.profit = (this.inPrice * this.factor) - this.inPrice;
		this.outPrice = (this.inPrice + this.profit) * percentToFactorPositive(this.mva);
		
		return this;
	};
	
	this.calculateFromOutPrice = function()
	{
		this.profit = this.outPrice * percentToFactorNegative(this.mva) - this.inPrice;
		this.factor = (this.profit + this.inPrice) / this.inPrice;
		this.percent = positiveFactorToPercent(this.factor);
		return this;
	};
	
	this.calculateFromProfit = function()
	{
		this.factor = (this.profit + this.inPrice) / this.inPrice;
		this.percent = positiveFactorToPercent(this.factor);
		this.outPrice = (this.inPrice + this.profit) * percentToFactorPositive(this.mva);
		return this;
	};
}

function percentToFactorNegative(percent)
{
	return (100 / (1 + (percent / 100))) / 100;
}

function positiveFactorToPercent(factor)
{
	return (factor - 1) * 100;
}

function percentToFactorPositive(percent)
{
	return 1 + (percent / 100);
}


/**
 * Uhu
 */

function nrFormat(n,sep) {
	var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
	sValue=n+'';

	if (sep === undefined) {sep=' ';}
	while(sRegExp.test(sValue)) {
	sValue = sValue.replace(sRegExp, '$1'+sep+'$2');
	}
	sValue=sValue.replace(".", ",");
	return sValue;
};

