/*
 * app.js - Express server static files
 */

/*jslint         node    : true, continue : true,
  devel  : true, indent  : 2,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : true,
  regexp : true, sloppy  : true, vars     : false,
  white  : true
*/
/*global */

// ------------ BEGIN MODULE SCOPE VARIABLES --------------
'use strict';
var
    http = require('http'),
    express = require('express'),
    compression = require('compression'),
    bodyParser = require('body-parser'),
    morgan = require('morgan'),
    errorhandler = require('errorhandler'),
    methodOverride = require('method-override'),
    routes = require('./lib/routes'),
    env = process.env.NODE_ENV || 'development',
    app = express(),
    server = http.createServer(app),
    path = require('path');
//  var io      = require('socket.io').listen(server);

//get the application root so that every module knows where it needs to load files from (crypto key kg stuff)
global.appRoot = path.resolve(__dirname);

// ------------- END MODULE SCOPE VARIABLES ---------------

// ------------- BEGIN SERVER CONFIGURATION ---------------

//COMPRESSION MIDDLEWARE
app.use(compression());

//STATIC FILES
app.use(express.static(__dirname + '/public'));

if ('development' === env) {
    // configure stuff here

    //morgan logger
    app.use(morgan('dev'));

    //error handler returns errors to the client wherever possible
    //not for normal end-users
    app.use(errorhandler());
}


// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
    extended: false
}));

// parse application/json
app.use(bodyParser.json());

app.use(methodOverride());



if ('production' === env) {
    app.use(errorhandler());
}

//----------------- ROUTES ------------------------------
routes.configRoutes(app, server);



// -------------- END SERVER CONFIGURATION ----------------

// ----------------- BEGIN START SERVER -------------------
var listener = server.listen(process.env.PORT ? process.env.PORT : 3000);
console.log(
    'Express server listening on port %d in %s mode @ %s',
    listener.address().port, app.settings.env, new Date().toString()
);
// ------------------ END START SERVER --------------------