
var SECS_BETWEEN_ENTONGUES = 120;

/*
 * GET home page.
 */

if (process.env.NODE_ENV == 'production') {
    var MONGO_URL = "mongodb://entongue:entongue@paulo.mongohq.com:10007/app20376599";
}
else {
    var MONGO_URL = "mongodb://localhost/Entongue";
}

var mongoose        = require('mongoose')
  , db_lnk          = MONGO_URL
  , db              = mongoose.createConnection(db_lnk);

var locationSchema = require('../models/location'),
    Location = db.model('Location', locationSchema);

exports.index = function(req, res){

    var diff = ( Date.now() - (req.session.last_entongue || 0) ) / 1000. ;
    var s = ( SECS_BETWEEN_ENTONGUES > diff ? SECS_BETWEEN_ENTONGUES - diff : 0);
console.log(diff,s);    
    res.render('index', { 
        title: 'Entongue', 
        session: req.session, 
        secs_left_to_entongue: parseInt(s) ,
        SECS_BETWEEN_ENTONGUES: SECS_BETWEEN_ENTONGUES
    });
};

exports.setEntongue = function (req, res, next) {
    // getting lat, lon by params
    var lat = parseFloat(req.query.lat);
    var lon = parseFloat(req.query.lon);
    var tag = req.query.tag;

    if (!lat || ! lon || ! tag ) {
        return res.render('error401');
    }
    
    var diff = ( Date.now() - (req.session.last_entongue || 0) ) / 1000. ;

    if ( diff >  SECS_BETWEEN_ENTONGUES ) {
        req.session.last_entongue = Date.now();
        Location.create(
            {lat: lat, lon: lon, tag: tag}, 
            function(err, created){
            if (err) next(err);
            else {
                if (created) console.log("Entongue created");
                else console.log("Error creating Entongue");
                res.json('res', created);
            }
        });
    }
    else {
        console.log('Sorry, you can not entongue any more');
        res.json('res', null);
    }
};

exports.getEntongue = function (req, res, next) {
    var limit = Date.now() - 3600*1000;

    var limit_dt = new Date(limit);

//console.log("DT",limit_dt.toISOString());
    
    Location.find(
        {
            'updated': { $gt : limit_dt.toISOString()}
        }, 
        function(err, locations){
        if (err) next(err);
        else {
            var r = {entongues: locations};
            res.end(JSON.stringify(r, null, 3));
        }
    });
};


@@ -1262,16 +1262,71 @@
 000. ;%0A%0A
+    res.setHeader('Content-Type', 'application/json');%0A
     if (
@@ -1357,24 +1357,24 @@
 TONGUES ) %7B%0A
-
         req.
@@ -1713,27 +1713,41 @@
 res.
-json('res',
+end(JSON.stringify(%7B res:
  created
 );%0A 
@@ -1742,16 +1742,27 @@
  created
+%7D, null, 3)
 );%0A     
@@ -1876,24 +1876,49 @@
 res.
-json('res'
+end(JSON.stringify(%7B res: null%7D
 , null
+, 3)
 );%0A 
@@ -2268,32 +2268,32 @@
 %0A        else %7B%0A
-
             var 
@@ -2320,16 +2320,79 @@
 tions%7D;%0A
+            res.setHeader('Content-Type', 'application/json');%0A
         

fix content/types for heroku