// googleSearch: popup results from the Google search API
// Version 1.1
// Copyright (c) 2011 Daniel Wachsstock
// MIT license:
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

;(function ($){
	$.ui.ajaxpopup.subclass('ui.googleSearch', {
		_init: function (){
			var self = this, form = self.element.closest('form');
			self.contents = this.options.contents;
			var websearch = new google.search.WebSearch();
			// allow using the new (google/cse) or old (google/search) parameters
			websearch.setSiteRestriction(form.find('[name="as_sitesearch"],[name="sitesearch"]').val());
			websearch.setLinkTarget (google.search.Search.LINK_TARGET_SELF);
			websearch.setSearchCompleteCallback(self, function(){
				// create the backup url from the original form
				self.searchurl = form.attr('action')+'?'+form.serialize();
				// if the ajax search can't find it, use full Google (why google.com/search finds things that google.com?q=site:xxx doesn't is beyond me)
				if (websearch.results.length == 0) window.location = self.searchurl;
				self.contents = $.map(websearch.results, function(x) {return x.html} );
				self._trigger('found', 0, [websearch.results]);
				self.show();
			});
			form.bind('submit.googleSearch', function(evt){
				websearch.execute (self.element.val());
				return false;
			});
		},
		show: function(){
			this.box().find('a.moreresults').attr('href', this.searchurl);
			this.box().find('div.resultsdiv').html(this.contents);
			this._super();
		},
		options: {
			url: '/inc/search.html',
			trigger: null,
			contents: $([]) // the initial value of the search results DIV. Could be set to a loading... image
		},
		destroy: function(){
			var form = this.element.closest('form');
			form.unbind ('.googleSearch');
		}
	});

})(jQuery);

