// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['jquery'], function() {
    (function($) {
        // jQuery plugin definition
        $.fn.hpCollapsible = function(options) {
          
            var instance;

            function hpCollapsible(elem) {
                var self, label, content;

                this.initialize = function (elem) {
                    self = this;
                    $(elem).addClass('hp-collapsible hp-collapsed');
                    label = $('> h1, > label', elem);
                    content = $('> ol, > div', elem);
                    label.click(function () {
                        if ($(elem).hasClass("hp-collapsed")) {
                            self.expand();
                        } else {
                            self.collapse();
                        }
                    });
                };
                
                this.collapse = function () {
                    $(elem).addClass('hp-collapsed');
                    $(elem).trigger('collapse');
                };
                
                this.expand = function () {
                    $(elem).removeClass('hp-collapsed');
                    $(elem).trigger('expand');
                };
            }

            if ( typeof options === 'string' ) { 
                // call method
                var args = Array.prototype.slice.call( arguments, 1 );

                this.each(function() {
                    instance = $.data( this, 'hpCollapsible' );
                    if ( !instance ) {
                        if (window.console) {
                            window.console.error( "cannot call methods on hpCollapsible prior to initialization; " +
                                "attempted to call method '" + options + "'" );
                        }
                        return;
                    }
                    if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
                        if (window.console) {
                            window.console.error( "no such method '" + options + "' for hpCollapsible instance" );
                        }
                        return;
                    }
                    // apply method
                    instance[ options ].apply( instance, args );
                });  
            } else {
                // pluginify
                var ret;
                this.each(function() {
                    var $elem = $(this);
                    instance = new hpCollapsible($elem[0]);
                    $.data(this, 'hpCollapsible', instance);
                    instance.initialize($elem[0]);
                    ret = ret ? ret.add($elem) : $elem;
                });
                return ret;
            }
        };
    }(jQuery));
});
