/**
 * Phoebe pedagogic planner
 *
 * PHP version 5
 *
 * LICENSE: The GNU General Public License (GPL), version 2. See LICENSE.txt
 *
 * Copyright (c) 2006-2008 JISC/HEFCE/University of Oxford
 *
 * @author      David Balch <david.balch@conted.ox.ac.uk>
 * @license     http://opensource.org/licenses/gpl-license.php GPL2
 * @link        http://phoebe-project.conted.ox.ac.uk/
 */

var appName = "Phoebe";
var editStructure = false;

/** defaultLayout:
 * 0 = Horizontal split pane
 * 1 = Vertical split pane
 * 2 = Maximise controls, content floating
 * 3 = Maximise guidance, controls floating
 **/

var currentLayout = 1;
var prevLayout = currentLayout;
var leftMargin = 20; // Minumim margin between edge of floating window and viewport edge
var toolBarH;
var availWidth;
var availHeight;
var horizSplitRatio = 0.5; // Bigger values = more control area
var vertSplitRatio = 0.5; // Bigger values = more content area
var handleGripSize = 6;

var ctrlFloatPos = {h : 200, w : 400, t : 200, l : 500};
var guidFloatPos = {h : 200, w : 400, t : 300, l : 400};

$(document).ready(function(){
    if (supportedEnv()) {
        // We can run in this environment, so lets do it.
        /* window management */
        // Add events
        window.onresize = screenResize;

        // Hide unsupportedMsg
        $('#unsupportedMsg').remove();
        // Show Phoebe elements
        $('#phoebeArea').removeClass('hidden');

        // Set screen real estate and layout
        screenResize();

        // Setup draggable resizable panes
        // Controls
        $('#controlsArea').Resizable({
            minWidth: 100,
            minHeight: 100,
            dragHandle: "#controlsAreaTitleBar",
            handlers: {
                se: '#controlsAreaStatusBar'
            },
            onStop: function(){savePos('#controlsArea');},
            onDragStop: function(){savePos('#controlsArea');}
        });

        // Guidance
        $('#guidanceArea').Resizable({
            minWidth: 100,
            minHeight: 100,
            dragHandle: "#guidanceAreaTitleBar",
            handlers: {
                se: '#guidanceAreaStatusBar'
            },
            onStop: function(){savePos('#guidanceArea');},
            onDragStop: function(){savePos('#guidanceArea');}
        });

        /* Design work */
        $('#designMeta').append('<p id="initLoadMsg">Loading design...</p>');
        // Load design data

        // Get the design data
        designData = "/db/getDesign.php?mode=json&design_id="+qs.get('design_id');
        $.getJSON(designData, function(json){
            receiveDesign(json);
            $('#initLoadMsg').remove();
        });
    }

});

function screenResize() {
    // Update screen real estate
    setScreenAvail();
    updatePos();
}

function setScreenAvail() {
    // Find toolbar height
    toolBarH = $('#phoebeToolbar').height() + 5; // Add 5px for padding and border
    // Adjust the main (non-toolbar) area size accomodating the toolbar
    $('#phoebeMain').css("top", toolBarH);

    // Find height and width in the main area
    if(typeof document.body.style.maxHeight != "undefined") {
        availHeight = $('#phoebeMain').height();
        availWidth = $('#phoebeMain').width();
    } else {
        availHeight = document.body.clientHeight - document.getElementById('phoebeToolbar').offsetHeight;
        availWidth = document.body.clientWidth;
    }
    //console.log(availHeight);
}

