/**
 * Accordion
 * 
 * @version $Id: accordion.js 402 2009-07-03 21:43:11Z  $
 */
Accordion = function(config) {
  $.extend(this, config || {});
  
  if(this.auto_init)
    this.init();
}

Accordion.prototype = {
  // configurable {
  selector: '', // required
  auto_init: true,
  speed: 'normal',
  expand_first: true,
  process_anchors: false,
  // }
  
  init: function() {
    this._initTitles();
    if(this.process_anchors)
      this.processAnchor();
    else if(this.expand_first)
      this.expandFirst();
  },
  
  _initTitles: function() {
    $('.acc_title', this.getEl()).click(this.onClick.createDelegate(this)).each(function() {
      $(this).generateId();
    });
  },
  
  processAnchor: function() {
    var id = this._extractAnchor() + '_';
    var $title = this.getTitleEl(id);
    if($title.length != 0) {
      this.expand(id);
    } else if(this.expand_first) {
      this.expandFirst();
    }
  },
  
  _extractAnchor: function() {
    var matches = /#(city[0-9]+)$/.exec(location.href);
    return matches ? matches[1] : null;    
  },
  
  expandFirst: function() {
    var first_id = $('.acc_title', this.getEl()).eq(0).attr('id');
    if(first_id)
      this.expand(first_id);
  },
  
  expand: function(id) {
    if(this.isVisible(id))
      return;
      
    this.collapseOther(id);
    if(this.process_anchors)
      this.getContentEl(id).show();
    else
      this.getContentEl(id).slideDown(this.speed);
    this.getTitleEl(id).addClass('active');
  },
  
  collapse: function(id) {
    if(!this.isVisible(id))
      return;
      
    if(this.process_anchors)
      this.getContentEl(id).hide();
    else
      this.getContentEl(id).slideUp(this.speed);
    this.getTitleEl(id).removeClass('active');
  },
  
  toggle: function(id) {
    if(this.isVisible(id))
      this.collapse(id);
    else
      this.expand(id);
  },
  
  isVisible: function(id) {
    return this.getContentEl(id).is(':visible');
  },
  
  collapseOther: function(id) {
    var _this = this;
    $('.acc_title', this.getEl()).each(function() {
      var title_id = $(this).attr('id');
      if(title_id != id)
        _this.collapse(title_id);
    });
  },
  
  _unfocus: function(id) {
    this.getTitleEl(id).blur();
  },
  
  onClick: function(event) {
    var id = $(event.currentTarget).attr('id');
    this.toggle(id);
    this._unfocus(id);
    if(!this.process_anchors)
      return false;
  },
  
  getEl: function() {
    return $(this.selector);
  },
  
  getContentEl: function(id) {
    return this.getTitleEl(id).next('.acc_content');    
  },
  
  getTitleEl: function(id) {
    return $('#' + id);    
  }
}
