// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function include(library) {
	var heads = document.getElementsByTagName('head');
	if(heads.length > 0) {
		var head = heads[0];
		var script = document.createElement('script');
		script.setAttribute('type', 'text/javascript');
		if(library.match(/^http.+/)) {
			script.setAttribute('src', library);
		} else {
			script.setAttribute('src', '/javascripts/' + library + '.js');
		}
		head.appendChild(script);
	}
}

function hide() {
  var sites = $$('div.site');
  
  sites.each(function(site) {
    site.addClassName('hidden');
  });
}

function show(id) {
  hide();
  var show = $(id);
  if(show) {
    show.removeClassName('hidden');
  }
}

function bindPortfolio() {
  var bookmarks = $$('div.bookmarks a');
  
  bookmarks.each(function(bookmark) {
    bookmark.observe('click', function(e) {
      e.stop();
      window.location.hash = bookmark.getAttribute('rel');
      show(bookmark.getAttribute('rel'));
    }.bind(bookmark));
  });
}

var HashCheck = Class.create({
  lastHash: '',
  timer: null,

  initialize: function() {
    this.timer = setInterval(function() {
      this.checkTarget();
    }.bindAsEventListener(this), 100);
  },

  checkTarget: function() {
    var hash = window.location.hash;
    if(this.lastHash != hash) {
      this.lastHash = hash;
      var bookmark = $(hash.substring(1));
      if(bookmark) {
        show(bookmark);
      } else {
        hide();
      }
    }
  }
});

FastInit.addOnLoad(function() {
  if($('bookmarks')) {
    hide();
    bindPortfolio();
    var h = new HashCheck();
  }
});
