var currentShape = 'box';

function calculateBox(h, w, d) {
	return (h * w * d);
}

function calculateCylinder(r, h) {
	return ((Math.PI * (r*r)) * h);
}

function calculateCone(r, h) {
	return ((1/3) *  (Math.PI) * (r * r) * h);
}

function convertToYards(value, uom) {
	switch(uom) {
                case 'yards' : 
		case 'Yards' : return value;
			       break;
		case 'feet' :
		case 'Feet' : return value / 3;
			      break;
		case 'meters' :
		case 'Meters' : return value / 0.9144;
				break;
		case 'inches' :
		case 'Inches' : return value / 36;
				break;
		default: return 0;
	}
}

function calculate() {

	var shape = currentShape;
 
	var w = getUnits(shape, 'width');
       var h = getUnits(shape, 'height');
	var d = getUnits(shape, 'depth');
	
	var r = getUnits(shape, 'radius');
	var h = getUnits(shape, 'height');

	var result = 0;

	switch(shape) {
		case 'box': result = calculateBox(h, w, d);
			    break;
		case 'cone': result = calculateCone(r, h);
			     break;
		case 'cylinder': result = calculateCylinder(r, h);
				 break;
		default: result = 0;
	}

       result *= getProductFactor();
	result += "";

	if (isNaN(result)) {
		result = 0;
	} else if(result.indexOf('.') > -1) {
		result = result.substring(0, (result.indexOf('.') + 2));
	} else {
		result += ".00";
	}

	document.getElementById('calculated_amount').value = result; 
}

function getUnits(shape, unitType) {
	var uom = "";
	var value = 0;

	if(document.getElementById(shape + '_' + unitType + '_units')) {
		uom = document.getElementById(shape + '_' + unitType + '_units').value;
	} else {
		return 0;
	}

	if(document.getElementById(shape + '_' + unitType)) {
		value = convertToYards((document.getElementById(shape + '_' + unitType).value), uom);
		return value;
	} else {
		return 0;
	}
}

function getProductFactor() {
	if(document.getElementById('material_type')) {
		switch(document.getElementById('material_type').value) {
			case 'stone' :
			case 'Stone' : return 1.5;

			case 'sand'  :  
			case 'Sand'  : return 1.3;

			default: return 0;
		}
	}
}


function switchCalculator(shape) {
	var shapeList = new Array('box', 'cone', 'cylinder');
	for(var i = 0; i < shapeList.length; i++) {
		document.getElementById('calculator_' + shapeList[i]).style.display = 'none';		
	}

	if(document.getElementById('calculator_' + shape)) {
		document.getElementById('calculator_' + shape).style.display = 'block';		
		currentShape = shape;
	}
	
	document.getElementById('calculated_amount').value = ""; 
}


function clearCalculator() {
	var shape = currentShape;
	clearUnits(shape, 'width');
       clearUnits(shape, 'height');
	clearUnits(shape, 'depth');

	clearUnits(shape, 'radius');


       document.getElementById('calculated_amount').value = '';
}

function clearUnits(shape, unitType) {
	var shape = currentShape;

	if(document.getElementById(shape + '_' + unitType)) {
		document.getElementById(shape + '_' + unitType).value = "";
	}

}
