(function (context, $) {

    "use strict";

    /*
       internal logger with no-ops when console is missing.
    */
    context.JK = context.JK || {};

    var console_methods = [
        'log', 'debug', 'info', 'warn', 'error', 'assert',
        'clear', 'dir', 'dirxml', 'trace', 'group',
        'groupCollapsed', 'groupEnd', 'time', 'timeEnd',
        'timeStamp', 'profile', 'profileEnd', 'count',
        'exception', 'table'
    ];

    var log_methods = {
      'log':null, 'debug':null, 'info':null, 'warn':null, 'error':null,  'assert':null, 'trace':null, 'exception':null
    }

    var backend_methods = {
      "log" : 4,
      "debug" : 4,
      "info" : 3,
      "warn" : 2,
      "error" : 1
    }

    var logCache = [];

    if ('undefined' === typeof(context.console)) {
        context.console = {};
        $.each(console_methods, function(index, value) {
            context.console[value] = $.noop;
        });
    }

    if (!console.debug) {
        console.log("No console.debug found - defining...");
        context.console.debug = function() { console.log(arguments); }
    }

    console.proxy_logs_to_backend = false;

  // http://tobyho.com/2012/07/27/taking-over-console-log/
  function takeOverConsole(){
    var console = window.console
    if (!console) return;
    var i = null;
    function intercept(method){
      var original = console[method]
      console[method] = function(){

        var logAsString = [];
        for(i in arguments) {
          var arg = arguments[i];
          try {
            logAsString.push(JSON.stringify(arg));
          }
          catch(e) {
            logAsString.push("unable to parse node: " + e.toString());
          }
        }
        logCache.push([method].concat(logAsString));
        if(logCache.length > 50) {
          // keep the cache size 50 or lower
          logCache.shift();
        }

        if (original.apply){
          // Do this for normal browsers
          original.apply(console, arguments)
        }else{
          // Do this for IE
          var message = Array.prototype.slice.apply(arguments).join(' ')
          original(message)
        }
        if(console.proxy_logs_to_backend && context.jamClient) {
          var backendLevel = backend_methods[method];
          if(backendLevel) {
            context.jamClient.log(backendLevel, logAsString.join(', '));
          }
        }
      }
    }
    var methods = ['log', 'warn', 'error', 'debug', 'info']
    for (var i = 0; i < methods.length; i++)
      intercept(methods[i])
  }

  takeOverConsole();

  context.JK.logger = context.console;
  context.JK.logger.logCache = logCache;


})(window, jQuery);