// Accordion Menu Plugin
// v 1.0

/*
  Options that can  be passed to the plugin:
    slideTime: Time in milliseconds for the slide duration, or
               one of "slow", "normal", "fast"
*/
jQuery.fn.accordionMenu = function(options) {
  var defaults = {
    slideTime: 400 // in milliseconds
  }

  var settings = $.extend({}, defaults, options);

  var obj = $(this);

  $(obj).find('ul ul').hide();

  $.each($(obj), function() {
    /*
    var check = $(this).find('li.active a:not(.arrow)').next();
    if ( check.is('ul') ) {
      check.show().parent().addClass('down');
    }
    */
    var check = $(this).find('a.current').next();
    if ( check.is('ul') ) {
      check.show().parent().addClass('down');
    }
    check = $(this).find('a.current').parent().parent();
    while ( check.is('ul.collapsible') ) {
      check.show().parent().addClass('down');
      check = check.parent().parent();
    }
    
  
    var cookie = null//$.cookie(this.id);
    if ( cookie === null || String(cookie).length < 1 ) {
      $('#' + this.id + '.expandfirst ul:first').show();
    } else {
      $('#' + this.id + ' .' + cookie).next().show();
    }
  });

  $(obj).find('li a.arrow').click(function() {
    var checkElement = $(this).next().next();
    var parent = $(this).parent().parent();

    if ( parent.hasClass('noaccordion') ) {
      //if ( (String(parent).length > 0) && (String(this.className).length > 0) ) {
      if ( (String(this.className).length > 0) ) {
        /*
        if ( $(this).next().is(':visible') ) {
          $.cookie(parent, null);
        } else {
          $.cookie(parent, this.className);
        }
        */
        $(this).next().slideToggle(settings.slideTime);
      }
    }
    if ( (checkElement.is('ul')) && (checkElement.is(':visible')) ) {
      /*
      if ( parent.hasClass('collapsible') ) {
        parent.find('ul:visible').slideUp(settings.slideTime).parent().removeClass('down');
        return false;
      }
      */
      if ( checkElement.hasClass('collapsible') ) {
        checkElement.slideUp(settings.slideTime).parent().removeClass('down');
        return false;
      }
      return false;
    }
    if ( (checkElement.is('ul')) && (!checkElement.is(':visible')) ) {
      //parent.find('ul:visible').slideUp(settings.slideTime).parent().removeClass('down');
      //if ( (String(parent).length > 0) && (String(this.className).length > 0) ) {
      //    $.cookie(parent, this.className);
      //}
      checkElement.slideDown(settings.slideTime).parent().addClass('down');
      return false;
    }
  });
}
