/* common.js */

// úr firebugx.js
if (!("console" in window) || !("firebug" in console))
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}


function popup(u,w,h,s,extra) {
  if (extra) { extra = ","+extra; } else { extra = ""; }
  var popup = window.open(u,'popup','toolbar=no,location=no,directories=no,status=no,scrollbars=' + s + ',menubar=no,resizable=yes,titlebar=no,width=' + w + ',height=' + h + extra);
  popup.focus();
}

function createCookie(name,value,days,path) {
  if (!path) { path = "/"; }
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    expires = "; expires="+date.toGMTString();
  }
  document.cookie = name+"="+value+expires+"; domain=.blog.is; path="+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;
}

if (! ("jQuery" in window)) window.jQuery = function () {}
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toGMTString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toGMTString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


// "DHTML MicroAPI" building block from quirksmode.org.
// Returns an object representing a named element in HTML. 
// Properties of the object: obj and style.
// Usage : var x = new getObj(id);

function getObj(name) {
  if (document.getElementById) {
  	this.obj = document.getElementById(name);
	if (this.obj) {
		this.style = document.getElementById(name).style;
    }
  }
  else if (document.all) {
	this.obj = document.all[name];
	if (this.obj) {
	    this.style = document.all[name].style;
    }
  }
  else if (document.layers) {
   	this.obj = document.layers[name];
	if (this.obj) {
   	    this.style = document.layers[name];
    }
  }
}

// Submit form upon enter. 
function entsub(myform) {
	if (window.event && window.event.keyCode == 13) {
		myform.submit();
	} else {
		return true;
	}
}

// Auxiliary function for form_as_hash
function form_elem (el, curval) {
  var to = typeof(curval);
  if (to == 'undefined') {
	curval = el.value;
  } else if (to == 'object') {
	curval.push(el.value);
  } else {
	var ar = new Array ();
	ar.push(curval, el.value);
	curval = ar;
  }
  return curval;
}

// Read form values and return as an Object (hash)
function form_as_hash (frm) {
  var h = {};
  for (i=0; i<frm.elements.length; i++) {
	var el = frm.elements[i];
	var type = el.type ? el.type.toLowerCase() : "";
	if (type == "checkbox") {
	  if (el.checked) {
		h[el.name] = form_elem(el, h[el.name]);
	  }
    }
	else if (type == "radio") {
	  if (el.checked) h[el.name] = el.value;
    }
	else if (type == "select-one") {
	  h[el.name] = el.options[el.selectedIndex].value;
    }
	else if (type == "select-multiple") {
	  h[el.name] = new Array ();
	  for (j=0; j<el.options.length; j++) {
	    if (el.options[j].selected)
	      h[el.name].push(el.options[j].value);
	  }
    }
	else if (type) {
	  var nam = el.name || ('--' + el.type + '_' + i);
      h[nam] = form_elem(el, h[nam]);
    }
    else if (window.console && console.debug) {
	  console.debug("Strange non-type form element: "+el);
    }
  }
  return h;
}

/* ** CALLBACK MECHANISM - used mainly for LINA-based functionality ** */

var CB;
if (!CB) CB = {};

function add_callback (slot,fn) {
  if (!CB[slot]) {
    CB[slot] = new Array;
  }
  CB[slot].push(fn);
}
function handle_callbacks (slot, args) {
   if (!CB[slot]) return;
   for (var i=0; i<CB[slot].length; i++) {
	  var fn = CB[slot][i];
	  fn(args);
   }
}


/* **************************** */
/* "LINA Is Not AJAX" */

/**
 * @fileoverview
 * LINA - Asynchronous communication 
 */

var browser_recommendation = "Vafrinn þinn ræður ekki við JavaScript sem þessi síða notar.\nMælt er með að nota einhvern eftirtalinna vafra:\n  * Firefox 1.0+\n  * Microsoft Internet Explorer 6+\n  * Mozilla 1.6+\n  * Safari 1.2+\n  * Opera 7.6+\n  * Konqueror 3.3.4+";


var LINA_TIMEOUT = 20000;

/**
 * LINA, version 2.
 */
