/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
if (typeof (_FC) === 'undefined') {
  var _FC = {};
  _FC.listener = function() {
    var that = {};
    var onWindowLoad = function(func) {
      if (window.addEventListener) // W3C DOM
        window.addEventListener('load', func, false);
      else if (window.attachEvent) { // IE DOM
        var r = window.attachEvent("onload", func);
        return r;
      }
    };
    that.onWindowLoad = onWindowLoad;
    return that;
  }();
  _FC.onloadHandler = function() {
    var that = {};
    var init = function(st) {
      var req = opensocial.newDataRequest();
      var opt_params = {};
      opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [
          opensocial.Person.Field.ID, opensocial.Person.Field.NAME ];
      req.add(req.newFetchPersonRequest('VIEWER', opt_params), 'viewer');
      req.send(initSuccess);
    }
    var initSuccess = function(data) {
      var viewer = data.get('viewer').getData();
      if (viewer) {
        if (!FC_CORRECT_LOGIN) {
          window.top.location.href = FC_BASE_URI + 'modules/mod_friendconnect/mod_friendconnect_server.php';
          return;
        }
      } else {
        if (FC_JOOMLA_LOGIN) {
          window.top.location.href = FC_LOGOUT_URL;
          return;
        }
      }
      var loginForm = document.getElementById('form-login');
      if (loginForm) {
        var inputs = loginForm.getElementsByTagName('input');
        var i = 0, l = inputs.length, is_logout = false;
        for (i = 0; i < l; i++) {
          if (inputs[i].name == 'task' && inputs[i].value == 'logout') {
            is_logout = true;
            break;
          }
        }
        if (is_logout) {
          loginForm.onsubmit = function() {
            google.friendconnect.requestSignOut();
          };
        }
      }
    };
    that.init = init;
    return that;
  }();
}