// Lightstreamer Basic Portfolio Demo
// Table Management

//////////////// Portfolio Table Management

// the current portfolio should be chosen by the user according to the user profile;
// in this sample, user authentication is not included and a single portfolio is
// shared among all the connected users
var portfolioId = "portfolio1";

// portfolio contents; provided by the PORTFOLIO_ADAPTER in COMMAND mode
var schema = ["key", "command", "qty"];

// cell highlighting time (milliseconds)
var hotTime = 500;

// create a DynaMetapushTable with the specified schema
var table = new DynaMetapushTable([portfolioId], schema, "COMMAND");

table.setDataAdapter("PORTFOLIO_ADAPTER");
table.setSnapshotRequired(true);
table.setPushedHtmlEnabled(false);

// define visual effects
table.onChangingValues = function (domNode, visualUpdateInfo) {
  if (visualUpdateInfo != null) {
    visualUpdateInfo.setHotTime(hotTime);
    visualUpdateInfo.setRowStyle("lshot", "lscold");
    visualUpdateInfo.setStyle("command", "commandhot", "commandcold")
  }
};

// bind the table to the corresponding HTML template
pushPage.addTable(table, "portfolio");


//////////////// Table Sort Management

var initialSort = "key";
var direction = false; // true = decreasing; false = increasing; null = no sort

function changeSort(sortOn) {
  var sortedBy = table.getMetapushSortFieldName();
  if (sortOn == sortedBy) {
    if (direction == false) {
      direction = true;
      document.getElementById("img_" + sortOn).src = "images/down.gif";
    } else if (direction == true) {
      direction = null;
      document.getElementById("img_" + sortOn).src = "images/spacer.gif";
      document.getElementById("col_" + sortOn).className = "tableTitle";
    } else {
      direction = false;
      document.getElementById("img_" + sortOn).src = "images/up.gif";
    }
  } else {
    direction = false;
    if (sortedBy != null) {
      document.getElementById("img_" + sortedBy).src = "images/spacer.gif";
      document.getElementById("col_" + sortedBy).className = "tableTitle";
    }
    document.getElementById("img_" + sortOn).src = "images/up.gif";
    document.getElementById("col_" + sortOn).className = "tableTitleSorted";
  }

  if (direction == null) {
    table.setMetapushSort(null);
    return;
  } else {
    if (sortOn == "qty") {
      table.setMetapushSort(sortOn, direction, true, false);
    } else {
      table.setMetapushSort(sortOn, direction);
    }
  }
}

// let's define the initial sorting column
changeSort(initialSort);
