function trimString(str) {
  while (str.charAt(0) == ' ')
    str = str.substring(1);
  while (str.charAt(str.length - 1) == ' ')
    str = str.substring(0, str.length - 1);
  return str;
}

Portfolio = Class.create();

Portfolio.prototype = {

  initialize: function(ui) {
    this.ui = ui;
  },

  load: function(url) {
    new Ajax.Request(url,
    {
      method: "get",
      asynchronous: true,
      onComplete: this.parseDoc.bind(this)
    });
  },

  categoryCount: 0,
  categories: new Object(),
  currentCategory: null,
  name: null,

  parseDoc: function(transport) {
    //this.ui.updateStatus("Parsing XML", 0);
    var doc = null;
    if (document.all) {  //IE is Doggy
      doc = new ActiveXObject("Microsoft.XMLDOM");
      doc.async = false;
      doc.loadXML(transport.responseText);
    }
    else {
      doc = transport.responseXML;
    }
    var portfolioElt = doc.documentElement;
    if (!portfolioElt || portfolioElt.tagName != 'portfolio') {
      alert('Document must begin with a portfolio tag');
      return;
    }
    this.name = portfolioElt.getAttribute("name");

    //Create all the categories.
    var categoryElts = $A(portfolioElt.getElementsByTagName('category'));
    categoryElts.each(this.addCategory.bind(this));

    var defaultCat = categoryElts[0].parentNode.getAttribute("default");
    if(defaultCat != null) this.currentCategory = this.categories[defaultCat];
    else this.currentCategory = this.categories[categoryElts[0].getAttribute("name")];

    //Create all the projects
    var projectElts = $A(portfolioElt.getElementsByTagName('project'));
    projectElts.each(this.addProject.bind(this));
    setTimeout("ui.initUI()", 400);
  },


  addCategory: function(node) {
    this.categoryCount++;
    var name = node.getAttribute('name');
    this.categories[name] = new Category(node, this, this.ui);
    this.categories[name].index = this.categoryCount;
  },

  addProject: function(node) {
    if (!node.getAttribute("category") || node.getAttribute("category") == '') {
      alert("All projects must have a category.");
      return;
    }

    var categories = node.getAttribute("category").split(',');
    for (var i = 0; i < categories.length; i++) {
      var category = trimString(categories[i]);
      var categoryObj = this.categories[category];
      if(categoryObj == null) {
        alert("A category by the name " + category + " was found on a project but does not exist in the list of know categories.");
      }
      var project = new Project(node, this, this.ui);
      categoryObj.addProject(project);
    }
  },

  getName: function() {
    return this.name;
  }
}
