// generic point class (same as webnote)
function Point(x, y) {
  this.x = x ? x : 0;
  this.y = y ? y : 0;
}
Point.prototype.add = function(rhs) { return new Point(this.x + rhs.x, this.y + rhs.y); };
Point.prototype.sub = function(rhs) { return new Point(this.x - rhs.x, this.y - rhs.y); };
Point.prototype.div = function(n) { return new Point(this.x/n, this.y/n); };
Point.prototype.equals = function(rhs) { return this.x == rhs.x && this.y == rhs.y; };
Point.prototype.toString = function() { return '(' + this.x + ', ' + this.y + ')'; };

// from http://www.developingskills.com/ds.php?article=jstrim&page=1
String.prototype.trim = function() {
  return this.replace(/^\s+/,'').replace(/\s+$/,'');
}
String.prototype.startsWith = function(prefix) {
  return this.substring(0, prefix.length) == prefix;
}

// modified from http://www.quirksmode.org/js/findpos.html
function get(name) {
 if (document.getElementById)
   return document.getElementById(name);
 else if (document.layers)
   return document.layers[name];
 else if (document.all)
   return document.all[name];
 return null;
}

// modified from http://www.quirksmode.org/js/findpos.html
function findPos(obj) {
  var cur = new Point();
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      cur.x += obj.offsetLeft;
      cur.y += obj.offsetTop;
      obj = obj.offsetParent;
    }
  } else if (obj.x) {
    cur.x += obj.x;
    cur.y += obj.y;
  }
  return cur;
}

// cookie methods and alternate style selector
// from http://www.alistapart.com/articles/alternate/
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

// simple encryption stuff from http://shop-js.sourceforge.net/crypto.htm
// I wasn't able to find a license for this . . .
var b64s='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"';
function rc4(key, text) {
 var y, t, x;
 var s=new Array(256);

 for (var i=0; i<256; i++) {
  s[i]=i;
 }
 y=0;
 for (x=0; x<256; x++) {
  y=(key.charCodeAt(x % key.length) + s[x] + y) % 256;
  t=s[x]; s[x]=s[y]; s[y]=t;
 }
 y=0;
 var z="";
 for (x=0; x<text.length; x++) {
  var x2=x % 256;
  y=( s[x2] + y) % 256;
  t=s[x2]; s[x2]=s[y]; s[y]=t;
  z+= String.fromCharCode((text.charCodeAt(x) ^ s[(s[x2] + s[y]) % 256]));
 }
 return z;
}
function textToBase64(t) {
 var r='';
 var m = 0, a=0;
 var tl=t.length-1;
 var c;
 for(var n=0; n<=tl; n++) {
  c=t.charCodeAt(n);
  r+=b64s.charAt((c << m | a) & 63);
  a = c >> (6-m);
  m+=2;
  if(m==6 || n==tl) {
   r+=b64s.charAt(a);
   if((n%45)==44) {
     r+="\n";
   }
   m=a=0;
  }
 }
 return r;
}
function base64ToText(t) {
 var r=''; var m=0; var a=0; var c;
 for(var n=0; n<t.length; n++) {
  c=b64s.indexOf(t.charAt(n));
  if(c >= 0) {
   if(m) {
    r+=String.fromCharCode((c << (8-m))&255 | a);
   }
   a = c >> m;
   m+=2;
   if(m==8) { 
     m=0;
   }
  }
 }
 return r;
}
function encrypt(key, text) {
  return textToBase64(rc4(key, text));
}
function decrypt(key, text) {
  return rc4(key, base64ToText(text));
}

// user info cookie stuff
function getUserInfo() {
  // get user info if we're on a comment page
  var elt = get('cname');
  if (!elt || elt.value.trim().length == 0)
    return '';
  
  var name = elt.value.trim();
  
  var fields = ['cname', 'cemail', 'curi'];
  var tokens = new Array();
  for (var id in fields) {
    elt = get(fields[id]);
    tokens[id] = encrypt(name, elt.value.trim());
  }
  return tokens.join('|');
}
function setUserInfo() {
  var elt = get('cname');
  if (!elt || elt.value.trim().length == 0)
    return;
  var name = elt.value.trim();
  var cookie = readCookie("userinfo");
  if (cookie) {
    var tokens = cookie.split('|');
    if (decrypt(name, tokens[0]) == name) {
      get('cemail').value = decrypt(name, tokens[1]);
      get('curi').value = decrypt(name, tokens[2]);
    }
  }
}

