Geo = {}

Geo.formSubmit = function() {
	domains = $F("domains")
	keyword = $F("keyword")
	uk = $F("uk")
	if (keyword) {
		if (uk) {
			new Ajax.Request("/clickability.py/scrape_google_ie", {
				method:"post",
				postBody:"keyword="+escape(keyword),
				onSuccess:function(t) {
					var results = eval('('+t.responseText+')')
					domains = []
					results.each(function(r) {
						domains.push(r.link.split("/")[2])
					})
					Geo.handleDomains(domains)
				}
			})
		} else { 
			searcher = new GwebSearch()
			searcher.setNoHtmlGeneration()
			searcher.setResultSetSize(GSearch.LARGE_RESULTSET)
			searcher.setSearchCompleteCallback(this,
				Geo.submitCallback,
				[searcher])
			searcher.execute(keyword)
		}
	} else {
		Geo.handleDomains(domains)
	}
}

Geo.submitCallback = function(searcher) {
	var results = []
	searcher.results.each(function(r) {
		results.push(r.unescapedUrl.split("/")[2])
	})
	Geo.handleDomains(results.join("\n"))
}

Geo.handleDomains = function(domains) {
	if (typeof(domains) == "string")
		this.domains = domains.split("\n").uniq()
	else
		this.domains = domains.uniq()
	Geo.buildTable()
	q = []
	this.domains.each(function(d) {
		q.push("domains="+escape(d))
	})
	query = q.join("&")+"&geolocate=1"
	new Ajax.Request("/clickability.py/nslookup", {
		method:"post",
		postBody:query,
		onSuccess:function(r) {
			var results = eval('('+r.responseText+')')
			for (domain in results) {
				Geo.containers[domain].childNodes[1].appendChild(document.createTextNode(results[domain]['ip']))
				Geo.containers[domain].childNodes[2].appendChild(document.createTextNode(results[domain]['country'] || "unknown"))
			}
			new Effect.Highlight("results")
		},
		onFailure:function() {
			Element.infanticide(Geo.cont)
			Geo.cont.appendChild(Builder.node("p", "Sorry, there was an error with your request. Please try again."))
			new Effect.Highlight("results")
		}
	})
}

Geo.buildTable = function() {
	Element.infanticide(Geo.cont)
	containers = {}
	tbody = Builder.node("tbody")
	this.cont.appendChild(
		Builder.node("table", [
			Builder.node("thead", [
				Builder.node("tr", [
					Builder.node("th", "Domain"),
					Builder.node("th", "IP"),
					Builder.node("th", "Country")
				])
			]),
			tbody
		])
	)
	this.domains.each(function(d) {
		cont = Builder.node("tr", [
			Builder.node("td", d),
			Builder.node("td"),
			Builder.node("td")
		])
		tbody.appendChild(cont)
		containers[d] = cont
	})
	this.containers = containers
	Element.show("results")
}

Event.observe(window, "load", function() {
	Geo.cont = $("results_cont")
})

