﻿$(document).ready(function()
{
    // set up sortable columns
    var draggableColumns = $(".col");
    draggableColumns.sortable({
        connectWith: [".col"],
        placeholder: "newlocation",
        tolerance: "intersect",
        handle: ".header",
        distance: 1,
        scroll: false,
        start: onSortStart,
        stop: onSortEnd,
        over: function(e, ui) { ui.placeholder.height(ui.helper.height()); }
    });

    // set up draggable panels
    var draggablePanels = $(".panel");
    draggablePanels.panel({
        stateChanged: savePanels,
        header: ".header",
        maxClass: "maxBtn",
        minClass: "minBtn",
        closeClass: "closeBtn"
    });
    draggableColumns.restoreChildren($.cookie("columns"));
    draggablePanels.panelState("refresh");
    draggablePanels.panelSettings("#strapline", { save: savePanels });
    $("[state=min]").children(".btmLeft, .btmRight").hide();
    refreshColHeight();

    function onSortStart(e, ui)
    {
        refreshColHeight(ui.helper.height());
        // IE needs zindex set explicitly or the panels overlap
        ui.helper.css("zindex", 1000);
    }

    function onSortEnd(e, ui)
    {
        savePanels();
        refreshColHeight();
        // IE needs zindex set explicitly or the panels overlap
        ui.item.css("zindex", "");
    }

    // saves the location of all the panels 
    function savePanels(e, ui)
    {
        var locations = draggableColumns.serializeChildren(".panel", { attributes: ["state"] });
        $.cookie("columns", locations, { expires: 90 });

        $("[panel=panel]").children(".btmLeft, .btmRight", e).show();
        $("[state=min]").children(".btmLeft, .btmRight", e).hide();
    }

    function refreshColHeight(panelHeight)
    {
        var cols = $(".col");
        var height = 0;
        cols.each(function()
        {
            var col = $(this);
            col.css("min-height", "");
            if (col.innerHeight() > height)
            {
                height = col.innerHeight();
            }
        });
        cols.css("min-height", (height + (panelHeight | 50)) + "px");
    }
});
