var d=$("<span />").css({position:"relative"}).insertBefore("#stickylinks #search")
d.append($("#stickylinks #search"))

var months={"jan":1,"feb":2,"mar":3,"apr":4,"may":5,"jun":6,"jul":7,"aug":8,"sep":9,"oct":10,"nov":11,"dec":12}

$("#search").parent().unbind("keyup blur")
.keyup(function(e){
	if(e.which==13){//if press enter, search
		var it=$(this).children("#search"),
			v=it.val().replace(/^\s+|\s+$/g,'').replace(/\s{2,}/g,' ').toLowerCase()
		location.href="http://www.google.com/search?q=site%3Adailypaul.com+"+escape(v)
	} 
	clearTimeout(window.stim)
	window.stim=setTimeout(function(me){
		var it=$(me),
			v=it.val().replace(/^\s+|\s+$/g,'').replace(/\s{2,}/g,' ').toLowerCase()
		//console.log(v)
		if(me.was!=v) performSearch()
		me.was=v
	},500,$("#search").get(0))
})
//.blur(function(){$("#results").remove()})
.hover(
	function(){clearTimeout(window.searchBoxGoAway)},
	function(){
		if(!$("#search").get(0).loading&&$("#results").length)
			window.searchBoxGoAway=setTimeout(function(x){
				x.kill()
			},500,$("#results").get(0))
	}
)

function performSearch(pageN){
	var search=$("#search"),
		v=search.val(),
		perPage=8,//has to be
		start=pageN?pageN*perPage:0
	if(v.length&&v.match(/\S/)&&(!pageN||pageN<=7)){
		search.get(0).loading=1
		
		//multiple ajax events need an object to coordinate
		var o={
			need:2,
			got:0,
			spell:false,
			increment:function(){
				this.got++
				if(this.got==this.need) this.proceed()
				//console.log("incremented",this.got)
			},
			proceed:function(){
				if(this.spell){
					$("#under").html("<b>or perhaps:</b> <span id=perhaps>"+this.spell+"</span> <b>?</b>")
						.css({display:"block"})
					var p=$("#under")
					p.click(function(){
						$("#search").val(this.spell).parent().keyup()
					})
					p.get(0).spell=this.spell
					//console.log("went on",this.spell)
					if($("#results table tr").length<=1) $(".more").remove()
					this.spell=false
				}
				else{
					$("#under").remove()
				}
			}
		}
		
		//get spell check
		$.ajax({
			url:"http://gdata.youtube.com/feeds/videos?q="+v+"&alt=json-in-script",
			dataType:"jsonp",
			success:function(r){
				o.spell=r.feed.link[1].title
				//console.log("suc")
			},
			error:function(){
				o.spell=false
				//console.log("fail")
			},
			complete:function(){
				o.increment()
				//console.log("spellchecked")
			}
		})
		
		
		//get search results
		$.ajax({
			dataType:"jsonp",
			url:"http://ajax.googleapis.com/ajax/services/search/web",
			data:{
				v:"99.0",
				rsz:perPage,
				cx:"partner-pub-9854783963896813:3qozvajd801",
				start:start,
				q:v
			},
			beforeSend:function(){},//doesn't fire?
			success:function(r){
				//console.log(r)
				var a=$("#search").parent().find("#results")
				if(!pageN){//if new instance
					if(a.length) a.remove()//get rid of old
					a=$("<div />").attr("id","results")
						.html("<a id=under href='javascript:void(0)' ></a><table></table>")
						.appendTo($("#search").parent())
						.scroll(function(e){
							var scroll=$(this).scrollTop(),
								frame=$(this).height(),
								content=$(this).children("table").height(),
								tol=10
							
							//console.log(scroll,frame,content,(content-(frame+scroll))-tol < 0)
							
							if((content-(frame+scroll))-tol < 0) $(this).find(".more").click()
							
						})
					a.get(0).kill=function(){$(this).fadeOut(100,function(){$(this).remove()})}
					
					var more=$("<tr />").html("<td colspan=2>&#9660; more &#9660;</td>").addClass("more")
						.css({color:"white","text-align":"center",padding:".5em"})
						.bind("mouseover click",function(){
							this.page++
							performSearch(this.page)
						}).appendTo(a.children("table:first"))
					more.get(0).page=0
					a.get(0).o={}
				}
				var x=r.responseData.results,
					more=a.find(".more")
					//,at=a.children("table:first")
				for(var i in x){
					//make relative
					var url=x[i].url.replace(/http\:.*\.com\//,"/")
					if(url.length>1){//if not "/"
						//get most identifying part of URL, what immediately follows /
						var id=url.match(/\/([^\/]+)\/|\/([^\/]+)$/)
						//if it's something more siginificant than the home page
						if(id&&id[1]){
							id=id[1]
							//if it's not already there, add
							if(!a.get(0).o[id]){
								var date=x[i].content.match(/\w{3,} \d+\, \d+/)
								if(date){
									date=(date+'').split(" ")
									date=months[date[0].toLowerCase()]+"/"+date[1].replace(/\,/g,'')+"/"+date[2].substr(-2)
								}
								else{
									date=x[i].content.match(/\d+\s*\/\s*\d+\s*\/\s*\d+/)
									if(date) date=(date+'').replace(/\s+|^0+/g,'').replace(/\/20(\d{2})$/,"/$1")
									else date=""
								}
								a.get(0).o[id]=1
								
								var nu=$("<tr />")
									.append(
										$("<td />").addClass("res").append(
											$("<a />").css({"font-size":"13px"})
												.html(x[i].titleNoFormatting.replace(/\| Ron.*/i,'')).attr({href:url})
										)
									)
									.append(
										$("<td />").html(date.replace(/\/?undefined\/?/g,''))
									)
									.css({display:"none"})
									.insertBefore(more)
								nu.slideDown(100)
							}
						}
					}
				}
				//if(!pageN) a
			},
			complete:function(){
				search.get(0).loading=0
				o.increment()
				//console.log("searched")
			}
		})
	}
	else if(pageN>7) $("#results .more").remove()
	else if(!v.length||!v.match(/\S/)) $("#results").get(0).kill()
}
