﻿var expandingSummary = Class.create({
    initialize: function(summaryElement, shortenedLength) {
        this.summaryElement = summaryElement;
        this.shortenedLength = (shortenedLength) ? shortenedLength : 100;
        this.id = this.summaryElement.identify();
        this.fullText = this.summaryElement.innerHTML.stripTags();

        if (this.fullText.length >= this.shortenedLength) {
            var minLength = this.shortenedLength - 49;
            this.shortenedText = this.fullText.substr(0, minLength) + this.fullText.substr(minLength, this.fullText.substr(minLength, 49).indexOf(' ') + 1);
        }
        else {
            this.shortenedText = this.fullText;
        }

        this.isExpanded = true;
        this.moreElement = new Element('a', { 'href': '#' }).update(' ...less').observe('click', this.toggle.bindAsEventListener(this));

        this.container = this.summaryElement.wrap('span', { 'class': 'expandor-container' });

        if (this.fullText.length > this.shortenedLength) {
            this.container.appendChild(this.moreElement);
        }

        this.shrink();
    },

    toggle: function(event) {
        if (this.isExpanded) {
            this.shrink();
        }
        else {
            this.expand();
        }
    },

    shrink: function() {
        this.summaryElement.update(this.shortenedText);
        this.isExpanded = false;
        this.moreElement.update(' more...');
    },

    expand: function() {
        this.summaryElement.update(this.fullText);
        this.isExpanded = true;
        this.moreElement.update(' ...less');
    }
});

var expandingSummaries = new Object();

function setupSummaries() {
    var lists = $$("span.expandor");

    for (var i = 0; i < lists.length; i++) {
        expandingSummaries[i] = new expandingSummary(lists[i], 100);
    }
}

document.observe("dom:loaded", function() {
    setupSummaries();
});