  var limit = 2500;
  var current = 0;
  var unit = "&nbsp;kcal";
  var isEven = false;
  var today;
  var entries = new Array();
  var limitCookie = null;
  var entriesCookie = null;
  var metricCookie = null;
  
  function setup() {
    limitCookie = new Cookie("limit");
    entriesCookie = new Cookie("entries");
    today = new Date();
    today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    var value = limitCookie.get();
    if (value) {
      try {
        limit = parseFloat(value);
      }
      catch (e) {
        alert(e);
      }
    }
    document.getElementById("LimitInput").value = limit;
    limitChanged();
    reloadEntries();
    metricCookie = new Cookie("metric");
    if (metricCookie.get() == "true") {
      $("MetricCheck").checked = true;
    }  
    metricChanged();
    setTimeout(function() {window.scrollTo(0, 1)}, 1);
  }
  
  function limitChanged() {
    limit = parseInt($("LimitInput").value);
    if (isNaN(limit)) {
      limit = 2500;
    }
    $("SummaryLimit").innerHTML = limit + unit;
    $("GraphLimit").innerHTML = limit + unit;
    $("LimitSection").style.display = "none";
    $("AddSection").style.display = "block";
    updateCurrent();

    limitCookie.store(limit);
    window.scrollTo(0, 0);
  }
  
  function changeLimit() {
    $("LimitSection").style.display = "block";
    $("AddSection").style.display = "none";    
  }
  
  function addValue() {
    var value = parseInt($("AddInput").value);
    if (isNaN(value)) {
      return;
    }
    $("AddInput").value = "";
    current += value;
    updateCurrent();
    addEntry(value);
    entries.push(value);
    saveEntries();
    window.scrollTo(0, 0);
  }  

  function addEntry(value) {
    var tr = document.createElement("tr");
    var td = document.createElement("td");
    td.innerHTML = value + unit;
    tr.appendChild(td);
    tr.appendChild(td);
    if (isEven) {
      tr.className = "even";
    }  
    isEven = !isEven;
    $("TodayBody").appendChild(tr);
    $("TodayHead").style.display = "none";
  }  
    
  function updateCurrent() {  
    $("SummaryValue").innerHTML = current + unit;    
    $("SummaryPercent").innerHTML = parseInt(100 * current / limit);
    if (current > limit) {
      $("SummaryValue").style.color = "orange";
      $("SummaryPercent").style.color = "orange";
    } else {
      $("SummaryValue").style.color = "white";
      $("SummaryPercent").style.color = "white";      
    }
    $("GraphValue").innerHTML = current + unit;
    $("TodayTotal").innerHTML = current + unit;
    $("TodayDiff").innerHTML = limit - current + unit;
    if (limit < current) {
      $("TodayDiff").style.color = "#C00000";      
    }
    else {
      $("TodayDiff").style.color = "black";            
    }
    updateGraph();
  }
  
  function updateGraph() {
    var width = 290;
    if (current < limit * 1.5) {
      var left = 200;
      $("LeftBar1").width = left;
      $("LeftBar2").width = left;
      $("RightBar1").width = width - left - 1;
      $("RightBar2").width = width - left - 1;
      var bar = Math.min(width - 1, 2 + (left - 2) * current / limit);
      $("ForeBar").width = bar;
      $("GraphBackground2").style.width = bar + "px";
      $("GraphLimit").style.left = left - 50 + "px";
      $("GraphValue").style.left = Math.min(Math.max(0, bar - 50), width - 100) + "px";
    }
    else {
      var size = width * limit * 1.5 / current;
      var left = size / 1.5;
      $("LeftBar1").width = left;
      $("LeftBar2").width = left;
      $("RightBar1").width = size - left;
      $("RightBar2").width = size - left;
      var bar = width;
      $("ForeBar").width = bar;
      $("GraphBackground2").style.width = bar + "px";
      $("GraphLimit").style.left = Math.max(0, left - 50) + "px";
      $("GraphValue").style.left = width - 100 + "px";
    }
  }
  
  function clearEntries() {
    current = 0;
    entries = new Array();
    saveEntries();
    $("TodayBody").innerHTML = "";
    $("TodayHead").style.display = "block";
    updateCurrent();
  }
  
  function saveEntries() {
    var value = "[";
    value += new Date().getTime();
    for (var i = 0; i < entries.length; i++) {
      var item = entries[i];
      value += ",";
      value += item;   
    }
    value += "]";
    entriesCookie.store(value);
  }
  
  function reloadEntries() {
    var value = entriesCookie.get();
    if (value) {
      try {
        var storage = eval(value);
        var date = new Date(storage[0]);
        entries = storage.slice(1);
        current = 0;
        for (var i = 0; i < entries.length; i++) {
          var item = entries[i];
          addEntry(item);
          current += item;
        }
        updateCurrent();
      }
      catch (e) {
        alert(e);
        entries = new Array();
      }
    }
  }
  
  function emailEntries() {
    var text = "Entries from " + new Date().toLocaleDateString();
    for (var i = 0; i < entries.length; i++) {
    	text += "<br>" + entries[i];
    }
    window.open("mailto:?subject=Your calories of today&body=" + text, "_self");    
  }
  
  function calcBmr() {
    var isMetric = $("MetricCheck").checked;
    var weight = parseFloat($("WeightInput").value) / 2.2;
    if (isMetric) {
      weight = parseFloat($("WeightInput").value);
    }  
    if (isNaN(weight)) {
      alert("No Weight");
      return;
    }
    if ($("InchesInput").value.length == 0) {
      $("InchesInput").value = 0;
    }
    var height = (parseFloat($("FeetInput").value) * 12 + parseFloat($("InchesInput").value)) * 2.54;
    if (isMetric) {
      height = parseFloat($("FeetInput").value) * 100 + parseFloat($("InchesInput").value);
    }  
    if (isNaN(height)) {
      alert("No Height");
      return;
    }
    var age = parseFloat($("AgeInput").value);
    if (isNaN(age)) {
      alert("No Age");
      return;
    }
    var act = parseFloat($("ActivitySelect").value);
    var bmr = 0;
    if ($("SexSelect").value == "0") {
      bmr = parseInt((66.5 + 13.75 * weight + 5 * height + 6.75 * age) * act);  
    }
    else {
      bmr = parseInt((655 + 9.6 * weight + 1.85 * height + 4.7 * age) * act);        
    }
    $("LimitInput").value = bmr;
    calcBmi();
  }
  
  function calcBmi() {
    $("BMI").style.display = "none";
    var isMetric = $("MetricCheck").checked;
    var weight = parseFloat($("WeightInput").value) / 2.2;
    if (isNaN(weight)) {
      return;
    }
    if (isMetric) {
      weight = parseFloat($("WeightInput").value);
    }  
    var height = (parseFloat($("FeetInput").value) * 12 + parseFloat($("InchesInput").value)) * 2.54;
    if (isMetric) {
      height = parseFloat($("FeetInput").value) * 100 + parseFloat($("InchesInput").value);
    }
    if (isNaN(height)) {
      return;
    }
    if (height == 0) {
      alert("Height can't be 0");
      return;
    }
    bmi = 10000 * weight / (height * height);    
    $("BMI").style.display = "block";
    
    $("BmiValue").innerHTML = bmi.toFixed(1);
    if (bmi < 16.5) {
      $("BmiText").innerHTML = "You should a lot eat more than the limit each day!";
      $("BmiText").className = "severe";
    }
    else if (bmi < 19) {
      $("BmiText").innerHTML = "You should eat more than the limit each day!";
      $("BmiText").className = "warn";
    }
    else if (bmi > 30) {
      $("BmiText").innerHTML = "You should eat a lot less than the limit each day!";      
      $("BmiText").className = "severe";
    }
    else if (bmi > 25) {
      $("BmiText").innerHTML = "You should eat less than the limit each day!";      
      $("BmiText").className = "warn";
    }
    else {
      $("BmiText").innerHTML = "You should stay within the limit each day.";      
      $("BmiText").className = "";
    }
  }
    
  function metricChanged() {
    var isMetric = $("MetricCheck").checked;
    metricCookie.store(isMetric + "");    
    if (isMetric) {
      $("WeightUnit").innerHTML = "kg";
      $("FeetUnit").innerHTML = "m";
      $("InchesUnit").innerHTML = "cm";
      var weight = parseFloat($("WeightInput").value) / 2.2;
      if (isNaN(weight)) {
        $("WeightInput").value = "";
      }
      else {
        $("WeightInput").value = weight.toFixed(1);
      }  
      var height = (parseFloat($("FeetInput").value) * 12 + parseFloat($("InchesInput").value)) * 2.54;
      if (isNaN(height)) {
        $("FeetInput").value = "";
        $("InchesInput").value = "";
      }
      else {
        $("FeetInput").value = Math.floor(height / 100);
        $("InchesInput").value = parseInt(height) % 100;
      }  
    }
    else {
      $("WeightUnit").innerHTML = "lb";
      $("FeetUnit").innerHTML = "feet";
      $("InchesUnit").innerHTML = "inches";
      var weight = parseFloat($("WeightInput").value) * 2.2;
      if (isNaN(weight)) {
        $("WeightInput").value = "";
      }
      else {
        $("WeightInput").value = weight.toFixed(1);
      }  
      var height = (parseFloat($("FeetInput").value) * 100 + parseFloat($("InchesInput").value));
      if (isNaN(height)) {
        $("FeetInput").value = "";
        $("InchesInput").value = "";
      }
      else {
        var feet = Math.floor(height / 2.54 / 12);
        $("FeetInput").value = feet;
        $("InchesInput").value = (height / 2.54 - feet * 12).toFixed(1);
      }  
    }      
  }
  
  function toggleMetric() {
    $("MetricCheck").checked = !$("MetricCheck").checked;
    metricChanged();
  }
    
  function tellFriend() {
    var body = "Hi,<br><br>I just stumbled upon this Calories iPhone application:" +
        "<br><br>http://calories.speedymarks.com<br><br>" +
        "which helps to track your daily calories." +
        "<br><br>Best regards";
    window.open("mailto:?subject=Calories on the iPhone&body=" + body, "_self");  
  }  

  function debug(msg) {
    var e = document.getElementById("Debug");
    e.innerHTML += msg + "<br>";
  }
  
  function $(id) {
    return document.getElementById(id);
  }
