function checkNoResults() {
	var show_no_results = true;
	for (var searcher in SEARCHERS) { 
		searcher = SEARCHERS[searcher];
		if (searcher.completionStatus == undefined) {
			show_no_results = false;
		}
	}
	$('.results_container').each(function() {
		if ($(this).html() != '') {
			show_no_results = false;
		}
	});
	if (show_no_results) {
		$('#no_results_container').slideDown();
	}
}

function formatDisplayUrl(displayUrl) {
	var parts = parseUri(displayUrl).host.split(".");
	displayUrl = '';
	for ( var i = parts.length - 1; i > parts.length - 3 && i >= 0; i--) {
		displayUrl = parts[i] + "." + displayUrl;
	}
	if (displayUrl == 'co.uk.') {
		displayUrl = parts[parts.length-3] + "." + displayUrl;
	}
	return displayUrl.substring(0, displayUrl.length - 1);
}

function getImageResultHTML(result) {
	return '<td valign="bottom" align="center"><a href="' + result.originalContextUrl + '" target="_blank"><img src="' + result.tbUrl + '" style="margin: 0; padding:0"></a></td>';
}

function getImageLinkHTML(result) {
	return '<td valign="top" align="center">' + getVisUrlWithFav(result.originalContextUrl) + '</td>';
}
function getVisUrlWithFav(fullUrl) {
	var parsed = parseUri(fullUrl);
	var fav_url = parsed.protocol + '://' + parsed.host + '/favicon.ico';
	return '<img src="' + fav_url + '" onerror="$(this).hide()" align="absmiddle" width="16" height="16"> <a href="' + fullUrl + '" target="_blank">' + formatDisplayUrl(fullUrl) + '</a>';
}

function imageSearchComplete(searcher, divBase, header) {
	// Check that we got results
	if (searcher.results && searcher.results.length > 0) {
		$('#no_results_container').hide();
		// Grab our content div, clear it.
		page = 1;
		if (searcher.cursor) {
			page = searcher.cursor.currentPageIndex + 1;
		}
		var contentDiv = $('#' + divBase + "_search_content_" + page);

		var html = '';

		var results = searcher.results;

		var resultString = '<small> - ' + number_format(searcher.cursor.estimatedResultCount) + ((searcher.cursor.estimatedResultCount == 1)? ' result':' results');
		if ($('#filter_' + divBase).attr('href') != undefined) {
			resultString += ' - <a href="#" onclick="location.href=$(\'#filter_' + divBase + '\').attr(\'href\');\">View Just These</a>';
		}
		resultString += '</small>';
		html += '<h1>' + header + resultString + '</h1>';
		html += '<table width="100%" cellpadding="0" cellspacing="0" style="margin-top: 5px;"><tr>';
		for ( var i = 0; i < results.length && i < 4; i++) {
			html += getImageResultHTML(results[i]);
		}
		html += '</tr><tr>';
		for ( var i = 0; i < results.length && i < 4; i++) {
			html += getImageLinkHTML(results[i]);
		}
		html += '</tr><tr><td colspan="4"><hr></td></tr>';

		if (results.length > 4) {
			html += '<tr>';
			for ( var i = 4; i < results.length; i++) {
				html += getImageResultHTML(results[i]);
			}
			html += '</tr><tr>';
			for ( var i = 4; i < results.length; i++) {
				html += getImageLinkHTML(results[i]);
			}
			html += '</tr><tr><td colspan="4"><hr></td></tr>';
		}

		html += '</table>';

		if (searcher.cursor && searcher.cursor.pages && searcher.cursor.pages[searcher.cursor.currentPageIndex + 1]) {
			more_results[divBase] = true;
		} else {
			more_results[divBase] = false;
		}
		displayMoreResultsLink();
		html += '<div style="float:right; margin-bottom: 5px"><small>Image results powered by <img src="http://www.google.com/uds/css/small-logo.png" align="absmiddle"></small></div><div style="clear:right"></div><br><br>';
		contentDiv.html(html);
		// contentDiv.append(google.search.Search.getBranding(null, google.search.Search.HORIZONTAL_BRANDING));
		contentDiv.slideDown('slow');
	}
	checkNoResults();
}




function webSearchComplete(searcher, divBase, header, additionalHTML) {
	more_results[divBase] = false;
	// Check that we got results
	if ((searcher.results && searcher.results.length > 0) || additionalHTML != undefined) {
		$('#no_results_container').hide();
		// Grab our content div, clear it.
		page = 1;
		if (searcher.cursor) {
			page = searcher.cursor.currentPageIndex + 1;
		}
		var contentDiv = $('#' + divBase + "_search_content_" + page);

		var resultString = '<small> - ';
		if (searcher.cursor) {
			resultString += number_format(searcher.cursor.estimatedResultCount) + ((searcher.cursor.estimatedResultCount == 1)? ' result':' results');
		}
		if ($('#filter_' + divBase).attr('href') != undefined) {
			resultString += ' - <a href="#" onclick="location.href=$(\'#filter_' + divBase + '\').attr(\'href\');\">View Just These</a>';
		}
		resultString += '</small>';
		contentDiv.html('<h1>' + header + resultString + '</h1>');
		contentDiv.append('<br>');
		if (additionalHTML != undefined) {
			contentDiv.append(additionalHTML);
		}
		if (searcher.results && searcher.results.length > 0) {
			var results = searcher.results;
			for ( var i = 0; i < results.length; i++) {
				contentDiv.append('<h2><a href="' + results[i].url + '" target="_blank">' + results[i].titleNoFormatting + '</a></h2>');
				//console.log(results[i].html);
				contentDiv.append('<p>' + results[i].html.childNodes[0].childNodes[1].innerHTML + '</p>');
				//contentDiv.append('<p>' + $('.gs-snippet', results[i].html).html() + '</p>');
				contentDiv.append('<p>' + getVisUrlWithFav(results[i].url) + '</p>');
				contentDiv.append('<hr>');
			}
			
			if (searcher.cursor && searcher.cursor.pages && searcher.cursor.pages[searcher.cursor.currentPageIndex + 1]) {
				more_results[divBase] = true;
			}
			displayMoreResultsLink();
			contentDiv.append('<div style="float:right; margin-bottom: 5px"><small>Web results powered by <img src="http://www.google.com/uds/css/small-logo.png" align="absmiddle"></small></div><div style="clear:right"></div><br><br>');
		}
		contentDiv.slideDown('slow');
	}
	checkNoResults();
}

function displayMoreResultsLink() {
	var results = false;
	for (var i in more_results) {
		if (more_results[i]) {
			results = true;
			break;
		}
	}
	if (results) {
		$('#more_results_link_div')
				.html('<a href="#">Click Here for More Results</a>');
	} else {
		$('#more_results_link_div')
			.html('');
	}
}

//parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri(str) {
	var o = parseUri.options, m = o.parser[o.strictMode ? "strict" : "loose"]
			.exec(str), uri = {}, i = 14;

	while (i--)
		uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function($0, $1, $2) {
		if ($1)
			uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
strictMode : false,
key : ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q : {
name : "queryKey",
parser : /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser : {
strict : /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose : /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};


function number_format(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

