function cal_bac(wgt, num, hrs, dt, gen) {
   kgs = wgt; 
   tbw = kgs * gen * 1000; 
   walc = 23.36; 
   ac = walc / tbw; 
   acb = ac * .806; 
   ibac = acb * 100; 
   
   tac = ibac * dt * num;  

   bac = tac - (hrs * 0.012); 

	if (bac < 0) {
		bac = 0;
	}

   diff = bac * 10000;
   f_bac = Math.round(diff);
   bac = f_bac / 10000;

   return bac;
}

function calculate() {
   var f = document.bac_input;
   var gen = f.gen.options[f.gen.selectedIndex].value;
   //var dt = f.dt.options[f.dt.selectedIndex].value;
   //var num = f.num.value;
   var numBeers = f.txtBeer.value;
   numBeers = (chkw(numBeers)) ? numBeers : 0 ;
   var numWine = f.txtWine.value;
   numWine = (chkw(numWine)) ? numWine : 0 ;
   var numSpirits = f.txtSpirits.value;
   numSpirits = (chkw(numSpirits)) ? numSpirits : 0 ;
   var wt = f.wt.value;
   var hrs = f.hrs.value;

	if (chkw(wt) && wt){
		
			if (chkw(hrs) && hrs){
				f.bac.value = Math.round((cal_bac(wt, numBeers, hrs, 0.54, gen)
							 +cal_bac(wt, numWine, hrs, 0.7, gen)
							 +cal_bac(wt, numSpirits, hrs, 0.6, gen)
							 )*10000)/10000;
				
				if (f.bac.value > 0.05){
					document.getElementById("message").innerHTML = "You are over the legal blood-alcohol limit. Don't drink and drive.";
				} else {
					document.getElementById("message").innerHTML = "";
				}
			} else {
			f.hrs.focus();
			alert("Please enter the number of hours consuming the drinks.");
			}
		
	} else {
	f.wt.focus();
	alert("Please enter a number for your weight.");
	}


   // Set cookies for future views of this page
   // Expires when user closes browser
   document.cookie = "bac=" + f.bac.value;
   document.cookie = "wt=" + f.wt.value;
   document.cookie = "hrs=" + f.hrs.value;
   document.cookie = "gen=" + f.gen.selectedIndex;
}

function chkw(w) {
   if (isNaN(w)) {
      return false;
   } else if (w < 0) {
      return false;
   }
   else {
      return true;
   }
}

function load_cookies() {
	var f = document.bac_input;
	f.wt.value = loadcookie("wt");
	f.bac.value = loadcookie("bac");
	f.hrs.value = loadcookie("hrs");
	f.gen.selectedIndex = loadcookie("gen");
}

function loadcookie(name) {
    var allcookies = document.cookie;
	var value;
	var pos = allcookies.indexOf(name + "=");
	
	var len = name.length + 1; 
	if (pos != -1) {
		var start = pos + len;
		var end = allcookies.indexOf(";", start);
		if (end == -1) end = allcookies.length;
		value = allcookies.substring(start,end);
		
		value = unescape(value);
    	return value;
	}

    return 0;
}
