
// Terry Y. Liu Design Portfolio
// Pagination Engine
// Copyright 2009 Drew Hamlin

var current_page, paths;
var transition_duration = 200;
var projects = ['aaarc', 'unbalanced', 'halo', 'want', 'mustlovetype', 'elitica', 'rome', 'livelife', 'random', 'marks'];

function go(page) {
  if (page == 'projects')
    page = 'projects/1';
  paths = page.split('/');
  if (paths.length > 2 || (page && !['projects', 'about'].include(paths.first()))) {
    go('');
    return;
  }
  if (paths.length == 2) {
    var project = paths.last();
    if (project == parseInt(project)) {
      go('projects/' + projects[paths.last() - 1]);
      return;
    }
    if (!projects.include(project)) {
      go('projects');
      return;
    }
  }
  if (current_page != null && ((window.location.hash == '#/' + page) || (!page && window.location.hash == '')))
    return;
  current_page = page;
  if (page != '' || window.location.hash != '')
    window.location.hash = '/' + page;
  _load(page);
}

function _load(page) {
  Animation($('page')).to('opacity', 0.01).ease(Animation.ease.begin).duration(transition_duration).go();
  setTimeout(function() {
    var project = paths.length && paths.last();
    var projectNumber = projects.indexOf(project) + 1;
    document.body.className = (project ? 'work' + projectNumber : '');
    document.body.scrollTop = 0;
    document.body.scrollLeft = 0;
    document.body.id = paths.first() || 'home';
    $('nav').className = (page ? 'visible' : '');
    $('page').style.backgroundImage = '';
    $('description').removeClassName('collapsed');
    if (!page) {
      var random = Math.ceil(3*Math.random());
      $('page').style.opacity = 0.01;
      $('page').style.backgroundImage = 'url(images/home' + random + '.jpg)';
    }
    Animation($('page')).to('opacity', 0.99).ease(Animation.ease.begin).duration(transition_duration).go();
  }, transition_duration);
}

setInterval(function listen_for_page_change() {
  var current_path = _current_path();
  if (current_path != current_page)
    go(current_path);
}, 100);

function _current_path() {
  var path = new Array();
  window.location.hash.replace(/#/, '').split('/').each(function(element) {
    if (element)
      path.push(element);
  });
  return path.join('/');
}
