// wrapped into a function to have our own namespace
// returns a new function, which should be called by page
;var erovation_track = function() {
	
	var Cookie = {
	  set: function(name, value, daysToExpire) {
	    var expire = '';
	    if (daysToExpire != undefined) {
	      var d = new Date();
	      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
	      expire = '; expires=' + d.toGMTString();
	    }
	    return (document.cookie = escape(name) + '=' + escape(value || '') + expire + "; path=/");
	  },
	  get: function(name) {
	    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
	    return (cookie ? unescape(cookie[2]) : null);
	  },
	  erase: function(name) {
	    var cookie = Cookie.get(name) || true;
	    Cookie.set(name, '', -1);
	    return cookie;
	  },
	  accept: function() {
	    if (typeof navigator.cookieEnabled == 'boolean') {
	      return navigator.cookieEnabled;
	    }

	    Cookie.set('_test', '1');
	    return (Cookie.erase('_test') == '1');
	  }
	};
	
	function uuid2() {
	  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random()*16|0;
			var v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
	  }).toLowerCase();
	};	
	
	if (Cookie.accept()) {
		var cn = "_es";

		var es = Cookie.get(cn)
		if (es == null) {
			es = uuid2();
			Cookie.set(cn, es);
		}

		var seq = 0;
		
		var qs = "?s=" + es +
			"&u=" + escape(document.location.href);

		if (document.referrer) {
			qs += "&r=" + escape(document.referrer);
		}
		
		var tracking_function = function(platform, ev_id) {
			var img = new Image();
			var host = "http://wtf.erovation.com";
			if (typeof(LOCAL) != 'undefined') {
				host = "";
			}
			
			var loc = host + "/p.gif" + qs + "&p=" + escape(platform);
			if (ev_id) {
				loc += "&e=" + escape(ev_id);
			}
			
			img.src = loc + "&z=" + seq;
			
			seq += 1;
		};

		// kickoff
		return function(platform, ev_id) {
			tracking_function(platform, ev_id);
			// window.setInterval(function() { tracking_function(platform, ev_id) }, 60*1000);
		};
	} else {
		// cannot work without cookies
		return null;
	}
}();

