var cache={};
var searchPending=false;
if(typeof console === "undefined") {
    console = { log: function() { } };
}

//
// TODO:
//   When you click on a search result and go to another page, then click back button
//   there is a big delay before we get the search results back on the page.
//   A solution would be if the browser bfcache would just display the results
//   from memory.
//   Another problem: two change events being fired from the category links.
//   Interestingly only one from the search windows.  Only one on subsequenct searces.
//
function process(d) {
	var r=d.result;
	var arLen=r.length;
	var q=d.q;
	searchPending=false;
	cache[q]=d;
	console.log('cache entry:',q);
	h="<div class='searchresults'>";
	h+="<h3 class='post-title entry-title'>Search for: "+d.title+"</h3>";
	if (arLen == 0) {
		h+="No results found, please try another search.</div>";
	} else {
		var high = r[0].count;
		h+="<ol>";
		for ( var i=0, len=arLen; i<len; ++i ){
		  if ((high>=1000) && (r[i].count<1000)) {
			  h+="<div class='divider'></div>"
			  high=0;
		  }
		  h+="<li><a class='search_link' href='"+r[i].link+"'>"+r[i].title+"</a></li>";
		}
		h+="</ol></div>";
	}
	$("#cssbakery-search-results").html(h);
	//$("#main-wrapper a.search_link").address();
	Cufon.replace('.searchresults h3');
	window.scrollTo(0,0);
}


jQuery.address.init(function(event) {
    console.log("init called");
}).change(function(event) {
    console.log("change called: ",event.value); 
	if (event.value && event.value.indexOf('blogsearch.google') > 0) {
	  console.log("runSearch on:",event.value);
	  runSearch(event.value,'Search results');
	} else {
	  $("#cssbakery-search-results").html('');
	  window.scrollTo(0,0);
	}
	return false;
});

function runSearch(h,t) {
	var href = h.replace(/^(.)*\?/,'');
    href = href.replace(/site:cssbakery.com/,'');
    href = href.replace('+','');
    href = href.replace('[','');
    href = href.replace(']','');
    href = href.replace(/"/g,"'");
    q = href.replace("q=","").replace('+',' ');
    if (cache[q]) {
    	console.log('cache hit on:',q);
    	process(cache[q]);
    } else {
    	console.log('cache miss on:',q);
	    href = href+'&callback=?'
	    href = 'http://tools.cssbakery.com/search?showform=1&'+href+"&title="+q;
	    // FIXME: Tracking pending search results should not be needed, but
	    // need to figure out why runSearch is being run twice for a single
	    // click on a category, or when the search term includes a space
	    // (e.g. search for "PHP" runs once, but type in "PHP " and it'll run
	    // two searches!)
	    if (!searchPending) {
	      $.getJSON(href, process);
	      searchPending = true;
	    }
    }
    return false; 	
}

$(document).ready(function() {
	$('.categories_div ul li a').address();
    $('#searchthis').address();
})

