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),
    timePerRequest : 2500,
    json     : null,
    results  : null,
    numRows	 : null,
    callBack : null,

    setSiteID: function(siteID)
    {
    	tws_Global.siteID = siteID;
        this.siteID = siteID;
    },

    search: function(queryString, maxResults, resultsOffset)
    {
        if (this.siteID == null) throw "siteID not defined";
        if (queryString == null || typeof queryString == 'undefined' || queryString == '') throw "queryString not valid";
        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 = fields.length; 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 != '') fields += ',';
                    fields += this.search.arguments[i][j];
                }
            }
            if (fields != '') fields += ',';
            fields += this.search.arguments[i];
        }

        var now = new Date();
        var url = this.baseURL + escape(this.siteID) + "/select?nocache=" + now.getTime() + "&wt=json&json.wrf=tws_Search._json&version=2.2&start=" + resultsOffset + "&rows=" + maxResults + "&q=" + escape(queryString) + "&fl=" + escape(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';
        head.appendChild(script);
    },

    _json: function(ob)
    {
        this.json = ob;
        if (this.callBack != null) this.callBack();
    },

    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;
    },

    buildQueryString: function(str, type, fuzzy)
    {
    	if(typeof type == 'undefined' || type === null) type = '';
    	if(typeof fuzzy == 'undefined' || fuzzy === null) fuzzy = '0.65';

        str = unescape(str.toLowerCase().replace(/\+/g, " ")) + " ";
        str = str.replace(/'[^\s]*\s/g, " ");
        str = str.replace(/^\s+|\s+$/g, "");
		
		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 += 'title_text:"'+ str +'"^' + (fields.length + 2) + ' OR ';
                ret += 'originalTitle_text:"'+ 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" || typeof words[j] == "number")
                        {
                        	ret += '('+ fields[i] +':' + words[j] + '*^' + (fields.length - i);
                        	if(fuzzy)
                        	{
                            	ret += ' OR '+ fields[i] +':' + words[j] + fuzzy + '^' + (fields.length - i);
                            }
                            ret += ')'
                            if(j < words.length - 1) { ret += ' OR '; }
                        }
                    }
                    ret += ')';
                    if(i < fields.length - 1) { ret += ' OR '; }
                }
    			break;
    	}
    	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() {};
    },
    
    loaded: tws_Global.scriptLoaded('tws_Search')
};
