/* Get the static JavaScript from a heredoc */
$output = <<<JS
<script type="text/javascript">
var urlIdentifiers = [];
var numDLs = [];
var generationRules = [];

function sel (clicked_obj) {
  var idx;

  // Get the selected download site
  var urlIdentifier = clicked_obj.childNodes[0].innerHTML;
  var numDl = clicked_obj.childNodes[1].innerHTML;

  // Un-highlight all entries.
  var numSites = document.getElementById("siteList").childElementCount / 2;
  for (idx=0; idx<numSites; idx++) {
    document.getElementById("r" + idx).style.backgroundColor = "white";
  }

  // Highlight the clicked entry.
  clicked_obj.style.backgroundColor = "gray";

  document.getElementById("delUrlIdentifier").value = urlIdentifier;
  document.getElementById("delNumDls").value = numDl;

  // Populate the substitution template.
  for (idx=0; idx<urlIdentifiers.length; idx++) {
    if ((urlIdentifiers[idx] == urlIdentifier) && (numDLs[idx] == numDl)) {
      document.getElementById("generationRule").value = generationRules[idx];
      document.getElementById("urlIdentifier").value = urlIdentifiers[idx];
    }
  }
}

function loadSiteList () {
  var idx;
  var html = "<span id=\"r0\" onClick=\"sel(this);\" class=\"bgWhite\"><span class=\"firstLeft w400\">" + urlIdentifiers[0] + "</span><span class=\"firstRight w60\">" + numDLs[0] + "</span></span><br>";
  for (idx=1; idx<urlIdentifiers.length; idx++) {
    html = html + "<span id=\"r" + idx + "\" onClick=\"sel(this);\" class=\"bgWhite\"><span class=\"nextLeft w400\">" + urlIdentifiers[idx] + "</span><span class=\"nextRight w60\">" + numDLs[idx] + "</span></span><br>";
  }
  document.getElementById("siteList").innerHTML = html;
}

function init () {
    loadSiteList ();
}

JS;

/* Get the downloadSites table from the DB. */
$sql = "select * from DownloadSites order by urlIdentifier, numDLs";
$stmt = $modx->prepare($sql);
$result = $stmt->execute();
if (! $result) {
    $msg = $stmt->errorInfo();
    echo 'Error in snippet "ms-mtk-getUtilityJS" ' . $msg[2];
}
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $stmt->fetch()) {
    $output .= 'urlIdentifiers.push ("' . $row["urlIdentifier"] . '");' . PHP_EOL;
    $output .= 'numDLs.push ("' . $row["numDLs"] . '");' . PHP_EOL;
    $row["generationRule"] = str_replace ('"', '\"', $row["generationRule"]);
    $output .= 'generationRules.push ("' . $row["generationRule"] . '");' . PHP_EOL . PHP_EOL;
}

$output .= '</script>' . PHP_EOL;

$modx->regClientStartupScript($output);