  var landscape = true;
  var dailysCookie;
  var settingsCookie;
  var lastId = 0;
  
  function Daily(data) {
    this.id = null;
    this.title = "Daily Task";
    this.history = "0";
    this.lastDate = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
    
    this.updateToday = function() {
      var today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
      while (this.lastDate.getTime() < today.getTime()) {
        this.history = "0" + this.history;
        this.lastDate.setDate(this.lastDate.getDate() + 1);
      }
      if (this.history.length > 50) {
        this.history = this.history.substring(0, 50);
      }
      this.lastDay = today;
    };

    if (data) {
      this.title = data.title;
      this.history = data.history;
      this.lastDate = new Date(data.lastTime);
      this.updateToday();
    }  
    
    this.getDay = function(index) {
      return this.history.charAt(index) == "1";
    };
    
    this.getToday = function() {
      return this.getDay(0);
    };
    
    this.setDay = function(index, checked) {
      if (checked) {
        this.history = this.history.substring(0, index) + "1" + this.history.substring(index + 1);
      }
      else {
        this.history = this.history.substring(0, index) + "0" + this.history.substring(index + 1);
      }
    };
    
    this.setToday = function(checked) {
      this.setDay(0, checked);
    };
    
    this.getStats = function(days) {
      if (!days) {
        days = this.history.length;
      }
      days = Math.min(days, this.history.length);
      var sum = 0;
      for ( var i = 0; i < days; i++) {
        if (this.history[i] == "1") {
          sum++;
        }        
      }
      return {done:sum, average:sum * 100.0 / days};
    };  
  }
	    
  function setup() {
    landscape = window.innerWidth < window.innerHeight;    
    setTimeout(function() {window.scrollTo(0,1)}, 1);
    $("Loading").style.visibility = "hidden";
    $("List").innerHTML = "";
    dailysCookie = new Cookie("Dailys");
    if (dailysCookie.get()) {
      var data = eval(dailysCookie.get());
      for (var i = 0; i < data.length; i++) {
      	var id = data[i];
      	if (lastId < id) {
      	  lastId = id;
      	}  
        addDaily(data[i]);
      }
      if (data.length == 0) {
        loadDefaults();
      }
    }
    else {
      loadDefaults();
    }
    //addTestDaily();
    settingsCookie = new Cookie("DailySettings");
    if (settingsCookie.get()) {
      try {
        var settings = eval("new Object({" + settingsCookie.get() + "})");
      }
      catch (e) {
        alert(e);
      }  
    }
  }
  
  function loadDefaults() {
    createDaily("20 Push ups");
    createDaily("Stop Smoking");
    createDaily("Write Blog");
    createDaily("Smile");
  }
  
  function addTestDaily() {
    daily = new Daily();
    daily.title = "Test";
    for ( var i = 0; i < 40; i++) {
      var day = "0";
      if (Math.random() > 0.5) {
        day = "1";
      }  
      daily.history += day;
    }
    saveDaily(daily);
    addDaily(daily.id);    
  }
  
  function showDaily(daily) {
    $("Daily").daily = daily;
    $("DailyTitle").innerHTML = daily.title;
    updateStats(daily);
    $("Table").innerHTML = "";
    var check = document.createElement("div");
    $("Table").appendChild(check);
    if (daily.getToday()) {
      check.className = "dailyCheck dailyChecked";
    }
    else {
      check.className = "dailyCheck dailyUnchecked";
    }
    var label = document.createElement("label");
    check.appendChild(label);
    label.innerHTML = "Today";
    label.style.paddingLeft = "30px";
    
    var date = new Date();
    for ( var i = 1; i < daily.history.length; i++) {
      date.setDate(date.getDate() - 1);
      check = document.createElement("div");
      $("Table").appendChild(check);
      check.daily = daily;
      check.index = i;
      check.checked = daily.getDay(i);
      check.updateState = function(state) {
        this.daily.setDay(this.index, state);
        this.checked = state;
        this.checkbox.checked = state;
        if (state) {
          this.className = "dailyCheck dailyChecked";
        }
        else {
          this.className = "dailyCheck dailyUnchecked";
        }
        updateStats(daily);
      }  
      var checkBox = document.createElement("input");
      check.appendChild(checkBox);
      check.checkbox = checkBox;
      checkBox.type = "checkbox";
      checkBox.onclick = function() {
        this.parentNode.updateState(this.checked);
      }
      var label = document.createElement("label");
      check.appendChild(label);
      label.innerHTML = " " + date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
      label.onclick = function() {
        this.parentNode.updateState(!this.parentNode.checked);
      }
      check.updateState(daily.getDay(i));
    }
    openDaily();
  }
  
  function showTitleInput() {
    $("DailyTitle").style.display = "none";
    $("DailyTitleInput").style.display = "inline";
    $("DailyTitleInput").value = $("Daily").daily.title;
    $("DailyTitleInput").focus();
  }
  
  function titleChanged() {
    $("DailyTitleInput").style.display = "none";
    $("DailyTitle").style.display = "block";
    var title = $("DailyTitleInput").value;
    if (title.length > 0) {
      $("Daily").daily.title = title;
      saveDaily($("Daily").daily);
      $("DailyTitle").innerHTML = title;
      $("Daily").daily.li.titleNode.innerHTML = title;
    }  
  }
  
  function updateStats(daily) {
    var stats = daily.getStats();
    $("StatsDays").innerHTML = daily.history.length;
    $("StatsDone").innerHTML = stats.done;
    $("StatsNotDone").innerHTML = daily.history.length - stats.done;
    $("StatsTotal").innerHTML = Math.round(stats.average) + "%";
    $("Stats7").innerHTML = Math.round(daily.getStats(7).average) + "%";
    $("Stats30").innerHTML = Math.round(daily.getStats(30).average) + "%";        
  }
  
  function saveDaily(daily) {
    var id = daily.id;
    var isNew = !daily.id;
    if (isNew) {
      lastId++;
      id = lastId;
      daily.id = id;
    }  
    var cookie = new Cookie("Daily" + id);
    var text = "title:'" + encode(daily.title) + "'";
    text += ",history:'" + daily.history + "'";
    text += ",lastTime:" + daily.lastDate.getTime();
    cookie.store(text);
    return id;
  }
  
  function encode(text) {
    text = text.replace(/\n/g, "\\n");
    return text.replace(/\'/g, "\\'");
  }
  
  function clearDaily(daily) {
    if (!daily) {
      daily = $("Daily").daily;
    }
    daily.history = daily.history.substring(0, 1);
    showDaily(daily);
  }
  
  function addDaily(id) {    
    var list = $("List");
    var li = document.createElement("li");

    var cookie = new Cookie("Daily" + id);
    if (cookie.get()) {
      try {
        li.daily = eval("new Daily(new Object({" + cookie.get() + "}))");
        li.daily.id = id;
        li.daily.li = li;
        li.cookie = cookie;
        saveDaily(li.daily);
      }
      catch (e) {
        alert(e + " " + cookie.get());
        return;
      }  
    }  
    else {
      return;
    }
    
    list.appendChild(li);
    
    /*
    var remove = document.createElement("img");
    remove.li = li;
    remove.src = "close4.png";
    remove.className = "listClose";
    remove.onclick = function() {
      removeDaily(this.li.daily);
    };
    li.appendChild(remove);
    */
    
    var graph = document.createElement("img");
    graph.li = li;
    graph.src = "more.png";
    graph.className = "listGraph";
    graph.onclick = function() {
      var entry = this.parentNode;
      if (entry.parentNode) {
        showDaily(entry.daily);
      }  
    }
    li.appendChild(graph);

    var text = document.createElement("div");
    text.className = "listDailyTitle"
    text.innerHTML = li.daily.title;
    li.appendChild(text);
    li.className = "listEntry";
    if (li.daily.getToday()) {
      li.className += " dailyDone";
    }  
    li.titleNode = text;
    li.dailyId = id;
    text.onclick = function() {
      var entry = this.parentNode;
      if (entry.parentNode) {
        var daily = entry.daily;
        daily.setToday(!daily.getToday());
        if (daily.getToday()) {
          entry.className = "listEntry dailyDone";
        }
        else {
          entry.className = "listEntry";
        }
        saveDaily(daily);
      }  
    }
    saveDailys();
  }
  
  function removeDaily(daily) {
    if (!daily) {
      daily = $("Daily").daily;
    }  
    var li = daily.li;
    if (confirm("Do you really want to remove this task?")) {
      li.cookie.remove();
      li.parentNode.removeChild(li);
      saveDailys();
    }
    closeDaily();
  }
  
  function openDaily() {
    $("Content").style.display = "none";
    $("Daily").style.display = "block";
    window.scrollTo(0, 1);
  }  
  
  function closeDaily() {
    $("Content").style.display = "block";
    $("Daily").style.display = "none";    
    window.scrollTo(0, 0);
  }
  
  function newDaily() {
    createDaily($("NewInput").value);
  }
  
  function createDaily(title) {
    daily = new Daily();
    daily.title = title;
    saveDaily(daily);
    addDaily(daily.id);
  }
  
  function saveDailys() {
    var data = "[";
    var list = $("List");
    var lis = list.childNodes;
    for (var i = 0; i < lis.length; i++) {
    	if (i > 0) {
    	  data += ',';
    	} 
    	data += lis[i].dailyId;
    }
    data += "]";
    dailysCookie.store(data);
  }
  
  function saveSettings() {
    var text = "";
    settingsCookie.store(text);
  }

  function tellFriend() {
    var body = "Hi,<br><br>I just stumbled upon this Daily iPhone application:" +
        "<br><br>http://www.itunes.com/app/daily<br><br>" +
        "Remember, track and motivate yourself to do your daily tasks." +
        "<br><br>Best regards";
    window.open("mailto:?subject=Daily on the iPhone&body=" + body, "_self");  
  }

	function orientationChanged() {
    landscape = window.innerWidth < window.innerHeight;
    pause();
    window.scrollTo(0,1);
    updateControlsPosition();
  }
	
  function debug(msg) {
    var e = document.getElementById("Debug");
    e.innerHTML += msg + "<br>";
  }
  
  function $(id) {
    return document.getElementById(id);
  }