// File: chat.js
// Version: 1.05
// Desc: javascript file containing functions to
//       support the chat and user interface
//       elements required for ABNet 2.0
//
// Copyright (c) 2002-2008 KimballSoftware 

ABNetApp.Chat.gUsersComposing=[];

var chatBox=null;
var chatLog = [];
var chatForm=null;
var chatComposeTimeOutTask=null;

//========================================================================
//-- Chat User Interface methods -- 

ABNetApp.Chat.init = function () {
    // wire up event handlers for chat fields
    chatBox=document.getElementById('chatBox');
    
    chatForm=document.getElementById('chatForm');
    chatForm.onsubmit = function() { chatSendMsg(chatForm); return false; };
    
    ABNetApp.Chat.sendButton = document.getElementById('sendbutton');

    var gestureList = document.getElementById('gestureList');
    gestureList.onchange = function() { ABNetApp.Chat.uiTriggerGesture(gestureList); return true; }

    var messageFld = document.getElementById('message');
    messageFld.onkeypress = function() { chatEmpty(messageFld); chatKey(messageFld); return true; };
    messageFld.onclick = function() {  chatEmpty(messageFld); return true; };
    messageFld.value = '<Type here, then press enter to send a message>';

    ABNetApp.Chat.append(ABNetApp.welcome);

    try { f.message.focus();} catch(e) {;}
};

ABNetApp.Chat.resize = function () {

};

ABNetApp.Chat.append = function (newMsg) {
  var lines=new Array();
  var newMsgs=new Array();

  try {
    newMsgs=newMsg.split('\n');
        
    lines=chatBox.value.split('\n');
        
    while ( lines.length >= (ABNetApp.Chat.maxChatLines) ) {
      chatLog.push(lines.shift().replace(/\r/g,''));
    }
        
    while ( (l=newMsgs.shift()) ) {
      lines.push(l.replace(/\r/g,''));
    }
        
    chatBox.value = lines.join('\n');
        
    chatBox.scrollTop = chatBox.scrollHeight;
  }
  catch(e) {;}
};

function chatSendMsg(f) {
  var msgFld = f.message;
  if ( msgFld.value.length > 0 ) {
    if ( chatComposeTimeOutTask ) {
      clearTimeout(chatComposeTimeOutTask);
      chatComposeTimeOutTask=null;
    }
    var msg = ABNetApp.User.me.username + ': ' + msgFld.value;
    if ( msgFld.value.indexOf("/g") == 0 ) {
      var gIndx = parseInt(msgFld.value.substr(2));
      sendGesture(gIndx);
    }
    else {
      ABNet.SendToAllExcept(ABNetApp.User.me.uniqID,'onChat',escape(msg));
    }
    ABNetApp.Chat.append(msg);
    ABNetApp.Scene.setFieldValue('ABNetSharedEvents', 'groupChat', msgFld.value);
    msgFld.value='';
  }
  try { f.message.focus();} catch(e) { ;}
  return false;
}

function chatEmpty(messageFld) {
  if ( !messageFld.inited ) {
    messageFld.inited=true;
    messageFld.value='';
    ABNetApp.Chat.sendButton.disabled=false;
    // enable the key press now that we are inited
    messageFld.onkeypress = function() { chatKey(messageFld); return true; };
  }
}

function chatComposeTimeOut() {
  ABNet.SendToAllExcept(ABNetApp.User.me.uniqID, 'onCompose', '0');
  chatComposeTimeOutTask=null;
}

function chatKey(fld) {
  if ( chatComposeTimeOutTask == null ) {
    ABNet.SendToAllExcept(ABNetApp.User.me.uniqID, 'onCompose', '1');
    chatComposeTimeOutTask = setTimeout('chatComposeTimeOut()',parseInt(ABNetApp.Chat.composeTimeout*1000));
  }
}

function ABNetApp.Chat.chatStatusMsg(p) {
  var sMsg='';

  try {
    var userTyping=[];

    if ( p && p.typing == true ) {
      userTyping.push(p);
    }

    while( (np=ABNetApp.Chat.gUsersComposing.pop()) ) {
	// skip me, and existing entries
	if ( p && !p.isMe && p.uniqID != np.uniqID ) { 
	userTyping.push(np);
      }
    }

    for ( var i=0; i < userTyping.length; i++ ) {
      if ( sMsg.length > 0 ) { sMsg += ','; }
      np = userTyping[i];
      sMsg += unescape(np.username);
    }

    if ( sMsg.length ) {
      if ( userTyping.length > 1 ) {
	sMsg = sMsg + ' are writing messages';
      }
      else {
	sMsg += ' is writing a message.';
      }
    }
    ABNetApp.Chat.gUsersComposing = userTyping;
  }
  catch(e) {
      alert(e.message); sMsg = '';
  }

  if ( sMsg.length ) {
    window.status=sMsg;
  }
  else {
    window.status=DEF_STATUS;
  }
}

function ABNetApp.Chat.uiTriggerGesture(c) {
    gL = document.getElementById('gestureList');

    if ( gL.length > 0 && gL.value > 0 ) {
	sendGesture(gL.value);
	// revert the drop down selection to the default label
	setTimeout( function (){ gL.selectedIndex=0; }, 1000);
    }
};

function ABNetApp.Chat.uiSetGestureList(v) {
  if ( false ) { alert('gesture count='+v.length + ', ' + v.join(',')); }

  var sl=document.getElementById('gestureList');

  for ( i=sl.options.length-1; i >=0; i-- ) {
    sl.options.remove(i);
  }
  var nO = document.createElement("OPTION");
  nO.text = "- GESTURE -";
  sl.options.add(nO,0);
  for ( i=0; i < v.length; i++ ) {
    nO = document.createElement("OPTION");
    nO.text = v[i];
    nO.value = i+1;
    sl.options.add(nO,-1);
  }
};

function ABNetApp.Chat.uiUpdateUserList() {
  var theUserList=document.getElementById("theUserList");

  if ( theUserList ) {
    var newData='<TABLE width="100%;" border=0>';
    var pList = ABNetApp.Comm.personList.toArray();
    newData='<TABLE width="100%;" border=0>';
    for ( i=0; i < pList.length; i++ ) {
      p = pList[i];
      newData+='<TR>';
      newData+='<TD style="width: 100%; font-size: .7em" align="right">';
      newData+=unescape(p.username);
      newData+='</TD>';
      newData+='</TR>';
    }
    newData+='</TABLE>\n';
    theUserList.innerHTML=newData;
  }
};

function sendGesture(n) {
    ABNet.SendToAll('onGesture', n);
}

function fix3dsize() {
    var d = document.all;
    var headerH = d.header.offsetHeight;
    var chatAreaH = d.chatArea.offsetHeight;
    var footerH = d.footer.offsetHeight;
    var _3dH = document.body.clientHeight - (headerH + footerH + chatAreaH + (0));
    try {
	document.all.CC3D.height=_3dH;
	document.body.style.overflow='hidden';
    } catch(e) { ; }
}

function selectField(el) {
  if ( el.createTextRange ) {
    var v = el.value;
    var r = el.createTextRange();
    r.moveStart("character", 0); 
    r.moveEnd("character", el.value.length); 
    r.select();
  }
}
