(function($) {
  $.handleJSON = function(data) {
    var handlers = {
      prepend: function(selector, value) {
        $(selector).prepend(value);
      },
      append: function(selector, value) {
        $(selector).append(value);
      },

      before: function(selector, value) {
        $(selector).before(value);
      },
      after: function(selector, value) {
        $(selector).after(value);
      },

      remove: function(selector) {
        $(selector).remove();
      },
      replace: function(selector, value) {
        $(selector).replaceWith(value);
      },

      hide: function(selector) {
        $(selector).hide();
      },
      show: function(selector) {
        $(selector).show();
      }
    }

    if (data.status == "ok") {
      if (data.prejs) {
        eval(data.prejs);
      }

      for (var action in data) {
        var handler = handlers[action];
        //console.log("Got action: " + action);

        if (handler) {
          //console.log("Found a handler: " + handler);
          for (var idx in data[action]) {
            var selector = idx;

            if ($.isArray(data[action])) {
              selector = data[action][idx];
            }
            
            //console.log("Invoking handler on selector: " + selector)
            handler(selector, data[action][idx]);
          }
        }
      }

      if (data.postjs) {
        $(function() {
          eval(data.postjs);
        });
      }
    }
  }
})(jQuery);
