var g_iConversationLineCount = 0;
var g_timerLineMover = 0, g_timerPageMover = 0;
var g_iMoveLeft = 0;
var g_iMoveSize = 0;
var g_sPushedAgentLine = "";
var g_sUserGUID = "";
var g_iUnseenHeight = 0;
var g_iStepCount = 0;
var g_iPendingSlideSize = 0;
var g_iSlideSize = 60;
var g_aWaitingLines = new Array();
var g_bLineOwner = new Array();
var g_bUpButtonDisabled = 0, g_bDownButtonDisabled = 0;

function loadMantiQL(userid)
{
  g_sUserGUID = userid;

  if( window.addEventListener ) 
    window.addEventListener('DOMMouseScroll', wheel, false);
  window.onmousewheel = document.onmousewheel = wheel;
  
  var varBGPanel = document.getElementById("bgpanel");
  if( varBGPanel )
    varBGPanel.style.top = -1000;
  var varPanel = document.getElementById("panel");
  var varOnFlyPanel = document.getElementById("onflypanel");
  if( varOnFlyPanel )
    {
      varOnFlyPanel.style.display = '';
      varOnFlyPanel.style.position = 'absolute';
      varOnFlyPanel.style.left = (document.body.clientWidth-1024)/2;
      varOnFlyPanel.style.top = 250;
      varOnFlyPanel.style.zIndex = 100;
      var sContent = varPanel.innerHTML;
      varOnFlyPanel.innerHTML = sContent;
    }

  var varMessage = document.getElementById("message");
  if( varMessage )
    addConversationLine(varMessage.innerHTML, 1);

  positionScrollButtons();
}

function onSubmitQuery(form)
{
  // add conversation line
  if( g_timerLineMover == 0 )
    addConversationLine(form.userquery.value, 0);
  else
    pushConversationLine(form.userquery.value, 0);

  var parameters = "command=QRY&USER="+g_sUserGUID+"&QUERY="+escape(form.userquery.value);
  // send the response
  makePOSTRequest("/run_answergrid.cmd", parameters, function() { onResponse() });

  form.userquery.value = '';

  return false;
}

function onResponse()
{
  if ( req.readyState == 4 && req.status == 200)
    {
      if( g_timerLineMover == 0 && g_timerPageMover == 0 )
	addConversationLine(req.responseText, 1);
      else
	pushConversationLine(req.responseText, 1);
    }
}

function pushConversationLine(msg, is_agent)
{
  g_aWaitingLines.push(msg);
  g_bLineOwner.push(is_agent);
}

function addConversationLine(msg, is_agent)
{
  // calculate the height of this new message
  var iMsgHeight = getMessageHeight(msg);

  // position the message behind panel
  positionConversationLine(msg, is_agent, iMsgHeight);

  // move up existing messages
  moveConversationLines(iMsgHeight+2);
}

function getMessageHeight(msg)
{
  var varBGPanel = document.getElementById("bgpanel");
  if( varBGPanel )
    {
      varBGPanel.innerHTML = msg;
      var iHeight = parseInt(varBGPanel.clientHeight)+10;
      if( iHeight < 30 ) iHeight = 30;
      return iHeight;
    }
  return 30;
}

function positionConversationLine(msg, is_agent, msg_height)
{
  var varConversationPanel = document.getElementById("conversationpanel");
  var varOnFlyPanel = document.getElementById("onflypanel");
  if( varConversationPanel && varOnFlyPanel )
    {
      var varLine = document.createElement("div");
      var varInLine = document.createElement("div");
      varInLine.setAttribute("width", "100%");
      varLine.appendChild(varInLine);

      varLine.setAttribute("id","clinetable_"+g_iConversationLineCount);

      var sMsgLine = "<table cellpadding=0 cellspacing=0 height="+msg_height+" class=ConversationLine><tr>";
      sMsgLine += "<td width=20 align=right class=MidText style='padding-right:5px;color:#C0C0C0' nowrap><small>"+(g_iConversationLineCount+1)+"</small></td>";
      var cColor = "";
      if( is_agent == 1 )
	{
	  cColor = "#D5F6CE";
	  sMsgLine += "<td width=10 bgcolor=#83e96f nowrap>&nbsp;</td>";
	  sMsgLine += "<td width=50 bgcolor=#D5F6CE align=right nowrap><b>AG :</b></td>";
	}
      else
	{
	  cColor = "#DBF3FF";
	  sMsgLine += "<td width=10 bgcolor=b5ebfb nowrap>&nbsp;</td>";
	  sMsgLine += "<td width=50 bgcolor=#DBF3FF align=right nowrap><b>You :</b></td>";
	}
      sMsgLine += "<td bgcolor="+cColor+" width=100% style='padding-left:10px'>"+msg+"</td>";
      sMsgLine += "</tr></table>";
      varInLine.innerHTML = sMsgLine;

      varLine.style.display = 'block';
      varLine.style.position = 'absolute';
      varLine.style.left = (document.body.clientWidth-600)/2-30;
      varLine.style.right = (document.body.clientWidth+600)/2+30;
      varLine.style.height = msg_height;
      varLine.style.top = parseInt(varOnFlyPanel.style.top)-15;
      varLine.style.zIndex = 90;

      varConversationPanel.appendChild(varLine);
      g_iConversationLineCount++;
    } 
}