function LINA (json_args, callback, cb_context, error_cb, opt) {

  var THIS = this; // reference to be used in closures

  if (! opt) opt = {};

  // simple check for legacy browsers 
  if (typeof XMLHttpRequest == 'undefined') {
    this.notify('info', browser_recommendation);
    return false;
  }

  if (!callback) {
    this.log_error('LINA: Callback not given');
    return false;
  }

  var type; // GET or POST
  
  if (cb_context == null)
    cb_context = window;

  var json_args_raw = this.to_json(json_args);
  var json_args_escaped;
  var secure_json = false;

  // Send a secured request when we have an active session 
  // - unless the LINA request specifically asks us not to
  if (!opt.no_encryption && Session && Session.magic_cookie) {
	var key = Session.magic_cookie + ':' + Session.sessionid;
	var cr = new MblCrypto ( key );
	json_args_raw = cr.encrypt(json_args_raw);
	// NB! strToHex is defined in common.js
	json_args_escaped = strToHex(json_args_raw);
	secure_json = true;
  }
  else {
	json_args_escaped = escape(json_args_raw);
	json_args_escaped = json_args_escaped.replace(/\+/g, "%2b");
  }

  var json_send_param = null;

  // Use GET if query is short, otherwise use POST
  if (json_args_escaped.length <= 1024) {
    type = 'GET';
    url  = this.json_url(json_args_escaped, true, secure_json);
  } else {
    type = 'POST';
    url = '/utils/lina.json';
	  json_send_param = (secure_json ? 'sjson=' : 'json=') + json_args_escaped + ';rnd=' + Math.random();
  }

  // wrapper around the callback to be able to call it in context
  var on_success = function () {
    if (callback) 
      callback.apply(cb_context, arguments);
  };

  var on_error = function (xhr, msg) {
    msg = 'Villa kom upp við samskipti með LÍNU [from jQuery]';
//     if (xhr) msg += '\nHTTP status: ' + xhr.status;
    THIS.log_error(msg);
    if (typeof error_cb == 'function') {
      error_cb.call(cb_context, 'error', xhr, msg);
    }
  };

  // Make the actual request
  var req = jQuery.ajax({
    type:     type,
    url:      url,
    dataType: 'json',
    data:     json_send_param,
    success:  on_success,
    error:    on_error,
    timeout:  LINA_TIMEOUT
  });

  return req;
}


LINA.prototype.notify = function () {
  try {
    if (typeof mbl != 'undefined') 
      mbl.notify.apply(window, arguments);
  } catch (e) {}
};


LINA.prototype.log_error = function () {
  try {
    if (typeof mbl != 'undefined') {
      mbl.logError.apply(window, arguments);
    } else if (typeof console != 'undefined') {
      console.log.apply(window, arguments);
    } 
  } catch (e) {}
};


LINA.prototype.json_url = function (args, noescape, secure) {
  var url = "/utils/lina.json";
  var rnd = Math.random(); // prevent client-side caching
  var json = noescape ? args : escape(to_json(args));
  if (! noescape) json = json.replace(/\+/g, "%2b");
  return url + (secure ? '?sjson=' : '?json=') + json + ';rnd=' + rnd;
};


// Source for to_json(): http://www.crockford.com/JSON/js.html - (c) json.org.
// License: BSD-style (with addendum: "The Software shall be used for Good, not Evil")
LINA.prototype.to_json = function (arg) {
  var c, i, l, o, u, v;
  switch (typeof arg) {
  case 'object':
	if (arg) {
	  if (arg.constructor == Array) {
		o = '';
		for (i = 0; i < arg.length; ++i) {
		  v = this.to_json(arg[i]);
		  if (o) {
			o += ',';
		  }
		  if (v !== u) {
			o += v;
		  } else {
			o += 'null,';
		  }
		}
		return '[' + o + ']';
	  } else if (typeof arg.toString != 'undefined') {
		o = '';
		for (i in arg) {
		  v = this.to_json(arg[i]);
		  if (v !== u) {
			if (o) {
			  o += ',';
			}
			o += this.to_json(i) + ':' + v;
		  }
		}
		return '{' + o + '}';
	  } else {
		return;
	  }
	}
	return 'null';
  case 'unknown':
  case 'undefined':
  case 'function':
	return u;
  case 'string':
	l = arg.length;
	o = '"';
	for (i = 0; i < l; i += 1) {
	  c = arg.charAt(i);
	  if (c >= ' ') {
		if (c == '\\' || c == '"') {
		  o += '\\';
		}
		o += c;
	  } else {
		switch (c) {
		case '\b':
		  o += '\\b';
		  break;
		case '\f':
		  o += '\\f';
		  break;
		case '\n':
		  o += '\\n';
		  break;
		case '\r':
		  o += '\\r';
		  break;
		case '\t':
		  o += '\\t';
		  break;
		default:
		  c = c.charCodeAt();
		  o += '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); // /;
		}
	  }
	}
	return o + '"';
  default:
	return String(arg);
  }
};


