/*
  all the stuff that happens straight after page load
  ----------------------------------------------------
*/

Event.observe(document, 'dom:loaded', function() {

  // add the video overlay to the video thumbnails
  $$('.ug_video').each(function(video){
    var img = new Element('img', { src:'/images/icons/video_overlay.png' });
    img.setStyle({marginTop:'16px', float:'none'});
    img.addClassName('png-fix');
    video.down('a').appendChild(img);
  });

  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'));
    });
  }
  
  // fire up the image/video carousels
  $$('.carousel').each(function(carousel){
    new Carousel(carousel);
  });

  // 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
  update_for_session_state();

  // attach the events for the actor-changers
  init_actor_pickers();
  
  // deal with the tournament sub-navigation
  if (!$('btn_tournaments').hasClassName('selected')) {
    Event.observe($('btn_tournaments'), 'mouseover', function(e){ Event.stop(e); $('btn_tournaments').addClassName('selected'); $('s-nav-tour').show(); });
    Event.observe($('navbar'), 'mouseover', function(e){ Event.stop(e); $('btn_tournaments').removeClassName('selected'); $('s-nav-tour').hide(); });
    Event.observe($('top-nav'), 'mouseover', function(e){ Event.stop(e); $('btn_tournaments').removeClassName('selected'); $('s-nav-tour').hide(); });
  }
});

function attach_focus_handler(arr)
{
  arr.each(function(s){
    Event.observe(s,'focus',function(){
      if(!logged_in())
      {
        request_login();
      } 
    });
  });  
}

function update_for_session_state() {
  // show and hide elements according to rules within them
  show_and_hide();

  // update the pickers to have the defaults set
  reset_actor_pickers();
}


function init_actor_pickers() {
  $$('.actor-picker').each(function(changer){
    Event.observe(changer.down('.actor-switch'), 'click', function(e){
      e.stop();
      // pick the actor
      actor_picker(function(actor_id){
        changer.down('input').value = actor_id;
        changer.down('.actor-identity').innerHTML = actor(actor_id).name;
      }, { rules:changer.getMetaData().rules, current_actor_id:changer.down('input').value });
    });
  });
}

function reset_actor_pickers() {
  $$('.actor-picker').each(function(changer){
    // find the first actor that matches the rule (if there is one)
    var matching = matching_actors(changer.getMetaData().rules, rights)
    if (matching.length > 0) {
      changer.down('input').value = matching[0];
      changer.down('.actor-identity').innerHTML = actor(matching[0]).name;
    }
    // show or hide the option to switch actors
    if (matching.length > 1)
      changer.down('.actor-switch-cta').show();
    else
      changer.down('.actor-switch-cta').hide();
  });
}


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 and hide items that required multiple actors / single actors on an account
  $$('.show_on_multiple').each(function(elm){
    if (is_multiple_actors())
      elm.show();
    else
      elm.hide();
  });
  $$('.hide_on_multiple').each(function(elm){
    if (is_multiple_actors())
      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();
      }
    }
  });
}

// include the ability to extract metadata from elements
Element.addMethods({
  getMetaData: function(element){
    element = $(element);
    var found = element.className.match(/\{.*\}/);
    if (found) {
      try {
        return eval("(" + found[0] + ")");
      } catch(e) {
        return {};
      }
    } else {
      return {};
    }
  }
});


/*
  pop-ups that are used all over the place
*/

// display the mini profile
function show_mini_profile(url) {
  // make sure they're logged in first
  if (!logged_in()) {
    request_login(function(){ show_mini_profile(url); });
    return false;
  }
  // create a new object to put it in
  var profile_holder = new Element('div');
  new Ajax.Updater({ success:profile_holder }, url, { method: 'get', onComplete:function(){ pop_over(profile_holder); } } );
}

// display the become a friend form
function show_inline_befriend_form(url, rights_set) {
  // store the existing pop_over form in the popover
  var current_form = $('pop-over-content').firstChild;
  $('pop-over-content').firstChild.remove();

  actor_picker(function(actor_id){ show_inline_befriend_form_actual(current_form, url, actor_id) }, { rules : { role : '!friend', actor : '!context' }, rights_set : rights_set })
}
function show_inline_befriend_form_actual(old_form, url, actor_id) {
  // show the form again
  pop_over(old_form);
  new Ajax.Updater({ success: 'mini_profile_additonal_form' }, url + '?actor_id=' + actor_id.toString(), { method: 'get', onComplete:function(){ $('mini-pop-divide').show(); } });
}


// show the actor chooser for becoming a friend
function befriend_actor(url) {
  // make sure they're logged in first
  if (!logged_in()) {
    request_login(function(){ befriend_actor(url); });
    return false;
  }
  actor_picker(function(actor_id){ befriend_actor_with_id(url, actor_id); }, { rules:{ role:'!friend', actor:'!context' } });
}
// submit the form to become a friend
function befriend_actor_with_id(url, actor_id) {
  var friend_form = new Element('div');
  new Ajax.Updater({ success:friend_form }, url + '?actor_id=' + actor_id.toString(), { method: 'get', onComplete:function(){ pop_over(friend_form); } } );
}

// submit a friend request
function befriend_submit(form) {
  form = $(form);
  
  if (form.down('.comment').value == 'Include a comment...')
    form.down('.comment').value = '';
  
  new Ajax.Request(form.action,
    {
      asynchronous:true, 
      parameters:form.serialize(),
      onSuccess:befriend_onSuccess
    });
}

function befriend_onSuccess(t) {
  var result = t.responseJSON;
  display_notification(result.response_message);

  if (result.rights)
    rights = result.rights;
  if (result.can_act_as)
    can_act_as = result.can_act_as;

  // update everything now that they're friends (for teams and tournaments)
  update_for_session_state();
  
  // go back to the server and load any elements on the page that have been hidden away
  // note - authentication against the login is still applied on the server
  fetch_unloaded_data();
}


// post js login stuff
Event.observe(document, 'session:logged_in', function(e){
  var result = e.memo;

  // switch the headers
  $('login_register_score').show();
  $('nologin_register_score').hide();
  $('loggedin_sticker').show();
  $('notlogged_sticker').hide();
  $('account_box_my_page').href = "/members/" + result.actor.alias;

  // update everything now that they're logged in
  update_for_session_state();
  
  // go back to the server and load any elements on the page that have been hidden away
  // note - authentication against the login is still applied on the server
  fetch_unloaded_data();
});

// load missing page elements
function fetch_unloaded_data() {
  // figure out what needs loading
  var to_load = {};
  $$('.li_unloaded').each(function(unl){
    var md = unl.getMetaData();
    to_load[md.d_name] = unl;
  });
  
  // ask the server for everything we want
  var url = window.context_url + '/profile_data';
  new Ajax.Updater('login-post-loaded', url, {
      evalScripts : true
    , parameters  : 'require=' + $H(to_load).keys().join()
    , insertion   : 'bottom'
    , onComplete  : function(){ fetch_unloaded_data_onSuccess(to_load) }
  });
}

function fetch_unloaded_data_onSuccess(to_load) {
  // build an object full of all the just loaded stuff
  var loaded = {};
  $$('#login-post-loaded .li_loaded').each(function(ld){
    loaded[ld.getMetaData().d_name] = ld;
  });
  
  // loop through the stuff we're waiting for
  $H(to_load).keys().each(function(d_name){
    if (loaded[d_name]) {
      // replacing with the loaded one if it's found
      Element.replace(to_load[d_name], loaded[d_name]);
    }
  });
}
