/* ALL CODE COPYRIGHT ZEHN 2009 */

/* try to login a user */

document.observe('dom:loaded', function()
{
  FB.init("f4211ca85a947e42836e5bbb08a3b49a",
  TO_WEB + "facebook/xd_receiver.htm", {
    'doNotUseCachedConnectState': true,
    ifUserConnected: function()
    {
      if(FB_LOGIN === false && typeof(Zehn.no_facebook_redirect) == 'undefined')
      {
        Zehn.login_refresh();
        
        // should just be able to refresh the left
        
        // need to refresh any add comments?
        
        // must refresh navigation
      }
    },
    ifUserNotConnected: function()
    {
      if(FB_LOGIN === true && typeof(Zehn.no_facebook_redirect) == 'undefined')
      {
        window.location = TO_WEB + "facebook/connected?from=" +
          facebook_from + '&destroy_fb_session=true';
      }
    }
  });
  
  if(typeof(FB.Connect) != 'undefined' &&
     typeof(FB.Connect._singleton) != 'undefined')
  {
    var singleton=FB.Connect._singleton;
    singleton._feedStatusRefetch();
  }
});

Zehn.facebook_onlogin = function()
{
  if(typeof(Zehn.no_facebook_redirect) == 'boolean')
  {
    document.fire('facebook:login');
    return;
  }
  window.location = TO_WEB + "facebook/connected/?from=" + facebook_from;
};

Zehn.facebook_comment_onlogin = function()
{
  document.fire('facebook:login');
  return;
};

Zehn.login_refresh = function()
{
  new Ajax.Request('', {
    parameters: {
      sessid : sessid,
      module : 'Facebook',
      func   : 'login_refresh',
      TO_WEB : TO_WEB
    },
    onComplete: function(response)
    {
      if(response.status.toString()[0] != '2')
        return;
      
      // eval the json
      var data = response.responseText.evalJSON();
      
      // for each element in the json, put content into replace, fire a
      // content updated event
      data.each(function(update)
      {
        if(!$(update.element))
          return;
        
        var el = $(update.element);
        if(typeof(update.replace) != 'undefined')
        {
          el.hide();
          el.insert({ before: update.content });
        }
        else
        {
          el.update(update.content);
        }
        el.fire('content:updated');
        if(typeof(update.replace) != 'undefined')
        {
          el.remove();
        }
      });
      
    }
  });
};
