function onFBLoginReady() {
  checkIfUserIsFBConnected();
}

function checkIfUserIsFBConnected() {
  $.ajax({
      url:'/account/sessions/facebook-login',
      dataType: "json",
      success: function(msg) {
       if (msg.success == true) {
         if (msg.registered == false) {
           userIsRegistered();
         } else {
           location.href = '/';
         }
       } else {
         popupRegisterWithFB();
       }
      }
    });
}

function userIsRegistered() {
  $('.btn_join').trigger('click');
}

function showRegOption(id,show) {
  var otherId = (id + 1) % 2;
  if (show) {
    $("#fbc" +id).fadeIn('fast');
    $("#fbc" +otherId).hide();
    $("#lab" +id).toggleClass("regLabelOn");
    $("#lab" +otherId).toggleClass("regLabelOn",false);
  }else {
    $("#fbc" +otherId).fadeIn('fast');
    $("#fbc" +id).hide();
    $("#lab" +otherId).toggleClass("regLabelOn");
    $("#lab" +id).toggleClass("regLabelOn",false);
  }
}


function doLoginWithFb() {

  $("form#fbConnect").submit(function() {
    $("#fbcErrors").html('<img src="/i/blue-load.gif"/>');
    $.ajax({
      type: "POST",
      url: "/account/sessions/connect-and-login?_service_=fb",
      dataType: "json",
      data: $("form#fbConnect").serialize(),
      success: function(data) {
        processConnectAccountResp(data);
      }
    });
  });
  
}


function processConnectAccountResp(response) {
  if (response.success == true) {
    location.href = '/account/connect/fbinvite';
    $("#fbcErrors").html('');
  }else {
    $("#fbcErrors").html(response.errors);
  }
}

function initPopupEvents() {
  showRegOption(0,true);
  $("#fbReg0").attr("checked","checked");
  $("#fbReg0").change(function(){showRegOption(0, true)});
  $("#fbReg1").change(function(){showRegOption(1, true)});
  $("#fbRegButton").click(function(){location.href = "/account/sessions/register-with-connect?_service_=fb";});
  $("#fbLoginButton").click(doLoginWithFb);
}

function popupRegisterWithFB() {
  //FB.apiClient.get_session().uid
  $.ajax({
    type: "GET",
    url: "/account/signup/facebook",
    cache: false,
    success: function(html) {
      $.facebox(html);
      initPopupEvents();
    }
  });
}

function fbLogout() {
  location.href = '/signout';
}