var s7WC_Globals = new Object();

// START CONFIG
s7WC_Globals["userId"] = (S7WebChatUser == undefined) ? "" : S7WebChatUser;
s7WC_Globals["userUrl"] = (S7WebChatUserUrl == undefined) ? "" : S7WebChatUserUrl;
s7WC_Globals["crossDomain"] = false;
s7WC_Globals["serviceURL"] = "http://community.imaginefx.com/forums/WebChatProxy.aspx";
s7WC_Globals["chatWidth"] = "1600px";
s7WC_Globals["chatHeight"] = "130px";
s7WC_Globals["RefreshRate"] = 10;
s7WC_Globals["mainBoxHeader"] = "<div style='border: 0px solid white; background-color: #B59608 ; text-align: left; padding: 3px;padding-left:8px;'><span style='color:#FFF;font-weight:bold;font-family:Tahoma, Arial, Helveticia;'>ImagineFX Live Chat</span></div>"
s7WC_Globals["styleMainBox"] = "width:720px;border: solid 1px #CCCCCC; background-color: #EBE2BE; margin-bottom: 5px";
s7WC_Globals["styleMessageWindow"] = "width: 710px; height: 300px; padding: 5px; margin-bottom: 4px; border-bottom: solid 1px #CCCCCC; font-family: arial, sans serif; background-color: rgb(255, 255, 255); color: black; overflow: auto;";
s7WC_Globals["styleEditBox"] = "margin-left: 3px; margin-bottom: 3px; margin-right: 0px;";
s7WC_Globals["styleSpeakBtn"] = "margin-left: -1px; margin-bottom: 3px";
s7WC_Globals["styleUsername"] = "font-size: 75%; color: rgb(148,149,151);;";
s7WC_Globals["styleUsernameLink"] = "font-size: 75%; color: rgb(148,149,151);; text-decoration: underline;";
s7WC_Globals["styleMyUsername"] = "font-size: 75%; color: rgb(148,149,151);;";
s7WC_Globals["styleMyUsernameLink"] = "font-size: 75%; color: rgb(148,149,151);; text-decoration: underline;";
s7WC_Globals["isUsernameBold"] = true;
s7WC_Globals["styleMsgCreated"] = "font-size: 75%; color: #444444;";
s7WC_Globals["styleMessage"] = "font-size: 80%; color: black";
s7WC_Globals["styleAllMsgItems"] = "margin-bottom: 2px";
// END CONFIG 

s7WC_Globals["myLastMessage"] = 0;
s7WC_Globals["currSessionId"] = null;
s7WC_Globals["oMessageWin"];
s7WC_Globals["sendHttp"]=false;
s7WC_Globals["updatesHttp"]=false;

/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
    s7WC_Globals["sendHttp"] = new ActiveXObject("Msxml2.XMLHTTP");
    s7WC_Globals["updatesHttp"] = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
    try {
        s7WC_Globals["sendHttp"] = new ActiveXObject("Microsoft.XMLHTTP");
        s7WC_Globals["updatesHttp"] = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
        s7WC_Globals["sendHttp"] = false;
        s7WC_Globals["updatesHttp"] = false;
    }
}
@end @*/
if (!s7WC_Globals["sendHttp"] && typeof XMLHttpRequest!='undefined')
{
    s7WC_Globals["sendHttp"] = new XMLHttpRequest();
    s7WC_Globals["updatesHttp"] = new XMLHttpRequest();
    
    if (s7WC_Globals["sendHttp"].overrideMimeType)
    {
        s7WC_Globals["sendHttp"].overrideMimeType('text/xml');
        s7WC_Globals["updatesHttp"].overrideMimeType('text/xml');
    }
}

window.onload = S7WC_Initialize;

function S7WC_CatchEnterKey(evt)
{
	// When the user clicks ENTER during entry of a message, cause this to submit the message
	//
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13 || charCode == 3)
    {
		S7WC_OnSubmit();
        return false;
    } else {
        return true;
    }
}

