~grubng-dev/grubng/searchinterface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>

	<title>grub (alpha)</title>
	<script type="text/javascript" src="prototype.js"></script>
	<link rel="stylesheet" type="text/css" href="grub.css"/>
	<link rel="icon" href="images/grub.ico" type="image/x-icon">
<script type="text/javascript">

// sets focus in search field	
window.onload = init;

// semaphore to lock loading of further results to often
var sem = 0;

var coargs = new Array();
var cogc = new Array();
// TODO get these from a config file, depending from the user agent language
var loadingString = "Loading..."
var endString = "End"
var winheight; // the window height

// TODO center output for 0 search results
// TODO add some links like "download source", project site, how can I help, forum?, FAQ?
// TODO add a max count for search results to load, should be temporarely here for damage limitation reasons of bad JavaScript 
// TODO make this site use the GET method instead of post, so we can give search URLs away
// TODO add "more results" link to end of the site, if JS does not work properly

/*
* TODO
*/
function callOut(func, url, arg) {
	// non-blocking jsonp fetcher
	var i = document.createElement('iframe');
	cogc[cogc.length] = i; // garbage collector
	i.style.display = "none";
	document.getElementsByTagName('head')[0].appendChild(i);
	var doc = null;
	
	if (i.contentDocument) { // Firefox, Opera
		doc = i.contentDocument;
	} else if(i.contentWindow) { // Internet Explorer
		doc = i.contentWindow.document;
	} else if(i.document) { // Others?
		doc = i.document;
	}
	if(doc == null) {
		throw "Document not initialized";
	}
	coargs[coargs.length] = arg;
	doc.open();
	doc.write("<script type=\"text/javascript\">function "+func+"(j){parent."+func+"(parent.coargs["+(coargs.length-1)+"],j);parent.setTimeout('cocleanup("+(cogc.length-1)+")',1);}</scr"+"ipt>");
	doc.write("<script type=\"text/javascript\" src=\""+url+"\" defer=\"defer\"></scr"+"ipt>");
	doc.close();
}

/*
TODO
*/
function cocleanup(id){
	cogc[id].parentNode.removeChild(cogc[id]);
	cogc[id] = 0;
}

/*
TODO
*/
function comma(number) {
  
  number = '' + number;
  
  if (number.length > 3) {  
    var mod = number.length % 3;
    var output = (mod > 0 ? (number.substring(0,mod)) : '');
      
    for (i=0 ; i < Math.floor(number.length / 3); i++) {
      if ((mod == 0) && (i == 0)) {
        output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
      } else {
        output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
      }
    }
  return (output);
  }
  else return number;
}

/*
returns month or months depending on what's needed
*/
function plural(num, word){
	return word = (num != 1) ? word+"s" : word;
}

/*
FIXME Why do we need this method?
*/
function getspan(i) {
	return i;
	}

/*returns friendly time difference
TODO get all String from variables that catch the correct language version
*/
function whenAgo(t1, t2) {
	if(!t1 || !t2) return getspan("just now");
	var diff = t1 - t2;
	diff /= 1000;
	if(diff == 0) return getspan("just now");
	if(diff < 120) return getspan("moments ago");
	var months = Math.floor(diff / 2592000);
	if(months > 0) return months + " " + getspan(plural(months,"month")) + " " + getspan("ago");
	var days = Math.floor(diff / 86400);
	if(days > 0) return days + " " + getspan(plural(days,"day"))+" " + getspan("ago");
	var hours = Math.floor(diff / 3600);
	if(hours > 0) return hours + " " + getspan(plural(hours,"hour"))+" " + getspan("ago");
	var minutes = Math.floor(diff / 60);
	if(minutes > 0) return minutes + " " + getspan(plural(minutes, "minute")) + " "+getspan("ago");
}

/*
 * (re)calculates the window height and updates the variable winheight
 */
function calculateWinheight() {
	winheight = document.getElementById('results').offsetHeight;
}

/*
* detecs if we are at the end of the site and loads new results if true
*/
function isSiteEnd() {
	// determine scroll position
	var scrollTop = document.body.scrollTop;
	if (scrollTop == 0) {
    	if (window.pageYOffset) {
			scrollTop = window.pageYOffset;
		} else {
			scrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
		}
	}
	if (winheight - scrollTop < 1000) {
		// the semaphore prevents too many fetches
		if (sem == 1) {
			return;
		} 
		sem = 1;

		var q = encodeURIComponent(document.forms[0].searchField.value);
		// fetch more search results
    	callOut("scented", 
    	"http://46.4.15.84:8080/solr/select?indent=on&version=2.2&q="+q+"&hl=true&hl.fl=body&hl.snippets=3&start="+nextres+"&rows=20&qt=dismax&debugQuery=on&wt=json&fl=url,ip,length,description,score,fetchedtime&json.wrf=scented",
    	"");
	}
}

/*
* TODO
*/
var scents = new Object();
var doctitle = document.title;

