var SearchController = Class.create();
SearchController.prototype = {
  initialize: function(form, options) {
    this.setOptions(options);
    this.setFormComponent(form);
  },
  
  setOptions: function(options) {
    this.options = {
      empty:      "Search everyone's weblogs",
      emptyColor: '#aaa',
      textColor:  '#555',
      parameters: ''
    }
    Object.extend(this.options, options || {});
  },
  
  setFormComponent: function(form) {
    var f = this.form = $(form);
    var q = f.q;  // query input component
    
    Event.observe(q, 'focus', 
      this.prepareQueryInput.bindAsEventListener(this));
    Event.observe(q, 'blur', 
      this.concludeQueryInput.bindAsEventListener(this));
    Event.observe(f, 'submit',
      this.searchAction.bindAsEventListener(this));
    this.prepareFormComponent();
  },
  
  prepareQueryParameter: function() {
    var f = this.form;
    var q = f.q;
    if (encodeURIComponent == null) return;
    if (q.value != '') return;
    
    var path = (document.location.href.match(/\/search\/(q\/.+)/) || [])[1];
    if (path != null) {
	  var items = path.split('/');
	  if (items[0] == 'q') q.value = decodeURIComponent(items[1]);
	  if (items[2] == 'blog' && f.blog != null) f.blog.value = decodeURIComponent(items[3]);
    } else {
      // old style
      var params = document.location.search.toQueryParams();
      if (params.q != null) q.value = decodeURIComponent(params.q);
      if (f.blog != null && params.blog != null) f.blog.value = decodeURIComponent(params.blog);
    }
  },
  prepareFormComponent: function() {
    this.prepareQueryParameter();
    this.concludeQueryInput();
  },
  
  searchAction: function(event) {
    if (encodeURIComponent == null) return;
    
    var f = this.form;
    var qv = f.q.value;
    
    if (this.options.empty == qv) qv = '';
    
    var params = {q: qv};
    var type = f.getElements().find(function(element) {
      return element.name == 'type';
    })
    
    if ((type && type.value == 'this') ||
        (!type && f.blog && f.blog.value != '')) 
    {
      params.blog = f.blog.value;
    }
    
    // 2007-03-01: Pretty URL
    /*var url = f.action+'?'+$H(params).toQueryString();*/
    var url = f.action;
    url = url.replace(/https?:\/\/[^/]+/, '');
    url = [url, 'q', encodeURIComponent(params.q)].join('/');
    if (params.blog) url = [url, 'blog', encodeURIComponent(params.blog)].join('/');
    url = url.replace(/\/+/g, '/');
    
    document.location = url;
    Event.stop(event);
  },
  
  prepareQueryInput: function() {
    var q = this.form.q;
    if (q.value == this.options.empty) 
      q.value = '';
    q.style.color = this.options.textColor;
  },
  concludeQueryInput: function() {
    var q = this.form.q;
    if (q.value != '') {
      q.style.color = this.options.textColor;
      return;
    }
    q.value = this.options.empty;
    q.style.color = this.options.emptyColor;
  }
}

