var AUTH_COOKIE_KEY = "melkauth"; // XXX duplicated in melkjug/lib/constants.py
var STAT_COOKIE_KEY = "melkstat"; // XXX duplicated in melkjug/lib/constants.py

function _get_cookie(key) {
  key += '=';
  var keylen = key.length;
  var cookies = document.cookie.split('; ');
  for (var i=0; i<cookies.length; ++i) {
    var cookie = cookies[i];
    if (cookie.substring(0, keylen) == key) {
      return unescape(cookie.replace(key, ''));
    }
  }
  return null;
}

// http://www.quirksmode.org/js/cookies.html
function _set_cookie(key, value, days) {
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + days*24*60*60*1000);
    expires = "; expires=" + date.toGMTString();
  }
  document.cookie = key + "=" + value + expires + "; path=/";
}

function _del_cookie(key) {
  _set_cookie(key, '', -1);
}


var authcookie = _get_cookie(AUTH_COOKIE_KEY);
var melk_username = authcookie ? authcookie.split(',')[1] : null;
var melk_useremail = authcookie ? authcookie.split(',')[2] : null;

function _body() {
  if (melk_username) {
    jQuery('body').addClass('logged-in');
  }
}

function _topnav() {
  var topnav_ul = jQuery('#top-nav');
  if (melk_username) {
    topnav_ul.empty();
    topnav_ul.append(
      '<li id="user-home"><a href="/' + melk_username + '">' + melk_username + '</a></li>' +
      '<li id="logout"><a href="/logout">logout</a></li>'
      );
  }
}

function _tagline() {
  if (melk_username) {
    jQuery('#tagline-bar').remove();
  }
}

function _stat() {
  var statusmsg = _get_cookie(STAT_COOKIE_KEY);
  if (statusmsg) {
    Melk.display_status_message(statusmsg);
    _del_cookie(STAT_COOKIE_KEY);
  }
}

jQuery(document).ready(function() {
  _body();
  _topnav();
  _tagline();
  _stat();
});
