// frontend_gui.js $Rev: 34023 $ $Date: 2008-08-04 15:59:17 -0700 (Mon, 04 Aug 2008) $
//////////////////
///     GUI    ///
//////////////////

//variables
var cpHist = new Array();//history storage
var cpHistPos = -1;//current history position

var delayWPM;
var delayMin;
var delayMax;
var delayFlag = true;
var delayedOutputs = [];

var smoothScrollInterval = null;
var prevScrollTop = 0;

function appendLog(text, smooth)
{
	//fix formatting
	text = text.replace(/\r\n/g, '<br />');
	text = text.replace(/\r/g, '<br />');
	text = text.replace(/\n/g, '<br />');
	
	prevScrollTop = chatlog.scrollTop;
	setInnerHTML(elChatlog, chatlog.innerHTML + text);
	scrollToLastInput(smooth);
}

function setLog(text)
{
	setInnerHTML(elChatlog, text + "<hr style='display:none;' />");
	scrollToLastInput(false);
}

function setInnerHTML(element, htmlText)
{
	var el = $(element);
	if(el)
	{
		if(document.createRange != null)
		{
			var rng = document.createRange();
			if(rng.createContextualFragment != null)
			{
				//primarily for Mozilla
				rng.setStartBefore(el);
				var htmlFrag = rng.createContextualFragment(htmlText);
				while(el.hasChildNodes())
					el.removeChild(el.lastChild);
				el.appendChild(htmlFrag);
			}
			else
			{
				//primarily for Opera
				el.innerHTML = null;
				el.innerHTML = htmlText;
			}
		}
		else
		{
			//primarily for IE
			el.innerHTML = null;
			el.innerHTML = htmlText;
		}
	}
}

function asyncLoadHtml(elementId, contentUrl)
{
	var m = new Array();
	m["__contentDest__"] = elementId;
	m["__url__"] = contentUrl;
	sendQueue.push(m);
}

function scrollToBottom(elementId)
{
    if(document.getElementById != null)
	{
		var el = document.getElementById(elementId);		
        el.scrollTop = el.scrollHeight;
	}
}

function scrollToLastInput(smooth)
{
    if(document.getElementById != null)
    {
        var bottomPadding = document.getElementById(chatlog.id + "_bottomPadding");
        if(bottomPadding)
        {
            chatlog.removeChild(bottomPadding);
        }
        
        var padHeight = 150;
        if(chatlog.clientHeight)
            padHeight = chatlog.clientHeight;
        var bottomPaddingHTML = "<div id=\"" + chatlog.id + "_bottomPadding\" style=\"height:" + padHeight + "px\"></div>";
        setInnerHTML(elChatlog, chatlog.innerHTML + bottomPaddingHTML);
            
        var targetElement = findScrollToElement();
        if(targetElement != null)
        {
            chatlog.scrollTop = prevScrollTop;
            scrollChatLogTo(targetElement, smooth);
        }
    }
}

function findScrollToElement()
{
    //if the end of the log is question - answer, scroll to the question
    //if the end of the log is answer - answer, scroll to the last answer
    var spanRet = null;
    if(chatlog)
    {
        var spans = chatlog.getElementsByTagName('span');
        for(var i = spans.length - 1; i >= 0; i--)
        {
            if(spans[i].className == "username")
            {
                spanRet = spans[i];
                break;
            }
            else if(spans[i].className == "agentname" || spans[i].className == "enginename")
            {
                if(spanRet != null)//we're at the second from last answer
                    break;
                else//we're at the last answer
                    spanRet = spans[i];
            }
        }
    }
    return spanRet;
}

function elementPosition(obj) {
    var curleft = 0, curtop = 0;
    
    if (obj.offsetParent) {
        curleft = obj.offsetLeft;
        curtop = obj.offsetTop;
        
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        }
    }
    
    return { x: curleft, y: curtop };
}

function scrollChatLogTo(dest, smooth) {
    var bottom = chatlog.scrollHeight - chatlog.clientHeight;
    if(typeof(dest) == "string") {
        if(dest == '--end--') {
            dest = bottom;
        } else {
            var targetElement = document.getElementById(dest);
            if(targetElement != null)
            {
                dest = targetElement;
            }
        }
    }
    if(typeof(dest) == "object") {
        var targetTop = elementPosition(dest).y;
        var logTop = elementPosition(chatlog).y; 
        dest = targetTop - logTop;
    }
    if(typeof(dest) == "number") {
        if(dest > bottom)
            dest = bottom;
            
        if(dest != chatlog.scrollTop) {
            if(smoothScrollInterval != null)
                clearInterval(smoothScrollInterval);
            if(smooth)
                smoothScrollInterval = setInterval("doSmoothScroll(" + dest + ")", 50);
            else
                chatlog.scrollTop = dest;
        }
    }
}

function doSmoothScroll(dest) {
    var jumpDist = Math.ceil((dest - chatlog.scrollTop) / 4.0);
    if(jumpDist != 0)
        chatlog.scrollTop += jumpDist;
    else
        clearInterval(smoothScrollInterval);
}

function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}


