﻿(function($) {
    var $s = $.serpentine;

    $.extend($s, {
        window: function(element, options) {
            $.extend(this, options);
            this.element = element;
            this._init();
            $s.trigger(element, 'load');
        }
    });

    $.extend($s.window.prototype, {
        _init: function() {
            this.collapsedCss = this.expandedCss + "Collapsed";
            this.titleBand = this.find(this.titleBandSelector);


            this.body = new Array();

            if (typeof (this.bodySelector) == "object") {
                for (var i in this.bodySelector) {
                    if (this.find(this.bodySelector[i]).length > 0) {
                        this.body[i] = this.find(this.bodySelector[i]);
                    }
                }
            }
            else {
                this.body[0] = this.find(this.bodySelector)
            }

            this.titleBand.live("click", $s.delegate(this, this._click));

            if (this.defaultState == "Collapsed")
                this._toggle(false);
        },

        _click: function(sender, args) {
            this._toggle(true);
        },

        _toggle: function(isSlideToggle) {
            if (this._shouldChangeCss()) {
                if (this.titleBand.hasClass(this.collapsedCss))
                    this.titleBand.removeClass(this.collapsedCss);
                else
                    this.titleBand.addClass(this.collapsedCss);
            }

            for (var i in this.body) {
                if (isSlideToggle) {
                    var elementInstance = this.element;
                    
                    this.body[i].slideToggle("slow", function() {
                        elementInstance.className = elementInstance.className;
                    });
                }
                else
                    this.body[i].hide();
            }
        },

        _shouldChangeCss: function() {
            return this.expandedCss;
        },

        children: function(selector) {
            return $("#" + this.element.id + ">" + selector);
        },

        find: function(selector) {
            return $("#" + this.element.id).find(selector);
        }
    });

    $.fn.sWindow = function(options) {
        options = $.extend({}, $.fn.sWindow.defaults, options);

        return this.each(function() {
            options = $.meta ? $.extend({}, options, $(this).data()) : options;

            if (!$(this).data('sWindow'))
                $(this).data('sWindow', new $s.window(this, options));
        });
    };
})(jQuery);