var userList = new Array();
var userListHash = new Array();
var lastLat = null;
var lastLng = null;
var userOnMapEnabled = true;
var savedUserList;
var openMyPubling=false;
var myPublingAlreadyOpened = false;
var statusObjectOnProfile = null;


function getUserOnMap(userId){
  if(userId==myLoginStatus.idUser) return myLoginStatus;
  else return userListHash[userId];
}




function enableUserOnMap(){
  userOnMapEnabled = true;
  refreshUsers(savedUserList);
}
function disableUserOnMap(){
  savedUserList = userList;
  for(var i=0; i<userList.length; i++){
    map.deleteMarker('user'+userList[i].idUser);
  }
  userList = new Array();
  userOnMapEnabled = false;
}




function refreshUsers(newUserList){
  if(userOnMapEnabled){
    var activeUserListHash = new Array();
    var listChanged = false;
    for(var i=0; i<newUserList.length; i++){
      activeUserListHash[newUserList[i].idUser]=1;
      if(!userListHash[newUserList[i].idUser]){
        listChanged = true;
      }
      userListHash[newUserList[i].idUser]=newUserList[i];
    }
    for(var i=0; i<userList.length; i++){
      if(Object.isUndefined(activeUserListHash[userList[i].idUser])){
        userListHash[userList[i].idUser]=null;
        map.deleteMarker('user'+userList[i].idUser);
        listChanged = true;
      }
    }
    userList.length=0;
    userList = newUserList;
    if(listChanged){
      refreshFollowingsWhereItNeeds();
    }
  	for(var i=0; i<newUserList.length; i++){
      if(myLoginStatus.result=='OK' && newUserList[i].idUser==myLoginStatus.idUser){
        if(openMyPubling && !myPublingAlreadyOpened && (window.location.href.indexOf('noStartupMyPubling')==-1)){
          if(windowModalManager.activeWindowPile.length==0){
            openUserProfil(myLoginStatus.idUser);
          }
        }
        myPublingAlreadyOpened = true;
      }
  		map.addMarker(new CUserOnMap(newUserList[i]));
    }
  } else {
    savedUserList = newUserList;
  }
}


var CUserOnMap = Class.create(CMarkerManager, {
  initialize: function($super, user) {
    var isNotFollowing = Object.isUndefined(followingsListHash[user.idUser]);
    $super('user'+user.idUser,
           new GLatLng(user.lat, user.lng),
           user.login,
           (isNotFollowing?MARKER_TYPE_USER:MARKER_TYPE_USER_FOLLOWING),
           {
							'imageUrl' : getUserAvatarLink(user.idUser, 'map'+(isNotFollowing?'':'_following'+(user.online?'':'_offline')), user.avatar),
        			'shadowUrl' : 'Img/user/userWindowShadow.png',
        			'transparent' : 'Img/user/avatar_map_edge.png',
        			'imageMap' : [0,0,28,0,28,28,0,28,0,0],
        			'iconSize' : new GSize(32, 32),
        			'iconAnchor' : new GPoint(13,31),
        			'infoWindowAnchor' :  new GPoint(13,0),
        			'shadowSize' : new GSize(42, 32),
							'markerClickEvent' : function(){
                openUserProfil(user.idUser);
							},
							'markerMouseOverEvent' : function(){
                startUserHint(user.idUser);
							},
							'markerMouseOutEvent' : function(){
                stopHint();
							}
  				 }
          );
  }
});


