﻿// **************************************************************
// simpleAccordion
//
// simpleAccordion is my first try at writing jQuery plugins
// it provides a means for displaying a so called 'accordion' view
// mostly used in navigation, but can be used otherwise.
//
// Author      : Richard van den Winkel
// Website     : http://www.vandenwinkel.com/jquery/simpleAccordion
// E-mail      : richardvandenwinkel@gmail.com
// Releasedate : May 13 2009
// Version     : 1.0
// **************************************************************

/*

--- An example ---
html:
<div class="accordion">
    <h2>trigger</h2>
    <ul>
        <li>item</li>
        <li>item</li>
        <li>item</li>
    </ul>

    <h2>trigger</h2>
    <ul>
        <li>item</li>
        <li>item</li>
        <li>item</li>
    </ul>
</div>

function call: 
<script type="text/javascript">
    $(document).ready(function(){
        $('.accordion').simpleAccordion({
            speed: 'fast',
            container: 'ul'
        });
    });
</script>

*/

;(function($) {
    $.fn.simpleAccordion = function(o) {

        // default settings
        var o = jQuery.extend({
            trigger: 'h2',
            container: 'div',
            speed: 'slow',
            index: 0
        }, o);


        return this.each(function() {
            // this => the accordion container
            var $this = this;

            // Variable for the current open item
            $this.curThis = "";

            // Set trigger cursor to pointer
            $(this).find(o.trigger).css('cursor', 'pointer');

            // Default close all item containers
            $(this).find(o.trigger).next(o.container).hide();

            // Add click logic to all triggers
            $(this).find(o.trigger).click(function() {
                if ($this.curThis != "") {
                    $($this.curThis).next(o.container).toggle(o.speed);
                }

                var newThis = this;
                if ($this.curThis == newThis) {
                    $this.curThis = "";
                }
                else {
                    $this.curThis = newThis;
                    $(newThis).next(o.container).toggle(o.speed);
                }
            });

            // try to open the container with the corresponding index (if there are any...)
            if ($(this).find(o.trigger).length > 0) {
                if (o.index < $(this).find(o.trigger).length) {
                    $(this).find(o.trigger + ':eq(' + o.index + ')').click();
                }
                else {
                    $(this).find(o.trigger + ':first').click();
                }
            }
        });
    };
})(jQuery);
