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_Highscore =
{
    scriptId            : "tws_Highscore_highscore",
    cookieName          : "tws_Highscore",
    baseURL             : "http://highscore.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,
    position			: null,
    scores		        : null,
    params				: null,
	nameRequestPage		: null,
	texts				: null,
	competitionid		: 0,
	requestEmail		: false,
	
    setSiteID: function(siteID)
    {
    	tws_Global.siteID = siteID;
        tws_Highscore.siteID = siteID;
    },

    setCallBackFunction: function(callBackFunction)
    {
        tws_Highscore.callBackFunction = callBackFunction;
        return true;
    },
	
	setNameRequestPage: function(url)
    {
        tws_Highscore.nameRequestPage = url;
        return true;
    },
    
    setCompetitionId: function(id)
    {
    	tws_Highscore.competitionid = id;
    	return true;
    },
    
    setRequestEmail: function(bool)
    {
    	tws_Highscore.requestEmail = bool;
    	return true;
    },
    
    getXML: function()
    {
        return tws_Highscore.XML;
    },
	
	getType: function(t)
	{
		if(typeof t == 'number')
		{
			switch(t)
			{
				case 5: return 'mochi'; break;
				case 4: return 'lowhigh'; break;
				case 3: return 'email'; break;
				case 2: return 'fggame'; break;
				case 1: return 'game'; break;
				default: return 'none'; break;
			}			
		}
		else
		{
			switch(t)
			{
				case 'mochi': return 5; break;
				case 'lowhigh': return 4; break;
				case 'email': return 3; break;
				case 'fggame': return 2; break;
				case 'game': return 1; break;
				default: return 0; break;
			}
		}
	},
	
    submitScore: function(params)
    {
    	if(	typeof params.game == 'undefined' || params.game == null ||
    		typeof params.score == 'undefined' || params.score == null ||
    		typeof params.session == 'undefined' || params.session == null)
    	{
    		return false;
    	}
    	if(typeof params.competitionid == 'undefined') { params.competitionid = tws_Highscore.competitionid }
    	tws_Highscore.params = params;
    	tws_Highscore._executeCall('submit',tws_Highscore.params);
    },
    
    getScores: function(gameid, competitionid)
    {
    	if(typeof competitionid != 'undefined')
    	{
    		tws_Highscore.params = {"game":gameid,"competitionid":competitionid};
    	}
    	else
    	{
    		tws_Highscore.params = {"game":gameid};
    	}
    	tws_Highscore._executeCall('scores',tws_Highscore.params);
    },
    
    setTexts: function(texts)
    {
    	if(
    		typeof texts.name != 'undefined' &&
    		typeof texts.submit != 'undefined' &&
    		typeof texts.position != 'undefined' &&
    		typeof texts.storetext != 'undefined'
    	) {
    		tws_Highscore.texts = texts;
    		return true;
    	}
    	else
		{
			return false;
		}
    },
    
    getPostParams: function()
    {
    	var params = tws_Highscore._getParameters();
    	if(typeof params['q'] != 'undefined' && params['q'] != null)
    	{
    		return tws_Highscore._getParameters(tws_Highscore._decode64(params['q']));
    	}
    	else
		{
			return false;
		}
    },
    
    /**
     * Removes the created elements for the overlaying.
     */
    closeOverlay: function()
    {
        var div = document.getElementById("tws_Highscore_overlay_div");
        if (div != null) document.body.removeChild(div);
        var iframe = document.getElementById("tws_Highscore_content_div");
        if (iframe != null) document.body.removeChild(iframe);
        div = document.getElementById("tws_Highscore_overlay_close_div");
        if (div != null) document.body.removeChild(div);
    },
    
    _submitScoreWithName: function()
    {
    	nameObj = document.getElementById('tws_Highscore_name_input');
    	if(tws_Highscore.params != null && nameObj && nameObj.value.toString().length > 0)
    	{
    		tws_Highscore.params.name = nameObj.value.toString();
    		mailObj = document.getElementById('tws_Highscore_email_input');
    		if(mailObj && mailObj.value.toString().length > 0)
    		{
    			tws_Highscore.params.email = nameObj.value.toString();
    		}
			tws_Highscore._executeCall('submit',tws_Highscore.params);    		
    	}
    	else
    	{
    		return false;
    	}
    },
    
    _requestName: function()
    {
    	if(typeof tws_Highscore.params.game != 'undefined' && tws_Highscore.params.game != null)
    	{
    		if(tws_Highscore.nameRequestPage !== null)
    		{
    			var str = '';
    			for(var i in tws_Highscore.params)
    			{
    				if(str != '') str += '&';
    				str += i + '=' + tws_Highscore.params[i];
    			}
                
                if (tws_Highscore.position)
                {
                    for (var pos in tws_Highscore.position)
                    {
                        if(str != '') str += '&';
                        str += 'position_' + pos + '=' + tws_Highscore.position[pos];
                    }
                }
    			document.location.href = tws_Highscore.nameRequestPage + ( (tws_Highscore.nameRequestPage.toString().indexOf('?') > 0) ? '&' : '?' )+'q='+tws_Highscore._encode64(str);
    		}
    		else if(typeof tws_Highscore.texts != 'undefined' && tws_Highscore.texts !== null)
    		{
    			tws_Highscore._openOverlay(500,200);
    		}
    		else
    		{
    			try
    			{
    				console.warn("No name or retrieval method specified!");
    			}
    			catch(e) {}
    		}
    	}
    },
    
    /**
     * Creates and shows elements to overlay.
     * @param url       the location to load.
     * @param width     the width of the overlay.
     * @param height    the height of the overlay.
     */
    _openOverlay: function(width, height)
    {
        var div = document.createElement("div");
        div.id                      = "tws_Highscore_overlay_div";
        div.style.display           = "block";
        div.style.zIndex            = tws_Highscore._getMaxZindex() + 1;
        div.style.opacity           = "0.65";
        div.style.filter            = "alpha(opacity=65)";
        div.style.backgroundColor   = "#323031";
        div.style.position          = "fixed";
        // TODO: if IE6 > absolute;
        div.style.top               = "0px";
        div.style.left              = "0px";
        div.style.width             = "100%";
        div.style.height            = tws_Highscore._getPageHeight() + "px";
        document.body.appendChild(div);

        var contentdiv = document.createElement("div");
        contentdiv.id                   = "tws_Highscore_content_div";
        contentdiv.className            = "tws_Highscore_overlay_content";
        contentdiv.style.zIndex         = tws_Highscore._getMaxZindex() + 1;
        contentdiv.style.border         = "1px solid #333333";
        contentdiv.style.backgroundColor= "#FFFFFF";
        contentdiv.style.padding        = "2px";
        contentdiv.style.position       = "absolute";
        contentdiv.style.top            = this._getTopOffset(50);
        contentdiv.style.left           = "50%";
        contentdiv.style.marginLeft     = ((width / 2) * -1) + "px";
        contentdiv.style.width          = width + "px";
        contentdiv.style.height         = height + "px";
        
        span1 = document.createElement("span");
        span1.className = "tws_Highscore_name_position";
        span1.innerHTML = tws_Highscore.texts.position.replace("%%pos%%", ((typeof tws_Highscore.position != 'undefined') ? tws_Highscore.position.standing : '?' ) );
        contentdiv.appendChild(span1);
        
        span2 = document.createElement("span");
        span2.className = "tws_Highscore_name_storetext";
        span2.innerHTML = tws_Highscore.texts.storetext;
        contentdiv.appendChild(span2);
        
        label = document.createElement("label");
        label.htmlFor = "tws_Highscore_name_input";
        label.innerHTML = tws_Highscore.texts.name;
        contentdiv.appendChild(label);
        
        input = document.createElement("input");
        input.id = "tws_Highscore_name_input";
	    contentdiv.appendChild(input);
	    
	    if(tws_Highscore.requestEmail)
	    {
	        label = document.createElement("label");
	        label.htmlFor = "tws_Highscore_email_input";
	        label.innerHTML = ( (typeof tws_Highscore.texts.email != 'undefined') ? tws_Highscore.texts.email : 'E-mail');
	        contentdiv.appendChild(label);
	        
	        input = document.createElement("input");
	        input.id = "tws_Highscore_email_input";
	        contentdiv.appendChild(input);
    	}
		
        submitButton = document.createElement("input");
        submitButton.type	= "button";
        submitButton.id		= "tws_Highscore_submit_input";
		submitButton.value	= tws_Highscore.texts.submit;
		submitButton.onclick = tws_Highscore._submitScoreWithName;
        contentdiv.appendChild(submitButton);
        
        document.body.appendChild(contentdiv);

        var closediv = document.createElement("div");
        closediv.id                      = "tws_Highscore_overlay_close_div";
        closediv.style.display           = "block";
        closediv.style.zIndex            = tws_Highscore._getMaxZindex() + 1;
        closediv.style.position          = "absolute";
        closediv.style.top               = this._getTopOffset(35);
        closediv.style.left              = "50%";
        closediv.style.marginLeft        = ((width / 2) - 10) + "px";
        closediv.style.width             = "30px";
        closediv.style.height            = "30px";
        closediv.style.cursor            = "pointer";
        closediv.style.backgroundImage	= "url(" + tws_Highscore.baseURL + "images/closebox.png)";
        
        if (div.addEventListener)
            closediv.addEventListener("click", tws_Highscore.closeOverlay, false);
        else if (div.attachEvent)
            closediv.attachEvent("onclick", tws_Highscore.closeOverlay);
        document.body.appendChild(closediv);
    },

    /**
     * Returns the maximum zindex of all elements on the page.
     * @return          the max zindex.
     */
    _getMaxZindex: function()
    {
        var maxZIndex = 0;
        var elements = document.getElementsByTagName("*");
        for (i = 0; i < elements.length; i++)
        {
            var element = elements[i];
            var zindex;
            if (element.currentStyle)
                zindex = element.currentStyle.zIndex;
            else if (document.defaultView)
                zindex = document.defaultView.getComputedStyle(element, null).getPropertyValue("z-index");
            if (!isNaN(zindex))
            {
                if (zindex > maxZIndex)
                    maxZIndex = zindex;
            }
        }
        return parseInt(maxZIndex);
    },
    
    /**
     * Returns the height of the page.
     * @return          the height of the page.
     */
    _getPageHeight: function()
    {
        var result = 0;
        if (window.innerHeight && window.scrollMaxY)
            result = window.innerHeight + window.scrollMaxY;
        else if (document.body.scrollHeight > document.body.offsetHeight)
            result = document.body.scrollHeight;
        else
            result = document.body.offsetHeight;
        var result2 = Math.max(document.body && document.body.scrollHeight || 0, document.documentElement && document.documentElement.scrollHeight || 0);
        if (result2 > result)
            result = result2;
        return result;
    },
    
    _getTopOffset: function(diff)
	{
		var h = parseInt((window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop));
		if(h)
		{
			if(typeof diff != 'undefined')
			{
			 	return (h + parseInt(diff)) + 'px';
			}
			else
			{
				return h+'px';
			}
		}
		else if(typeof diff != 'undefined')
		{
		 	return parseInt(diff) + 'px';
		}
		return 0;
	},
	
    _executeCall: function(methodName, params)
    {
        tws_Highscore.XML         = null;
        tws_Highscore.status      = null;
        tws_Highscore.lastCall    = null;
        tws_Highscore.errors      = null;

        if (tws_Highscore.siteID == null) throw "siteID not defined";

        var url     = tws_Highscore.baseURL + methodName + "?" + tws_Highscore._createQueryString(params) + "&nocache=" + new Date().getTime();
        var script  = document.getElementById(tws_Highscore.scriptId);
        var head    = document.getElementsByTagName("head")[0];

        if (script) head.removeChild(script);
        script      = document.createElement("script");
        script.id   = tws_Highscore.scriptId;
        script.src  = url;
        script.type = "text/javascript";
        head.appendChild(script);
    },

    _createQueryString: function(params)
    {
        var queryString = "siteid=" + tws_Highscore.siteID;
        if (typeof params != "undefined")
        {
            for (var key in params)
            {
                var value = params[key];
                if (typeof value == "string")
                {
                    queryString += "&" + key + "=" + tws_Highscore._encode64(value);
                }
                else if(typeof value == "number")
                {
                	queryString += "&" + key + "=" + tws_Highscore._encode64(value.toString());
                }
            }
        }
        return queryString;
    },

    _processXML: function(xmlString)
    {
        // Create XML document from string.
        if (window.ActiveXObject)
        {
            tws_Highscore.XML = new ActiveXObject("Microsoft.XMLDOM");
            tws_Highscore.XML.loadXML(xmlString);
        }
        else if (document.implementation && document.implementation.createDocument)
        {
            var domParser = new DOMParser();
            tws_Highscore.XML = domParser.parseFromString(xmlString, "application/xml");
        }

        // Parse XML into status, errors, credentials, etc.
        if (tws_Highscore.XML)
        {
            var root                = tws_Highscore.XML.documentElement;
            tws_Highscore.lastCall  = root.attributes.getNamedItem("callname").value;
            tws_Highscore.status    = root.attributes.getNamedItem("status").value;
            tws_Highscore.errors    = null;
            tws_Highscore.position	= null;
            tws_Highscore.scores	= null;
			
			nodes = root.getElementsByTagName("position");
			if(nodes && nodes.length >= 1) tws_Highscore._toJSON("tws_Highscore.position", nodes[0].childNodes);
			
            var nodes = root.getElementsByTagName("error");
            if (typeof nodes != "undefined" && nodes.length > 0)
            {
                tws_Highscore.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;
                    }
                    if(error.value == 'name_request')
                    {
                    	tws_Highscore._requestName();
                    }
                    tws_Highscore.errors.push(error);
                }
                return;
            }
			
			if(tws_Highscore.lastCall == "scores" || tws_Highscore.lastCall == "submit")
			{
				nodes = root.getElementsByTagName("scores");
				tws_Highscore._toJSON("tws_Highscore.scores", nodes[0].childNodes);
			}
        }

        // Call back function.
        if (tws_Highscore.callBackFunction != null) tws_Highscore.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 && node.attributes.length >= 1))
                    {
                        tws_Highscore._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) ? "'" + this._addslashes(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;
    },
    
	_decode64: function(input)
	{
		var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		var output = "";
		var chr1, chr2, chr3 = "";
		var enc1, enc2, enc3, enc4 = "";
		var i = 0;
		
		// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
		var base64test = /[^A-Za-z0-9\+\/\=]/g;
		if (base64test.exec(input)) {
			try{
				console.warn("There were invalid base64 characters in the input text.\n" +
							"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
							"Expect errors in decoding.");
			}
			catch(e) {}
		}
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
		
		do {
			enc1 = keyStr.indexOf(input.charAt(i++));
			enc2 = keyStr.indexOf(input.charAt(i++));
			enc3 = keyStr.indexOf(input.charAt(i++));
			enc4 = keyStr.indexOf(input.charAt(i++));
			
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
			
			output = output + String.fromCharCode(chr1);
			
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
			
			chr1 = chr2 = chr3 = "";
			enc1 = enc2 = enc3 = enc4 = "";
			
		}
		while (i < input.length);
		
		return unescape(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(str)
    {
        if(typeof str == 'undefined' || str == null)
        {
        	var string  = window.location.href.substring(window.location.href.indexOf("?") + 1);
        }
        else
        {
        	var string = str;
        }
        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];
            for(var j = 1; j < arr.length; j++)
            {
            	params[arr[0]] += arr[j];
            	if(j > 1) params[arr[0]] += '=';
            }
        }
        return params;
    },
    
    /**
	 * Add slashes.
	 */
    _addslashes: function(str)
	{
		str=str.replace(/\\/g,'\\\\');
		str=str.replace(/\'/g,'\\\'');
		str=str.replace(/\"/g,'\\"');
		str=str.replace(/\r/g,'\\r');
		str=str.replace(/\n/g,'\\n');
		str=str.replace(/\0/g,'\\0');
		return str;
	},

	/**
	 * Strip slashes.
	 */
	_stripslashes: function(str)
	{
		str=str.replace(/\\'/g,'\'');
		str=str.replace(/\\"/g,'"');
		str=str.replace(/\\r/g,'\\r');
		str=str.replace(/\\n/g,'\\n');
		str=str.replace(/\\0/g,'\0');
		str=str.replace(/\\\\/g,'\\');
		return str;
	},
    
    loaded: tws_Global.scriptLoaded("tws_Highscore")
};