﻿//jQuery plugin that enables "collapsible" functionality on specified elements.
//Show/Hide is triggered on the 'body' elements when the 'head' element is clicked.

(function ($) {

    var settings, methods = {
        "init": function (options) {
            var defaults = {
                headSelector: ".collapsible-head",
                bodySelector: ".collapsible-body",
                duration: 0,
                defaultOpen: false,
                openClass: "open",
                closeClass: "close"
            };

            settings = $.extend(defaults, options);

            return this.each(function () {
                var $this = $(this);

                if (!settings.defaultOpen) {
                    $this.addClass(settings.closeClass).children(settings.bodySelector).hide();
                }
                else
                    $(this).addClass(settings.openClass);

                $this.find(settings.headSelector).first().click(function (e) {
                    $this.toggleClass(settings.closeClass).toggleClass(settings.openClass).children(settings.bodySelector).toggle(settings.duration);
                    e.preventDefault();
                });
            });
        },
        "show": function () {
            $this = $(this);
            $this.removeClass(settings.closeClass).addClass(settings.openClass).children(settings.bodySelector).show(settings.duration);
        },
        "hide": function () {
            $this = $(this);
            $this.addClass(settings.closeClass).removeClass(settings.openClass).children(settings.bodySelector).hide(settings.duration);
        }
    };

    $.fn.collapsible = function (method) {

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        }
        else {
            $.error('Method ' + method + ' does not exist on jQuery.collapsible');
        }
    };
})(jQuery);