function openUserProfil(userId){
  openPoonMessage(-1);
  var user;
  var userOnMap = getUserOnMap(userId);
  if(null==userOnMap || Object.isUndefined(userOnMap) || Object.isUndefined(userOnMap.idUser)){
    user={};
    user.idUser = userId;
  } else {
    user = userOnMap;
  }
  if(user.idUser!=0){
    idPodOpened = -1;
    idUserSelected = user.idUser;
    selectedOnglet=0;
    var ongletList = new Array();
    var ongletColors = new Array();
    var ongletTextColors = new Array();
    if(ongletsAppForm != null) delete ongletsAppForm;
    appList = new Array();

    $('applicationForm.onglets').style.paddingTop = '35px';

    $('applicationForm.subscriptionContainer').innerHTML = '';

    updateUserForm(user);
    controller.requestController('getUser', 'idUser='+user.idUser, updateUserForm);

    if(user.idUser==myLoginStatus.idUser){
      controller.requestController('track', 'section=User&name=Open My Publing');
      appList.push({'idApplication':0, 'name':'What\'s up ?', url:'Applications/MyPubling/Feeds/', position:0, 'icon':'Img/feeds.png', 'textColor':''});
      appList.push({'idApplication':0, 'name':'My Contacts', url:'Applications/MyPubling/Followers/', position:0, 'icon':'Img/followers.png', 'textColor':''});
      appList.push({'idApplication':0, 'name':'My PODs', url:'Applications/MyPubling/Pods/', position:0, 'icon':'Img/communities.png', 'textColor':''});
      appList.push({'idApplication':0, 'name':'My Profile', url:'Applications/MyPubling/Profil/', position:0, 'icon':'Img/profil.png', 'textColor':''});
    } else {
      controller.requestController('track', 'section=User&name=Open User');
      appList.push({'idApplication':0, 'name':'Profile', url:'Applications/MyPubling/Profil/', position:0, 'icon':'Img/profil.png', 'textColor':''});
      appList.push({'idApplication':0, 'name':'Contacts', url:'Applications/MyPubling/Followers/', position:0, 'icon':'Img/followers.png', 'textColor':''});
      appList.push({'idApplication':0, 'name':'PODs', url:'Applications/MyPubling/Pods/', position:0, 'icon':'Img/communities.png', 'textColor':''});
    }

    for(var i=0; i<appList.length; i++){
      ongletList[i] = '<img border="0" width="64px" height="64px" src="'+appList[i].icon+'"><br />'+appList[i].name;
      ongletColors[i] = appList[i].color || '';
      ongletTextColors[i] = appList[i].textColor || '';
    }

    ongletsAppForm = new COnglet(ongletList, 'switchOnglet', {
                                          'color':ongletColors,
                                          'textColor':ongletTextColors});
    openTheApplicationForm();
  }
}


function setUserFollow(status){
  if(myLoginStatus.result=='OK'){
    $('applicationForm.userFollow').disabled = true;
    $('applicationForm.userFollow').href = 'javascript:return false;';
    controller.requestController('setUserFollow', 'idUser='+idUserSelected+'&status='+status, updateUserForm);
  } else {
	openSignUpForm({
		"onCloseLoginSignUp":function(){
			if(myLoginStatus.result=='OK'){
				setUserFollow(1);
			}
		}
	});
  }
}

function oneClickFollow(idUser){
	controller.requestController('setUserFollow', 'idUser='+idUser+'&status=1', updateUserFormOneClick);
}

function updateUserFormOneClick(user){
  var theUser;
  if(!Object.isUndefined(user[0])){
    theUser = user[0];
  } else {
    theUser = user;
  }
  updateUserForm(user);
}

function setUserBlock(status){
  $('applicationForm.userBlock').href = 'javascript:return false;';
	controller.requestController('setUserBlock', 'idUser='+idUserSelected+'&status='+status, updateUserForm);
}

function updateUserForm(user){
  controller.requestController('getMyFollowings', '', refreshFollowingsList);
  var buttons = '';
  var theUser;
  if(!Object.isUndefined(user[0])){
    theUser = user[0];
  } else {
    theUser = user;
  }
  var buttons='';
  if(    theUser.idUser!=myLoginStatus.idUser
      && myLoginStatus.idUser!=0
      && !Object.isUndefined(theUser.followed)){
    if(theUser.login) buttons+=theUser.login+' '+theUser.status+'<br />';
    if(theUser.followed){
      buttons += '<a id="applicationForm.userFollow" href="javascript:setUserFollow(0);" style="font-size:0.6em;">Remove this user from my following list</a>';
    } else {
      buttons += '<input type="button" id="applicationForm.userFollow" onclick="setUserFollow(1);" style="font-size:1.2em;" value="Follow this user" />';
    }
    if(theUser.blocked){
      buttons += ' - <a id="applicationForm.userBlock" href="javascript:setUserBlock(0);" style="font-size:0.6em;">Remove this user from my blocking list</a>';
    } else {
      buttons += ' - <a id="applicationForm.userBlock" href="javascript:setUserBlock(1);" style="font-size:0.6em;">Block this user</a>';
    }
  } else {
    buttons+='<span style="font-size:1.5em; font-weight:bold;">My Publing:</span><br />'
            +theUser.login+' <input type="text" id="applicationForm.statusUpdate" style="width:300px" /><input style="margin-left:5px;" type="button" value="post" onclick="statusObjectOnProfile.submitAction();" />';
    $('applicationForm.subscriptionContainer').innerHTML = '<input id="openMyPubling" name="openMyPubling" type="checkbox"'+(openMyPubling?' checked':'')+' onchange="switchOpenMyPublingOnStartUp(this);" /><label for="openMyPubling" style="font-size:0.8em;"> open on startup</label>';
  }
  $('applicationForm.title').innerHTML =
          '<table cellpadding="5px" style="padding:0; margin:0;">'
        + ' <tr>'
        + '   <td width="90px" valign="top">'
        + '     <div style="position:absolute;">'+getUserAvatar(theUser.idUser, 'big', {"dimension":86,"avatar":theUser.avatar, border:3})+'</div>'
        + '   </td>'
        + '   <td valign="top" style="font-size: 1.2em;">'
        + '     '+buttons
        + '   </td>'
        + ' </tr>'
        + '</table>';

    $('applicationForm.subscriptionContainer').innerHTML = '<a href="http://www.publing.com/user-'+encodeURIComponent(theUser.login)+'">Direct link</a> - <a href="http://www.addthis.com/bookmark.php?v=250&pub=xa-4a4df379403cbc1e" onmouseover="return addthis_open(this, \'\', \'http://www.publing.com/user-'+encodeURIComponent(theUser.login)+'\', \''+theUser.login+'\')" onmouseout="addthis_close()" onclick="return addthis_sendto()"><img src="http://s7.addthis.com/static/btn/sm-share-en.gif" width="83" height="16" alt="Bookmark and Share" style="border:0"/></a>';

  if($('applicationForm.statusUpdate')){
    statusObjectOnProfile = new CInputGestion('applicationForm.statusUpdate', {
                                              'defaultValue':'Put your mood here.',
                                              'initValue': myLoginStatus.status,
                                              'onSubmit':function(status){
                                                $('statusText').value = status;
                                                $('applicationForm.statusUpdate').blur();
                                                statusObject.submitAction();
                                              }});
  }

}

