import Page from 'page';
import Folder from 'folder';
import FolderListView from 'folder_list_view';
import PageView from 'page_view';


var App = Backbone.Router.extend({
  initialize: function () {
    this.bind('all', this.updateHighlights);
  },

  routes: {
    "":              "folder",
    "*folder/":      "folder",
    "*folder/:page": "page",
    ":page":         "page",
  },

  updateHighlights: function (route) {
    $('a[href="' + window.location.pathname + '"]').addClass("active");
    $('a[href!="' + window.location.pathname + '"]').removeClass("active");
  },

  folder: function (folder) {
    window.appView.setFolder(folder || '/');
  },

  page: function (folder, page) {
    if (!page) {
      // Root page
      page = '/' + folder;
      folder = '/';
    } else {
      page = folder + '/' + page;
    }
    window.appView.setFolder(folder);
    window.appView.setPage(page);
  },
});


var AppView = Backbone.View.extend({
  folder: new Folder(),
  page: new Page(),

  initialize: function () {
    this.folderListView = new FolderListView({model: this.folder});
    $('#list').append(this.folderListView.el);
    this.pageView = new PageView({model: this.page});
    $('#page').append(this.pageView.el);
  },

  setFolder: function (path) {
    this.folder.id = path;
    this.folder.fetch();
  },

  setPage: function (path) {
    this.page.id = path;
    this.page.fetch();
  },
});


// From https://gist.github.com/tbranyen/1142129
$(document).delegate("a", "click", function(e) {
  var href = this.getAttribute("href");
  var protocol = this.protocol + "//";
  if (href.slice(protocol.length) !== protocol) {
    e.preventDefault();
    window.app.navigate(href, {trigger: true});
  }
});


$(function () {
  window.app = new App();
  window.appView = new AppView();
  Backbone.history.start({pushState: true});
});

@@ -601,24 +601,196 @@
  (folder) %7B%0A
+    if (folder) %7B%0A      // Normal folder%0A      folder = %22/%22 + folder + %22/%22;%0A    %7D else %7B%0A      // Root%0A      folder = %22/%22;%0A    %7D%0A    console.log(%22setting folder%22, folder);%0A
     window.a
@@ -816,15 +816,8 @@
 lder
- %7C%7C '/'
 );%0A 
@@ -894,42 +894,78 @@
 page
-%0A     
+, swap page and folder%0A      folder = %5Bpage,
  page =
- '/' +
  folder
+%5D%5B0%5D
 ;%0A      
 fold
@@ -964,20 +964,25 @@
     
-folder = '/'
+page = %22/%22 + page
 ;%0A  
@@ -1000,24 +1000,30 @@
       page =
+ %22/%22 +
  folder + '/
@@ -1042,35 +1042,61 @@
   %7D%0A    
-window.appView.setF
+console.log(%22setting page%22, page);%0A    this.f
 older(fo

fix routing