// JavaScript Document


function CALC_exe () {
	
	if (!CALC_checkElements()) {
		alert('Calculator Error: Fields missing or Field Id\'s incorrect');
		return;
	}
	
	var volume	 = document.getElementById('volume').value;
	var diameter = document.getElementById('diameter').value;
	var legs	 = document.getElementById('legs').value;
	
	if (!CALC_checkParse(volume, diameter, legs)) {
		CALC_render('Err', 'Err');
		return;
	}
	
	var calcarea	 = CALC_calcarea(diameter);		
	var calclength	 = CALC_calclength(volume, calcarea);
	
	var width		 = CALC_width(diameter, legs);
	var length		 = CALC_length(diameter, calclength, legs, width);
	
	var manifold	 = CALC_manifold(diameter);
	var straight	 = CALC_straight(length, manifold);
	
	CALC_render(CALC_rounddp(width), CALC_rounddp(length));
	
}


function CALC_render (width, length) {
	
	document.getElementById('width').value = width;
	document.getElementById('length').value = length;
	
}


function CALC_checkElements () {
	
	if (!CALC_exists('volume')) { return false; }
	if (!CALC_exists('diameter')) { return false; }
	if (!CALC_exists('legs')) { return false; }
	if (!CALC_exists('width')) { return false; }
	if (!CALC_exists('length')) { return false; }
	
	return true;
	
}

function CALC_exists (id) {
	
	return eval(document.getElementById(id));
	
}

function CALC_checkParse (volume, diameter, legs) {
	
	if (volume == 0 || isNaN(volume)) {
		return false;
	}
	
	if (diameter == 0 || isNaN(diameter)) {
		return false;
	}
	
	if (legs == 0 || isNaN(legs)) {
		return false;
	}
	
	return true;
	
}

function CALC_rounddp (float) {
	
	return Math.round(float*1000)/1000;
	
}

function CALC_calcarea(diameter) {
	
	return diameter*diameter*Math.PI/4;
	
}

function CALC_calclength (volume, calcarea) {
	
	return volume / calcarea;
		
}

function CALC_width (diameter, legs) {
	
	if (legs == 1) {
		return diameter;
	} else {
		return ((diameter*legs)+(0.6*(legs-1)))
	}
	
}

function CALC_length (diameter, calclength, legs, width) {
	
	return (calclength-(width*2))/legs+(diameter*2);
	
}

function CALC_manifold (diameter) {
	
	return diameter + 0.5;
	
}

function CALC_straight (length, manifold) {
	
	return length-(manifold*2);
	
}



