var refreshPrivateChatContactList=null;
var userNewMessages = new Array();
var userUnReadMessages = new Array();
var chatToOpen=0;
var switchTitle = '';
var savedTitle = '';
var savedUnreadMessagesCount = -1;








var timeoutHandlePrivateChat = null;
function clearTimeoutHandlePrivateChat(){
  if(timeoutHandlePrivateChat != null){
    clearTimeout(timeoutHandlePrivateChat);
    timeoutHandlePrivateChat = null;
  }
}
function displayPrivateChat(){
  if(parseFloat($('privateChat').style.left)!=0
      && openedChat == 0
      && chatToOpen!=0)
    openPrivateChatWindow(chatToOpen);
  if(openedChat != 0){
    userUnReadMessages[openedChat] = 0;
    refreshUnreadMessages();
  }
  clearTimeoutHandlePrivateChat();
  $('privateChat').style.left='0px';
}
function hidePrivateChat(){
  clearTimeoutHandlePrivateChat();
  timeoutHandlePrivateChat = setTimeout(actionHidePrivateChat, 200);
}
function actionHidePrivateChat(){
  clearTimeoutHandlePrivateChat();
  var deltaW = 30;
  $('privateChat').style.left='-'+($('privateChat').getWidth()-deltaW)+'px';
}


Array.prototype.sum = function() {
  return (! this.length) ? 0 : this.slice(1).sum() +
      ((typeof this[0] == 'number') ? this[0] : 0);
};


function refreshUnreadMessages(){
  var buttonContent;
  var count = userNewMessages.sum()+userUnReadMessages.sum()
  if(count>0){
    buttonContent='<span style="color:#F00; font-weight:bold;">'+count+'</span>';
    if(savedUnreadMessagesCount < count && count!=0) {
      soundManager.play('bipNewMessage');
      window.focus();
    }
    switchTitle = count+' new message(s)';
  } else {
    buttonContent='<span style="font-weight:bold;">0</span>';
    switchTitle = '';
  }
  savedUnreadMessagesCount = count;
  $('chatBar.privateChatButton').innerHTML = buttonContent;
  if(Object.isFunction(refreshPrivateChatContactList))refreshPrivateChatContactList();
}


function processNotifMessages(messages){
  if(myLoginStatus.result=='OK'){
    if(messages.length!=0){
      for(var i=0; i<messages.length; i++){
        chatToOpen = messages[i].idUser;
        userNewMessages[messages[i].idUser]=messages[i].nbMessages;
      }
      refreshUnreadMessages();
    }
  }
}


function openPrivateChatWindow(idUser){
  chatToOpen=(idUser==null)?0:idUser;
  openPrivateChat(chatToOpen);
}











function getPublicChatMessageContent(idUser, image, message){
  return  '<table width="100%" style="color: inherit;">'
        + ' <tr>'
        + '   <td width="35px" style="vertical-align: top;">'
        + '     '+image
        + '   </td>'
        + '   <td style="vertical-align: top;">'
        + '     '+message
        + '   </td>'
        + ' </tr>'
        + '</table>';
}

function generateHistoryMessageContent(theUser, theMessage){
  var receivedDate = new Date(theMessage.postedDate*1000);
  var timeTxt;
  if(formatDate(new Date())==formatDate(receivedDate)){
    timeTxt = formatHour(receivedDate);
  } else {
    timeTxt = formatDate(receivedDate)+' '+formatHour(receivedDate);
  }

  return getPublicChatMessageContent(theUser.idUser, getUserAvatar(theUser.idUser, 'small', {"dimension":35, border:1}),
              '     <table cellspacing="0"  cellpadding="0" style="color:inherit; font-size:0.7em;" width="100%"><tr><td>'
            + '       '+theUser.login+' says:'
            + '     </td><td align="right">'
            + '       '+timeTxt
            + '     </td></tr></table>'
            + '     <span style="text-align:right; font-weight:bold">'
            + '     '+theMessage.message
            + '     </span>');
}




function isFiltered(value, filter){
  return (''==filter || value.toLowerCase().indexOf(filter.toLowerCase())!=-1);
}

function getUserOnContactList(user){
  var idUser = user.idUser;
  return '<a class="'+((openedChat==idUser)?'contact contact_selected':'contact')+'" href="javascript:openPrivateChat(\''+idUser+'\');">'
        +getUserResume(user)
        +'</a>';
}

function switchOngletPrivateChat(isContactList){
  contactList = isContactList;
  if(isContactList) {
    refreshPrivateChatContactList();
  } else {
    controller.requestController('getHistoryConversation', '', onHistoConvReceived);
  }
  return false;
}

var histoConv = new Array();
function getUserOnHistoConv(idUser){
  for(var i=0; i<histoConv.length; i++){
    if(histoConv[i].idUser==idUser)
      return histoConv[i];
  }
  return null;
}

function onHistoConvReceived(result){
  histoConv = result;
  refreshPrivateChatContactList();
}