function S7WC_Initialize()
{
	var oBox = document.getElementById("S7WebChat");
	oBox.style.cssText = s7WC_Globals["styleMainBox"];
	
    // Setup messages window
    // 
    var innerHtml = "";
    if (s7WC_Globals["mainBoxHeader"] != "")
    {
		innerHtml += s7WC_Globals["mainBoxHeader"];
    }
    innerHtml += "<div id='S7WCMessages' style='"+s7WC_Globals["styleMessageWindow"]+"'></div>";
    if (s7WC_Globals["userId"] != "") // check logged on
    {
        innerHtml += "<input id='S7WCInput' type='text' size='40'>&nbsp;<input id='S7WCSubmit' type='submit' value='Speak'>";
    }
    oBox.innerHTML = innerHtml;
    s7WC_Globals["oMessageWin"] = document.getElementById("S7WCMessages");
     
    // Make sure URL is absolute for XMLHTTP to use
    //
    if (s7WC_Globals["serviceURL"].substr(0, 4).toLowerCase() != "http")
    {
        var myUrl = document.location.href;
        myUrl = myUrl.substr(0, myUrl.lastIndexOf("/")) + "/" + s7WC_Globals["serviceURL"];
        s7WC_Globals["serviceURL"] = myUrl;
    }
    
    // Setup message submission form
    //
    if (s7WC_Globals["userId"] != "") // check logged on
    {
        var oSubmit = document.getElementById("S7WCSubmit");
        oSubmit.style.cssText = s7WC_Globals["styleSpeakBtn"];
        oSubmit.onclick = S7WC_OnSubmit;
        
        var oInput = document.getElementById("S7WCInput");
        oInput.style.cssText = s7WC_Globals["styleEditBox"];
        oInput.onkeydown = S7WC_CatchEnterKey;
    }
    
    // Start retrieving messages...
    //
    S7WC_OnGetMessages();
}

function S7WC_OnSubmit()
{
    var oEdit = document.getElementById("S7WCInput");
    
    // Trim input, and do not accept empty messages
    //
    var oText = oEdit.value.replace(/^\s+|\s+$/, '');
    oEdit.value = "";    
    if (oText  == "")
		return;
    
    S7WC_OnSendMessage(s7WC_Globals["userId"], s7WC_Globals["userUrl"], oText);
    return false;
}

