/*
  all the stuff that happens straight after page load
  ----------------------------------------------------
*/

Event.observe(document, 'dom:loaded', function() {

  if(!logged_in()) {
    // If a form requires a login, attach this class
    // Find elements with focuslogin
    $$('.focusLogin').each(function(elm){
      // Find inputs and capture focus
      attach_focus_handler(elm.select('input'));
      attach_focus_handler(elm.select('textarea'));
    });
  }

  if ($('page-blanker') ) {
    // hide the pop-over whenever they click outside it
    Event.observe($('page-blanker'), 'click' , function(e){
      pop_over_close();
    });
  }

  // run all the logged in / rights switches
  show_and_hide();
  
  // set up the stuff to run after the user logs in
  Event.observe(document, 'session:logged_in', after_login);
});

function after_login(e) {
  var result = e.memo;
  
  // set all the rights etc in the page
  _member.logged_in = true;
  if (result) {
    if (result.rights)
      rights = result.rights;
    if (result.can_act_as)
      can_act_as = result.can_act_as;  
  }


  // display/hide things they could/couldn't see before (based on their new rights)
  show_and_hide();
}

function attach_focus_handler(arr)
{
  arr.each(function(s){
    Event.observe(s,'focus',function(){
      if(!logged_in())
      {
        request_login();
      } 
    });
  });  
}

function show_and_hide(){
  // show and hide login required items
  $$('.show_on_li').each(function(elm){
    if (logged_in())
      elm.show();
    else
      elm.hide();
  });
  $$('.hide_on_li').each(function(elm){
    if (logged_in())
      elm.hide();
    else
      elm.show();
  });


  // show elements that match the rules
  $$('.show_on_matching').each(function(elm){
    md = elm.getMetaData();
    if (md.rules) {
      var match_on = 'all';
      if (md.match_on)
        match_on = md.match_on;
      if (md.match_on == 'all') {
        if (all_actors_match(md))
          elm.show()
        else
          elm.hide()
      }
      if (md.match_on == 'some') {
        if (some_actors_match(md))
          elm.show()
        else
          elm.hide()
      }
    }
  });
  
  // hide elements that match the rules
  $$('.hide_on_matching').each(function(elm){
    md = elm.getMetaData();
    if (md.rules) {
      var match_on = 'all';
      if (md.match_on)
        match_on = md.match_on;
      if (md.match_on == 'all') {
        if (all_actors_match(md))
          elm.hide();
        else
          elm.show();
      }
      if (md.match_on == 'some') {
        if (some_actors_match(md))
          elm.hide();
        else
          elm.show();
      }
    }
  });
};
