// http://ivorycity.com/blog/2009/08/18/3/
jQuery.fn.extend( {

  outerHtml: function( replacement )
  {

    if (replacement)
    {
      return this.each(function (){ $(this).replaceWith(replacement); });
    }

    var tmp_node = $("<div></div>").append( $(this).clone() );
    var markup = tmp_node.html();

    tmp_node.remove();
    return markup;
  }
});

function emptyFieldAnimate(item)
{
	$(item).css('position', 'relative')
	.animate({left: '+=5px'}, 100)
	.animate({left: '-=5px'}, 100)
	.animate({left: '+=5px'}, 100)
	.animate({left: '-=5px'}, 100)
	.focus();
}

function doSearch(auto)
{
	var searchControl = new google.search.SearchControl();
	searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF); // should work. doesn't.

	var options = new google.search.SearcherOptions();
	options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
	
	var siteSearch = new google.search.WebSearch();
	siteSearch.setUserDefinedLabel("EE 2 User Guide");
	siteSearch.setUserDefinedClassSuffix("siteSearch");
	siteSearch.setSiteRestriction("expressionengine.com/user_guide");
	searchControl.addSearcher(siteSearch, options);

	var siteSearch = new google.search.WebSearch();
	siteSearch.setUserDefinedLabel("EE 1.7 User Guide");
	siteSearch.setUserDefinedClassSuffix("siteSearch");
	siteSearch.setSiteRestriction("expressionengine.com/legacy_docs");
	searchControl.addSearcher(siteSearch, options);

	var siteSearch = new google.search.WebSearch();
	siteSearch.setUserDefinedLabel("EE Forums");
	siteSearch.setUserDefinedClassSuffix("siteSearch");
	siteSearch.setSiteRestriction("expressionengine.com/forums");
	searchControl.addSearcher(siteSearch, options);

	var siteSearch = new google.search.WebSearch();
	siteSearch.setUserDefinedLabel("Devotee");
	siteSearch.setUserDefinedClassSuffix("siteSearch");
	siteSearch.setSiteRestriction("devot-ee.com");
	searchControl.addSearcher(siteSearch, options);
	
	var siteSearch = new google.search.WebSearch();
	siteSearch.setUserDefinedLabel("EE Wiki");
	siteSearch.setUserDefinedClassSuffix("siteSearch");
	siteSearch.setSiteRestriction("expressionengine.com/wiki");
	searchControl.addSearcher(siteSearch, options);
	
	var webSearch = new google.search.WebSearch();
	webSearch.setQueryAddition('expression engine');
	searchControl.addSearcher(webSearch, options);
	
	var siteSearch = new google.search.WebSearch();
	siteSearch.setUserDefinedLabel("Archived EE Forums");
	siteSearch.setUserDefinedClassSuffix("siteSearch");
	siteSearch.setSiteRestriction("expressionengine.com/archived_forums");
	searchControl.addSearcher(siteSearch, options);
	
	searchControl.setSearchCompleteCallback(null, SearchComplete);
	
	searchControl.setNoResultsString('No results found.');
	
	searchControl.draw(document.getElementById("searchcontrol"));
	
	// check for an anchor tag and run a search if one is found
	if(auto)
	{
		var query = window.location.hash;
		if(query)
		{
			// hide the landing page and show the results page
			$("#searchpage").css('display', 'block');
			$("#landingpage").css('display', 'none');
			
			// run the search
			query = unescape(query.substring(1));
			$("#query").val(query);
			searchControl.execute(query);
		}
	}

}


google.load("search", "1", {"nocss" : true});

function OnLoad() {
	doSearch(true);	
}

google.setOnLoadCallback(OnLoad, true);

$(document).ready(function() {

	// no prior searches have occurred so the google api connection/DOM is fine
	window.restartSearch = false;
	
	// autofocus the search field
	$("#landing_query").focus();

	// process the landing 'page' input 
	$("#landing_search").submit(function() {
		if($("#landing_query").val() == '')
		{
			emptyFieldAnimate("#landing_query");
		}
		else
		{	
			$("#query").val($("#landing_query").val());
			$("#custom_search").submit();
			$("#searchpage").css('display', 'block');
			$("#landingpage").slideUp('slow');
		}
		return false;
	});

	$("#custom_search").submit(function() {

		if($("#query").val() == '')
		{
			emptyFieldAnimate("#query");
		}
		else
		{
			// reinitiate the search object if we've previously relocated blocks
			// (screwing around with the DOM objects breaks the link with Google's API)
			if(window.restartSearch)
			{
				doSearch(false);
			}

			$("#searchcontrol:hidden").show();
			$("input.gsc-input").val($("#query").val());
			$("input.gsc-search-button").click();
		}
		return false;
	});
	
	// try our best to disable google' f**cking 'twiddle' feature
	$("#searchcontrol").click(function(e) {

		var originalElement = e.srcElement || e.originalTarget;
		if(typeof originalElement != 'undefined' && originalElement.className == 'gsc-title')
		{
			$(".gsc-webResult").css('display', 'block');
		}
	})
	
});


// Post-search processing
function SearchComplete()
{
	$("#branding").css('position', 'static');
	
	// remove pagination where only 1 page is present
	$(".gsc-cursor").each(function(index) {
		if($(this).html() == '<div class="gsc-cursor-page gsc-cursor-current-page">1</div>')
		{
			$(this).css('display', 'none');
		}
	});

	// move empty results blocks to the bottom
	$(".gsc-resultsRoot:contains('No results found')").each(function(index) {
		var markup = $(this).outerHtml();
		$(this).remove();
		$('.gsc-control > div:first').append(markup);

	});

	// track whether any blocks have been relocated (if they have we need to reinitiate the API for the next request)
	if($(".gsc-resultsRoot:contains('No results found')").length > 0)
	{
		window.restartSearch = true;
	}
	else
	{
		window.restartSearch = false;
	}
	
	// lay everything out neatly
	$('.gsc-resultsbox-visible').masonry({
		singleMode: true,
		columnWidth: 430,
		itemSelector: '.gsc-resultsRoot',
		animate: true,
		animationOptions: {
			duration: 250,
			easing: 'linear',
			queue: false
		}
	});
    
    setWidth();
    
    window.location.hash = escape($("#query").val());
}

// Set the results container width as the highest possible multiple of 430
$(window).resize(setWidth);
$(document).ready(setWidth);

function setWidth()
{
	var width = $(window).width();
	var block_width = 430;
	var blocks_per_row = Math.floor(width/block_width);
	$(".gsc-control").width(blocks_per_row * block_width + 'px');
}
