/*
	This file contains function used in calculation; for now is used to compile dinamyc edit.

*/
/**
This a simple switch to choose what function to call.
*/
function selectCallFunction(calcFunc){
	var getValue = null;
	var calcFuncName;
	var calcFuncParam;
	//get index of open and close parenthesis
	var openParPos, closeParPos;
	
	openParPos = calcFunc.indexOf('(');
	closeParPos = calcFunc.indexOf(')');
	
	if (openParPos != -1 && closeParPos != -1){
		calcFuncName = calcFunc.slice(0, openParPos);
		calcFuncParam = calcFunc.slice(openParPos + 1, closeParPos);
	}
	switch(calcFuncName)
	{
		case "peritiGiudizPerc":
		 	getValue = judicialExpertsPerc(calcFuncParam);
			break;
		default:
			getValue = getValueFromFormula(calcFunc);
			break;
	}			
	
	return getValue;
}

/**
	Perform judicial expert calculation
*/
function judicialExpertsPerc(calcFuncParam){
	var splitParam = calcFuncParam.split(",");
	var getValue = 0;
	//
	if (splitParam.length == 6){
		var fromValue, toValue, percMin, percMax, workValue, srcControl;
		workValue = controlValueToFloat(splitParam[0]);
		fromValue = controlValueToFloat(splitParam[1]);
		toValue = controlValueToFloat(splitParam[2]);
		percMin = controlValueToFloat(splitParam[3]);
		percMax = controlValueToFloat(splitParam[4]);
		srcControl = $(splitParam[5]);
		//
		if (workValue >= toValue){
			getValue = percMax;	
			//enable control
			srcControl.disabled = false;
		}
		else{
			if (workValue >= fromValue){
				var perc;
				perc = workValue * 100 / toValue;
				getValue = percMax * perc / 100;
				if (getValue < percMin)
					getValue = percMin;
				if (getValue > percMax)
					getValue = percMax;	
				//enable control
				srcControl.disabled = false;			
			}
			else{
				//if not in range, disable control
				srcControl.disabled = true;
				getValue = 0;
			}
		}
	}	
	//
	return formatNum(getValue, 4);
}

/*
 Utility function to convert control value to float.
*/
function controlValueToFloat(controlID){
	strControlValue = $(controlID).value;
	strControlValue = strControlValue.replace('.', '');
	strControlValue = strControlValue.replace('.', '');
	strControlValue = strControlValue.replace('.', '');
	strControlValue = strControlValue.replace(',', '.');
	return 	parseFloat(strControlValue);		
}

/*
This function manage number formatting.
*/
function formatNum(expr,decplaces) {
	var str = (Math.round(parseFloat(expr) * Math.pow(10,decplaces))).toString();
	while (str.length <= decplaces) {
		str = '0' + str;
	}
	var decpoint = str.length - decplaces;
	return str.substring(0,decpoint) + ',' + str.substring(decpoint,str.length);
}