CatToggler = Class.create()
CatToggler.prototype = {
  initialize: function (brand) 
  {
    this.brand = brand
    $$('img[class~="cat_toggler"]').each(
      function (v) {
        YAHOO.util.Event.addListener(v, "click", this.toggleCat, null, this)
      }
    ,this)

    $$('span[class~="cat_name"]').each(
      function (v) {
        YAHOO.util.Event.addListener(v, "click", this.catNameClick, null, this)
      }
    ,this)

    if ( $('catMultiples') ) 
      YAHOO.util.Event.addListener('catMultiples', "click", this.toggleCatBoxes, null, this)
    if ( $('uncheckAllCat') ) 
      YAHOO.util.Event.addListener('uncheckAllCat', "click", this.uncheckCatBoxes, null, this)
  },

  catNameClick: function(e)
  {
    target = YAHOO.util.Event.getTarget(e)
    if ( $('catMultiples') && $('catMultiples').checked )
      this.toggleCat(e)
    else if ( this.brand )
      window.location = '/products/search?clear=1&category[]='+target.id+'&brands[]='+this.brand
    else
      window.location = '/products/search?cont=1&category[]='+target.id;
  },

  toggleCatBoxes: function(e)
  {
    target = YAHOO.util.Event.getTarget(e)
    $$('input[class~="cat_checkbox"]').each(
      function (v) {
        Element.extend(v)
        if ( target.checked )
          v.removeClassName('hide') 
        else
          v.addClassName('hide') 
      }
    )

    if ( target.checked )
      $('uncheckAllCat').removeClassName('hide') 
    else
      $('uncheckAllCat').addClassName('hide') 
  },

  uncheckCatBoxes: function(e)
  {
    $$('input[class~="cat_checkbox"]').each(
      function (v) {
        v.checked = false
      }
    )
  },

  toggleCat: function(e)
  {
    target = YAHOO.util.Event.getTarget(e)

    // FF might grab the img not the A
    if ( target.tagName != 'A' )
      target = target.parentNode

    this.cleanWhitespace(target)
    this.cleanWhitespace(target.parentNode.parentNode)

    // IE doesn't automagically extend the elements
    Element.extend(target.parentNode.nextSibling)

    if ( target.parentNode.nextSibling.hasClassName('hide') ) {
      target.parentNode.nextSibling.removeClassName('hide')
      target.childNodes[0].src = '/images/toggle_active.png'
    } else {
      target.parentNode.nextSibling.addClassName('hide')
      target.childNodes[0].src = '/images/toggle.png'
    }
  },

  cleanWhitespace: function(element) {
    for (var i = 0; i < element.childNodes.length; i++) {
      var node = element.childNodes[i]
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        Element.remove(node)
    }
  }
}

