/**
 * Google API interface.
 *
 * @author Jakob Kruse <kruse@kruse-net.dk>
 * @version $Id: Google.js,v 1.2 2006/03/03 20:14:37 Jakob Kruse Exp $
 */

// Check requirements
if (typeof Prototype != "object")
  alert("Prototype (prototype.js) required in Google.js");
if (typeof WS != "object")
  alert("WS-AJAX (ws.js) required in Google.js");
if (typeof SOAP.Element.prototype.get_first_child != "function")
  alert("WS-AJAX extensions (ws-x.js) required in Google.js");
if (typeof Document != "undefined" && typeof Document.prototype.loadXML != "function")
  alert("Document extensions (DocumentX.js) required in Google.js");
if (typeof Behaviour != "object")
  alert("Behaviour (behaviour.js) required in Google.js");

/**
 * The Google object.
 * Calling Google.search('my query') will put 10 first results into <ul> element
 * with id="results" and the estimated total number of results into element with
 * id="estimated_count".
 */
var Google = {
  search : function(search_string) {
    var call = new WS.Call('http://api.google.com/search/beta2');
    //call.add_handler(new Google.DebugHandler());
    call.invoke_rpc(
      new WS.QName('doGoogleSearch', 'urn:GoogleSearch'),
      new Array(
        // Please, get and use your own key!
        // http://www.google.com/apis/
        { name: 'key',        value: 'CpFtnKBQFHIN/S4yPbfao1V0T/8Q/4l2' },
        { name: 'q',          value: search_string },
        { name: 'start',      value: '0' },
        { name: 'maxResults', value: '10' },
        { name: 'filter',     value: 'true' },
        { name: 'restrict',   value: '' },
        { name: 'safeSearch', value: 'false' },
        { name: 'lr',         value: '' },
        { name: 'ie',         value: 'utf-8' },
        { name: 'oe',         value: 'utf-8' }
      ),
      SOAP.SOAPENCODING,
      function(call, envelope, text) {
        $('results').innerHTML = '';
        var result = ((envelope.get_body().get_all_children())[0].get_all_children())[0];
        var count = result.get_first_child('estimatedTotalResultsCount').get_value();
        var resultElements = result.get_first_child('resultElements').get_all_children();
        $('estimated_count').innerHTML = count;
        resultElements.each(function (item) {
          var title =   item.get_first_child('title').get_value();
          var url =     item.get_first_child('URL').get_value();
          var snippet = item.get_first_child('snippet').get_value();
          $('results').innerHTML += '<li><a href="' + url + '">' + title + '</a><br />' + snippet + '</li>';
        });
      }
    );
  }
};

/**
 * Optional handler, logging request/response to page and displaying errors.
 * Uncomment 'call.add_handler(...)' above to use.
 */
Google.DebugHandler = Class.create();
Google.DebugHandler.prototype = Object.extend(new WS.Handler(), {
  on_request : function(call, envelope) {
    $('request').innerHTML = envelope.asElement().xml.escapeHTML();
  },
  on_response : function(call, envelope, transport) {
    $('response').innerHTML = transport.responseText.escapeHTML();
  },
  on_error : function(call, exception) {
    alert('Error:\n' + exception);
  }
});

/**
 * Register some event handlers. Your page needs elements name 'searchingGoogle'
 * and 'result_section' for this to work.
 */
Ajax.Responders.register({
  onCreate : function() {
    Element.show('searchingGoogle');
  },
  
  onComplete : function() {
    Element.show('result_section');
    if (Ajax.activeRequestCount == 0) {
      Element.hide('searchingGoogle');
    }
  }
});

/**
 * Behaviours
 */
Google.behaviours = {
  '#search_string' : function(element) {
    Behaviour.addEventObserver(element, 'keydown',
      function(e) {
        if (!e) var e = window.event;
        if (e.keyCode == Event.KEY_RETURN) {
          $('search_button').click();
        }
      }, false
    );
  },
  
  '#search_button' : function(element) {
    Behaviour.addEventObserver(element, 'click',
      function() {
        Google.search($F('search_string'));
      }, false
    );
  }
};

Behaviour.register(Google.behaviours);

// EOF
