﻿$.fn.page = function(maxHeight, reset) {
    this.each(function() {
        var source = $(this);
        source.css('height', maxHeight);
        var children = source.children();
        var height = 0;
        var page = $('<div class="page"/>');
        var pages = [page];
        source.append(page);
        for (var i = 0; i < children.length; i++) {
            var c = $(children[i]);
            var childHeight = c.outerHeight() + parseInt(c.css('margin-top')) + parseInt(c.css('margin-bottom'));

            height += childHeight;
            if (height > maxHeight) {
                height = childHeight;
                page = $('<div class="page"/>');
                pages.push(page);
                source.append(page);
            }

            page.append(children[i]);
        }
        source.find('.page:gt(0)').hide();

        if (reset) $('.pager').remove();

        if (pages.length > 1) {
            var pageLinks = '<p class="pager"><span>Page:</span>';
            source.find('.page').each(function(i) {
                pageLinks += '<a class="page-link' + (i == 0 ? ' current' : '') + '" href="#page-' + (1 + i).toString() + '">' + (1 + i).toString() + '</a>';
            });
            pageLinks += '</p>';
            source.after(pageLinks);
        }

        var anchors = $('.pager').find('a');
        var currentIndex = 0;
        function showPage(index) {
            pages[currentIndex].hide();
            $(anchors[currentIndex]).removeClass('current');
            $(anchors[index]).addClass('current');
            pages[index].show()
            currentIndex = index;
        }

        function navigated(hash) {
            var m = hash.match(/page\-([0-9]+)/);
            if (m) {
                var p = m[1];
                var pageIndex = parseInt(p) - 1;
                showPage(pageIndex);
            } else {
                showPage(0);
            }
        }

        $.historyInit(navigated);
        $('.pager a').click(function() {
            var hash = this.href;
            hash = hash.replace(/^.*#/, '');
            $.historyLoad(hash);
            return false;
        });
    });

    return this;
};

if ($.fn.editable) {
    $.fn.editable.updateDOM = function(target, content) {
        target.html(content);
        $('#content .editable').page(500, true);        
    };
}

$(function() {
    if (cms.adminId) {
        $('#content .editable').page(500);
    } else {
        $('#content .containee').page(500);
    }
});