function trim(value) {
	
		while(value.length > 0 && value.charAt(0) == ' ') {
			value = value.substring(1);
		}

		while(value.length > 0 && value.charAt(value.length - 1) == ' ') {
			value = value.substring(0, value.length - 1);
		}
	
		return value;
	}

	function isIntegerFieldValid(fieldValue, fieldName, incorrectZero) {

		fieldValue = trim(fieldValue);

		if(fieldValue == "") {
			alert("Missing field: Make sure you fill the " + fieldName);
			return false;
		}
		var intValue = parseInt(fieldValue);
		if((intValue != fieldValue) || (intValue < 0)) {
			alert("Incorrect field: Make sure the " + fieldName + " is correct");
			return false;
		}
		if(incorrectZero && (intValue == 0)) {
			alert("Incorrect field: " + fieldName + " should not be equal to 0");
			return false;
		}
		return true;
	}
	
	function calculate() {
		var calc_form = document.forms["calculator"];

		if(!isIntegerFieldValid(calc_form.duration_hours.value, "Clip Duration", false)) {
			return;
		}
		if(!isIntegerFieldValid(calc_form.duration_minutes.value, "Clip Duration", false)) {
			return;
		}
		if(!isIntegerFieldValid(calc_form.duration_seconds.value, "Clip Duration", false)) {
			return;
		}

		var duration = parseInt(calc_form.duration_hours.value) * 3600 + parseInt(calc_form.duration_minutes.value) * 60 + parseInt(calc_form.duration_seconds.value);
		if(duration == 0) {
			alert("Missing field: Make sure you fill the Clip Duration");
			return;
		}
		var bit_rates = Array("28", "56", "64", "128", "lan", "dsl_low", "dsl_medium", "dsl_high");
		var bit_rate_field_names = Array("28.8K Modem", "56K Modem", "Single ISDN 64K", "Dual ISDN 128K", "LAN/T1", "DSL/Cable Low", "DSL/Cable Medium", "DSL/Cable High");
		var viewers_per_day = parseInt(calc_form["viewers_per_day"].value);
		if(!isIntegerFieldValid(viewers_per_day, "No. of Viewers/day", true)) {
			return;
		}

		for(i = 0; i < bit_rates.length; i++) {
			if(!isIntegerFieldValid(calc_form["bitrate_" + bit_rates[i]].value, "Bit Rate for " + bit_rate_field_names[i], true)) {
				return;
			}
			var bit_rate = parseInt(calc_form["bitrate_" + bit_rates[i]].value);
			calc_form["storage_" + bit_rates[i]].value = Math.round(10 * bit_rate * duration / (8 * 1024)) / 10;
			calc_form["transfer_" + bit_rates[i]].value = Math.round(1000 * 30.5 * viewers_per_day * bit_rate * duration / (8 * 1024 * 1024)) / 1000;
		}
	}
