<?PHP
#
#   FILE:  SPT--AJAXDropdown.php
#
#   VALUES EXPECTED (in $_GET):
#       Argument
#           - search string
#       FieldId
#           - numeric ID of field to search
#
#   Part of the Scout Portal Toolkit
#   Copyright 2006 Internet Scout Project
#   http://scout.wisc.edu
#

$AF->SuppressHTMLOutput();

    # make sure user is logged in with sufficient privileges
    if (!$G_User->HasPriv(PRIV_RESOURCEADMIN, PRIV_MYRESOURCEADMIN, PRIV_RELEASEADMIN))
    {
        return;
    }

    # maximum number of results to display
    $MaxResultsToDisplay = 50;
    
    # if a search string was entered and field ID is available
    $SearchString = trim($_GET["Argument"]);
    $FieldId = trim($_GET["FieldId"]);
    if (($SearchString != "") && ($FieldId != ""))
    {
        # if field ID is valid
        $Schema = new MetadataSchema();
        $Field = $Schema->GetField($FieldId);
        if ($Field !== NULL)
        {
            # add wildcard operators to search string to support stemming
            $SearchWords = preg_split(
                    "/\s+/", $SearchString, -1, PREG_SPLIT_NO_EMPTY);
            $SearchString = "";
            foreach ($SearchWords as $Word)
            {
                if (preg_match("/\"$/", $Word)
                        || preg_match("/\*$/", $Word))
                {
                    $SearchString .= $Word." ";
                }
                else
                {
                    $SearchString .= $Word."* ";
                }
            }
            $SearchString = trim($SearchString);

            # perform search
            $Factory = $Field->GetFactory();
            $SearchResults = $Factory->SearchForItemNames(
                    $SearchString. "*", ($MaxResultsToDisplay + 1));
        }
    }
    else
    {
        print "{ 'type' : 'error', 'message' : 'No search term was entered. Please enter one.',"
             ." 'resources' : [], 'numresources' : 0 }";
        return;
    }

    # if there are no results
    $NumberOfResults = count($SearchResults);
    if ($NumberOfResults < 1)
    {
        print "{ 'type' : 'error', 'message' : 'No results were found. Please enter a different"
             ." search term or broaden the search.', 'resources' : [], 'numresources' : 0 }";
    }
    # else if there are too many results
    else if ($NumberOfResults > $MaxResultsToDisplay)
    {
        print "{ 'type' : 'warning', 'message' : 'More than $MaxResultsToDisplay results were found."
             ." please narrow the search.', 'resources' : [], 'numresources' : 0 }";    
    }
    else
    {
        $Return = "{ 'type' : 'ok', 'message' : '', 'resources' : [";
        foreach($SearchResults as $TempResult)
        {
            # Create and add JSON objects
            $Return .= "{ 'value' : '$TempResult' },";
        }
        print $Return . "], 'numresources' : $NumberOfResults }";
    }
    
    return;

?>
