/* global Base64 */
//= require base64

/*
 TODO: CORS support here & on server
*/

(function ($) {
  var spade = {};

  spade.track = function (event, properties) {
    var insertScriptTag = function (data) {
      var el = document.createElement('script');
      el.type = 'text/javascript';
      el.async = true;

      var protocol = ('https:' === document.location.protocol ? 'https:' : 'http:');
      el.src = protocol + '//spade.twitch.tv/?data=' + data;
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(el, s);

      var CLEAN_UP_DELAY = 5000;
      setTimeout(function () {
        $(el).remove();
      }, CLEAN_UP_DELAY);
    };

    setTimeout(function () {
      var data = Base64.encode(JSON.stringify({
        event: event,
        properties: properties
      }));

      insertScriptTag(data);
    }, 0);

  };

  window.spade = spade;
})(jQuery);