// mouse hovers
function showtip(obj, name, str, dir, dist) {
  var tt = get(name);
  if (tt) {
    if (str)
      tt.innerHTML = str;
    var objPos = findPos(obj);
    
    if ("left" == dir) {
      tt.style.left = (objPos.x - tt.clientWidth - 4) + 'px';
      tt.style.top = (objPos.y - 2) + 'px';
    } else { // defaults to below the object
      tt.style.left = (objPos.x + 5) + 'px';
      var h = dist;
      if (!h)
        h = obj.clientHeight ? obj.clientHeight : 60;
      tt.style.top = (objPos.y + h + 4) + 'px';
    }
    tt.style.visibility = 'visible';
  }
}
function hidetip(name) {
  var tt = get(name);
  if (tt) {
    tt.style.visibility = 'hidden';
    tt.style.left = '-1000px';
  }
}

// font size changer
function getCurrentFontSize() {
  var size = document.body.style.fontSize;
  if (!size) size = '1em';
  return size.substr(0, size.length-2); // trim off the units
}
function fontSizeUp() {
  var size = getCurrentFontSize();
  document.body.style.fontSize = (size*1.2) + 'em';
}
function fontSizeDown() {
  var size = getCurrentFontSize();
  document.body.style.fontSize = (size * 0.83333) + 'em';
}
function toggleThemes() {
  var lay = get('themes');
  var spacer = get('spacer');
  var cur = lay.style.display;
  if (!cur) cur = 'none';
  
  if ('none' == cur) {
    lay.style.display = 'block';
    spacer.style.display = 'none';
  }
  else {
    lay.style.display = 'none';
    spacer.style.display = 'block';
  }
}

function search() {
  if (verifyInput('q')) {
    var query = get('q').value;
    var base = document.getElementsByTagName('base')[0];
    base = base.getAttribute('href');
    // remove characters that causes problems
    query = query.replace('/', '');
    document.location.href = base + 'search/' + encodeURIComponent(query);
  }
  return false;
}

// comment input validators
function isCommValid() {
  var elt = get('cbody');
  return elt && elt.value.trim().length > 0;
}
function updateButton(name) {
  var elt = get(name);
  if (elt)
    elt.disabled = !isCommValid();
}
function updateAddComment() {
  updateButton('addButton');
}
function updatePreviewComment() {
  updateButton('preview');
}
function verifyInput(id) {
  var input = get(id);
  return input && input.value.trim().length > 0;
}

function track(uri) {
  var img = new Image();
  img.src = 'http://ponderer.org/t?u=' + encodeURIComponent(uri);
}
function makeTrack(uri) {
  return function(ev) { track(uri) };
}

// page event handlers
window.onload = function(e) {
  // on reply pages, move down to the form
  var reply = get('reply');
  if (reply) {
    var pos = findPos(reply);
    var h;
    if (window.innerHeight)
      h = window.innerHeight;
    else if (document.documentElement && document.documentElement.clientHeight)
      h = document.documentElement.clientHeight;
    else if (document.body && document.body.clientHeight)
      h = document.body.clientHeight;
    if (h && pos) {
      // In safari, the browser bounce back to the top.  why?
      window.scrollTo(0, parseInt(pos.y - (0.15 * h)));
      get('cname').focus();
    }
  }
  
  var links = document.getElementsByTagName('a');
  var link;
  for (var i = 0; link = links[i]; ++i) {
    if (!link.href.startsWith('http://ponderer.org')) {
      link.onmousedown = makeTrack(link.href);
    }
  }
}

// Stop leaks in FF 1.5
function commentWindowUnload(e) {
  var cbody = get('cbody');
  var cname = get('cname');

  cbody.removeEventListener('keyup', updateAddComment, false);
  cbody.removeEventListener('change', updateAddComment, false);

  cname.removeEventListener('change', setUserInfo, false);
  cname.removeEventListener('keyup', setUserInfo, false);
}

window.onunload = function(e) {
  // save style sheet info
  createCookie("style", getActiveStyleSheet(), 365);
  
  // save comment info (if exists)
  var userinfo = getUserInfo();
  if (userinfo)
    createCookie("userinfo", userinfo, 365);
}

// set the style now rather than waiting until the page loads
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
