/*
 * 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() {
      // if the user is logged into joomla but not in friendconnect and
      // is a friendconnect user, log him out from joomla
      if(!FC_CORRECT_LOGIN && FC_JOOMLA_LOGIN && FC_IS_FC_USER) {
        window.top.location.href = FC_LOGOUT_URL;
      }
      
      if (!window.timesloaded && !FC_CORRECT_LOGIN) {
        window.timesloaded = 1;
        var login = document.getElementById('fc_login_button');
          if(login){
            google.friendconnect.renderSignInButton( {
              id : 'fc_login_button'
            });
          }
      } else {
        window.timesloaded++;
      }
      if (window.timesloaded > 1 && !FC_CORRECT_LOGIN) {
        window.top.location.href = FC_BASE_URI + 
          'modules/mod_friendconnect/mod_friendconnect_server.php';
      }
      
      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;
  }();
}

