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_Search =
{
    baseURL  : "http://search.tibaco.net/",
    siteID   : ((typeof tws_Global.siteID != 'undefined' && tws_Global.siteID !== null)?tws_Global.siteID:null),
    prefix   : "",
    languagecode : '',
    timePerRequest : 2500,
    json     : null,
    results  : null,
    numRows	 : null,
    callBack : null,

    setSiteID: function(siteID)
    {
    	tws_Global.siteID = siteID;
        this.siteID = siteID;
    },

    setPrefix: function(prefix)
    {
        this.prefix = prefix;
    },

    search: function(queryString, maxResults, resultsOffset)
    {
        if (this.siteID == null) throw "siteID not defined";
        if (queryString == null || typeof queryString == 'undefined') throw "queryString not valid";
        if (queryString == '') return false;
        if(typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'search'))
    	{
			console.log("SEARCH: QueryString: \n"+ queryString);
		}
        if (maxResults == null || typeof maxResults == 'undefined') maxResults = 99;
        if (resultsOffset == null || typeof resultsOffset == 'undefined') resultsOffset = 0;

        this.json = null;
        this.results = null;
        this.numRows = null;

        var fields = '';
        if(this.search.arguments.length <= 3)
        {
        	fields = 'id,code,title_text';
        }
        for (var i = 3; i < this.search.arguments.length; i++)
        {
            if (this.search.arguments[i] instanceof Array)
            {
                for (var j = 0; j < this.search.arguments[i].length; j++)
                {
                	if(fields.indexOf(this.search.arguments[i][j]) < 0)
                	{
	                    if (fields != '') fields += ',';
	                    fields += this.search.arguments[i][j];
	                }
                }
            }
            else
            {
	            if (fields != '') fields += ',';
    	        fields += this.search.arguments[i];
    	    }
        }
        var now = new Date();
        var url = this.baseURL + encodeURIComponent(this.prefix + this.siteID) + this.languagecode + "/select?nocache=" + now.getTime() + "&wt=json&json.wrf=tws_Search._json&version=2.2&start=" + resultsOffset + "&rows=" + maxResults + "&q=" + encodeURIComponent(queryString) + "&fl=" + encodeURIComponent(fields)+"&timeAllowed="+this.timePerRequest;
        
        var script = document.getElementById('tws_Search_search');
		var head = document.getElementsByTagName("head")[0];
        if (script) head.removeChild(script);
        script = document.createElement('script');
        script.id = 'tws_Search_search';
        script.src = url;
        script.type = 'text/javascript';
        if(typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'search'))
    	{
			console.log("SEARCH: Requesting URL: \n"+ url);
		}
        head.appendChild(script);
        if(typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'search'))
    	{
			console.log("SEARCH: Appended script to header");
		}
    },
	
	searchFavorites: function(cookiename, queryString, xmlPath, maxResults, resultsOffset)
	{
		if (typeof cookiename == "undefined" || cookiename == '') return false;
		if (typeof queryString == "undefined" || queryString == '') return false;
		if (maxResults == null || typeof maxResults == 'undefined') maxResults = 99;
        if (resultsOffset == null || typeof resultsOffset == 'undefined') resultsOffset = 0;
        
        this.json = null;
        this.results = null;
        this.numRows = null;
        
		var ct = this._getCookie(cookiename);
		if(!ct) {
			return false;
		} else {
			eval("ct = "+ct);
			this.results	= [];
			var currentID	= 0;
			for(var i in ct)
			{
				if(typeof ct[i][2] != "undefined" && ct[i][2] != "" && ct[i][2].indexOf(queryString) >= 0 && this.results.length <= maxResults)
				{
					try
					{
						if(currentID >= resultsOffset)
						{
							var ajax	= new AJAXConnection();
		        	    	ajax.get(xmlPath + i + ".xml", true);
		        	    	var xmlcontent = ajax.getContent(true);
		        	    	if(xmlcontent)
		        	    	{
								var game	= {};
								game.category_mstring	= xmlcontent.getElementsByTagName("category")[0].childNodes[0].nodeValue;
								game.code				= xmlcontent.getElementsByTagName("code")[0].childNodes[0].nodeValue;
								game.ema_float			= xmlcontent.getElementsByTagName("ema")[0].childNodes[0].nodeValue;
								game.id					= i;
								game.mediumDescription_text	= xmlcontent.getElementsByTagName("mediumDescription")[0].childNodes[0].nodeValue;
								game.screenshot_mstring	= [xmlcontent.getElementsByTagName("screenshot")[0].childNodes[0].nodeValue];
								game.title_text			= xmlcontent.getElementsByTagName("title")[0].childNodes[0].nodeValue;
								
								this.results.push(game);
							}
						}
						currentID++;
					}
					catch(e)
					{
						try { console.log(e); } catch(e) {}
						return false;
					}
				}
			}
			if(this.results && this.results.length > 0)
			{
				this.numRows	= 	this.results.length;
				
				if(typeof this.callBack != "undefined") this.callBack();
			}
		}
	},
	
    _json: function(ob)
    {
        this.json = ob;
        if (this.json && this.json.response && this.json.response.docs)
        {
            for (var i = 0; i < this.json.response.docs.length; i++)
            {
                if (this.json.response.docs[i].id > 900000)
                {
                    this.json.response.docs[i].type = "category";
                    this.json.response.docs[i].id -= 1000000;
                }
                else
                {
                    this.json.response.docs[i].type = "game";
                }
            }
        }
        if (this.callBack != null) this.callBack();
    },
	
	setCoreLanguage: function(languagecode)
	{
		this.languagecode = languagecode;
		return true;
	},
	
    getNumberOfMatches: function()
    {
        if (this.json && this.json.response) return this.json.response.numFound;
        return -1;
    },

    getResults: function()
    {
        if (this.results != null) return this.results;

        if (this.json && this.json.response && this.json.response.docs)
        {
            this.results = this.json.response.docs;
        }

        return this.results;
    },
    
    getNumRows: function()
    {
        if (this.numRows != null) return this.numRows;

        if (this.json && this.json.response && this.json.response.numFound)
        {
        	if(this.json.response.numFound <= 99)
            	this.numRows = this.json.response.numFound;
            else
            	this.numRows = 99;
        }

        return this.numRows;
    },

    setCallBackFunction: function(callBackFunction)
    {
        this.callBack = callBackFunction;
    },
	
	escapeQuery: function(start)
	{
		var str = start.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(/\-/g,'\\\-');
			str	= str.replace(/\[/g,'\\\[');
			str	= str.replace(/\]/g,'\\\]');
			str	= str.replace(/\{/g,'\\\{');
			str	= str.replace(/\}/g,'\\\}');
			str	= str.replace(/\(/g,'\\\(');
			str	= str.replace(/\)/g,'\\\)');
			str	= str.replace(/\0/g,'\\0');
		
		var remove = ['!','@','#','$','%','^','&','|', '\"'];
		for(var i = 0; i < remove.length; i++)
		{
			str = str.replace(remove[i], '');
		}
		
		if(typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'search'))
    	{
			console.log("SEARCH: Changed string \""+start+"\" to string \""+str+"\".");
		}
		
		return str;
	},
	
    buildQueryString: function(str, type, fuzzy, cats)
    {
    	if(typeof type == 'undefined' || type === null) type = '';
    	if(typeof fuzzy == 'undefined' || fuzzy === null) fuzzy = '0.65';
        if(typeof cats == 'undefined' || cats === null) cats = false;

        str = decodeURIComponent(str.toLowerCase().replace(/\+/g, " ")) + " ";
        str = str.replace(/'[^\s]*\s/g, " ");
        str = str.replace(/^\s+|\s+$/g, "");
		
		if(tws_Search.escapeQuery(str).length <= 0) return "";
		
		var ret = '';
    	switch(type)
    	{
    		case 'custom':
    			ret = str;
    			break;
    		default:
                if(type == 'exact')
                {
                    fuzzy = '';
                }
                else
                {
                    fuzzy = '~'+fuzzy;
                }
    			var words = str.split(' ');
                var fields = ['title_text','category_mstring','mediumDescription_text','originalTitle_text','concatTitle_text'];

                ret += 'id:[' + (!cats ? '* TO 900000' : '900000 TO *') + '] AND (';
                ret += 'title_text:"'+ tws_Search.escapeQuery(str) +'"^' + (fields.length + 2) + ' OR ';
                ret += 'originalTitle_text:"'+ tws_Search.escapeQuery(str) +'"^' + (fields.length + 1) + ' OR ';
                for(var i = 0; i < fields.length; i++)
                {
                	ret += '(';
                    for(var j = 0; j < words.length; j++)
                    {
                    	if (typeof words[j] == "string" && words[j].substr(0,4) == 'age:')
                    	{
                    		ret	+= 'targetAge_mstring:'+words[j].substr(4);
                    		i = fields.length;
                    		if(j < words.length - 1) { ret += ' OR '; }
                    	}
                        else if(typeof words[j] == "string" && words[j].substr(0,7) == 'gender:')
                    	{
                    		ret	+= 'targetGender_mstring:'+words[j].substr(7);
                    		i = fields.length;
                    		if(j < words.length - 1) { ret += ' OR '; }
                    	}
                        else if (typeof words[j] == "string" || typeof words[j] == "number")
                        {
                        	if((words.length <= 3 || i < 3) && words[j].length > 0)
		                	{
		                		ret += ' ('+ fields[i] +':' + tws_Search.escapeQuery(words[j]) + '*^' + (fields.length - i);
	                        	if(fuzzy != '')
	                        	{
	                            	ret += ' OR '+ fields[i] +':' + tws_Search.escapeQuery(words[j]) + fuzzy + '^' + (fields.length - i);
	                            }
	                            ret += ')';
	                            if(j < words.length - 1) { ret += ' OR '; }
			                }
			                else if(j == 0)
		                	{
		                    	ret += ' '+fields[i] +':"' + tws_Search.escapeQuery(str) + '"^' + (fields.length - i);
		                	}                        	
                        }
                    }
                	ret += ')';
                	if(i < fields.length - 1) { ret += ' OR '; }
                }
                ret += ')';
    			break;
    	}
    	
    	if(typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'search'))
    	{
			console.log("SEARCH: Search Query:\n" + ret.replace(/OR \(/g, 'OR \n(\n').replace(/\)\)/g, ')\n)'));
			console.log("SEARCH: Query Length: " + ret.length);
		}
    	if(ret.length > 1900 && fuzzy)
    	{
    		return tws_Search.buildQueryString(str, 'exact', false);
    	}
    	
    	return ret;
    },


    start: function(value)
    {
        if (value.length > 2 && value != document.tws_search_last)
        {
            tws_Search.setCallBackFunction(tws_Search.complete);

            document.tws_search_last = value;
            if (typeof document.tws_search_wait !== 'undefined' && document.tws_search_wait !== null)
            {
                clearTimeout(document.tws_search_wait);
                document.tws_search_wait = null;
            }
            document.tws_search_wait = setTimeout("tws_Search.search('" + tws_Search.buildQueryString(value) + "', 10, 0);", 300);
        }
    },

    complete: function()
    {
        var results = tws_Search.getResults();
        var suggestBox = document.getElementById('suggestResults');
        suggestBox.innerHTML = '';

        if (results.length > 0)
        {
            // TODO: staticURL must come from sites.xml
            var staticURL   = 'http://static.playtime.nl/screenshots/';
            var onClick     = null;
            var aTemplate   = document.getElementById('tws_syndication_atemplate');
            if (aTemplate)
            {
                for (var i = 0; i < aTemplate.attributes.length && onClick == null; i++)
                {
                    if (aTemplate.attributes[i].nodeName == 'href')
                        onClick = aTemplate.attributes[i].nodeValue;
                }
            }

            suggestBox.innerHTML = '<div class="tws_syndication_suggesttop"></div>';
            for (i = 0; i < results.length; i++)
            {
                html  = '<div class="tws_syndication_suggestitem" onclick="' + onClick.replace("%@code%", results[i].code) + '">';
                html += '<img src="' + staticURL + results[i].id + '.jpg" width="33px" height="26px" alt="' + results[i].title_text + '" title="' + results[i].title_text + '" />';
                html += '<span>' + results[i].title_text + '</span>'
                html += '</div>';
                suggestBox.innerHTML += html;
            }
            suggestBox.innerHTML += '<div class="tws_syndication_suggestbottom"></div>';
            suggestBox.style.display = 'block';

            window.onclick = function() {tws_Search.hide();};
            document.onclick = function() {tws_Search.hide();};
        }
        else
        {
            suggestBox.style.display = 'none';
        }
    },

    hide: function()
    {
        var suggestBox = document.getElementById('suggestResults');
        suggestBox.innerHTML = '';
        suggestBox.style.display = 'none';

        window.onclick = function() {};
        document.onclick = function() {};
    },
    
    _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++)
        {
            if (pars[i].indexOf("=") != -1)
            {
                var name = pars[i].substr(0, pars[i].indexOf("="));
                var value = pars[i].substr(pars[i].indexOf("=") + 1);
                params[name] = value;
            }
        }
        return params;
    },
    
    _getCookie: function(cookieName)
	{
	    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 == cookieName)
	        {
	            if (cookie.length > 1)
	            {
	                return unescape(cookie[1].replace(/^\s+|\s+$/g, ""));
	                break;
	            }
	        }
	    }
	    return null;
	},
    
    loaded: tws_Global.scriptLoaded('tws_Search')
};

