/**
 * Determines the normalized Google distance between two search terms
 * see http://en.wikipedia.org/wiki/Semantic_relatedness#Google_distance
 */
var ngd = function() {
	// timeout in milliseconds
	var timeoutdelay = 3000;
	// number of pages in google index (as in ngd paper) -> actually should be more
	var tot_pages = 26000000000;
	// base url for google search api
	var googleSearchUrl = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0';
	// indicator for a failed search
	var failed = false;
	var colors= ['#023373', '#177FBF', '#66D8F2', '#99F2F8', 'B9FFFF'];
	// number of result for the different terms
	var hitsTerm1 = null, hitsTerm2 = null, hitsTerm1plus2 = null;
	function retrieveData(searchResult, whichTerm) {
		if(failed === false) {
			window.clearTimeout(ngd.to);
			var freq = searchResult.responseData.cursor.estimatedResultCount;
			switch (whichTerm) {
			case "term1":
				hitsTerm1 = freq;
				break;
			case "term2":
				hitsTerm2 = freq;
				break;
			case "term1plus2":
				hitsTerm1plus2 = freq;
				break;
			default: // not gonna happen
				break;
			}
			if(!(hitsTerm1 === null || hitsTerm2 === null|| hitsTerm1plus2 === null)){
				var term1 = $('#term1').val();
				var term2 = $('#term2').val();
				var resultingNGD = term1 === term2 ? 0 : computeNGD();
				$('#ngdRes').html('ngd: ' + resultingNGD);
				var val = resultingNGD > 1 ? 0 : 100 - Math.round(resultingNGD*100) ;
				$("#progressbar").progressbar( 'value' , val);
				$(".ui-progressbar-value").css("background", "none");
				$(".ui-widget-header").css("background-color", determineColor(val));
				$("#searchHistory").append(term1 + " <-> " +  term2 + " : " + resultingNGD +"<br />");
			}
		}
	}
	function determineColor(val){
		var color = "#ffffff";
		if(val>80){
			color = colors[0];
		} else if (val > 60){
			color = colors[1];
		} else if (val > 40){
			color = colors[2];
		} else if (val > 20){
			color = colors[3];
		} else {
			color = colors[4];
		}
		return color;
	}
	function computeNGD() {
		var nd = (Math.max(Math.log(hitsTerm1), Math.log(hitsTerm2)) - Math.log(hitsTerm1plus2)) / 
		(Math.log(tot_pages) - Math.min(Math.log(hitsTerm1), Math.log(hitsTerm2)));
		if (!isFinite(nd) || isNaN(nd)){
			nd = 0;
		}
		return nd;

	}
	function appendScript(url) {
		var script = document.createElement('script');
		script.setAttribute('src', url);
		document.getElementsByTagName('head')[0].appendChild(script);
	}
	return {
		retrieveData1 : function(searchResult) {
		retrieveData(searchResult, "term1");
	},
	retrieveData2 : function(searchResult) {
		retrieveData(searchResult, "term2");
	},
	retrieveData1plus2 : function(searchResult) {
		retrieveData(searchResult, "term1plus2");
	},
	determineNGD : function() {
		$('#ngdRes').html("<img src='img/ajax-loader.gif' />"); 
		hitsTerm1 = null; 
		hitsTerm2 = null;
		hitsTerm1plus2 = null;
		var term1 = $('#term1').val();
		var term2 = $('#term2').val();
		var url1 = googleSearchUrl + "&q=" + $.URLEncode(term1) + "&callback=ngd.retrieveData1";
		var url2 = googleSearchUrl + "&q=" + $.URLEncode(term2) + "&callback=ngd.retrieveData2";
		var url1plus2 = googleSearchUrl + "&q=" + $.URLEncode(term1 + " " + term2) + 
			"&callback=ngd.retrieveData1plus2";
		appendScript(url1);
		appendScript(url2);
		appendScript(url1plus2);
		ngd.to = window.setTimeout('ngd.failure()', timeoutdelay);
	},
	// failure - follows the link if there was a 404
	failure : function() {
		window.clearTimeout(ngd.to);
		failed = true;
		$('#ngdRes').html('<img src="img/link_error.png"/> Connection Error'); 
	}, 
	getColors: function() {
		return color;
	}
	};
}();
$(document).ready(function() {
	$('#term2').keyup(function(e) {
		if(e.keyCode == 13) {
			ngd.determineNGD();
		}
	});
	$('#term1').keyup(function(e) {
		if(e.keyCode == 13) {
			ngd.determineNGD();
		}
	});
	$("#progressbar").progressbar({
		value: 0
	});

});