function updatePos() {
    switch (currentLayout) {
        // Calculate sizes
        case 0: // Split pane horizontal
            usableH = (availHeight - handleGripSize) - 2;// 2px for borders

            ctrlW = availWidth - 2;// 2px for border
            ctrlH = usableH * horizSplitRatio;
            ctrlT = 0;
            ctrlL = 0;

            guidW = availWidth - 2;// 2px for border
            guidH = usableH - ctrlH;
            guidT = ctrlH + handleGripSize;
            guidL = 0;

            spltW = availWidth;
            spltH = 6;
            spltT = ctrlH;
            spltL = 0;
            break;

        case 1: // Split pane vertical
            usableW = (availWidth - handleGripSize) - 3;// 3px for borders (2 seems a bit twitchy)

            guidW = usableW * vertSplitRatio;
            guidH = availHeight - 2;// 2px for border
            guidT = 0;
            guidL = 0;

            ctrlW = usableW - guidW;
            ctrlH = availHeight - 2;// 2px for border
            ctrlT = 0;
            ctrlL = guidW + handleGripSize;

            spltW = 6;
            spltH = availHeight;
            spltT = 0;
            spltL = guidW;
            break;

        case 2: // Maximise controls, content floating
            $('#guidanceArea').css("z-index", 1);
            $('#controlsArea').css("z-index", 0);
            ctrlW = availWidth - 2;// 2px for border
            ctrlH = availHeight - 2;// 2px for border
            ctrlT = 0;
            ctrlL = 0;

            guidW = guidFloatPos.w;
            guidH = guidFloatPos.h;
            guidT = guidFloatPos.t;
            guidL = guidFloatPos.l;
            break;

        case 3: // Maximise guidance, controls floating
            $('#controlsArea').css("z-index", 1);
            $('#guidanceArea').css("z-index", 0);
            ctrlW = ctrlFloatPos.w;
            ctrlH = ctrlFloatPos.h;
            ctrlT = ctrlFloatPos.t;
            ctrlL = ctrlFloatPos.l;

            guidW = availWidth - 2;// 2px for border
            guidH = availHeight - 2;// 2px for border
            guidT = 0;
            guidL = 0;
            break;
    }

    // Set sizes
    //alert("Position controls: Width="+ctrlW+" Height="+ctrlH+" Top="+ctrlT+" Left="+ctrlL);
    //console.log("Position controls: Width="+ctrlW+" Height="+ctrlH+" Top="+ctrlT+" Left="+ctrlL);
    $('#controlsArea').width(ctrlW);
    $('#controlsArea').height(ctrlH);
    $('#controlsArea').css("top", ctrlT);
    $('#controlsArea').css("left", ctrlL);

    //console.log("Position guidance: Width="+guidW+" Height="+guidH+" Top="+guidT+" Left="+guidL);
    $('#guidanceArea').width(guidW);
    $('#guidanceArea').height(guidH);
    $('#guidanceArea').css("top", guidT);
    $('#guidanceArea').css("left", guidL);

    if (currentLayout == 0 || currentLayout == 1) {
        //console.log("splitBar guidance: Width="+spltW+" Height="+spltH+" Top="+spltT+" Left="+spltL);
        $('#splitBar').width(spltW);
        $('#splitBar').height(spltH);
        $('#splitBar').css("top", spltT);
        $('#splitBar').css("left", spltL);
    }

    // Adjust UI
    switch (currentLayout) {
        case 0: // Horizontal split pane
            $("#guidanceArea").removeClass("hidden");
            // Hide window decorations
            $("#controlsAreaTitleBar:visible, #controlsAreaStatusBar:visible, #guidanceAreaTitleBar:visible, #guidanceAreaStatusBar:visible").addClass("hidden");

            $('#splitBar').addClass('horiz');
            $('#splitBar').removeClass('vert');
            $("#splitBar").css("display", "block");

            // split pane divider
            if (document.getElementById('splitBar').isDraggable) {
                // Remove other draggable
                $('#splitBar').DraggableDestroy();
            }
            $('#splitBar').Draggable({
                zIndex: 1000,
                axis: "vertically",
                onStart: maskOn,
                onStop: maskOff,
                onChange: splitMoved
            });
            break;

        case 1: // Vertical split pane
            $("#guidanceArea").removeClass("hidden");
            // Hide window decorations
            $("#controlsAreaTitleBar:visible, #controlsAreaStatusBar:visible").addClass("hidden");
            $("#guidanceAreaTitleBar:visible, #guidanceAreaStatusBar:visible").addClass("hidden");

            $('#splitBar').addClass('vert');
            $('#splitBar').removeClass('horiz');
            $('#splitBar').removeClass('hidden');
            $("#splitBar").css("display", "block");

            // split pane divider
            if (document.getElementById('splitBar').isDraggable) {
                // Remove other draggable
                $('#splitBar').DraggableDestroy();
            }
            $('#splitBar').Draggable({
                zIndex: 1000,
                axis: "horizontally",
                onStart: maskOn,
                onStop: maskOff,
                onChange: splitMoved
            });
            break;

        case 2: // Maximise controls, content floating
            $("#guidanceArea").removeClass("hidden");
            $("#controlsAreaTitleBar:visible, #controlsAreaStatusBar:visible").addClass("hidden");
            $("#splitBar").css("display", "none");
            $("#guidanceAreaTitleBar.hidden, #guidanceAreaStatusBar.hidden").removeClass("hidden");
            break;

        case 3: // Maximise guidance, controls floating
            $("#guidanceArea").removeClass("hidden");
            $("#guidanceAreaTitleBar:visible, #guidanceAreaStatusBar:visible").addClass("hidden");
            $("#splitBar").css("display", "none");
            $("#controlsAreaTitleBar.hidden, #controlsAreaStatusBar.hidden").removeClass("hidden");
            break;
    }
}

function editDesignMode(startup) {
    // Edit the design, not the template
    currentLayout = prevLayout;

    $('#editTemplateButton').css("display", "inline");
    $('#editDesignButton').css("display", "none");
    $('#editNodes').css("display", "none");

    // disable dragable nodes
    if (!startup) {
        $('.node').SortableDestroy();
    }
    // Change appearance
    $('#designRoot').removeClass('editTemplate');

    updatePos();
    cancelEditProp();
}

function changeLayout(layout) {
    currentLayout = layout;
    updatePos();
}

function splitMoved() {
    if (currentLayout == 0) {
        // horiz
        splitPos = $('#splitBar').css("top");
        splitPos = splitPos.substring(0, splitPos.indexOf('px')) * 1 + (handleGripSize/2);
        //console.log(splitPos);
        horizSplitRatio = splitPos / availHeight;
    } else {
        // vert
        splitPos = $('#splitBar').css("left");
        splitPos = splitPos.substring(0, splitPos.indexOf('px'))  * 1 + (handleGripSize/2);
        //console.log(splitPos);
        vertSplitRatio = splitPos / availWidth;
        //console.log(vertSplitRatio);
    }
    updatePos();
}

function savePos(pane) {
    // Save the current position
    switch (pane) {
        case "#controlsArea":
            store = ctrlFloatPos;
            break;

        case "#guidanceArea":
            store = guidFloatPos
            break;
    }

    store.h = $(pane).height();
    store.w = $(pane).width();
    store.t = $(pane).css("top");
    store.l = $(pane).css("left");
}

function loadGuidance(url) {
    // Update the guidance iframe with a new page
    $('#guidanceAreaContent').attr("src",url);
}