function moveConversationLines(height)
{
  g_iMoveLeft = height;
  g_iMoveSize = height/4;
  g_timerLineMover = setTimeout("moveLines()", 100);
}

function moveLines()
{
  var iMove = g_iMoveSize;
  if( g_iMoveLeft < iMove )
    iMove = g_iMoveLeft;

  for(var i = 0; i < g_iConversationLineCount; i++ )
    {  
      var varConversationLine = document.getElementById("clinetable_"+i);
      if( varConversationLine )
	{
	  varConversationLine.style.top = parseInt(varConversationLine.style.top) - g_iMoveSize;

	  if( i == 0 )
	    {
	      if( parseInt(varConversationLine.style.top) < 0 )
		g_iUnseenHeight = -parseInt(varConversationLine.style.top);
	      else
		g_iUnseenHeight = 0;
	    }
	  var iTop = parseInt(varConversationLine.style.top);
	  if( iTop < 0 ) iTop = 0;
	  var opacity = 0.15+iTop/100;
	  //varConversationLine.style.filter = 'alpha(opacity=' + 100*opacity + ');';
	  //varConversationLine.style.opacity = opacity; 
	}
    }
  
  updateScrollButtons();

  g_iMoveLeft -= g_iMoveSize;
  if( g_iMoveLeft > 0 )
    g_timerLineMover = setTimeout("moveLines()", 100);
  else
    {
      g_iMoveLeft = 0;
      g_timerLineMover = 0;
      
      if( g_aWaitingLines.length > 0 )
	{
	  var sPushedAgentLine = g_aWaitingLines.shift();
	  var bIsAgent = g_bLineOwner.shift();
	  addConversationLine(sPushedAgentLine, bIsAgent);
	}
      else if( g_iPendingSlideSize > 0 )
	{
	  slidePage(g_iPendingSlideSize);
	  g_iPendingSlideSize = 0;
	}
    }
}

function movePage()
{
  var varOnFlyPanel = document.getElementById("onflypanel");
  if( parseInt(varOnFlyPanel.style.top) == document.body.clientHeight-63 && g_iUnseenHeight == 0 && g_iMoveSize < 0 )
    {
      clearTimeout(g_timerLineMover);
      g_iMoveLeft = 0;
      g_iStepCount = 0;
      g_timerLineMover = 0; 
      return;
    }

  var iMove = g_iMoveSize;
  if( g_iMoveLeft < iMove )
    iMove = g_iMoveLeft;

  var bStopSliding = 0;
  var iPanelTop = parseInt(varOnFlyPanel.style.top);

  if( iPanelTop-g_iMoveSize < 250 )
    {
      g_iMoveSize = iPanelTop-250;
      bStopSliding = 1;
    }

  var iLastY = 0;
  var varConversationLine = document.getElementById("clinetable_"+(g_iConversationLineCount-1));
  if( varConversationLine )
    iLastY = parseInt(varConversationLine.style.top)+parseInt(varConversationLine.style.height) - g_iMoveSize;

  if( (iLastY+17 >= iPanelTop && iLastY < (document.body.clientHeight-63)) || iLastY < iPanelTop )
    {
      if( iLastY+17+63 > document.body.clientHeight )
	varOnFlyPanel.style.top = document.body.clientHeight-63;
      else if( iLastY+17 < 250 )
	varOnFlyPanel.style.top = 250;
      else
	varOnFlyPanel.style.top = iLastY+17;
    }

  if( g_iMoveSize != 0 )
    {
      for(var i = 0; i < g_iConversationLineCount; i++ )
	{  
	  var varConversationLine = document.getElementById("clinetable_"+i);
	  if( varConversationLine )
	    {
	      varConversationLine.style.top = parseInt(varConversationLine.style.top) - g_iMoveSize;
	      if( i == 0 )
		{
		  if( parseInt(varConversationLine.style.top) < 0 )
		    g_iUnseenHeight = -parseInt(varConversationLine.style.top);
		  else
		    g_iUnseenHeight = 0;
		}
	      var iTop = parseInt(varConversationLine.style.top);
	      if( iTop < 0 ) iTop = 0;
	      var opacity = 0.15+iTop/100;
	      //varConversationLine.style.filter = 'alpha(opacity=' + 100*opacity + ');';
	      //varConversationLine.style.opacity = opacity; 
	    }
	}
    }

  if( g_iUnseenHeight == 0 )
    bStopSliding = 1;

  updateScrollButtons();

  g_iMoveLeft -= g_iMoveSize;
  g_iStepCount--;
  if( g_iStepCount > 0 && bStopSliding == 0 )
    g_timerPageMover = setTimeout("movePage()", 50);
  else
    {
      clearTimeout(g_timerPageMover);
      g_iMoveLeft = 0;
      g_iStepCount = 0;
      g_timerPageMover = 0; 

      if( g_iPendingSlideSize > 0 )
	{
	  slidePage(g_iPendingSlideSize);
	  g_iPendingSlideSize = 0;
	}
      else if( g_aWaitingLines.length > 0 )
	{
	  var sPushedAgentLine = g_aWaitingLines.shift();
	  var bIsAgent = g_bLineOwner.shift();
	  addConversationLine(sPushedAgentLine, bIsAgent);
	}
    }
}

