var _ = require('underscore'),
    Events = require('events'),
    exec = require('../client-exec').exec,
    request = require('request');

// TODO : Remove this in favor of HAPI smart caching
// TODO : Make this conditional as users that implement user behavior on the server will not
// want this.
var cache = {};

module.exports = function($) {
  var ajax = new Events.EventEmitter(),
      log = {};

  ajax.toJSON = function() {
    return JSON.stringify(log, undefined, 2);
  };
  ajax.allComplete = function() {
    return !_.any(_.values(log), function(value) { return value === null; });
  };

  $.ajax = function(options) {
    function callback(err, response, body) {
      // TODO : Handle any cookie info that might be necessary
      exec(function() {
        try {
          var xhr = {
            readyState: 4,
            status: response.statusCode,
            responseText: body
          };

          if (!err && response.statusCode === 200) {
            try {
              body = JSON.parse(body);
            } catch (err) {
              body = undefined;
              return options.error(xhr, 'parseerror', err);
            }

            options.success(body, 'success', xhr);
          } else {
            options.error(xhr, 'error', err);
          }
        } finally {
          options.complete();

          cache[options.cacheUrl || options.url] = log[options.cacheUrl || options.url] = body || false;
          if (options.cacheUrl != options.url) {
            delete cache[options.url];
            delete log[options.url];
          }

          ajax.emit('complete');
        }
      });
    }

    if (cache[options.url]) {
      process.nextTick(function() {
        callback(undefined, {statusCode: 200}, cache[options.url]);
      });
      return;
    }

    log[options.url] = null;
    request({
        method: options.type || 'GET',
        url: options.url,
        form: options.data
      },
      callback);
  };

  return ajax;
};

@@ -842,16 +842,28 @@
  status:
+ response &&
  respons
@@ -1355,21 +1355,19 @@
         
-cache
+log
 %5Boptions
@@ -1398,54 +1398,83 @@
 %5D = 
-log%5Boptions.cacheUrl %7C%7C options.url%5D = body %7C%7C
+body %7C%7C false;%0A          cache%5Boptions.url%5D = body ? JSON.stringify(body) :
  fal
@@ -1530,47 +1530,8 @@
 ) %7B%0A
-            delete cache%5Boptions.url%5D;%0A
     

Fix ajax caching layer