/**
 * @author geraldyeo
 */
(function($){

    function init(settings){
        var that = this;
        
        that.each(function(i, group){
            var $titleElm = $(group).find(settings.titleElm);
            $titleElm.find("+ " + settings.copyElm).hide();
            $titleElm.data("isClosed", true);
            $titleElm.append(settings.indicator);
            
            $titleElm.click(function(e){
                $curr = $(this);
                $curr.find("+ " + settings.copyElm).toggle();
                $curr.data("isClosed", !$curr.data("isClosed"));
                updateIndicator.apply(that, [$curr, settings]);
            });
        });
    }
    
    function updateIndicator($curr, settings){
        if ($curr.data("isClosed")) {
            (typeof settings.closeStyle === 'string') ? $curr.find("> span.more").addClass(settings.closeStyle) : $curr.find("> span.more").css(settings.closeStyle);
        }
        else {
            (typeof settings.openStyle === 'string') ? $curr.find("> span.more").addClass(settings.openStyle) : $curr.find("> span.more").css(settings.openStyle);
        }
    }
    
    // jQuery plugin implementation
    $.accordion = {
        defaults: {
            titleElm: "dt",
            copyElm: "dd",
            indicator: '<span class="more" />',
            openStyle: {
                "background-position": "0 -13px"
            },
            closeStyle: {
                "background-position": "0 0"
            }
        }
    };
    
    // constructor
    $.fn.extend({
        accordion: function(options){
            var settings = $.extend({}, $.accordion.defaults, options);
            init.apply(this, [settings]);
            return this;
        }
    });
})(jQuery);