/* **************************** */
/* dulkóðunarbakendi */

/*
  mblcrypto.js - RC4-based encryption in Javascript.
  Author: Baldur Kristinsson (bk@mbl.is), March 2007.

  Usage:

    var mcr = new MblCrypto (key);
    var ciphertext = mcr.encrypt(plaintext);
    var plaintext2 = mcr.decrypt(ciphertext);

  About RC4: http://en.wikipedia.org/wiki/RC4
  This implementation based on Crypt::RC4 by Kurt Kincaid.
*/

// Constructor. Required parameter: key.
function MblCrypto (key) {
  if (! key) {
    alert("MblCrypto: need key");
    return false;
  }
  this.key = key;
  this.rc4 = this.is_ie() ? this.rc4_array_impl : this.rc4_string_impl;
}

// Class definition
MblCrypto.prototype = {
  // For non-IE browsers (IE string concatenation is extremely slow)
  rc4_string_impl: function (txt) {
    var x = 0, y = 0, tmp = 0;
    var state = this.state;
    var ret = '';
    for (var i = 0; i < txt.length; i++) {
      x = x==255 ? 0 : x+1;
      y += state[x];
      if (y > 255) y -= 256;
      tmp = state[x];
      state[x] = state[y];
      state[y] = tmp;
      ret += String.fromCharCode( txt.charCodeAt(i) ^ state[( state[x] + state[y] ) % 256] );
    }
    return ret;
  },
  // For IE 6 and 7 (Safari array element assignment is extremely slow)
  rc4_array_impl: function (txt) {
    var x = 0, y = 0, tmp = 0;
    var state = this.state;
    var ret = [];
    for (var i = 0; i < txt.length; i++) {
      x = x==255 ? 0 : x+1;
      y += state[x];
      if (y > 255) y -= 256;
      tmp = state[x];
      state[x] = state[y];
      state[y] = tmp;
      ret[i] = String.fromCharCode( txt.charCodeAt(i) ^ state[( state[x] + state[y] ) % 256] );
    }
    return ret.join('');
  },
  // Initializes the RC4 state table based on IV + key.
  rc4_setup: function () {
    var key = this.iv + this.key;
    var ka = [];
    for (var i = 0; i<key.length; i++) {
      ka[i] = key.charCodeAt(i);        
    }
    var state = [];
    for (var j=0; j<256; j++) {
      state[j] = j;
    }
    var y = 0;
    var tmp = 0;
    for (var x = 0; x < 256; x++) {
      y = ( ka[x % ka.length] + state[x] + y ) % 256;
      tmp = state[x];
      state[x] = state[y];
      state[y] = tmp;
    }
    return state;
  },
  // Returns a 16-byte random string to use as IV
  get_iv: function () {
    var iv = '';
    for (i=0; i<16; i++) {
      iv += String.fromCharCode( Math.floor( Math.random() * 256) );
    }
    return iv;
  },
  // Encrypts text; note that a 16-byte IV 
  // is prepended to the output
  encrypt: function (txt) {
    this.iv = this.get_iv();
    this.state = this.rc4_setup();
	if (txt.match(/[^\x00-\xff]/)) {
	  txt = txt.replace(/[^\x00-\xff]/g, this.escape_unicode_char);
    }
    return this.iv + this.rc4(txt);
  },
  // Decrypts text; note that the first 16 bytes 
  //   of the output are assumed to be an IV
  decrypt: function (txt) {
    var iv = txt.substr(0,16);
    txt = txt.substr(16);
    this.iv = iv;
    this.state = this.rc4_setup();
    return this.rc4(txt);
  },
  // True if IE 5, 6 or 7; false otherwise
  is_ie: function () {
    /*@cc_on
    return true;
    @*/;
    return false;
  },
  escape_unicode_char: function (chr) {
    return "&#" + chr.charCodeAt(0) + ";"
  }
}; 