function switchOpenMyPublingOnStartUp(el){
  controller.requestController('openMyPublingOnStartUp', 'status='+(el.checked?'1':'0'), openMyPublingOnStartUpUpdated);
  el.disabled=true;
}

function openMyPublingOnStartUpUpdated(result){
  openMyPubling = result.status;
  $('openMyPubling').disabled = false;
  $('openMyPubling').checked = openMyPubling;
}

function getUserHint(user){
  var content = '<a href="javascript:openUserProfil(\''+user.idUser+'\');" style="font-size:0.7em;">profile</a>';
  if(myLoginStatus.result=='OK'){
    if(Object.isUndefined(followingsListHash[user.idUser])){
      content += ' - '
                +'<a href="javascript:openPrivateChatWindow(\''+user.idUser+'\');" style="font-size:0.7em;">chat</a>'
                +'<br />'
                +'<a href="javascript:oneClickFollow(\''+user.idUser+'\');" style="font-size:0.7em;">follow</a>';
    } else {
      content += '<br />'
                +'<a href="javascript:openPrivateChatWindow(\''+user.idUser+'\');" style="font-size:0.7em;">chat</a>';
    }
  }
  if((myLoginStatus.result=='OK' && user.idUser==myLoginStatus.idUser) || (userListHash[myLoginStatus.idUser] && userListHash[myLoginStatus.idUser].idUser==user.idUser && user.idUser!=0)){
    if(user.idUser==0){
      content = '<a href="javascript:openLoginForm();" style="font-size:0.7em;">Login / Sign Up</a>';
    } else {
      content = '<a href="javascript:openUserProfil(\''+user.idUser+'\');" style="font-size:0.7em;">my publing</a>';
    }
  }
  if(user.idUser!=0){
    content = '<table width="100%">'
            + ' <tr>'
            + '   <td style="padding:0; margin:0; margin-bottom:3px; font-size:0.6em; color:#000;">'
            + '     '+user.following+' <span style="color:#555;">followings</span><br />'+user.followers+' <span style="color:#555;">followers</span>'
            + '   </td>'
            + '   <td style="text-align:right; vertical-align:bottom;">'
            + '     '+content
            + '   </td>'
            + ' </tr>'
            + '</table>';
  } else {
    content = '<table width="100%">'
            + ' <tr>'
            + '   <td style="text-align:right; vertical-align:bottom;">'
            + '     '+content
            + '   </td>'
            + ' </tr>'
            + '</table>';
  }
  content = getUserResume(user)+content;
  return '<div class="mini_profile_'+user.idUser+'">'+content+'</div>';
}

function updateMiniProfile(idUser){
  $$('.mini_profile_'+idUser).each(function(element){
    element.replace(getUserHint(getTheUser(idUser)));
  });
}

function refreshUserHint(idUser){
  var user=userListHash[idUser];
  refreshHintWindow(user, getUserHint(user));
}

function startUserHint(idUser){
  var user=userListHash[idUser];
  startHintOnMarker(user, getUserHint(user));
}