(function($, undefined) {

    var SLIDE_DURATION = 350;

    function init(jQueryObject, params, resizeFlag) {
        jQueryObject.css({ height : 'auto' });
        var $dd = jQueryObject.find('dd').css({ height : 'auto' }).show();
        var $dt = jQueryObject.find('dt');

        var maxHeight = 0;
        for (var i = 0; i < $dd.length; i++) {
            var d = $dd.get(i);
            if (d.scrollHeight > maxHeight)
                maxHeight = d.scrollHeight;
            if (!params.adjustHeight)
                $dd.eq(i).height($dd.eq(i).height());
        }
        if (params.adjustHeight)
            $dd.height(maxHeight);

        $dd.hide();
        if (resizeFlag) {
            $dd.filter('.active').show();
        } else {

            $dd.eq(0).addClass('active').show();

        }
        if (params.adjustHeight)
            jQueryObject.height(jQueryObject.height());
        if (!resizeFlag) {
            $dt.click(expandHandler);
            if (!$.browser.msie) {
                $(window).resize(function() {
                    init(jQueryObject, params, true);
                });
            }
        }
    }

    function expandHandler() {
        var $this = $(this);
        var $dd = $this.next('dd');
        if (!$dd.hasClass('active')) {
            var $ac = $this.siblings('dd.active')
                .removeClass('active')
            $dd.addClass('active');
            var height = $dd.height();
            var coeff = $ac.height() / height;
            $dd
                .height(0)
                .show()
                .animate({
                    height : height
                }, {
                    duration : SLIDE_DURATION,
                    easing : 'swing',
                    step : function(now) {
                        var h = (height - now) * coeff;
                        $ac.height(Math.ceil(h));
                    },
                    complete : function() {
                        $ac.hide().height(height * coeff);
                    }
                });
        }
    }

    $.fn.extend({
        accordion : function(params) {
            if (!params)
                params = {};
            init(this, params);
            return this;
        }
    });

})(jQuery);

