<?PHP

/**
* Get the controls for sorting and ordering.
* @param mixed $SortField The field to sort by.
* @param bool $SortDescending Set to TRUE to indicate that sorting is in
*      descending order.
* @param array $SearchGroupArray Array of search groups for the form.
* @param array $SortableFields Array of sortable fields.
* @return Returns the sort controls HTML as a string.
*/
function GetResourceSortControls($SortField, $SortDescending, $SearchGroupArray, $SortableFields)
{
    list($AscOrderInfo, $DescOrderInfo) = GetSortOrderDetails($SortField);
    $SafeUniqId = defaulthtmlentities(uniqid());
    $SafeSortFieldId = NULL;

    ob_start();
    ?>
    <div class="cw-search-sort-controls-container">
      <form id="<?PHP print $SafeUniqId; ?>-sort-form"
            class="cw-search-sort-form"
            action="index.php"
            method="get">
        <input name="P" type="hidden" value="AdvancedSearch" />
        <input name="Q" type="hidden" value="Y" />
    <?PHP
    foreach ($SearchGroupArray as $Key => $Value)
    {
        $SafeKey = defaulthtmlentities($Key);
        $SafeValue = defaulthtmlentities(urldecode($Value)); ?>
        <input type="hidden"
                name="<?PHP print $SafeKey; ?>"
                value="<?PHP print $SafeValue; ?>" />
  <?PHP
    } ?>

        <label for="<?PHP print $SafeUniqId; ?>_SF">Sort by:</label>
        <select id="<?PHP print $SafeUniqId; ?>_SF" name="SF">
  <?PHP
    foreach ($SortableFields as $Data) {
        list($FieldId, $FieldName, $IsSelected) = $Data;
        $SafeFieldId = defaulthtmlentities($FieldId);
        $SafeFieldName = defaulthtmlentities($FieldName);
    if ($IsSelected) $SafeSortFieldId = $SafeFieldId; ?>
        <option value="<?PHP print $SafeFieldId; ?>"
        <?PHP if ($IsSelected) print "selected"; ?>><?PHP print $SafeFieldName; ?></option>
  <?PHP } ?>
        </select>

        <input class="cw-button cw-button-constrained cw-button-elegant"
               type="submit"
               value="Sort" />
      </form>
      <form id="<?PHP print $SafeUniqId; ?>-order-form"
            class="cw-search-order-form"
            action="index.php"
            method="get">
        <input name="P" type="hidden" value="AdvancedSearch" />
        <input name="Q" type="hidden" value="Y" />
        <input name="SF" type="hidden" value="<?PHP print $SafeSortFieldId; ?>" />
    <?PHP
    foreach ($SearchGroupArray as $Key => $Value) {
              $SafeKey = defaulthtmlentities($Key);
              $SafeValue = defaulthtmlentities(urldecode($Value)); ?>
              <input type="hidden"
              name="<?PHP print $SafeKey; ?>"
              value="<?PHP print $SafeValue; ?>" />
    <?PHP } ?>

        <span class="cw-search-order-label">Order:</span>

        <input type="radio" name="SD" value="0"
               id="<?PHP print $SafeUniqId; ?>_SD_0"
               <?PHP if (!$SortDescending) print "checked"; ?> />
        <label for="<?PHP print $SafeUniqId; ?>_SD_0" class="cw-search-order-button cw-button cw-button-constrained cw-button-elegant">
          <span class='cw-search-arrow'>&darr;</span>
          <span class='cw-search-order-button-text'>
          Ascending
          (<?PHP print $AscOrderInfo["Text"][0]; ?>*<?PHP print $AscOrderInfo["Text"][1]; ?>)
          </span>
        </label>

        <input type="radio" name="SD" value="1"
               id="<?PHP print $SafeUniqId; ?>_SD_1"
               <?PHP if ($SortDescending) print "checked"; ?> />
        <label for="<?PHP print $SafeUniqId; ?>_SD_1" class="cw-search-order-button cw-button cw-button-constrained cw-button-elegant">
          <span class='cw-search-arrow'>&darr;</span>
          <span class='cw-search-order-button-text'>
          Descending
          (<?PHP print $DescOrderInfo["Text"][0]; ?>*<?PHP print $DescOrderInfo["Text"][1]; ?>)
          </span>
        </label>

        <input class="cw-button cw-button-constrained cw-button-elegant"
               type="submit"
               value="Reorder" />
      </form>
    </div>
    <script type="text/javascript">
      (function(){
        var sortForm = jQuery("#<?PHP print $SafeUniqId; ?>-sort-form"),
            orderForm = jQuery("#<?PHP print $SafeUniqId; ?>-order-form"),
            forms = sortForm.add(orderForm),
            submitButtons = jQuery("input[type='submit']", forms),
            sort = jQuery("select[name='SF']", sortForm),
            order = jQuery("input[name='SD']", orderForm);

        // hide the submit buttons
        submitButtons.hide();

        // hide the radio buttons in the order form
        order.hide();

        // submit the form when one of the form elements changes
        sort.add(order).change(function(){
          jQuery(this).parents("form").eq(0).submit();
        });

        // tweak the ordering forms
        orderForm.each(function(){
          var ascLabel = jQuery("label[for$='SD_0']", this),
              descLabel = jQuery("label[for$='SD_1']", this),
              selected = jQuery("input[name='SD']:checked", this),
              selectedLabel = jQuery("label[for='"+selected.attr("id")+"']"),
              labelTemp = "",
              label = null;

          // switch the label text
          labelTemp = ascLabel.html();
          ascLabel.html(descLabel.html());
          descLabel.html(labelTemp);

          // hide the label for the seleted option
          selectedLabel.hide();

          // tweak the text of the label that's dispalyed
          label = jQuery("label:visible", this);
          label.html(label.html().replace(/[()]/g, ""));
          label.html(label.html().replace(/\*/g, "<br />"));
          label.html(label.html().replace(/(a|de)scending/gi, ""));

        });
      }());
    </script>
    <?PHP

       return ob_get_clean();
}

/**
* Get the details for the sort order button, e.g., the label and help text.
* @param MetadataField $Field The metadata field to use as context.
* @return Returns the details for the sort order button.
*/
function GetSortOrderDetails(MetadataField $Field = NULL)
{
    $Ascending = array(
        "Message" => "Display the results in ascending order",
        "Text" => array("", ""),
        "Width" => 25);
    $Descending = array(
        "Message" => "Display the results in descending order",
        "Text" => array("", ""),
        "Width" => 25);

    # relevance or rating
    if (is_null($Field) || $Field->Name() == "Cumulative Rating")
    {
        $Ascending["Text"] = array("Lo", "Hi");
        $Descending["Text"] = array("Hi", "Lo");
        $Ascending["Width"] = 30;
        $Descending["Width"] = 30;
    }

    # based on field type
    else
    {
        switch ($Field->Type())
        {
            case MetadataSchema::MDFTYPE_NUMBER:
                $Ascending["Text"] = array("1", "10");
                $Descending["Text"] = array("10", "1");
                break;
            case MetadataSchema::MDFTYPE_DATE:
            case MetadataSchema::MDFTYPE_TIMESTAMP:
                $Ascending["Text"] = array("JAN", "DEC");
                $Descending["Text"] = array("DEC", "JAN");
                $Ascending["Width"] = 35;
                $Descending["Width"] = 35;
                break;
            default:
                $Ascending["Text"] = array("A", "Z");
                $Descending["Text"] = array("Z", "A");
                break;
        }
    }

    return array($Ascending, $Descending);
}
