function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

var SearchGo = Behavior.create({
  onclick: function(e) {
    e.stop();
    $('search').submit();
  }
});

var Sidebar = Behavior.create({
  initialize: function(toShow) {
    this.toShow = toShow;
  },
  onclick: function(e) {
    e.stop();
    if (this.toShow) {
      $('frame').removeClassName("one_column");
      createCookie("sidebar", "show", 365*3);
    } else {
      $('frame').addClassName("one_column");
      createCookie("sidebar", "hide", 365*3);
    }
  }
});

var PopupLink = Behavior.create({
  onclick: function(e) {
    e.stop();
    window.open(this.element.href);
  }
});

var SearchTermHighlighter = Behavior.create({
  initialize: function() {
    this.query = document.location.href.parseQuery()['q'];
    if (this.query && this.query.length > 0) {
      this.element.select('div.post').each(this.highlight.bind(this))
    }
  },
  highlight: function(el) {
    var title = el.down('h4.title');
    var content = el.down('div.content');
    // The following regexp is my attempt at not highlighting matches that are inside of an HTML tag.
    // i.e. we don't want to highlight 'href' in <a href="someURL">something</a>
    var queryRegexp = new RegExp('((?:<[^>]+>)*[^<]*\\b)(' + this.query + ')(\\b)', "gi");
    title.innerHTML = title.innerHTML.replace(queryRegexp, "$1<strong class='highlight'>$2</strong>$3");
    content.innerHTML = content.innerHTML.replace(queryRegexp, "$1<strong class='highlight'>$2</strong>$3");
  }
});

Event.addBehavior({
  'a.search_submit': SearchGo,
  '#hide_sidebar': Sidebar(false),
  '#show_sidebar': Sidebar(true),
  'a.popup': PopupLink,
  'div#the_blog': SearchTermHighlighter
});