function S7WC_OnSendMessage(userId, userUrl, message)
{
    var xmlhttp = s7WC_Globals["sendHttp"];
       
    var request = new Object();
    request["function"]  = "AddMessage";
    request["userId"] = userId;
    request["userUrl"] = userUrl;
    request["message"] = message;
    var postData = "request="+encodeURIComponent(JSON.stringify(request));
        
    if (s7WC_Globals["crossDomain"] && window.netscape != undefined)
        netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    
    xmlhttp.open("POST", s7WC_Globals["serviceURL"], true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", postData.length);
    xmlhttp.onreadystatechange=function()
    {
        S7WC_OnHandleHTTPCallback(s7WC_Globals["sendHttp"], S7WC_OnSendMessageComplete);
    }
    xmlhttp.send(postData);
}

function S7WC_OnSendMessageComplete(result)
{
    setTimeout("S7WC_OnGetMessages()", 1);
}

function S7WC_OnGetMessages()
{
    var xmlhttp = s7WC_Globals["updatesHttp"];
       
    var request = new Object();
    request["function"]  = "GetMessages";
    request["lastMessage"] = s7WC_Globals["myLastMessage"];
    var postData = "request="+encodeURIComponent(JSON.stringify(request));
        
    if (s7WC_Globals["crossDomain"] && window.netscape != undefined)
        netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    
    xmlhttp.open("POST", s7WC_Globals["serviceURL"], true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", postData.length);
    xmlhttp.onreadystatechange=function()
    {
        S7WC_OnHandleHTTPCallback(s7WC_Globals["updatesHttp"], S7WC_OnGetMessagesComplete);
    }
    xmlhttp.send(postData);
}

function S7WC_OnGetMessagesComplete(result)
{
    if (result["Status"] == "OK")
    {
        // Reset chat if remote chat has changed
        //
        if (s7WC_Globals["currSessionId"] != null && s7WC_Globals["currSessionId"] != result["ConversationId"])
        {
            S7WC_ClearMessages();
            return;
        }
        
        // Ignore these results if have arrived out-of-order (remember, asynchronous HTTP is used!!!)
        //
        if (s7WC_Globals["myLastMessage"] != result["RequestedFrom"])
        {
            return;
        }
        
        s7WC_Globals["currSessionId"] = result["ConversationId"];
        var messages =  result["NewMessages"];
        
        for (var i=0; i<messages.length; i++)
        {
            // Get "safe" representation of the message
            //
            var oW = document.createElement("SPAN");
            var oT = document.createTextNode(messages[i]["Message"]);
            oW.appendChild(oT);
            var parsedText = oW.innerHTML;
            
            // Work out color for username
            //
            var usernameColor;
            if (messages[i]["UserId"] == s7WC_Globals["userId"])
                usernameColor = s7WC_Globals["ownUsernameColor"];
            else {
                if (messages[i]["UserUrl"] != "")
                    usernameColor = s7WC_Globals["usernameLinkColor"];
                else 
                    usernameColor = s7WC_Globals["usernameColor"];
            }
                
            
            // Create html for username
            //            
            var userHtml;
            if (messages[i]["UserId"] == s7WC_Globals["userId"])
            {
				if (messages[i]["UserUrl"] != "")
					userHtml = "<a href='"+messages[i]["UserUrl"]+"' style='"+s7WC_Globals["styleUsernameLink"]+"'>"+messages[i]["UserId"]+"</a>";
				else
					userHtml = "<span style='"+s7WC_Globals["styleUsername"]+"'>"+messages[i]["UserId"]+"</span>";
            } else {
				if (messages[i]["UserUrl"] != "")
					userHtml = "<a href='"+messages[i]["UserUrl"]+"' style='"+s7WC_Globals["styleMyUsernameLink"]+"'>"+messages[i]["UserId"]+"</a>";
				else
					userHtml = "<span style='"+s7WC_Globals["styleMyUsername"]+"'>"+messages[i]["UserId"]+"</span>";            
            }
            if (s7WC_Globals["isUsernameBold"])
				userHtml = "<strong>"+userHtml+"</strong>";
            
            // Create html for created date
            //
            var dateHtml = "<span style='"+s7WC_Globals["styleMsgCreated"]+"'>"+messages[i]["Created"]+"</span>";
            
            // Create html for message text
            //
            var msgHtml = "<span style='"+s7WC_Globals["styleMessage"]+"'>"+parsedText+"</span>";
            
            // Create overall message entry
            //
            var oMsg = document.createElement("div");                        
            oMsg.innerHTML = userHtml+"&nbsp;"+dateHtml+"&nbsp;&nbsp;"+msgHtml+"<br />";
            oMsg.style.cssText = s7WC_Globals["styleAllMsgItems"];
            
            // Append entry to message list
            //
            s7WC_Globals["oMessageWin"].appendChild(oMsg);
            s7WC_Globals["oMessageWin"].scrollTop = s7WC_Globals["oMessageWin"].scrollHeight;
        }
        s7WC_Globals["myLastMessage"] = result["LastMessageCount"];
        
        setTimeout("S7WC_OnGetMessages()", s7WC_Globals["RefreshRate"]);
    }
}

function S7WC_ClearMessages()
{
    s7WC_Globals["currSessionId"] = null;
    s7WC_Globals["myLastMessage"] = 0;   
    
    while (s7WC_Globals["oMessageWin"].hasChildNodes())
    {
        s7WC_Globals["oMessageWin"].removeChild(s7WC_Globals["oMessageWin"].lastChild);
    }
}

function S7WC_OnHandleHTTPCallback(httpObj, OnCompleteHandler)
{
    if (httpObj.readyState == 4)
    {
        // Connection failure error handling for Mozilla
        var httpStatus = null;
        try {
            httpStatus = httpObj.status;
        } catch (e) {
            ;
        }
        if (httpStatus == null)
        {
            //alert("Remote function call failed because it was not possible to connect OR there was a problem with the connection");
        }
        else if (httpStatus == 200) 
        {
            // We dutifully adopt the session id we have been assigned
            //
            var res = JSON.parse(httpObj.responseText);

            OnCompleteHandler(res);
        }
        else if (httpStatus == 500)
        {
            alert("The remote function call failed because the remote Web server suffered an internal error");
        }
        else if (httpStatus == 12029) // IE on Windows
        {
            alert("The remote function call failed because it was not possible to connect to the server");
        }
        else if (httpStatus == 12030) // IE on Windows
        {
            alert("The remote function call failed because there was a problem with the connection");
        }
        else {
            alert("The HTTP-based remote function called failed with status: "+httpStatus);
        }
    }
}

// JSON stuff follows...

Array.prototype.______array = '______array';

var JSON = {
    org: 'http://www.JSON.org',
    copyright: '(c)2005 JSON.org',
    license: 'http://www.crockford.com/JSON/license.html',

    stringify: function (arg) {
        var c, i, l, s = '', v;

        switch (typeof arg) {
        case 'object':
            if (arg) {
                if (arg.______array == '______array') {
                    for (i = 0; i < arg.length; ++i) {
                        v = this.stringify(arg[i]);
                        if (s) {
                            s += ',';
                        }
                        s += v;
                    }
                    return '[' + s + ']';
                } else if (typeof arg.toString != 'undefined') {
                    for (i in arg) {
                        v = arg[i];
                        if (typeof v != 'undefined' && typeof v != 'function') {
                            v = this.stringify(v);
                            if (s) {
                                s += ',';
                            }
                            s += this.stringify(i) + ':' + v;
                        }
                    }
                    return '{' + s + '}';
                }
            }
            return 'null';
        case 'number':
            return isFinite(arg) ? String(arg) : 'null';
        case 'string':
            l = arg.length;
            s = '"';
            for (i = 0; i < l; i += 1) {
                c = arg.charAt(i);
                if (c >= ' ') {
                    if (c == '\\' || c == '"') {
                        s += '\\';
                    }
                    s += c;
                } else {
                    switch (c) {
                        case '\b':
                            s += '\\b';
                            break;
                        case '\f':
                            s += '\\f';
                            break;
                        case '\n':
                            s += '\\n';
                            break;
                        case '\r':
                            s += '\\r';
                            break;
                        case '\t':
                            s += '\\t';
                            break;
                        default:
                            c = c.charCodeAt();
                            s += '\\u00' + Math.floor(c / 16).toString(16) +
                                (c % 16).toString(16);
                    }
                }
            }
            return s + '"';
        case 'boolean':
            return String(arg);
        default:
            return 'null';
        }
    },
    parse: function (text) {
        var at = 0;
        var ch = ' ';

        function error(m) {
            throw {
                name: 'JSONError',
                message: m,
                at: at - 1,
                text: text
            };
        }

        function next() {
            ch = text.charAt(at);
            at += 1;
            return ch;
        }

        function white() {
            while (ch != '' && ch <= ' ') {
                next();
            }
        }

        function str() {
            var i, s = '', t, u;

            if (ch == '"') {
outer:          while (next()) {
                    if (ch == '"') {
                        next();
                        return s;
                    } else if (ch == '\\') {
                        switch (next()) {
                        case 'b':
                            s += '\b';
                            break;
                        case 'f':
                            s += '\f';
                            break;
                        case 'n':
                            s += '\n';
                            break;
                        case 'r':
                            s += '\r';
                            break;
                        case 't':
                            s += '\t';
                            break;
                        case 'u':
                            u = 0;
                            for (i = 0; i < 4; i += 1) {
                                t = parseInt(next(), 16);
                                if (!isFinite(t)) {
                                    break outer;
                                }
                                u = u * 16 + t;
                            }
                            s += String.fromCharCode(u);
                            break;
                        default:
                            s += ch;
                        }
                    } else {
                        s += ch;
                    }
                }
            }
            error("Bad string");
        }

        function arr() {
            var a = [];

            if (ch == '[') {
                next();
                white();
                if (ch == ']') {
                    next();
                    return a;
                }
                while (ch) {
                    a.push(val());
                    white();
                    if (ch == ']') {
                        next();
                        return a;
                    } else if (ch != ',') {
                        break;
                    }
                    next();
                    white();
                }
            }
            error("Bad array");
        }

        function obj() {
            var k, o = {};

            if (ch == '{') {
                next();
                white();
                if (ch == '}') {
                    next();
                    return o;
                }
                while (ch) {
                    k = str();
                    white();
                    if (ch != ':') {
                        break;
                    }
                    next();
                    o[k] = val();
                    white();
                    if (ch == '}') {
                        next();
                        return o;
                    } else if (ch != ',') {
                        break;
                    }
                    next();
                    white();
                }
            }
            error("Bad object");
        }

        function num() {
            var n = '', v;
            if (ch == '-') {
                n = '-';
                next();
            }
            while (ch >= '0' && ch <= '9') {
                n += ch;
                next();
            }
            if (ch == '.') {
                n += '.';
                while (next() && ch >= '0' && ch <= '9') {
                    n += ch;
                }
            }
            if (ch == 'e' || ch == 'E') {
                n += 'e';
                next();
                if (ch == '-' || ch == '+') {
                    n += ch;
                    next();
                }
                while (ch >= '0' && ch <= '9') {
                    n += ch;
                    next();
                }
            }
            v = +n;
            if (!isFinite(v)) {
                error("Bad number");
            } else {
                return v;
            }
        }

        function word() {
            switch (ch) {
                case 't':
                    if (next() == 'r' && next() == 'u' && next() == 'e') {
                        next();
                        return true;
                    }
                    break;
                case 'f':
                    if (next() == 'a' && next() == 'l' && next() == 's' &&
                            next() == 'e') {
                        next();
                        return false;
                    }
                    break;
                case 'n':
                    if (next() == 'u' && next() == 'l' && next() == 'l') {
                        next();
                        return null;
                    }
                    break;
            }
            error("Syntax error");
        }

        function val() {
            white();
            switch (ch) {
                case '{':
                    return obj();
                case '[':
                    return arr();
                case '"':
                    return str();
                case '-':
                    return num();
                default:
                    return ch >= '0' && ch <= '9' ? num() : word();
            }
        }

        return val();
    }
};