function pause (ms) {
  var now = new Date();
  var until = now.getTime() + ms;
  while (true) {
    now = new Date();
    if (now.getTime() > until) return;
  }
}

//Gróf vafragreining
function browser_type () {
  var ua = navigator.userAgent;
  if (! ua) return 'other';
  if (ua.match(/Opera/))     return 'opera';
  if (ua.match(/KHTML/))     return 'khtml';
  if (ua.match(/Gecko/))     return 'gecko';
  if (ua.match(/MSIE 6/))    return 'msie6';
  if (ua.match(/MSIE 7/))    return 'msie7';
  if (ua.match(/MSIE.*Mac/)) return 'iemac';
  if (ua.match(/MSIE 5/))    return 'msie5';
  if (ua.match(/^Mozilla\/4.0$|Proxy/)) return 'proxied';
  return 'other';
}

function mapCharsToHex () {
  if (window._str2hex) return window._str2hex;
  window._str2hex = {};
  for (var i = 0; i<256; i++) {
	window._str2hex[ String.fromCharCode(i) ] = (i < 16 ? "0" : "") + i.toString(16);
  }
  return window._str2hex;
}
// For Firefox, Opera, etc.
function strToHex_A (str) { // array + join impl.
  var s = mapCharsToHex();
  var ret = new Array(str.length);
  for (var i=0; i<str.length; i++) {
    ret[i] = s[ str.charAt(i) ];
  }
  return ret.join('');
}
// For IE and Safari
function strToHex_B (str) { //  replace + function impl.
  var s = mapCharsToHex();
  var re = /[\x00-\xFF]/g;
  var fn = function (x) { return s[x]; }
  return str.replace(re, fn);
}
var strToHex = browser_type() == 'khtml' ? strToHex_B : strToHex_A;
/*@cc_on
strToHex = strToHex_B;
@*/;


/* ********* GLOBAL LINA-BASED FUNCTIONS ********* */

var Session;
if (!Session) Session = {};

function lina_login (username, password) {
	handle_callbacks('login:wait');
	// This is mere obfuscation, not total protection
	var key = "pvZu^D1v~RgcoxVO2mMe_YrH@7i#98Iv";
	var cr = new MblCrypto( key );
	var up_combi = cr.encrypt( username + "::" + password );
	var lina = new LINA({ 
       "comp"   : "/utils/lina_methods", 
       "method" : "login", 
       "args"   : { "up": strToHex(up_combi), s: "1029477801" }
    }, lina_login_cb );
    return false;
}

function lina_login_cb (resp) {
  if (resp.error) {
	alert("Óvænt villa við innskráningu:\n"+resp.error);
	handle_callbacks('login:cleanup');
  }
  else if (resp.login_ok && resp.username) {
	createCookie("blog_reader",resp.sessionid);
	Session.sessionid = resp.sessionid;
	Session.username = resp.username;
	Session.magic_cookie = resp.magic_cookie;
	Session.expires = (new Date).getTime() + 82800000; // 23 klst
	handle_callbacks("login:ok",resp);
  }
  else {
	handle_callbacks("login:error",resp);
  }
}

function lina_is_logged_in_default_cb (resp) {
  if (resp.error) {
    alert("Villa við innskráningartékk:\n"+resp.error);
	handle_callbacks('is_logged_in:error',resp);
  }  
  else if (resp.ok) {
    Session.username = resp.username;
    Session.sessionid = resp.sessionid;
	Session.magic_cookie = resp.magic_cookie;
    Session.expires = (new Date).getTime() + 82800000; // 23 klst
	handle_callbacks('is_logged_in:ok',resp);
  }
}

