$(document).ready(function() {
  var project_list = new ProjectList();
  new InputHandler(project_list);
});




function InputHandler(project_list) {
  this._project_list = project_list;
  this._configure_project_hover();
  this._configure_category_switcher();
}

InputHandler.prototype._configure_project_hover = function() {
  var self = this;
  $('.project-link').hover(function() {
    self._project_list.toggle_hover(this, 'add');
  }, function () {
    self._project_list.toggle_hover(this, 'remove');
  });
}

InputHandler.prototype._configure_category_switcher = function() {
  var self = this;
  $('#project-category-switcher').change(function(event) {
    var category_id = parseInt($(this).find('option:selected').attr('value'), 10);
    if(category_id == -1) return;
    if(category_id == 0) {
      self._project_list.display_category('all');
      return;
    }
    self._project_list.display_category(category_id);
  });
}




function ProjectList() {
  this._fade_period = 500;
}

// category_id may be an integer or "all".
ProjectList.prototype.display_category = function(category_id) {
  var self = this;
  // As with portfolio_Detail.js, can't just use call $('.portfolio-project') -- in IE 6, it
  // returns "undefined" (which it never should -- jQuery should only return an empty set in such
  // instances). Specifying an element type before the class resolves this issue.
  var all_projects_selector = 'div.portfolio-project, li.portfolio-project';
  $(all_projects_selector).fadeOut(this._fade_period);
  // Using jQuery callback after fadeOut completes to fadeIn newly-visible projects results in
  // callback being called multiple times -- once for each element that was faded out. Since we
  // want the code to fadeIn the newly-visible projects executed only once, we handle it ourselves
  // using setTimeout.
  window.setTimeout(function() {
    var visible_category_selector = category_id == 'all' ?
                                    all_projects_selector :
                                    'div.portfolio-category-' + category_id + ', li.portfolio-category-' + category_id;
    $(visible_category_selector).fadeIn(self._fade_period);
  }, this._fade_period);
}

// "toggle" must be "add" or "remove".
ProjectList.prototype.toggle_hover = function(element, toggle) {
  var project_id =  parseInt(element.id.match(/\d+$/)[0], 10);
  $('#project-thumbnail-link-' + project_id).
    add('#project-list-link-' + project_id)[toggle + 'Class']('pseudo-hover');
}
