function FBCallback(post_id, exception){
  // empty for now
}

function formatAllFBContents(){
  formatFBUserData();
  formatFBAnnouncements();
}

function formatFBUserData(){
  var session = FB.Facebook.apiClient.get_session();
  var user = {};
  if (session) {
    $('#FBLoginButton').hide();
    $('#FBSetupButton').hide();
    // get user profile data
    FB.Facebook.apiClient.fql_query("SELECT name,pic_square,pic_square_with_logo FROM user WHERE uid="+session.uid,
                     function(rows) {
                        if(rows){
                          user = rows[0];
                          if(jQuery.browser.safari || jQuery.browser.msie)
                            $('#FBProfilePic').attr('src',user.pic_square);
                          else
                            $('#FBProfilePic').attr('src',user.pic_square_with_logo);
                          $('#FBProfileName').text(user.name);
                          $('#FBAuthor').text(user.name);
                          $('#FBUid').val(session.uid);
                          $('#FBProfileName').attr('href','http://www.facebook.com/profile.php?ref=profile&id='+session.uid);
                          $('#FBLoginDetails').parent().show();
                        }
                     });
  }
}

function formatFBAnnouncements(){
  var fql_wheres = "";
  try{
    if(!fb_ann_users)
      return;
  } catch(e){ return; }
  for (var i in fb_ann_users){
    fql_wheres += "uid="+fb_ann_users[i];
    if(i < fb_ann_users.length-1)
      fql_wheres += " OR ";
  }
  if(fql_wheres == "")
    return;
  
  FB.Facebook.apiClient.fql_query("SELECT uid,name,pic_square,pic_square_with_logo FROM user WHERE " + fql_wheres,
                   function(rows) {
                      if(rows){
                        for(i in rows){
                          var user = rows[i];
                          $('.FBUid_'+user.uid).find('.FBProfileName').text(user.name)
                              .attr('href','http://www.facebook.com/profile.php?ref=profile&id='+user.uid);
                          if(jQuery.browser.safari || jQuery.browser.msie)
                            $('.FBUid_'+user.uid).find('.FBAnnPic').attr('src',user.pic_square);
                          else
                            $('.FBUid_'+user.uid).find('.FBAnnPic').attr('src',user.pic_square_with_logo);
                        }
                      }
                   });
}

function showFBSetupButton(){
  $('FBSetupButton').show()
                    .click(function(){
                        // user is not connected with the app, display dialog
                        FB.Connect.showPermissionDialog("offline_access", function(perms) {
                         if (perms){
                           location.reload();
                           formatFBUserData();
                         }
                        });
                    });
}

function ajaxCommentAdded(){
  jQuery.ajax({'type': 'post',
               'url': location.href,
               'data': {':operation': 'addFBComment'}
             });
}

var SPLEEN_APP_ID = "409ee6a48d3af14ff3be10f2b203ce88";
var SPLEEN_UID = "100000526443227";

$(document).ready(function(){
  $('.jsCloseAnnouncementForm').click(function(e){
    e.preventDefault();
    $(this).closest('div').slideUp();
  });
  $('.jsOpenAnnouncementForm').click(function(e){
    e.preventDefault();
    var aF = $('.announcementForm');
    $(aF).find('input[name=title]').val('');
    setTimeout(function(){
      $(aF).find('input[name=title]').focus();
      }, 400);
    $(aF).find('textarea').val('');
    $(aF).slideToggle(400);
  });
  
  $('.jsShowFullAnnouncement').click(function(e){
    e.preventDefault();
    $(this).parent().find('.fullAnnouncement').slideToggle();
    $(this).parent().find('.shortAnnouncement').toggle();
    if ($(this).text() == '...mehr')
      $(this).text('..weniger');
    else
      $(this).text('...mehr');
  });
  
  $('.jsRemoveAnnouncement').click(function(e){
    e.preventDefault();
    var elem = $(this);
    var proceed = confirm("Wirklich entfernen? Kann nicht rückgängig gemacht werden.","");
    if (!proceed)
      return false;
    jQuery.ajax({type:'post',
                 url: $(this).attr('href'),
                 data: { ':operation': 'delete',
                         ':redirect': location.href },
                 success: function(){
                    $(elem).closest('li').remove();
                 }
     });
  });
  
  // FB Initial Setup
  FB.init(SPLEEN_APP_ID,"/spleengraz_at/xd_receiver.htm");
  FB.ensureInit(function(){
    // if user has granted app, first function callback, else second
    FB.Connect.ifUserConnected(formatAllFBContents(),showFBSetupButton());
    
    /* USE TO STORE COMMENTS OPTIONALLY Again in spleen profile page */
    FB_RequireFeatures(["Comments"], function() { 
      FB.CommentClient.add_onComment(function(){ajaxCommentAdded()});
    });
  });
  
  var submitContinue = false;
  $('#FBAnnounceForm').submit(function(){
    if(submitContinue)
      return true;
    var form = this;
    var title = $('#FBAnnounceForm input[name=title]').val();
    var content = $('#FBAnnounceForm textarea[name=content]').val();
    
    FB.ensureInit(function() {
      FB.Connect.streamPublish(title + ' ' + content, 
                               null, 
                               null, 
                               SPLEEN_UID, 
                               "spleengraz facebook:", 
                               function(id,exception){
                                if(exception){
                                  alert(exception);
                                  return false;
                                }else{
                                  submitContinue = true;
                                  $(form).find('#post_id').val(id);
                                  $(form).submit();
                                }
                               }, 
                               false, 
                               null);
    },function(){alert('no facebook connection available')});
    return false;
  });
  
  $('.FBComment').click(function(e){
    e.preventDefault();
    stream.addComment($(this).attr('id'),"test comment");
  });

});
