/*
 * Copyright (c) 2011-2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*global require, module*/
/*jslint sloppy:true, nomen:true*/


var liburl  = require('url'),
    libpath = require('path');

function trimSlash(str) {
    if (str.charAt(0) === '/') {
        str = str.substring(1, str.length);
    }
    if (str.charAt(str.length - 1) === '/') {
        str = str.substring(0, str.length - 1);
    }
    return str;
}


/**
 * Export a function which can create the handler.
 * @param {Object} config Data to configure the handler.
 * @return {Object} The newly constructed handler.
 */
module.exports = function (config) {
    var appConfig = config.store.getAppConfig({}) || {},
        staticPrefix,
        tunnelPrefix;

    staticPrefix = appConfig.staticHandling && appConfig.staticHandling.prefix;
    tunnelPrefix = appConfig.tunnelPrefix;

    if (staticPrefix) {
        staticPrefix = '/' + trimSlash(staticPrefix);
    }
    if (tunnelPrefix) {
        tunnelPrefix = '/' + trimSlash(tunnelPrefix);
    }

    staticPrefix = staticPrefix || '/static';
    tunnelPrefix = tunnelPrefix || '/tunnel';

    return function (req, res, next) {
        var hasTunnelPrefix = req.url.indexOf(tunnelPrefix) === 0,
            hasTunnelHeader = req.headers['x-mojito-header'] === 'tunnel',
            name,
            type,
            path,
            parts;

        // If we are not tunneling get out of here fast!
        if (!hasTunnelPrefix && !hasTunnelHeader) {
            return next();
        }

        req._tunnel = {};

        /**
        Tunnel examples

        RPC tunnel:
        /tunnel (or it could just have the tunnel header)

        Type tunnel:
        /static/{type}/definition.json
        /{tunnelPrefix}/{type}/definition.json // custom prefix
        /tunnel/static/{type}/definition.json  // according to a UT

        Spec tunnel:
        /static/{type}/specs/default.json
        /{staticPrefix}/{type}/specs/default.json  // custom prefix
        /tunnel/static/{type}/specs/default.json   // according to a UT
        **/

        path = liburl.parse(req.url).pathname;

        // Replace multiple slashes with a single one.
        path = libpath.resolve(path);

        // Normalization step to handle `/{tunnelPrefix}`, `/{staticPrefix}`,
        // and `/{tunnelPrefix}/{staticPrefix}` URLs.
        path = path.replace(staticPrefix, '')
                   .replace(tunnelPrefix, '');

        parts = path.split('/');

        if (parts.length) {
            // Get the basename without the .json extension.
            name = libpath.basename(path, '.json');

            // Get the mojit type.
            type = parts[1];

            // Spec tunnel
            if (parts[parts.length - 2] === 'specs') {
                req._tunnel.specsReq = {
                    type: type,
                    name: name
                };
                return next();
            }
            // Type tunnel
            if (name === 'definition') {
                req._tunnel.typeReq = {
                    type: type
                };
                return next();
            }
        }

        // RPC tunnel
        if (req.url === tunnelPrefix && req.method === 'POST') {
            req._tunnel.rpcReq = {};
            return next();
        }

        return next();
    };
};

@@ -291,235 +291,8 @@
 );%0A%0A
-function trimSlash(str) %7B%0A    if (str.charAt(0) === '/') %7B%0A        str = str.substring(1, str.length);%0A    %7D%0A    if (str.charAt(str.length - 1) === '/') %7B%0A        str = str.substring(0, str.length - 1);%0A    %7D%0A    return str;%0A%7D%0A
 %0A%0A/*
@@ -772,26 +772,16 @@
 = '/' + 
-trimSlash(
 staticPr
@@ -780,25 +780,24 @@
 staticPrefix
-)
 ;%0A    %7D%0A    
@@ -849,18 +849,8 @@
 ' + 
-trimSlash(
 tunn
@@ -857,17 +857,16 @@
 elPrefix
-)
 ;%0A    %7D%0A
@@ -870,31 +870,113 @@
  %7D%0A%0A    
-staticPrefix = 
+// normalize() will squash multiple slashes into one slash.%0A    staticPrefix = libpath.normalize(
 staticPr
@@ -975,24 +975,25 @@
 staticPrefix
+)
  %7C%7C '/static
@@ -1014,16 +1014,34 @@
 refix = 
+libpath.normalize(
 tunnelPr
@@ -1044,16 +1044,17 @@
 elPrefix
+)
  %7C%7C '/tu
@@ -2067,102 +2067,8 @@
 e;%0A%0A
-        // Replace multiple slashes with a single one.%0A        path = libpath.resolve(path);%0A%0A
     
@@ -2301,56 +2301,14 @@
     
-parts = path.split('/');%0A%0A        if (parts.leng
+if (pa
 th) 
@@ -2419,24 +2419,96 @@
  '.json');%0A%0A
+            // Time to get dirty.%0A            parts = path.split('/');%0A%0A
             

clean up the logic around path inspection