$(document).ready(function()
{ 
  externalLinks();
});

// quickndirty external links via form and checkbox
function externalLinks()
{
  // our checkbox form
  var form = "<form class=\"toggle-external-links\"><label class=\"checkbox\"><input type=\"checkbox\" id=\"new-window\"> Open external links in a new window.<\/label><\/form>";

  // get cookie value ("checked" or none)
  var checked = $.cookie('externalLinks');

  // open rel="external" in new window
  // via http://abeautifulsite.net/notebook.php?article=47
  function attachExternalLinks()
  {
    $('A[rel="external"]').click( function() {
      window.open( $(this).attr('href') );
      return false;
    });
  }
  
  // insert the checkbox after the subheadline
  $("#sidebar").append(form);
  
  // if our cookie contains "checked", tick checkbox and attach links
  if(checked)
  {
    $("form input[type=checkbox]").attr("checked","checked");
    attachExternalLinks();
  };
  
  // add onclick handler to checkbox #new-window
  $("#new-window").click(function()
  {
    // if checked
    if ($("#new-window").is(":checked"))
    {
        // attach links
        attachExternalLinks();
      
        // write cookie
        $.cookie('externalLinks', 'checked');
    }
    else
    {   
        // remove onclick event
        $('A[rel="external"]').unbind("click");
        
        // write cookie
        $.cookie('externalLinks', '');
    }
  });
}