function NestedList(selector) {
  
  var Row = function(list, rowMarkup) {
    var row        = $(rowMarkup),
        toggleLink = $('.toggle', row).click(function(e) {
                      e.preventDefault();
                      toggle();
                    }),
        level      = parseInt(row.attr('class').match(/level-(\d+)/)[1], 10),
        pageId     = parseInt(row.attr('id').match(/page-(\d+)/)[1], 10),
        isRoot     = level === 0,
        isOpen     = toggleLink.text() === '-',
        children   = [];
        
    $('.parent-' + pageId + '.level-' + (level + 1)).each(function(i) {
      children.push(new Row(list, this));
    });
    
    children.hide = function() {
      $(this).each(function(i, child) {
        child.hide();
        if (child.children.length > 0) child.children.hide();
      });
      isOpen = false;
      toggleLink.text('+');
      restripeTable();
    };
    
    function showNextChild() {
      $(children).each(function(i, child) {
        child.show();
      });
      isOpen = true;
      toggleLink.text('-');
      restripeTable();
    };
    
    function toggle() { isOpen ? children.hide() : showNextChild(); };
    
    function hide() { row.hide(); };
    function show() { row.show(); };
    
    var rowObject = {
      list: list, 
      row: row, 
      children: children,
      level: level,
      pageId: pageId,
      toggle: toggle, 
      hide: hide, 
      show: show, 
      isOpen: function() { return isOpen; },
      isRoot: function() { return isRoot; }
    };
    
    toggleLink.click();

    return rowObject;
  };

  var self = this;
  this.element = $(selector);
  
  var rows = [];
  $('tr.level-0', this.element).each(function(i) {
    rows.push(new Row(self, this));
  });
  
  this.rows = rows;

  function restripeTable() {
    $('tr:visible', this.element).removeClass('even').each(function(i, row) {
      if (i % 2 == 0) {
        $(row).addClass('even');
      };
    });
  };
};

$(document).ready(function() {  
  $('.image_list li').click(function(e) {
    var input = $('input', this);
    if (input.length > 0) {
      input.attr('checked', !input.is(":checked"));
      e.preventDefault();
    };
  });
  
  
  window.list = new NestedList('.pages-index.admin table tbody');
  reset_flash();
  setup_login();
  
  setup_expandable_lists();
  // setup_admin_nav_links();
  // setup_admin_nav_panel();
    
  $('table').tablesorter().bind("sortStart", function() {
    $('tr', this).removeClass('even');
  }).bind("sortEnd",function() { 
    $('tr', this).each(function(i, row) {
      if (i % 2 == 0) $(row).addClass('even');
    });
  });
  
  $('.button.add, .button.remove').corners('5px');
  
  if ($.browser.msie)
    $('input.text, input.title, input.password, textarea, select, option').focus(function(e) {
      $(this).addClass('focus');
    }).blur(function(e) {
      $(this).removeClass('focus');
    });
});

var defaultCookieOpts = {
  expires: 14, 
  path: '/'
};

function setup_expandable_lists () {
  $('.expandable_list dt').css({cursor: "pointer"}).click(function(e) {
    $(this).next('dd').animate({"height": "toggle"}, 200);
  }).next('dd').hide();

  if (window.location.hash) {
    $(window.location.hash).show();
  };
}

function setup_admin_nav_panel () {
  var current_status   = $.cookie('admin_panel_status');
  var current_position = $.cookie('admin_panel_position');
  var admin_panel      = $('#admin_nav');

  if (current_position) {
    var pos  = current_position.split(',');
    var top  = pos[0] + "px";
    var left = pos[1] + "px";
    admin_panel.css({top: top, left: left});
  }

  if (current_status) {
    admin_panel.addClass(current_status);
  };

  admin_panel.draggable({
    scroll: true,
    stop: function(e, ui) {
      $.cookie('admin_panel_position', [ui.position.top, ui.position.left].join(","), defaultCookieOpts);
    }
  }).corners('10px').css({'opacity': 0.3}, 500).hover(function() {
    $(this).stop(true).animate({'opacity': 1}, 500);
  }, function() {
    $(this).stop(true).animate({'opacity': 1}, 500).animate({'opacity': 0.3}, 500);
  });
  
  $('.handle', admin_panel)
    .css('cursor', 'pointer')
    .filter('.open')
      .click(function(e) {
        $('.body', admin_panel)
          .animate({"height": "toggle"})
          .queue(function() {
            $.cookie('admin_panel_status', null, defaultCookieOpts);
            admin_panel.removeClass('open');
            $(this).dequeue();
          });
        e.preventDefault();
      })
      .end()
    .filter('.closed')
      .click(function(e) {
        $('.body', admin_panel)
          .animate({"height": "toggle"})
          .queue(function() {
            $.cookie('admin_panel_status', 'open', defaultCookieOpts);
            admin_panel.addClass('open');
            $(this).dequeue();
          });
        e.preventDefault();
      });
}

function setup_admin_nav_links () {
  $('#sidebar ul.admin').hide();
  $('#sidebar li').mouseover(function(e) {
    $(this).children('.admin').show();
  }).mouseout(function(e) {
    $(this).children('.admin').hide();
  });
}

function current_page_is (pathOrRegExp) {
  return window.location.pathname.match(pathOrRegExp) || false;
}

function reset_flash () {
  $('.flash').css({
    'position': 'fixed',
    'bottom': '-10px',
    'margin': 0,
    'left': 0,
    'width': '100%',
    'opacity': 0
  }).animate({
    'bottom': 0,
    'opacity': 1
  }, 1000).animate({
    // Pause 1 second
    'opacity':1
  }, 1000).animate({
    'opacity': 'hide'
  }, 3000);
}

function select_first_text_field () {
  $('input[type="text"]').focus();
}

function setup_login () {
  $('#login_bar input').focus(function() {
    $(this).siblings('label').hide();
  }).blur(function() {
    if ($(this).val() == '') $(this).siblings('label').show();
  });
  
  $('#forgotten_password, .forgot_password .cancel').click(function(e) {
    e.preventDefault();
    $('.forgot_password, .login').toggle();
  });
  
  $('#open-login, .login .cancel').click(function(e) {
    e.preventDefault();
    $('#login_bar .forms').slideToggle();
    $('.forgot_password').hide();
    $('.login').show();
  });
  
  $('#openid-login, .forgot_password').hide();
  $("<a href='#' class='cancel' id='login_toggle'>Login with OpenID</a>").toggle(function() {
    // OpenID Login.
    $('#openid-login').show();
    $('#password-login').hide();
    $(this).text('Login with a password.').blur();
    // select_first_text_field();
  }, function() {
    // Password Login.
    $('#password-login').show();
    $('#openid-login').hide();
    $(this).text('Login with OpenId').blur();
    // select_first_text_field();
  }).insertAfter('.forms .login h1');
  // select_first_text_field();
}