/*
* submits search request to the server
*/
function smell() {
	// the semaphore prevents too many fetches
	if (sem == 1) {
		return;
	}
	sem = 1;

	scents = new Object();
	
	// show loading note
	$("loading").style.display = "block";
	
	var f = document.forms[0];
	var q = encodeURIComponent(f.searchField.value);
	callOut("scented", 
	"http://46.4.15.84:8080/solr/select?indent=on&version=2.2&q="+q+"&hl=true&hl.fl=body&hl.snippets=3&start=0&rows=20&qt=dismax&debugQuery=on&wt=json&fl=url,ip,length,description,score,fetchedtime&json.wrf=scented",
	"");
    document.title = doctitle + " - " + f.searchField.value;
	// FIXME does not seem to work properly
	// this is done to reset the scroll position of the user's browser on new searches
    scroll(0,0);
	// TODO decide to do this or not, pro: you can edit your seatch immidiately, con: you can not directly navigate using space 
    //f.searchField.blur();
	return false;
}

/*
prints the search results
*/
function scented(s, j) {
	/* hide loading note as it is completed now */
    $("loading").style.display = "none";
	var div = document.createElement("div");
	var now = new Date();
    var nowsecs = now.getTime();
    if (parseInt(j.responseHeader.params.start) == 0) {
		// show how much results we found
		// TODO get this translated and for plural and singular
        $("results").innerHTML = 
        				"<h5>" + comma(j.response.numFound) + " results found for </h5>" + 
        				"<h2>" + document.forms[0].searchField.value + "</h2>";
    }

	for(var i = 0; i < j.response.docs.length; i++) {
		var d = j.response.docs[i];
		var h = j.highlighting[d.url];
		var e = j.debug;
		var fetchdate = String(d.fetchedtime);
		var year = fetchdate.substr(0,4);
		var month = fetchdate.substr(4,2);
		var day = fetchdate.substr(6,2);
		var hour = fetchdate.substr(8,2);
		var minutes = fetchdate.substr(10,2);
		var seconds = fetchdate.substr(12);
		var sp = document.createElement("div");
        var fetchtime = new Date(year, (month - 1), day, hour, minutes, seconds, 0);
		var fetchtimesecs = fetchtime.getTime();
		var retrievetime = whenAgo(nowsecs, fetchtimesecs);
		sp.className="sr";
		var a = document.createElement("a");
		a.className = "title";
		// FIXME is there a limit for title length specified somewhere?
		a.title = d.description.substr(0,100);
		a.href = d.url;
		if (d.description.length > 50) {
		    a.innerHTML = d.description.substr(0,50) + "...";
        } else if (d.description.length == 0) {
            a.innerHTML = d.url;
        } else {
            a.innerHTML = d.description;
        }
		sp.appendChild(a);
		sp.innerHTML += "<br />"
				
        var length = Math.ceil(d.length / 1024);
        var strbytes;
        if (length > 1024) {
            length = Math.ceil(d.length / 1024);
            strbytes = "MB";
        } else {
            strbytes = "kB";
        }
		sp.innerHTML += "<font color=\"#1a831c\"><strong class=\"info\">" + d.url + "<span> IP:" + d.ip + "</span></strong><strong> " + length + " " + strbytes + " (" + retrievetime + ")</strong></font><br />";
		var temp = 0;
		var explainscore;
		for (var urls in e.explain) {
		    if (temp == i) {
		        explainscore = e.explain[urls];
		        explainscore = explainscore.replace("\n", "<br />");
		    }
		    temp++;
		}
		sp.innerHTML += "<strong class=\"info\">Score: " + d.score + "<span>" + explainscore + "</span></strong>";
		if(h && h.body && h.body.length > 0) sp.innerHTML += "<br /> - " + h.body.join("...<br />...");
		div.appendChild(sp);
	}
    nextres = parseInt(j.responseHeader.params.rows) + parseInt(j.responseHeader.params.start);
    if (nextres < parseInt(j.response.numFound)) {
		// enable "polling" to see if user reached the site's end
	    //var intervalid = setInterval( "howlow()" , 1000);
		var intervalid = setInterval( "isPrefetchNeeded()" , 1000);
    } else {
		// disable "polling" if there are no more results to fetch
	    clearInterval(intervalid);
		// don't print "end" if no results were found
		if (parseInt(j.response.numFound) != 0) {
			var sp2 = document.createElement("h3");
			sp2.innerHTML = endString;
		}
		div.appendChild(sp2);
    }
	$("results").appendChild(div);
	// update the window height variable; needed to load new results when the bottom is reached
	calculateWinheight();
	// reset semaphore
	sem = 0;
}

/*
* sets focus to search field
*/
function init() {
	document.getElementById("searchFieldID").focus();
	// TODO read the GET arguments if there are any, write them here and start a search
	document.getElementById("searchFieldID").value = "";
	 Event.observe(window, 'scroll', isSiteEnd);
}

</script>
</head>

<body>
    <div class="suma">
        <a href="http://suma-ev.de"><img src="images/sumalogo.jpg" alt="suma logo" title="suma logo" border="0"></a><br>
        Sponsored by <a href="http://suma-ev.de">SuMa e.V.</a>
    </div>
    <div class="grublogo"><img src="images/logo.png" alt="grub logo" title="grub logo"></div>

<!-- This shows the "loading..." note while fetching the results from the server -->
<div id="loading" class="loading">
    <strong>
    <script type="text/javascript">document.write(loadingString)</script>
    </strong><br />
    <img src="images/spinner.gif" border="0" alt="loading">
</div>

<!-- The input field for the search submit -->
<div id="top" class="searchField">
    <form action="javascript:" method="post" onsubmit="return smell()">
	    <input name="searchField" id="searchFieldID"/>
	</form>
</div>

<!-- divs which include the single search results will go here -->
<div id="results" class="results"></div>

</body>
</html>