function slidePage(height)
{
  if( g_timerPageMover == 0 && g_timerLineMover == 0 )
    {
      g_iMoveLeft = height;
      g_iStepCount = 3;
      g_iMoveSize = height/g_iStepCount;
      g_timerPageMover = setTimeout("movePage()", 50);
    }
  else
    {
      g_iPendingSlideSize += height;
    }
}

function handle(delta) 
{
  var varOnFlyPanel = document.getElementById("onflypanel");
  if (delta < 0)
    {
      // slide down the whole panel
      if( g_iUnseenHeight > 0 )
	slidePage(-g_iSlideSize);
    }
  else
    {
      // slide up the whole panel
      if( parseInt(varOnFlyPanel.style.top) > 250 )
	slidePage(g_iSlideSize);
    }
}

function wheel(event)
{
  var delta = 0;
  if (!event)
    event = window.event;
  if (event.wheelDelta)
    {
      delta = event.wheelDelta/120;
      if (window.opera)
	delta = -delta;
    }
  else if (event.detail) 
    {
      delta = -event.detail/3;
    }
  if (delta)
    handle(delta);
  if (event.preventDefault)
    event.preventDefault();
  event.returnValue = false;
}


function makePOSTRequest(url, parameters, callback)
{
    // Mozilla, Safari,...
    if( window.XMLHttpRequest )
    {
        req = new XMLHttpRequest();
        if (req.overrideMimeType)
	        req.overrideMimeType('text/xml');
    }
    // IE
    else if( window.ActiveXObject )
    {
        try {
	  req = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
        try
        {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) {}
        }
    }
    
    if( !req )
    {
        alert('Cannot create XMLHTTP instance');
        return false;
    }

    req.onreadystatechange = callback;
    try {
      req.open("GET", url+"?"+parameters, true);
    } catch (e) {
      alert(e); 
    }

    req.send(null);
}


function positionScrollButtons(show)
{
  var varConversationLine = document.getElementById("clinetable_0");
  var varButton = document.getElementById("upbutton");

  varButton.style.top = 5;
  if( show == 1 )
    {
      varButton.style.display = '';
      varButton.style.position = 'absolute';
    }
  varButton.style.left = parseInt(varConversationLine.style.right)-26;

  varButton = document.getElementById("downbutton");
  if( show == 1 )
    {
      varButton.style.display = '';
      varButton.style.position = 'absolute';
    }
  varButton.style.top = 5;
  varButton.style.left = parseInt(varConversationLine.style.right)-5;
}

function disableScrollButton(id)
{
  varButton = document.getElementById(id);
  varButton.style.opacity = 0.3;
  varButton.style.filter = "alpha(opacity=30)";

  if( id == "upimg" )
    g_bUpButtonDisabled = 1;
  else
    g_bDownButtonDisabled = 1;
}

function enableScrollButton(id)
{
  positionScrollButtons(1);

  varButton = document.getElementById(id);
  varButton.style.opacity = 1;
  varButton.style.filter = "alpha(opacity=100)";

  if( id == "upimg" )
    g_bUpButtonDisabled = 0;
  else
    g_bDownButtonDisabled = 0;
}

function hideScrollButtons()
{
  var varButton = document.getElementById("upbutton");
  varButton.style.display = 'none';
  varButton = document.getElementById("downbutton");
  varButton.style.display = 'none';
}

function updateScrollButtons()
{
  if( g_iUnseenHeight == 0 )
    disableScrollButton("upimg");
  else
    enableScrollButton("upimg");

  var varOnFlyPanel = document.getElementById("onflypanel");
  if( parseInt(varOnFlyPanel.style.top) == 250 )
    disableScrollButton("downimg");
  else
    enableScrollButton("downimg");

  if( g_bUpButtonDisabled == 1 && g_bDownButtonDisabled == 1 )
    hideScrollButtons();
}

function goUpInPage()
{
  if( g_bUpButtonDisabled == 0 )
    slidePage(-80);
}

function goDownInPage()
{
  if( g_bDownButtonDisabled == 0 )
    slidePage(80);
}
