scms.namespace("widget");

scms.widget.autoHeight = function(className, rootElement)
{
    this.dom = YAHOO.util.Dom;

    this.className = className;
    this.elementTag = "div";
    this.rootElement = rootElement;
};

scms.widget.autoHeight.prototype = {
    cache:null,

    registerInterval:function()
    {
        if (!this.intervalRegistered) {

            var inst = this;

            window.setInterval(
                function()
                {
                    inst.resize();
                },
                500
            );

            this.intervalRegistered = true;
        }
    },

    fetchFirstSibling:function(elm)
    {
        if (elm.previousSibling) {
            var sib = this.fetchFirstSibling(elm.previousSibling);
            if (sib) {
                return sib;
            }
        }

        return elm;
    },

    fetchHeight:function(elm)
    {
        if (elm.offsetHeight) {
            var height = elm.offsetHeight;
        } else {
            var height = 0;
        }

        if (elm.nextSibling) {
            var h = this.fetchHeight(elm.nextSibling);
            if (h > height) {
                height = h;
            }
        }

        return height;
    },

    resize:function(arg1, inst)
    {
        if (!inst) {
            var inst = this;
        }

        if (!this.cache) {
            this.cache = inst.dom.getElementsByClassName(inst.className, inst.elementTag, inst.rootElement);
        }

        scms.each(this.cache, function(div) {

            if (!div.scAutoHeightContainer) {
                div.scAutoHeightContainer = inst.fetchFirstSibling(div);
            }

            var height = inst.fetchHeight(div.scAutoHeightContainer);
            if (!div.scAutoHeight || div.scAutoHeight != height) {

                var cssProperty = "min-height";
                if (YAHOO.env.ua.ie > 0 && YAHOO.env.ua.ie < 7) {
                    cssProperty = "height";
                }

                inst.dom.setStyle(div, cssProperty, height + "px");

                div.scAutoHeight = height;
            }
        });

        if (!inst.onloadRegistered) {
            scms.event.addListener(window, "load", this.resize, this);

            inst.onloadRegistered = true;
        }
    }
};


