/*
 * Live search JavaScript code
 *
 * Copyright (c) 2006 Alastair J. Houghton
 * All rights reserved.
 *
 */

var search_data_valid = false;

/* A function that does nothing */
function dummy() {
}

/*
 * Makes a nice OSX-like search field
 *
 */

/* Work out which browser we're using */
function browser() {
  var agent = navigator.userAgent.toLowerCase ();

  this.isOpera = agent.indexOf ('opera') != -1;
  this.isNetscape = agent.indexOf ('netscape') != -1;
  this.isIE = agent.indexOf ('msie') != -1;
  this.isSafari = agent.indexOf ('safari') != -1;
  this.isSafari2 = false;

  if (this.isSafari) {
    var wkidx = agent.indexOf ('applewebkit/');
    var wklen = 'applewebkit/'.length;
    var wkrest;

    wkrest = agent.substring (wkidx + wklen, agent.length);
    if (parseFloat (wkrest.substring (0, wkrest.indexOf(' '))) >= 300)
      this.isSafari2 = true;
  }
}

var browser = new browser();

/* Our LiveSearchMgr object */
LiveSearchMgr = function() {
  bindMethods(this);
}

LiveSearchMgr.prototype.initialize = function() {
  this.searchHidden = true;
  
  this.fixupSearchField();

  connect("srchq", "onkeyup", this.updateSoon);
  connect("srchq", "onchange", this.update);

  var srchfrm = getElement("srchfrm");
  srchfrm.onsubmit=function() { return false; }
  srchfrm.action="javascript:dummy()";

  var query = getElement("srchq").value;
  if (query && query.length) {
    this.update();
  }
}

LiveSearchMgr.prototype.updateSoon = function() {
  this.cancelTimer();
  if (!this.deferred) {
    /* If the user stops typing for a bit, do an update. */
    this.timer = callLater(1.0, this.update);
  }
}

LiveSearchMgr.prototype.cancelTimer = function() {
  if (this.timer)
    this.timer.cancel();
  this.timer = null;
}

LiveSearchMgr.prototype.updateForSubmit = function() {
  this.update();
  return false;
}

LiveSearchMgr.prototype.update = function() {
  this.cancelTimer();
  if (!this.deferred) {
    this.submit();
  }
}

LiveSearchMgr.prototype.gotResults = function(req) {
  var elem = getElement("search-results");
  var text = req.responseText;

  elem.innerHTML = text;
  this.deferred = null;
}

LiveSearchMgr.prototype.cancel = function() {
  this.searchHidden = true;
  hideElement("search-results");
  showElement("normal-content");
}

LiveSearchMgr.prototype.submit = function() {
  var q = getElement("srchq");
  var query = q.value;

  if (!search_data_valid)
    query = "";

  if (this.deferred) {
    this.deferred.cancel();
    this.deferred = null;
  }

  if (!query || query.length < 3) {
    this.cancel();
    return;
  }

  if (this.searchHidden) {
    var elem = getElement("search-results");
    elem.innerHTML = "<h3>Searching, please wait&hellip;</h3>";
    hideElement("normal-content");
    showElement("search-results");
    this.searchHidden = false;
  }

  var req = getXMLHttpRequest();
  req.open("POST", "http://alastairs-place.net/movabletype/mt-search.cgi", true);
  req.setRequestHeader("Content-Type",
                       "application/x-www-form-urlencoded");
  
  var keys = ["IncludeBlogs", "Template", "search"];
  var values = ["1", "alastair-live", query];
  var data = queryString(keys, values);
  var d = sendXMLHttpRequest(req, data);

  d.addCallback(this.gotResults);

  var self = this;
  d.addBoth(function (res) {
      self.deferred = null;
      return res;
  });

  this.deferred = d;

  return d;
}

/* Fix the search field so that it looks right in other browsers. */
LiveSearchMgr.prototype.fixupSearchField = function() {
  var q = document.getElementById('srchq');

  /* In Safari, replace it with a fancy search field */
  if (browser.isSafari2) {
    var attrs = {
        "id": "srchq", 
        "type": "search",
        "name": "search",
        "placeholder": "Search this blog",
        "results": "5",
        "autosave": "alastairs-place.net search"
    };
    var newField = INPUT(attrs);
        
    search_data_valid = true;
    newField.style.width = "156px";

    swapDOM(q, newField);

    q = document.getElementById('srchq');
  } else {
    var b = document.getElementById('srchb');
    var lc = document.getElementById('searchleftcap');
    var rc = document.getElementById('searchrightcap');
    var searchtxt = "Search this blog";

    lc.style.display = "inline";
    rc.style.display = "inline";
    q.className = "sbox";
    q.value = searchtxt;
    q.style.color = "#888";
    b.className = "sbox";
    q.onfocus = function() {
      if (!search_data_valid) {
	q.value = ""; 
	q.style.color = "#000"; 
        search_data_valid = true;
      }
      return true;
    };
    q.onblur = function() { 
      if (!q.value.length) {
	search_data_valid = false;
	q.value = searchtxt;
	q.style.color = "#888";
      } else {
	search_data_valid = true;
      }
      return true;
    };
  }

  q.blur();
}

searchMgr = new LiveSearchMgr();
addLoadEvent(searchMgr.initialize);
