<{include file="header.tpl"}>
<body leftmargin="4" topmargin="4" marginwidth="4" marginheight="4" onLoad="loadContents()">
<script language="Javascript">
var staffname = "<{$staffname}>";
var chatstatus = 0;
var requestcount = 0;

function updateChatStatus(newchatstatus)
{
	chatstatus = newchatstatus;
	if (chatstatus == 3)
	{
		window.parent.doWinappLoop = false;
	}
}

function writeToDoc(data) {
	document.open();
	document.write(data);
	document.close();
}

function writeToDiv(data) {
	var divobj = browserObject("buffer");
	divobj.innerHTML = divobj.innerHTML+data;

	if (typeof(scrollBy) != "undefined")
	{
		window.scrollBy(0, 6000);
	} else if (typeof(scroll) != "undefined") {
		window.scrollBy(0, 6000);
	}
}

function displaySelfMessage(staffmsg) {
	if (chatstatus == 2)
	{
		var towrite = "<span class='staffname'>"+htmlize(staffname)+":</span><span class='staffmessage'>&nbsp;"+htmlize(staffmsg)+"</span><BR />";

		writeToDiv(towrite);	
	} else if (chatstatus == 1) {
		displayMessage("<{$language[errorchatnotstarted]}>");
	} else {
		displayMessage("<{$language[errorchatended]}>");
	}
}

function clearText()
{
	var divobj = browserObject("buffer");
	divobj.innerHTML = "";

	displayMessage("<b><{$language[fullname]}>: </b><{$fullname}><br/><b><{$language[email]}>: </b><{$email}><br/><b><{$language[department]}>: </b><{$department}>");
}

function startViewShare(url)
{
	window.external.JSOpenURL('<{$chatsessionid}>', url);
}

function displayStatusMessage(dispmsg) {
	writeToDiv("<span class='chatstatusmsg'>"+dispmsg+"</span><br />");
}

function displayMessage(dispmsg) {
	writeToDiv("<table width='100%'  border='0' cellspacing='0' cellpadding='1'><tr><td bgcolor='#CCCCCC'><table width='100%'  border='0' cellspacing='0' cellpadding='3'><tr><td bgcolor='#F7F7EF'><font face='Verdana, Arial, Helvetica' size='2'><div style='FONT-SIZE: 11px; COLOR: #333333; FONT-FAMILY: Verdana, Arial;'>"+ dispmsg +"</span></font></td></tr></table></td></tr></table><br />");
}

// =========== XML HTTP REQUEST STUFF ==============
var xmlhttp;
var xmlaction = "";
var xmlsubset = "";

function AjaxAlert(nosupport)
{
  if (!nosupport)
  {
    alert("XMLHttpRequest::open failed!  This usually occurs due to the URL of your Kayako installation being different from the one specified under Admin CP >> Settings >> General.  Due to limitations inherent in AJAX, the product URL needs to be exactly the same as the one specified in the settings; this includes \"www.\" and trailing slashes.");
  }
  else
  {
    alert("This browser does not appear to have AJAX support.  Please update to a current edition of a major browser, such as IE, Firefox, Safari, Opera or Konqueror.  If you are using such a browser already, check if AJAX support is turned off in your preferences.");  
  }
}

/*
 * Loads a URL through Ajax
 */
function loadXMLHTTPRequest(url)
{
  if (window.XMLHttpRequest)
  {
    // Not Internet Explorer
    try
    {
      xmlhttp = new XMLHttpRequest();
    }
    catch (e)
    {
      // Appears as if Ajax is not even supported.
      AjaxAlert(true);
    }
    
    if (xmlhttp)
    {
      xmlhttp.onreadystatechange = processStatusChange;
      
      try
      {
        xmlhttp.open("POST", url, true);
        xmlhttp.send("");
      }
      catch (e)
      {
         AjaxAlert(false);
      }               
    }
  }
  else if (window.ActiveXObject)
  {
    // Internet Explorer
    try
    {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
      try
      {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
        // Appears as if Ajax is not even supported.
        AjaxAlert(true);
      }
    }

    if (xmlhttp)
    {
      xmlhttp.onreadystatechange = processStatusChange;

      try
      {
        xmlhttp.open("POST", url, true);
        xmlhttp.send();
      }
      catch (e)
      {
        AjaxAlert(false);
      }
    }
  }
}

