var itemClassFolder = 'object.container';
var currentItemId = undefined;
var currentItems = [];

function browse(itemId, fromHistory) {
  var req = '<?xml version="1.0"?>\
  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\
  <s:Body>\
  <u:Browse xmlns:u="urn:schemas-upnp-org:service:ContentDirectory:1">\
  <ObjectID>' + itemId +'</ObjectID>\
  <BrowseFlag>BrowseDirectChildren</BrowseFlag>\
  <StartingIndex>0</StartingIndex>\
  <RequestedCount>500</RequestedCount>\
  <SortCriteria></SortCriteria>\
  </u:Browse>\
  </s:Body>\
  </s:Envelope>';
  $.post('/content/control', req, function (res) {
    var items = '';
    // Parse the DIDL-Lite XML
    res = $($('Result', res).text());
    //console.log(res);

    if (itemId != 0 && !fromHistory)
      history.pushState({itemId: itemId}, window.title, itemId);

    currentItemId = itemId;
    currentItems = res.children();

    // Process the results
    currentItems.each(function(index) {
      var e = $(this);
      var title = $('dc\\:title', e).text();
      var type = $('upnp\\:class', e).text();
      var isFolder = (type.indexOf(itemClassFolder) == 0);
      var item = '';
      if (isFolder) {
        item = '<div class="item" onclick="browse(\'' + e.attr('id') + '\')">' + title + '</div>';
      } else {
        //item = '<div>' + title + '</div>';
        item = '<div class="infoItem" onclick="showItem(' + index + ')">' + title + '</div>';
      }
      items += item;
    });

    $('#content').html(items);
  });
}

function showItem(index) {
    var xml = $(currentItems[index]).html();
    xml = xml.replace(/></g, '>\n<');
    xml = xml.replace(/</g, '&lt;');
    xml = xml.replace(/>/g, '&gt;');
    xml = xml.replace(/(http:\/\/.+)&lt/g, '<a href="$1">$1</a>&lt');
    $('#infoContent').html(xml);
    prettyPrint();
}

window.onpopstate = function (e) {
  if (e.state !== null) {
    browse(e.state.itemId, true);
  } else if (currentItemId !== undefined) {
    browse(0, true);
  }
};