function lina_is_logged_in (cb,nocache) {
  if (Session.expires && Session.expires > (new Date).getTime() && Session.magic_cookie && !nocache) 
    return Session;
  var cookie = readCookie('blog_reader');
  if (!(cookie && cookie.length)) return false;
  if (!cb) cb = lina_is_logged_in_default_cb;
  var lina = new LINA({ "comp" : "/utils/lina_methods",
						"method" : "is_logged_in",
						"args" : { "sessionid": cookie }
                       }, cb, null, {no_encryption:true});
  return false; // Status of LINA call will be handled by callback function
}

function lina_logout_cb (resp) {
  // don't really need to do anything
  if (resp.error && window.console && console.debug) 
    console.debug("Villa: Gat ekki eytt session úr gagnagrunni:\n" + resp.error);
}

function lina_logout () {
  handle_callbacks('logout:logout');
  var lina = new LINA({ "comp": "/utils/lina_methods",
                        "method": "logout",
                        "args": { "session": Session }
                      }, lina_logout_cb);
  Session = {};
  createCookie("blog_reader","");
}

function $_ (id) { return document.getElementById(id) }

function set_msg (msg, mode, id) {
  if (! msg)  return;
  if (! mode) mode = 'notice';
  if (! id)   id = 'msg';
  if ($_(id))
    $_(id).innerHTML = '<div class="message-box ' + mode + '">' + msg + '</div>';
}

function session_keepalive_cb (resp) { 
  if (resp.ok == 1) setTimeout('session_keepalive()',900000);
}
function session_keepalive () {
  var cookie = readCookie('blog_reader');
  if (!(cookie && cookie.length)) return false;
  var l = new LINA({ comp:   "/utils/lina_methods", 
					 method: "session_keepalive", 
                     args: { sessionid: cookie } },
				   session_keepalive_cb);
}



function AlbumInfo () {

  this.currrent = null;

  this.log =  function (msg) {
    if (typeof(log) == 'function')
      log(msg);
  };

  /*
   * Birtir upplýsingar um mynd nr. img_id
   */
  this.show = function (ev, div, img_id) {

    if (this.current) {
      if (this.current.div == div)
        return;
      else
        this.hide(null, div);
    }
    
    var el = document.getElementById('img_info_' + img_id);
    if (!el) {
      this.log("album_show_info: can't find img_info_" + img_id);
      return;
    }
   
    el.style.display = '';
    this.current = { div: div, p: el };
  };


  /*
   * Felur upplýsingar um mynd
   */
  this.hide = function (ev, div) {
    if (this.current) {
      if (this.current.p) 
        this.current.p.style.display = 'none';
      this.current = null;
    }
  };

};

var initCallbacks = [];
var initCallbacksCalled = false;

/*
 * Register a function to be called when the document is ready.
 */
function addInitCallback(func) {
  if (initCallbacksCalled) 
    func.apply(document);
  else
    initCallbacks[initCallbacks.length] = func; 
}

function callInitCallbacks() {
  for (var i = 0; i < initCallbacks.length; i++) {
    initCallbacks[i].apply(document);
  }
  initCallbacksCalled = true;
}


function escape_unicode(s) {
  var ret = '';
  var padnum = function(n, l) {
    n = n + '';
    while (n.length < l) n = '0' + n;
    return n;
  };
  for (var i = 0; i < s.length; i++) {
    var c = s.charAt(i);
    if (c.charCodeAt(0) > 0xff) 
      ret += '&#' + padnum(c.charCodeAt(0), 4) + ';';
    else 
      ret += c;
  }
  return ret;
}

function unescape_unicode(s) {
  return s.replace(/&#(\d{4});/g, function (x, y) {
    return String.fromCharCode(parseInt(y));
  });
}


// Notað í /no_read_permission.html
function requestReadPassword(form) {
	new LINA({
		comp: '/utils/lina_methods',
		method: 'request_read_password',
		args: { 
			name: form.name.value,
			email: form.email.value,
			blog_id: form.blog_id.value
		},
		with_context: true
	}, 
	function (ret) {
		if (ret.error) 
			alert("Villa kom upp: " + ret.error);
		else 
			$('#pwrequest').html('Ósk um að þú fáir lykilorð sent hefur verið send notandanum');
	});
	$('#pwrequest').html('Augnablik...');
	return false;
}

