<?PHP

#
#   FILE:  DBOrderFieldsComplete.php
#
#   Copyright 2011 Internet Scout Project
#   http://scout.wisc.edu
#

# ----- LOCAL FUNCTIONS ------------------------------------------------------

# Moves a single $FieldId $NumMoves positions
function MoveField($Schema, $FieldId, $NumMoves, $OrderType)
{
    global $Schema;

    # Move fields Up if value is positive
    if ($NumMoves > 0)
    {
        for($i = $NumMoves ; $i > 0 ; $i--)
        {
            $Schema->MoveUpInOrder($FieldId, $OrderType);
        }
    }

    # Move fields Down if value is Negative
    else if ($NumMoves < 0)
    {
        for($j = $NumMoves; $j < 0 ; $j++)
        {
            $Schema->MoveDownInOrder($FieldId, $OrderType);
        }
    }
}

# ----- MAIN -----------------------------------------------------------------

# non-standard global variables
global $Schema;

# check if current user is authorized
CheckAuthorization(PRIV_SYSADMIN, PRIV_COLLECTIONADMIN);

$Schema = new MetadataSchema();

# If Javascript is working properly, "Submit" will be the only
# active submit button. Act accordingly
if ($_POST["Submit"] == "Submit")
{
    # Parse the moves
    $Moves = explode("\n", $_POST["FieldMoves"]);

    foreach ($Moves as $move)
    {
        $MoveChunks = explode("*", $move);

        # Handle each move with a call to MoveField
        if ($MoveChunks[0] == "Display")
        {
            MoveField($Schema, $MoveChunks[1], intval($MoveChunks[2]),
                MetadataSchema::MDFORDER_DISPLAY);
        }

        else if ($MoveChunks[0] == "Edit")
        {
            MoveField($Schema, $MoveChunks[1], intval($MoveChunks[2]),
                MetadataSchema::MDFORDER_EDITING);
        }
    }
}

# if javascript isn't working properly, one of these cases will occur
else if ($_POST["Submit"] == "Up" || $_POST["Submit"] == "Down")
{
    $Direction = $_POST["Submit"];
    $Method = "Move" . $Direction . "InOrder";
    $DisplayFields = (isset($_POST["DisplayFields"]))
        ? $_POST["DisplayFields"] : array();
    $EditFields = (isset($_POST["EditFields"]))
        ? $_POST["EditFields"] : array();

    # reverse array of fields if we are moving field down to compensate
    # for the MetadataSchema object
    if ($Direction == "Down")
    {
        $DisplayFields = array_reverse($DisplayFields);
        $EditFields = array_reverse($EditFields);
    }

    foreach ($DisplayFields as $DisplayField)
    {
        # perform a single move on the given field value
        $Schema->$Method($DisplayField, MetadataSchema::MDFORDER_DISPLAY);
    }

    foreach ($EditFields as $EditField)
    {
        # perform a single move on the given field value
        $Schema->$Method($EditField, MetadataSchema::MDFORDER_EDITING);
    }
}

# return to the field ordering screen
$AF->SetJumpToPage("DBOrderFields");