var theFilter='';
var contactList = true;
var contactListSaved = '';
var ongletContactListSave = '';
var refreshPrivateChatContactList = function(filter){
  var content = '';

  if(contactList) content = 'Contact - <a href="#" onclick="switchOngletPrivateChat(false);">Conversations</a>';
  else content = '<a href="#" onclick="switchOngletPrivateChat(true);">Contact</a> - Conversations';
  if(ongletContactListSave != content){
    $('privateChat.onglets').innerHTML = content;
    ongletContactListSave = content;
  }

  content = '';

  if(filter===''){
    theFilter = '';
  } else {
    theFilter = filter || theFilter;
  }

  if(contactList){
    var onlineFollowings = '';
    var userOnMapList = '';
    var offlineFollowings = '';

    for(var i=0; i<followingsList.length; i++){
      if(isFiltered(followingsList[i].login, theFilter)){
        var theContent = getUserOnContactList(followingsList[i]);
        if(followingsList[i].onLine==1){
          onlineFollowings += theContent;
        } else {
          offlineFollowings += theContent;
        }
      }
    }

    for(var i=0; i<userList.length; i++){
      if(userList[i].idUser!=myLoginStatus.idUser && isFiltered(userList[i].login, theFilter)){
        if(userList[i].idUser==0){
          userOnMapList +=getUserOnContactList(userList[i]);
        } else {
          if(Object.isUndefined(followingsListHash[userList[i].idUser])){
            userOnMapList += getUserOnContactList(userList[i]);
          }
        }
      }
    }

    if(userOnMapList!=''){
      userOnMapList = getSectionContactList('Users on map', userOnMapList);
    }
    if(onlineFollowings!=''){
      onlineFollowings = getSectionContactList('My contacts online', onlineFollowings);
    }
    if(offlineFollowings!=''){
      offlineFollowings = getSectionContactList('My contacts offline', offlineFollowings);
    }
    content+=onlineFollowings+userOnMapList+offlineFollowings;
  } else {
    var histoContent = '';
    for(var i=0; i<histoConv.length; i++){
      if(isFiltered(histoConv[i].login, theFilter))
        histoContent +=getUserOnContactList(histoConv[i]);
    }
    if(offlineFollowings!=''){
      histoContent = getSectionContactList('Conversations', histoContent);
    }
    content+=histoContent;
  }

  if(contactListSaved != content){
    $('privateChat.contactList').innerHTML = content;
    contactListSaved = content;
  }
}

function getSectionContactList(title, content){
  var titleHTML = (title=='')?'':'<h4 style="margin:0px;">'+title+'</h4>';
  return  titleHTML
        + '<div class="box">'
        + content
        + '</div>';
}

var openedChat = 0;
function openPrivateChat(idChat){
  if(idChat==0){
    if(openedChat!=0) idChat=openedChat;
    else if(!Object.isUndefined(histoConv[0])) idChat = histoConv[0].idUser
  }


  var userHandle = null;
  userNewMessages[idChat] = 0;
  refreshUnreadMessages();

  userHandle = getUserOnHistoConv(idChat);

  if(userHandle == null){
    userHandle = getTheUser(idChat);
  }

  displaySmallProfile(userHandle);

  $('privateChat.title').innerHTML = userHandle.login;
  openedChat = userHandle.idUser;

  openWaitingForm();
  controller.requestController( 'getHistoPrivateChat',
                                'idUser='+openedChat,
                                onHistoReceived);
  setTimeout("$('privateChat.inputText').focus();", 200);
}

function onHistoReceived(histo){
  $('privateChat.histo').innerHTML = '';
  for(var i=histo.length-1; i>=0; i--){
    addToHistory(getPrivateMessage(histo[i]));
  }
  scrollDownHistoPrivateChat();
  closeWaitingForm();
  displayPrivateChat();
}

function onMessageSend(messages){
  addToHistory(getPrivateMessage(messages[0]));
  scrollDownHistoPrivateChat();
}

function processPrivateMessages(messages){
  if(parseFloat($('privateChat').style.left)!=0 && openedChat != 0){
    if(Object.isUndefined(userUnReadMessages[openedChat])) userUnReadMessages[openedChat]=0;
    userUnReadMessages[openedChat]+=messages.length;
    refreshUnreadMessages(savedUnreadMessagesCount + messages.length);
  }
  for(var i=0; i<messages.length; i++){
    addToHistory(getPrivateMessage(messages[i]));
  }
  scrollDownHistoPrivateChat();
}

function addToHistory(content){
  $('privateChat.histo').innerHTML += content;
}

function scrollDownHistoPrivateChat(){
  if($('privateChat.histoScrollArea')) {
    $('privateChat.histoScrollArea').scrollTop = $('privateChat.histoScrollArea').scrollHeight;
  }
}

function getPrivateMessage(message){
  message.postedDate = ((new Date()).getTime()/1000-message.ElapsedTime);
  theUser = getUserOnHistoConv(message.idUser_From);
  if(theUser==null) theUser = getTheUser(message.idUser_From);
  return generateHistoryMessageContent(theUser, message);
}

function stopPrivateChat(){
  controller.requestController('clearActivePrivateChat', '');
}

function displaySmallProfile(user){
  $('privateChat.profileContainer').innerHTML = '<br />'+getUserAvatar(user.idUser, 'big', {"dimension":150})
                                              + '<br /><br /><input type="button" onclick="startVideoChat();" value="Start video chat">';
}