///////////////////////////////
//     History Browsing      //
///////////////////////////////

function cpHistGo(url)
{
    if(url)
    {
        cpHist[++cpHistPos] = url;
        cpHist.length = cpHistPos + 1;
		asyncLoadHtml(elContent, url);
    }
}

function cpHistCanBack()
{
	return (!contentIsModal && cpHistPos > 0);
}

function cpHistCanForward()
{
	return (!contentIsModal && cpHistPos < cpHist.length - 1 && cpHistPos != -1);
}

function cpHistBack()
{
    if(cpHistCanBack())
        asyncLoadHtml(elContent, cpHist[--cpHistPos]);
    cpHistUpdateButtons();
}

function cpHistForward()
{
    if(cpHistCanForward())
        asyncLoadHtml(elContent, cpHist[++cpHistPos]);
    cpHistUpdateButtons();
}

function cpHistUpdateButtons()
{
	if(typeof(elBackButton) != "undefined" && typeof(elForwardButton) != "undefined")
	{
		var elBackImg = document.getElementById(elBackButton);
		var elForwardImg = document.getElementById(elForwardButton);
		if(elBackImg && elForwardImg)
		{
			elBackImg.className = cpHistCanBack() ? "leftarrowenabled" : "leftarrowdisabled";
			elForwardImg.className = cpHistCanForward() ? "rightarrowenabled" : "rightarrowdisabled";
		}
	}
}

///////////////////////
///  POPUP METHODS  ///
///////////////////////

var openpage_win;
var openpage_url;
function openpage(url, name, parms)
{
    //window.open(url, name, parms);
    if(!parms)
        parms = "menubar=yes,location=yes,resizable=yes,toolbar=yes,directories=yes,status=yes,width=800,height=600,";
        
    if(openpage_url != url || openpage_win.closed)
    {
        openpage_win = window.open(url,name,parms);
        openpage_url = url;
    }
    openpage_win.focus();
}

function convertAnchorsToJS(html)
{
    //href != "#" with target (single or double quotes)
    html = html.replace(/<a (.*?)href="(?!#)([^"]+)"(.*?)target="([^"]+)"(.*?)>/gi, "<a $1href=\"#\" onclick=\"openpage('$2', '$4');return false;\"$3$5>");
    html = html.replace(/<a (.*?)target="([^"]+)"(.*?)href="(?!#)([^"]+)"(.*?)>/gi, "<a $1href=\"#\" onclick=\"openpage('$4', '$2');return false;\"$3$5>");
    html = html.replace(/<a (.*?)href='(?!#)([^"]+)'(.*?)target='([^"]+)'(.*?)>/gi, "<a $1href=\"#\" onclick=\"openpage('$2', '$4');return false;\"$3$5>");
    html = html.replace(/<a (.*?)target'"([^"]+)'(.*?)href='(?!#)([^"]+)'(.*?)>/gi, "<a $1href=\"#\" onclick=\"openpage('$4', '$2');return false;\"$3$5>");
    //simple href != "#" (single or double quotes)
    html = html.replace(/<a (.*?)href="(?!#)([^"]+)"(.*?)>/gi, "<a $1href=\"#\" onclick=\"openpage('$2', '');return false;\"$3>");
    html = html.replace(/<a (.*?)href='(?!#)([^"]+)'(.*?)>/gi, "<a $1href=\"#\" onclick=\"openpage('$2', '');return false;\"$3>");
    return html;
}

///////////////////////
///  DELAY METHODS  ///
///////////////////////
function DelayedOutput(text, ext, sendtime, smooth)
{
    this.text = text;
    this.ext = ext;
    this.sendtime = sendtime;
    this.smooth = smooth;
}

function delayShow(text, ext, delay, smooth)
{
    var t1 = (new Date()).getTime();
    delay = parseInt(delay);
    if(delayedOutputs.length > 0)
        t1 = delayedOutputs[delayedOutputs.length - 1].sendtime;
    delayedOutputs.push(new DelayedOutput(text, ext, t1 + delay, smooth));
}

function delayTick()
{
    var now = (new Date()).getTime();
    for(var i = 0; i < delayedOutputs.length; i++)
    {
        var output = delayedOutputs[i];
        if(output.sendtime < now)
        {
            if(output.text != "")
                appendLog(output.text, output.smooth);
            hideTyping();
            handleExts(output.ext);
            delayedOutputs.shift();
            i--;
        }
    }
}
setInterval("delayTick()", 10);

function logToFirebug(text)
{
    if(typeof(console) == "object" && typeof(console.log) == "function")
    {
        console.log(text);
    }
}
/*
function embedHiddenIFrame(id, src)
{
    var iframe = document.getElementById(id);
    if(!iframe) {
        iframe = document.createElement('iframe');
        iframe.id = id;
        iframe.width = 100;
        iframe.height = 100;
        iframe.src = src;
        var chatdiv = document.getElementById('chatdiv');
        if(chatdiv && chatdiv.parentNode)
            chatdiv.parentNode.appendChild(iframe);
    } else {
        iframe.src = src;
    }
}
*/

