/*
Copyright 2014 American Dynamics

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

(function($) {
    $.fn.extend({
        collapsiblePanel: function() {
            // Call the ConfigureCollapsiblePanel function for the selected element
            return $(this).each(ConfigureCollapsiblePanel);
        }
    });

})(jQuery);

function ConfigureCollapsiblePanel() {

    // Wrap the contents of the container within a new div.
    $(this).children().wrapAll("<div class='collapsibleContainerContent'></div>");

    // Check the initial state of the container
    if ($(this).hasClass('expanded')) {
        $(".collapsibleContainerContent", $(this)).slideDown(0);
    } else {
        $(".collapsibleContainerContent", $(this)).slideUp(0);
    }

    // Create a new div as the first item within the container.  Put the title of the panel in here.
    $("<div class='collapsibleContainerTitle'><div>" + $(this).attr("title") + "</div></div>").prependTo($(this));

    // Assign a call to CollapsibleContainerTitleOnClick for the click event of the new title div.
    $(".collapsibleContainerTitle", this).click(CollapsibleContainerTitleOnClick);

}

function CollapsibleContainerTitleOnClick() {
    // The item clicked is the title div... get this parent (the overall container) and toggle the content within it.
    $(".collapsibleContainerContent", $(this).parent()).slideToggle(100);

    if ($($(this).parent()).hasClass('expanded')) {
        $($(this).parent()).removeClass('expanded').addClass('collapsed');
    }
    else {
        $($(this).parent()).removeClass('collapsed').addClass('expanded');
    }
}

$(document).ready(function() {
    $(".collapsibleContainer").collapsiblePanel();
});