// Get position of element on page
function getTopPos (elm) {
  if (! elm) return 0;
  var par = elm.offsetParent;
  return par ? elm.offsetTop + getTopPos(par) : 0;
}
function getLeftPos (elm) {
  if (! elm) return 0;
  var par = elm.offsetParent;
  return par ? elm.offsetLeft + getLeftPos(par) : 0;
}
function getPos (elm) {
  return [ getLeftPos(elm), getTopPos(elm) ];
}


/*
 * Óskráðum notendum er ekki boðið upp á vakt - því er kóði fyrir þá
 * kommentaður út. Stuðningur er þó fyrir hendi.
 */
var commentWatch = {
  act: function(action, args, cb) {
    if (!args) args = {};
    if (location.pathname.match(/\/(entry|image)\/(\d+)\/?$/)) {
      args.subject_type = RegExp.$1;
      args.subject_id = RegExp.$2;
      if ($('div.comment:last a.bookmark:first').length > 0) {
        args.last_cmt_seen = $('div.comment:last a.bookmark:first').attr('id').replace('comment','');
      }
      $('#comment-watch-waiting').show();
      new LINA({
        comp: '/lib/comments/watch',
        method: action,
        with_context: true,
        args: args
      }, function(resp) {
        $('#comment-watch-waiting').hide();
        if (resp.error) 
          console.log('Vöktun: Villa kom upp í samskiptum við þjón:\n' + resp.error);
        else
          cb(resp);
      });
    } else {
      console.log('commentWatch.act: Þekki ekki slóð');
    }
  },

  init: function() {
    $('#comment-watch a').click(function(){
      switch (this.rel) {
        case 'stop-watching': // Hætta að vakta [fyrir skráða]
          $('#comment-watch-watching').hide();
          commentWatch.act('stop', null, function(resp){
            console.log('Hætti að vakta', resp);
            $('#comment-watch-not-watching').show();
          });
          break;

        case 'start-watching': // Hefja vakt [allir]
          $('#comment-watch-not-watching').hide();
          if (Session.username) {
            // user logged in
            commentWatch.act('start', null, function(resp){
              $('#comment-watch-watching').show();
              console.log('Hóf vakt', resp);
            });
          }
          break;
      }
      return false;
    });

    if (Session.username)
      commentWatch.onLoggedIn();
    else 
      add_callback('is_logged_in:ok', commentWatch.onLoggedIn);

    add_callback('login:ok', commentWatch.onLoggedIn);
    add_callback('logout:logout', commentWatch.onLoggedOut);
  },

  onLoggedIn: function() {
    commentWatch.act('is_watching', null, function(resp){
      if (resp.disabled) {
        $('#comment-watch').hide(); // felum ef vöktun er óvirk fyrir notandann
      } else {
        $('#comment-watch').show(); // þarf ekki ef unreg er með
        if (resp.watching) {
          $('#comment-watch-not-watching').hide();
          $('#comment-watch-watching').show();
        } else {
          $('#comment-watch-not-watching').show();
          $('#comment-watch-watching').hide();
        }
      }
    });
  },


  onLoggedOut: function() {
    $('#comment-watch').hide(); // út og næstu inn ef unreg er með
  }

};


var Facebook = {
  // Share the page with the given URL on Facebook. The URL defaults
  // to the current page.
  share: function(url) {
    if (!url) url = location.href;
    if (url.charAt(0) == '/') 
      url = location.protocol + '//' + location.host + url + '?fb=1';
    t = document.title;
    window.open('http://www.facebook.com/sharer.php?u='
      + encodeURIComponent(url)
      + '&t=' +encodeURIComponent(t),
      'sharer','toolbar=0,status=0,width=626,height=436');
  },

  // To be used in click event handlers, i.e
  // <a href="#" onclick="return Facebook.clickHandler();">Share</a>
  clickHandler: function(url) {
    this.share(url);
    return false;
  }
};




