<?xml version="1.0" encoding="UTF-8" ?> 
<Module>
  <ModulePrefs title="Wave Dice Gadget" height="160">
    <Require feature="wave" /> 
  </ModulePrefs>
<Content type="html">
<![CDATA[ 

<style>
#content_div {
  border: 1px solid black;
  padding: 2px;
  width: auto;
}
#content_div img {
  width: 1em;
  height: 1em;
  border: 1px solid #CCCCCC;
  border-right: 2px solid #CCCCCC;
  border-bottom: 2px solid #CCCCCC;
}
</style>

<input type=text value="1d20 + 8" id="input"/>
<input type=button value="Roll!" onClick="roll()"/>
<div id="content_div" class="scrollable vertical">No rolls yet</div>

<script type="text/javascript">

var SAVED = 5 // length of history
var input = document.getElementById("input")
var div = document.getElementById('content_div')

function jsonEncode(value) {
  if (value.constructor == Object) {
    var copy = []
    for (var key in value)
      copy.push(jsonEncode(key) + ":" + jsonEncode(value[key]))
    return "{" + copy.join(",") + "}"
  }
  if (value.constructor == Array) {
    var copy = []
    for (var i = 0; i < value.length; i++)
      copy.push(jsonEncode(value[i]))
    return "[" + copy.join(",") + "]"
  }
  if (value.constructor == String) {
    value = value.replace("\\", "\\\\")
    value = value.replace("\n", "\\n")
    value = value.replace("\t", "\\t")
    value = value.replace("\r", "\\r")
    value = value.replace("\"", "\\\"")
    return '"' + value + '"'
  }
  else {
    return value.toString()
  }
}

function getHistory() {
  var history = wave.getState().get("history")
  if (!history) history = []
  else eval("history = " + history)
  return history
}

function roll() {
  var roll = input.value
  var subtotal = ''
  var total = 0
  var addends = roll.split("+")
  for (i = 0; i < addends.length; i++) {
    var subtractends = addends[i].split("-")
    for (j = 0; j < subtractends.length; j++) {
      var difference = 0
      var operands = subtractends[j].split("d")
      if (operands.length == 1) { // no "d" in subtractends[i]
        difference = parseInt(operands[0])
      }
      if (operands.length == 2) { // one "d" in subtractends[i]
        var dice = parseInt(operands[0])
        var sides = parseInt(operands[1])
        if (!dice) dice = 1 // roll 1 die if left operand is not a number
        if (!sides) sides = 6 // 6-sided dice if right operand is not a number
        for (var k = 0; k < dice; k++)
          difference += Math.floor((Math.random() * sides) + 1)
      }
      if (j == 0) total += difference // add first subtractend
      else        total -= difference // subtract other subtractends
      if      (j != 0) subtotal += " - "
      else if (i != 0) subtotal += " + "
      subtotal += difference
    }
  }
  var history = getHistory()
//  var history = wave.getState().get("history")
//  if (!history) history = []
//  else eval("history = " + history)
  history.push({
    "id": wave.getViewer().getId(),
    "roll": roll, 
    "subtotal": subtotal,
    "total": total})
  if (history.length > SAVED) history.shift()
  wave.getState().submitValue("history", jsonEncode(history))
}

function stateUpdated() {
  var html = ''
  var history = getHistory()
//  var history = wave.getState().get("history")
//  if (!history) history = []
//  else eval("history = " + history)
  for (var i = 0; i < history.length; i++) {
    var participant = wave.getParticipantById(history[i].id)
    html += '<div><table><tr>'
    html += '<td><img src="' + participant.getThumbnailUrl() + '"/></td>'
    html += '<td><i>' + participant.getDisplayName() + '</i></td>'
    html += '<td>' + history[i].roll + ' = ' + history[i].subtotal + ' = ' + history[i].total + '</td>'
    html += '</tr></table></div>'
  }
  if (html) div.innerHTML = html
}

function init() {
  if (wave && wave.isInWaveContainer())
    wave.setStateCallback(stateUpdated)
}
gadgets.util.registerOnLoadHandler(init);

</script>
]]> 
  </Content>
</Module>