var doWinappLoop = true;
function processStatusChange()
{ 
  // If the ajax object is in the "completed" state
  if (xmlhttp.readyState == 4)
  {
    // Try, because .status can throw an exception
    try
    {
      // Try to read the status response.
      // Note that this can throw an exception when the connection has been dropped.
      if (xmlhttp.status == 200)
      {
        var xml;
        xml = xmlhttp.responseXML;
        
        if (!xml)
        {
          alert("Invalid response received from server: " + xmlhttp.responseText);
        }
        else
        {
          chunks = xml.getElementsByTagName('chunk');
          
          if (chunks.length)
          {
            for (var i = 0; i < chunks.length; i++)
            {
              chunk = chunks[i];
              processChatChunk(chunk);
            }
          }
        }
 
        // Reset the timer so this runs again in n seconds
        if (window.parent.doWinappLoop)
        {
          setTimeout("loadContents();", <{$refreshinterval}>);
        }
      }
      else if (xmlhttp.status == 12029)
      {
        // 12029 is unable to establish connection.
        // Reset the timer and bail.
        setTimeout("loadContents();", <{$refreshinterval}>);
      }
    }
    catch (e)
    {
      // If .status throws, just reset the timer and bail.
      setTimeout("loadContents();", <{$refreshinterval}>);
    }
  }
}

var isUserTyping = false;
function processChatChunk(chunk) {
//	var debugBuffer = browserObject("debugbuffer");
//	if (!debugBuffer)
//	{
//		return false;
//	}

	chunktype = chunk.getElementsByTagName('type')[0].firstChild.nodeValue;
	requestcount++;
	
//	var divobj = browserObject("status");
//	divobj.innerHTML = requestcount;
//	debugBuffer.value = debugBuffer.value+"Chunk Type: "+chunktype+"\n";

	var shouldResetTyping = false;

	if (chunktype == 'message')
	{
		chunkmessage = chunk.getElementsByTagName('message')[0].firstChild.nodeValue;
		if (chunkmessage)
		{
			displayNewLine();
			displayMessage(chunkmessage);
			doMessageAlert();
		}
	} else if (chunktype == 'clientmessage') {
		chunkmessage = chunk.getElementsByTagName('message')[0].firstChild.nodeValue;
		chunkname = chunk.getElementsByTagName('clientname')[0].firstChild.nodeValue;
		if (chunkmessage && chunkname)
		{
			writeToDiv("<span class='clientname'>"+ chunkname +":</span><span class='clientmessage'>&nbsp;"+decode64(chunkmessage) + "</span><BR />");
			doMessageAlert();
						
			shouldResetTyping = isUserTyping;
		}
	} else if (chunktype == 'pushimage') {
		chunkurl = chunk.getElementsByTagName('url')[0].firstChild.nodeValue;
		if (chunkurl)
		{
			pushImage(chunkurl);
			doMessageAlert();
			
			shouldResetTyping = isUserTyping;
		}
	} else if (chunktype == 'pushcode') {
		chunkcode = chunk.getElementsByTagName('code')[0].firstChild.nodeValue;
		if (chunkcode)
		{
			pushStart();
			pushCode(chunkcode);
			pushEnd();
			doMessageAlert();
			
			shouldResetTyping = isUserTyping;
		}
	} else if (chunktype == 'viewshare') {
		chunkurl = chunk.getElementsByTagName('url')[0].firstChild.nodeValue;
		if (chunkurl)
		{
			startViewShare(chunkurl);
			doMessageAlert();
		}
	} else if (chunktype == 'usertyping') {
		chunkname = chunk.getElementsByTagName('name')[0].firstChild.nodeValue;
		if (chunkname)
		{
			if (!isUserTyping)
			{
				isUserTyping = true;
				doUserTyping(chunkname);
			}
		}
	} else if (chunktype == 'redirect') {
		chunkurl = chunk.getElementsByTagName('url')[0].firstChild.nodeValue;
		if (chunkurl)
		{
			parent.window.location.href = chunkurl;
		}
	} else if (chunktype == 'chatstatus') {
		chunkstatus = chunk.getElementsByTagName('status')[0].firstChild.nodeValue;
		if (chunkstatus)
		{
			updateChatStatus(chunkstatus);
//			debugBuffer.value = debugBuffer.value+"Chunk Status set to: "+chunkstatus+"\n";
		}
	}
	
	if (shouldResetTyping)
	{
		// We have received a message since we received a "usertyping" event;
		// reset the istyping event.
		resetUserTyping();
		isUserTyping = false;
	}
}

