/*
 * Copyright (c) 2009 ZephirWare
 * All rights reserved.
 *
 */

document.observe('dom:loaded', function() {
  
  /*
   * Facets.
   */
  if ($$('.facetbox').length > 0) {
    var newState = function (el) {
      return $(el).hasClassName('off') ? 'on': 'off';
    };
    
    /*
     * Open/close facets.
     */
    $$('.facetbox .level1').each(function(f) {
      if (f.hasClassName('forced_off')) {
        Event.observe(f, 'click', function() {
          if (this.hasClassName('off')) {
            this.removeClassName("off")
            set_facet_state(this, "on");
          } else {
            this.addClassName("off");
            set_facet_state(this, "off");
          }
        });
      } else {
        Event.observe(f, 'click', function() {
          new Ajax.Request("/editorial/search/toggle_facet/" + this.id + '?format=json&value=' + newState(f),
                          {asynchronous:true, evalScripts:true});
        });
      }
    });
    $$('.facetbox .level2 dt, .facetbox .level2 dt').each(function(f) {
      Event.observe(f, 'click', function(e) {
          new Ajax.Request("/editorial/search/toggle_facet/" + this.id + '?format=json&value=' + newState(f),
                          {asynchronous:true, evalScripts:true});
      });
    });
    $$('.facetbox .level2 dt a').each(function(f) {
      Event.observe(f, 'click', function(e) {
        if (e.shiftKey || e.ctrlKey) {
          /* Let the default behavior happen */
        } else {
          new Ajax.Request("/editorial/search/toggle_facet/" + this.parentNode.id + '?format=json&value=' + newState(f.parentNode),
                          {asynchronous:true, evalScripts:true});
          Event.stop(e);
        }
      });
    });
    
    
    /*
     * See more on facets.
     */
    $$('.facetbox .see-more').each(function(f) {
      Event.observe(f, 'click', function(e) {
        openInPopup(f, f.getAttribute('title'), {width: 610, height: 400});
        Event.stop(e);
      });
    });
  }
});
