(fixes #236) - url reformating

This solves a bug when initializing nano with a url with databasename, which
also occurs somewhere else in the url, eg. in the username.
Also makes it possible to use nano with couches which are exposed from a
subdirectory, eg the server lives at http://example.com/couchdb.
diff --git a/lib/nano.js b/lib/nano.js
index 277c1d9..f780a5e 100644
--- a/lib/nano.js
+++ b/lib/nano.js
@@ -718,10 +718,11 @@
 
   var path = u.parse(cfg.url);
   var pathArray = path.pathname.split('/').filter(function(e) { return e; });
-  var db = path.pathname && pathArray[0];
+  var db = pathArray.pop();
+  var rootPath = path.pathname.replace(/\/?$/, '/..');
 
   if (db) {
-    cfg.url = cfg.url.replace('/' + db, '');
+    cfg.url = u.resolve(cfg.url, rootPath).replace(/\/?$/, '');
     return docModule(db);
   }
 
diff --git a/tests/integration/shared/config.js b/tests/integration/shared/config.js
index 23089b6..43c1cff 100644
--- a/tests/integration/shared/config.js
+++ b/tests/integration/shared/config.js
@@ -50,6 +50,21 @@
     'with escaped auth');
 
   assert.equal(
+    Nano('http://a:b%20c%3F@someurl.com:5984/my%2Fdb').config.url,
+    'http://a:b%20c%3F@someurl.com:5984',
+    'with dbname containing encoded slash');
+
+  assert.equal(
+    Nano('http://mydb-a:b%20c%3F@someurl.com:5984/mydb').config.url,
+    'http://mydb-a:b%20c%3F@someurl.com:5984',
+    'with repeating dbname');
+
+  assert.equal(
+    Nano('http://a:b%20c%3F@someurl.com:5984/prefix/mydb').config.url,
+    'http://a:b%20c%3F@someurl.com:5984/prefix',
+    'with subdir');
+
+  assert.equal(
     Nano(baseUrl + ':5984/a').config.url,
     baseUrl + ':5984',
     'with port');