/*
* jquery.expandCollapseAll.js
* Arietis Software Innovations
* www.arietis-software.com
* version: 1.2
* ----------------------------
* distributed under the GNU General Public License Version 2
* http://www.arietis-software.com/license/gnu/license.txt
*
*/
(function($) {
	
  $.fn.expandCollapseAll = function(options) {
    var opts = $.extend( {}, $.fn.expandCollapseAll.defaults, options);
    return this.each(function() {
      $this = $(this);
      var o = $.meta ? $.extend( {}, opts, $this.data()) : opts;
      initGroup(o, $(this));
    });
  }

  function getBaseName(href) {
    if (href) {
      var arr = href.split('/');
      return href.replace(/^http:\/\/[\w\.]+/, '');
    } else {
      return false;
    }
  }

  function initGroup(o, obj) {
    var hasCurrPage = false;

    //get the browser url
    var href = document.location.href ? document.location.href
    : document.location;
    //get the filepath (without domain)
    var basename = getBaseName(href);
    /*
    * find the group with the selected page and make it visible
    */
    if (basename) {
      $kids = obj.next('ul').find('li a');
      $.each($kids, function() {
        $kid = $(this);
        var filename = getBaseName($kid.attr('href'));
        //does the span contain the selected page?
        if (basename == filename) { //yes (open the group)
          hasCurrPage = true;
        $ancestors = $kid.parents('ul');
        $.each($ancestors, function() {
          $ancestor = $(this);
          if ($ancestor.attr('id') == '') {
            $span = $ancestor.prev('span');
            //change the +/- icon
            $span.addClass(o.currGroupClass);
            //underline the select page
            $kid.addClass(o.currPageClass);
          }
        });
        }
      });
    }
    /*
    * close all groups that don't contain the selected page
    */
    if (!hasCurrPage) {
      //close the group
      obj.next('ul').hide();
      //bind mouseover (hover) event
      obj.mouseover(function() {
        $(this).addClass(o.mouseoverClass);
      });
      //bind mouseout (hover) event
      obj.mouseout(function() {
        $(this).removeClass(o.mouseoverClass);
      });
      //bind onclick event
      obj.click(function() {
        //change the +/- icon
        $(this).toggleClass(o.expandedClass);
        //toggle the ul visibility
        $(this).next('ul').toggle(o.toggleSpeed);
      });
    }
  }

  $.fn.expandCollapseAll.defaults = {
    mouseoverClass : 'mouseover',
    expandedClass : 'expanded',
    currGroupClass : 'on',
    currPageClass : 'underline',
    toggleSpeed : 'fast'
  }
})(jQuery);