function loadContents() {
	//writeToDiv("<{$swiftpath}>winapp/index.php?_m=livesupport&_a=chatloopframe&sessionid=<{$sessionid}>&chatsessionid=<{$chatsessionid}>&visitorsessionid=<{$visitorsessionid}>&chatchildid=<{$chatchildid}>");
	loadXMLHTTPRequest("index.php?_m=livesupport&_a=chatloopframe&sessionid=<{$sessionid}>&chatsessionid=<{$chatsessionid}>&visitorsessionid=<{$visitorsessionid}>&chatchildid=<{$chatchildid}>");
}

function pushImage(url) {
	writeToDiv("<br /><hr size='1'><img src='"+url+"' border='0'><hr size='1'><br />");
}

function getDivHTML()
{
	var divobj = browserObject("buffer");
	return divobj.innerHTML;
}

function printConvo()
{
	window.print();
}

function pushStart() {
	writeToDiv("<br /><hr size='1'>");
}

function pushEnd() {
	writeToDiv("<hr size='1'><br />");
}

function pushCode(htmldata) {
	writeToDiv(htmldata);
}

function displayNewLine() {
	writeToDiv("<br />");
}

function doMessageAlert()
{
	window.external.JSMessageAlert('<{$chatsessionid}>');
}

function doUserTyping(staffname) {
	typingmsg = "<{$language[typingmsg]}>";
	typingmsgfinal = typingmsg.replace("%s", staffname);

	window.external.JSUpdateStatusBar('<{$chatsessionid}>', typingmsg);
}

function resetUserTyping() {
	window.external.JSUpdateStatusBar('<{$chatsessionid}>', '');
}

function startVoiceChat(ipaddress, port) {
	window.external.JSStartVoiceChat('<{$chatsessionid}>', ipaddress, port, "30");
}


function isLiveResponse()
{
	if (window.external.JSIsLiveResponse() == true)
	{
		return true;
	} else {
		return false;
	}
}

bIsLiveResponse = isLiveResponse();

if (!bIsLiveResponse)
{
	alert("<{$language[noliveresponseerror]}>");
}

</script>
<div id="buffer" style="WIDTH: 100%; HEIGHT: 100%; PADDING: 4px;"><table width='100%'  border='0' cellspacing='0' cellpadding='1'><tr><td bgcolor='#CCCCCC'><table width='100%'  border='0' cellspacing='0' cellpadding='3'><tr><td bgcolor='#F7F7EF'><font face='Verdana, Arial, Helvetica' size='2'><div style='FONT-SIZE: 11px; COLOR: #333333; FONT-FAMILY: Verdana, Arial;'><b><{$language[fullname]}>: </b><{$fullname}><br/><b><{$language[email]}>: </b><{$email}><br/><b><{$language[department]}>: </b><{$department}></span></font></td></tr></table></td></tr></table><br /></div>
<!--<div style="display: block;" name="iframeblock">
<iframe src="index.php?_m=livesupport&_a=chatloopframe&sessionid=<{$sessionid}>&chatsessionid=<{$chatsessionid}>&visitorsessionid=<{$visitorsessionid}>&chatchildid=<{$chatchildid}>" name="loopframe" border="1"></iframe>-->
</div>
<!--<div id="status" style="WIDTH: 100%; HEIGHT: 10px; PADDING: 4px; BACKGROUND: #000000; COLOR: #FFFFFF; FONT-WEIGHT: bold; FONT: verdana;">0</div>-->
<!--<textarea name="debugbuffer" id="debugbuffer" rows="2" cols="30" style="BACKGROUND: red; COLOR: white; WIDTH: 100%;"></textarea>-->
</body>
</html>