if (typeof tws_Global == "undefined" || typeof tws_Global === null) {
	var tws_Global = {
		loaded: [],
		callbacks: [],
		
		scriptLoaded: function(objName)
		{
			tws_Global.loaded.push(objName);
			setTimeout("tws_Global.runCallbacks()",1);
		},
		
		runCallbacks: function()
		{
			for(var i =0 ; i < tws_Global.callbacks.length; i++)
			{
				if(tws_Global.callbacks[i] !== true)
				{
					try
					{
						tws_Global.callbacks[i]();
						tws_Global.callbacks[i] = true;
					}
					catch(e)
					{
						try { console.log(e); } catch(e) {}
					}
				}
			}
		},
		
		setCallback: function(func)
		{
			try
			{
				if(!func())
				{
					tws_Global.callbacks.push(func);
				}
			}
			catch(e)
			{
				tws_Global.callbacks.push(func);
			}
		}
	}
}

var tws_Account =
{
    scriptId            : "tws_Account_account",
    cookieName          : "tws_Account",
    baseUrl             : "http://account.tibaco.net/",

    siteID              : ((typeof tws_Global.siteID != "undefined" && tws_Global.siteID !== null) ? tws_Global.siteID : null),
    callBackFunction    : null,
    XML                 : null,
    status              : null,
    lastCall            : null,
    errors              : null,
    errorFields         : null,
    credentials         : null,

    setSiteID: function(siteID)
    {
    	tws_Global.siteID = siteID;
        tws_Account.siteID = siteID;
    },

    setCallBackFunction: function(callBackFunction)
    {
        tws_Account.callBackFunction = callBackFunction;
    },

    getXML: function()
    {
        return tws_Account.XML;
    },

    getStatus: function()
    {
        return tws_Account.status;
    },

    getLastCall: function()
    {
        return tws_Account.lastCall;
    },

    getErrors: function()
    {
        return tws_Account.errors;
    },

    getCredentials: function()
    {
    	
		if((typeof tws_Account.credentials == 'undefined' || tws_Account.credentials == null) && tws_Account._getCookie(tws_Account.cookieName))
		{
			xmlString = tws_Account._getCookie(tws_Account.cookieName);
			if (window.ActiveXObject)
			{
			    xml = new ActiveXObject("Microsoft.XMLDOM");
			    xml.loadXML(xmlString);
			}
			else if (document.implementation && document.implementation.createDocument)
			{
			    var domParser = new DOMParser();
			    xml = domParser.parseFromString(xmlString, "application/xml");
			}
			
			var root                = xml.documentElement;
			nodes = root.getElementsByTagName("credentials");
		    if (typeof nodes != "undefined" && nodes.length > 0)
		    {
		        tws_Account._toJSON("tws_Account.credentials", nodes[0].childNodes);
		    }
		}
    	
        return tws_Account.credentials;
    },


    isLoggedIn: function()
    {
        if (tws_Account._getParameters()["uuid"] &&
            tws_Account._getParameters()["confirm"] == 1)
        {
            var params          = new Array();
            params["userid"]    = tws_Account._getParameters()["uuid"];
            params["confirmed"] = tws_Account._getParameters()["confirm"];
            tws_Account.setCallBackFunction(tws_Account._confirmed);
            tws_Account.modify(params);
        }
        else
        {
            var cookie = tws_Account._getCookie(tws_Account.cookieName);
            if (cookie)
            {
                tws_Account._processXML(cookie);
            }
            else
            {
                tws_Account._executeCall("isLoggedIn", null);
            }
        }
    },

    logIn: function(params)
    {
        tws_Account._executeCall("logIn", params);
    },

    logOut: function()
    {
        tws_Account._executeCall("logOut", null);
    },

    register: function(params)
    {
        tws_Account._executeCall("register", params);
    },

    modify: function(params)
    {
        tws_Account._executeCall("modify", params);
    },

    requestPassword: function(params)
    {
        tws_Account._executeCall("requestPassword", params);
    },

    contact: function(params)
    {
        tws_Account._executeCall("contact", params);
    },


    _confirmed: function()
    {
        var url = window.location.href.substring(0, window.location.href.indexOf("?"));
        var sep = "?";
        params  = tws_Account._getParameters();
        for (var key in params)
        {
            var value = params[key];
            if (typeof value == "string" && key != "confirm" && key != "uuid")
            {
                url += sep + key + "=" + value;
                sep = "&";
            }
        }
        document.location.href = url;
    },

    _executeCall: function(methodName, params)
    {
        tws_Account.XML         = null;
        tws_Account.status      = null;
        tws_Account.lastCall    = null;
        tws_Account.errors      = null;
        if (typeof params == "undefined" || params === null ||
            typeof params["saveCredentials"] == "undefined" || (params["saveCredentials"] !== true && params["saveCredentials"] != "true"))
        {
        	tws_Account.credentials = null;
        }

        if (tws_Account.siteID == null) throw "siteID not defined";

        var url     = tws_Account.baseUrl + methodName + "?" + tws_Account._createQueryString(params) + "&nocache=" + new Date().getTime();
        var script  = document.getElementById(tws_Account.scriptId);
        var head    = document.getElementsByTagName("head")[0];

        if (script) head.removeChild(script);
        script      = document.createElement("script");
        script.id   = tws_Account.scriptId;
        script.src  = url;
        script.type = "text/javascript";
        head.appendChild(script);
    },

    _createQueryString: function(params)
    {
        var queryString = "siteid=" + tws_Account.siteID;
        if (typeof params != "undefined")
        {
            for (var key in params)
            {
                var value = params[key];
                if (typeof value == "string")
                {
                    queryString += "&" + key + "=" + tws_Account._encode64(value);
                }
                else if(typeof value == "number")
                {
                    queryString += "&" + key + "=" + tws_Account._encode64(value.toString());
                }
            }
        }
        return queryString;
    },

    _processXML: function(xmlString)
    {
        // Create XML document from string.
        if (window.ActiveXObject)
        {
            tws_Account.XML = new ActiveXObject("Microsoft.XMLDOM");
            tws_Account.XML.loadXML(xmlString);
        }
        else if (document.implementation && document.implementation.createDocument)
        {
            var domParser = new DOMParser();
            tws_Account.XML = domParser.parseFromString(xmlString, "application/xml");
        }

        // Parse XML into status, errors, credentials, etc.
        if (tws_Account.XML)
        {
            var root                = tws_Account.XML.documentElement;
            tws_Account.lastCall    = root.attributes.getNamedItem("callname").value;
            tws_Account.status      = root.attributes.getNamedItem("status").value;
            tws_Account.errors      = null;
            tws_Account.errorFields = null;

            var nodes = root.getElementsByTagName("error");
            if (typeof nodes != "undefined" && nodes.length > 0)
            {
                tws_Account.errors = new Array();
                for (var i = 0; i < nodes.length; i++)
                {
                    var error   = new Object();
                    error.code  = nodes[i].attributes.getNamedItem("code").value;
                    if (nodes[i].childNodes.length > 0)
                    {
                        error.value = nodes[i].childNodes[0].nodeValue;
                    }
                    tws_Account.errors.push(error);
                }
            }

            nodes = root.getElementsByTagName("field");
            if (typeof nodes != "undefined" && nodes.length > 0)
            {
                tws_Account.errorFields = new Array();
                for (i = 0; i < nodes.length; i++)
                {
                    var field = nodes[i].childNodes[0].nodeValue;
                    tws_Account.errorFields.push(field);
                }
            }

            nodes = root.getElementsByTagName("credentials");
            if (typeof nodes != "undefined" && nodes.length > 0)
            {
            	tws_Account.credentials = null;
                tws_Account._toJSON("tws_Account.credentials", nodes[0].childNodes);
            }

            if (tws_Account.lastCall == "isLoggedIn")
            {
                // XML correct, set in cookie to prevent too much server load.
                tws_Account._setCookie(tws_Account.cookieName, xmlString, null, "/", "");
            }
            else
            {
                tws_Account._setCookie(tws_Account.cookieName, "", -1, "/", "");
            }

            if ((tws_Account.lastCall == "isLoggedIn" || tws_Account.status == "ok") &&
                typeof tws_Account.getCredentials() != "undefined" && tws_Account.getCredentials() != null && 
                typeof tws_Session != "undefined")
            {
                // Call session server (it can handle the load) to recalculate favourites.
                tws_Session.setSiteID(tws_Account.siteID);
                tws_Session.setCallBackFunction(tws_Account._processSession);
                tws_Session.fetchSession();
            }
        }

        // Call back function.
        if (tws_Account.callBackFunction != null) tws_Account.callBackFunction();
    },

    _processSession: function()
    {
        function _calculateEMA(oldEMA, gamePlays)
        {
            var exponent = 2 / (28 + 1);
            return (gamePlays * exponent) + (oldEMA * (1 - exponent));
        }

        function _compareEMAs(a, b)
        {
            return b.ema - a.ema;
        }

        if (typeof tws_Session != "undefined" && tws_Session.getSession() != null &&
            typeof tws_Account.getCredentials() != "undefined" && tws_Account.getCredentials() != null)
        {
            var changed = false;
            var games   = (tws_Account.getCredentials().favourites ? tws_Account.getCredentials().favourites.game : new Array());
            if (typeof games.length == "undefined")
            {
                games    = new Array();
                games[0] = tws_Account.getCredentials().favourites.game;
            }

            for (var i = 0; i < tws_Session.getSession().counters.length; i++)
            {
                var counterName = tws_Session.getSession().counters[i].name;
                var counts      = tws_Session.getSession().counters[i].count;

                var pattern = /^Game\d+$/;
                if (pattern.test(counterName))
                {
                    var gameId  = counterName.substring(4);
                    var found   = false;

                    // Add/replace game in array.
                    for (var j = 0; j < games.length && !found; j++)
                    {
                        if (games[j].id == gameId)
                        {
                            games[j].ema = _calculateEMA(games[j].ema, counts);
                            found = true;
                        }
                    }
                    if (!found)
                    {
                        var game    = new Object();
                        game.id     = parseInt(gameId);
                        game.ema    = _calculateEMA(0, counts);
                        games.push(game);
                        changed     = true;
                    }
                }
            }

            if (changed)
            {
                // Resort games array.
                games.sort(_compareEMAs);
                if (!tws_Account.getCredentials().favourites)
                {
                    tws_Account.getCredentials().favourites = new Object();
                }
                tws_Account.getCredentials().favourites.game = games;
            }

            // Call back function.
            if (tws_Account.callBackFunction != null) tws_Account.callBackFunction();
        }
    },

    _toJSON: function(objectName, children, attributes)
    {
        var isArray     = false;
        var arrLength   = 0;
        var obj         = eval(objectName);

        if (obj)
        {
            if (typeof obj.length == "undefined")
            {
                var temp  = eval(objectName);
                eval(objectName + " = new Array()");
                obj       = eval(objectName);
                obj[0]    = temp;
            }

            isArray         = true;
            arrLength       = obj.length;
            obj[arrLength]  = new Object();
        }
        else
        {
            eval(objectName + " = new Object()");
        }

        for (var i = 0; i < children.length; i++)
        {
            var node = children[i];
            if (node)
            {
                var nodeName = node.nodeName;

                if (node.childNodes)
                {
                    if (node.childNodes.length > 1 ||
                        (node.childNodes[0] != null && node.childNodes[0].nodeType == 1) ||
                        node.attributes.length >= 1)
                    {
                        tws_Account._toJSON(objectName + "." + nodeName, node.childNodes, node.attributes);
                    }
                    else
                    {
                        var evalString  = "";
                        var nodeValue   = (node.childNodes[0] != null ? node.childNodes[0].nodeValue : null);
                        nodeValue       = (typeof nodeValue != "undefined" && isNaN(nodeValue) ? "'" + nodeValue + "'" : nodeValue);

                        if (isArray)
                            evalString  = objectName + "[" + arrLength + "]." + nodeName + " = " + nodeValue;
                        else
                            evalString  = objectName + "." + nodeName + " = " + nodeValue;

                        eval(evalString);
                    }
                }
            }
        }

        if (attributes && attributes.length > 0)
        {
            for (var j = 0; j < attributes.length; j++)
            {
                var attName     = attributes[j].nodeName;
                var attValue    = attributes[j].nodeValue;

                if (isArray)
                    evalString  = objectName + "[" + arrLength + "]." + attName + " = " + attValue;
                else
                    evalString  = objectName + "." + attName + " = " + attValue;

                eval(evalString);
            }
        }
    },

    _encode64: function(input)
    {
        var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        while (i < input.length)
        {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2))
            {
                enc3 = enc4 = 64;
            }
            else if (isNaN(chr3))
            {
                enc4 = 64;
            }

            output += (keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4));
        }

        return output;
    },

    _getCookie: function(checkName)
    {
        var cookies = document.cookie.split(";");
        for (var i = 0; i < cookies.length; i++)
        {
            var cookie  = cookies[i].split("=");
            var name    = cookie[0].replace(/^\s+|\s+$/g, "");
            if (name == checkName)
            {
                if (cookie.length > 1)
                {
                    return unescape(cookie[1].replace(/^\s+|\s+$/g, ""));
                    break;
                }
            }
        }
        return null;
    },

    _setCookie: function(name, value, expires, path, domain, secure)
    {
        var today = new Date();
        today.setTime(today.getTime());

        var expiresDate = new Date();
        if (expires)
        {
            expires = expires * 1000 * 60 * 60 * 24;
            expiresDate = new Date(today.getTime() + (expires));
        }

        document.cookie = name + "=" + escape(value) +
            ((expires) ? ";expires=" + expiresDate.toGMTString() : "") +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "") +
            ((secure) ? ";secure" : "");
    },

    _getParameters: function()
    {
        var string  = window.location.href.substring(window.location.href.indexOf("?") + 1);
        var pars    = string.replace("&amp;", "&").split("&");
        var params  = new Array();
        for (var i = 0; i < pars.length; i++)
        {
            var arr = pars[i].split("=");
            params[arr[0]] = arr[1];
        }
        return params;
    },
    
    loaded: tws_Global.scriptLoaded("tws_Account")
};

var alreadyrunflag = 0;
if (document.addEventListener)
{
    document.addEventListener("DOMContentLoaded", function(){alreadyrunflag=1; tws_Account.isLoggedIn()}, false)
}
else if (document.all && !window.opera)
{
    var script = document.createElement('script');
    script.type = "text/javascript";
    script.id = "contentloadtag";
    script.defer = "defer";
    script.src = "javascript:void(0);";
    document.getElementsByTagName('head')[0].appendChild(script);

    var contentloadtag = document.getElementById("contentloadtag");
    contentloadtag.onreadystatechange = function()
    {
        if (this.readyState == "complete")
        {
            alreadyrunflag = 1;
            tws_Account.isLoggedIn();
        }
    }
}
window.onload = function() {
    setTimeout("if (!alreadyrunflag) tws_Account.isLoggedIn()", 0);
}