// Copyright 2009 Daniel Arbuckle
//
// 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 setup_moreless() {
    $$('.moreless').each(function(item) {
        item.getChildren('.moreless-flexible').each(function(child) {
            var wrapper = new Element('div');
            var full_height = child.getStyle('height');
            var breaker = child.getChildren('.moreless-break')[0];
            if(breaker == null) {
                return;
            }
            var breaker_pos = breaker.getPosition(child);
            var min_height = breaker_pos.y;

            wrapper.wraps(child);
            child.store('state', 'closed');
            child.setStyle('overflow', 'hidden');
            child.setStyle('height', min_height);

            var toggle = new Element('span', {'class': 'moreless-toggle'});
            toggle.setProperty('text', 'Show More >');
            toggle.setStyle('cursor', 'pointer');
            toggle.addEvent('click', function(event) {
                if(child.retrieve('state') == 'closed') {
                    toggle.setProperty('text', '< Show Less');
                    child.store('state', 'open');
                    child.tween('height', min_height, full_height);
                }
                else {
                    toggle.setProperty('text', 'Show More >');
                    child.store('state', 'closed');
                    child.tween('height', full_height, min_height);
                }
            });

            wrapper.grab(toggle);
        });
    });
}

window.addEvent('load', setup_moreless); // domready leaves heights wrong



