$(document).ready(function() {
  var toolbar = $('.toolbar.widget');

  if (!toolbar) return;

  var list = toolbar.find('ul');
  var pcontext = $('.widget.page_context');

  $('<a/>').appendTo(toolbar).attr('href', '#toggle').append($('<img/>').attr('src', '/images/icons/toggle_admin.png'));
  if ($.cookie('toolbar_visible') == 0) toggle();

  toolbar.children('a').click(function(e) {
    toggle();
    return false;
  });  

  function toggle() {
    var vis = list.css('display') == 'none';

    if (vis) {
      $('body').addClass('toolbar_widget');
      toolbar.css('right', '0');
      list.show()
      pcontext.show();    
    } else {
      $('body').removeClass('toolbar_widget');
      toolbar.css('right', 'auto');
      list.hide();
      pcontext.hide();
    }

    $.cookie('toolbar_visible', vis ? 1 : 0);
  }

});
