$(function() {
  setupMenuBar()
  makeTargetBlank()
  hideSearchResults()
  setupSearch()
});

/*
 * HTML Strict does not allow 'target' attribute and we need it. So, instead of
 * using invalid target=_blank, we'll use class=target_blank and this function
 * will add onclick event that will emulate it.
 */
function makeTargetBlank() {
  $('a.target_blank').click(function() {
    open(this.href)
    return false
  });
}

/*
 * Preloads 'mouse hover' version of image for every menu image. This is to
 * prevent annoying split second delay between hovering mouse over menuitem and
 * that menuitem being highlighted, because it was waiting for highlight image
 * to load
 */
function setupMenuBar() {
  $('.menubar a img').each(function() {
    (new Image).src = this.src.slice(0, this.src.length-4) + '2' +
      this.src.slice(this.src.length-4);
  });
  $('.menubar a img').mouseover(toggleImage);
  $('.menubar a img').mouseout(toggleImage);
}

/*
 * Toggles image between normal and highlighted state
 */
function toggleImage() {
  var extPos = this.src.lastIndexOf('.');
  if (this.src.substr(extPos-1,1) == '2') {
    this.src = this.src.substr(0, extPos-1) + this.src.substr(extPos);
  } else {
    this.src = this.src.substr(0, extPos) + '2' + this.src.substr(extPos);
  }
}

/*
 * Search functoins
 */
function setupSearch() {
  $(".search input").keypress(function (e) {
    setTimeout('search($(".search input").val())', 1 * 10);
  })
}

function search(q) {
	 $.get('/search', {'query': q}, function(msg) {
     if (msg == "")
       msg = "Sorry. No matches found...";
     $('.search .results').slideDown('slow').html(msg);
	 });
}

function hideSearchResults() {
  $("html").click(function(){
    $('.search .results').hide();
  })
}
