//
// アクセス解析「Misty」
//
if (typeof(Misty) == 'undefined') { Misty = function() {}; }

Misty.Analysis = function(id) {
	this.id = id;
	this.beacon_id = "Misty-BEACON" + id;

	this.env = new Misty.Analysis.Env();
	this.img_url1 = this.env.img_url1;
	this.img_url2 = this.env.img_url2;
//	this.char = this.env.char;
	this.dynMousePositionPeriod = this.env.dynMousePositionPeriod;
	this.safariSupportDelayTime = 500;
}

Misty.Analysis.Browser = {
	IE: !!(window.attachEvent && !window.opera),
	Opera: !!window.opera,
	Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
	Safari: navigator.userAgent.toLowerCase().indexOf("safari") != -1,
	ModeStd: document.compatMode && document.compatMode != "BackCompat"
}

Misty.Analysis.prototype.getWinSize = function() {
	var width = null;
	var height = null;
	if (Misty.Analysis.Browser.ModeStd) {
		width = document.documentElement.clientWidth;
		height = document.documentElement.clientHeight;
	} else {
		if (document.body) {
			width = document.body.clientWidth;
			height = document.body.clientHeight;
		}
	}
	return { width:width, height:height };
}

Misty.Analysis.prototype.getScrSize = function() {
	var width = null;
	var height = null;
	var sw = screen.width;
	var sh = screen.height;
	var cd = screen.colorDepth;
	return { width:sw, height:sh, colorDepth:cd };
}

Misty.Analysis.Env = function() {
	return this;
}

//Misty.Analysis.Env.prototype.char = "null";
Misty.Analysis.Env.prototype.img_url1 = "//misty.hat.ne.jp/misty/a.php";
Misty.Analysis.Env.prototype.img_url2 = "//misty.hat.ne.jp/misty/b.php";
Misty.Analysis.Env.prototype.dynMousePositionPeriod = [ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 15, 15, 15, 15, 15, 15, 15, 15 ];

Misty.Analysis.convertEvent = function(event) {
	if (event == "DOMMouseScroll") {
		event = "mousewheel";
	}
	return event;	
}

Misty.Analysis.addEventListener = function(elem, event, func) {
	if (!Misty.Analysis.listeners) {
		Misty.Analysis.listeners = new Array();
	}
	Misty.Analysis.listeners.push({ elem:elem, event:event, func:func });

	if (window.addEventListener && !Misty.Analysis.Browser.Opera) {
		elem.addEventListener(event, func, false);
	} else if (window.attachEvent) {
		event = this.convertEvent(event);
		elem.attachEvent("on" + event, func);
	}
}

Misty.Analysis.removeAllEventListeners = function() {
	if (Misty.Analysis.listeners) {
		for (var i = 0;i < Misty.Analysis.listeners.length; i++) {
			var entry = Misty.Analysis.listeners[i];
			var elem = entry.elem;
			var event = entry.event;
			var func = entry.func;
			if (window.addEventListener && !Misty.Analysis.Browser.Opera) {
				elem.removeEventListener(event, func, false);
			} else if (window.attachEvent) {
				event = this.convertEvent(event);
				elem.detachEvent("on" + event, func);
			}
		}
	}
}

Misty.Analysis.prototype.setMouseClick = function(target, ev) {
	var nodeName = target.nodeName;
	if (nodeName) {
		if (nodeName.toUpperCase() == "A") {
			this.lastClickHref = target.href;
			this.lastClickTime = new Date().getTime();
			this.addMousePosition(ev);
		} else if (nodeName.toUpperCase() == "IMG") {
			this.lastClickHref = document.activeElement;
			this.lastClickTime = new Date().getTime();
			this.addMousePosition(ev);
		} else if (nodeName.toUpperCase() == "AREA") {
			this.lastClickHref = target.href;
			this.lastClickTime = new Date().getTime();
			this.addMousePosition(ev);
		} else if (nodeName.toUpperCase() == "INPUT") {
			var formName = target.form ? target.form.name : "";
			var formAction = target.form ? target.form.action : "";
			var inputForm = formName + "|" + formAction;
			var inputName = target.name + "|" + target.value;
			this.lastClickHref = "input(" + inputForm + "|" + inputName + ")";
			this.lastClickTime = new Date().getTime();
			this.addMousePosition(ev);
		} else {
			this.addMousePosition(ev);
		}
	} 
}

Misty.Analysis.prototype.mouseClick = function(ev){
	if (!ev) var ev = window.event;
	var target = ev.srcElement ? ev.srcElement : ev.target;
	if (target) {
		this.setMouseClick(target, ev);
	} 
}

Misty.Analysis.prototype.mouseScroll = function(ev){
	if (!ev) var ev = window.event;
	var delta = 0;
	if (ev.wheelDelta) {
		delta = (ev.wheelDelta / 120);
		if (window.opera) {
			delta = -delta;
		}
	} else if (ev.detail) {
		delta = (-ev.detail / 3);
	}
	if (0 < delta) {
		this.mouseWheelUp += delta;
	} else {
		this.mouseWheelDown += -delta;
	}
}

Misty.Analysis.prototype.mouseMove = function(ev) {
	if (!this.startMousePosition) {
		this.startMousePosition = this.eventPosition(ev);
	}
	if (!this.dynMousePositionRecord) {
		this.dynMousePositionRecord = new Array();
		this.dynMousePositionTime = this.startTime;
	} 
	var n = this.dynMousePositionRecord.length;
	if (n < this.dynMousePositionPeriod.length) {
		var x = ((new Date()).getTime() - this.dynMousePositionTime) / 1000;
		if (this.dynMousePositionPeriod[n] < x) {
			this.dynMousePositionTime = (new Date()).getTime();
			var v = this.eventPosition(ev);
			this.dynMousePositionRecord.push(v);
		}
	}
}

Misty.Analysis.prototype.eventPosition = function(ev) {
	var top = 0;
	var left = 0;
	if (ev.pageX) {
		top = ev.pageY;
		left = ev.pageX;
	} else {
		var scrollTop  = document.body.scrollTop  || document.documentElement.scrollTop;
		var scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
		top  = (ev.clientY + scrollTop);
		left = (ev.clientX + scrollLeft);
	}
	if (Misty.Analysis.Browser.IE && Misty.Analysis.Browser.ModeStd) {
		top -= 2;
		left -= 2;
	}
	return { x: left , y: top ,  t: Math.floor(((new Date().getTime()) - this.startTime) / 100) };
}

Misty.Analysis.prototype.addMousePosition = function(ev) {
	if (!this.mouseTimes) {
		this.mouseTimes = 0;
	}
	this.mouseTimes ++;
	if (!this.mousePositionRecord) {
		this.mousePositionRecord = new Array();
	}
	var v = this.eventPosition(ev);
	this.mousePositionRecord.push(v);
	if (10 < this.mousePositionRecord.length) {
		this.mousePositionRecord.shift();
	}
}

Misty.Analysis.prototype.setCookie = function(key, value, period) {
	var tmp = key + "=" + encodeURI(value) + ";";
	if (period) {
		var nowtime = new Date().getTime();
		var lim = new Date();
		lim.setTime(nowtime + period);
		tmp += "expires=" + lim.toGMTString() + ";";
	}
	document.cookie = tmp;
}

Misty.Analysis.prototype.getCookie = function(key) {
	var x = 0;
	var tmp = document.cookie + ";";
	var len = tmp.length;
	while (x < len) {
		var y = tmp.indexOf(";", x);
		var tmp2 = tmp.substring(x, y);
		while (tmp2.substring(0,1) == ' ') {
			tmp2 = tmp2.substring(1, tmp2.length);
		}
		var x3 = tmp2.indexOf("=");
		if (tmp2.substring(0,x3) == key) {
			return decodeURI(tmp2.substring(x3 + 1 ,tmp2.length)); 
		}
		x = y + 1;
	}
	return "";
}

Misty.Analysis.prototype.checkCookie = function() {
	var cookie_name = "Misty" + this.id;
	this.setCookie(cookie_name, "test");
	var tmp = this.getCookie(cookie_name);
	if (tmp == "test") {
		return true;
	}
	return false;
}

Misty.Analysis.prototype.getUid = function(stt, rand) {
	var cookie_name = "Misty" + this.id + "Uid";
	var tmp = this.getCookie(cookie_name);
	if (tmp == "") {
		tmp = stt.toString() + "-" +  rand.toString();
	}
	this.setCookie(cookie_name, tmp, 365 * 24 * 60 * 60 * 1000);
	return tmp;
}

Misty.Analysis.prototype.getTfv = function() {
	var now = new Date();
	var today = new Date(now.getYear(), now.getMonth(), now.getDate());
	var cookie_name1 = "Misty" + this.id + "DT";
	var cookie_name2 = "Misty" + this.id + "TFV";
	var cookie_name3 = "Misty" + this.id + "TLV";
	var tfv = 1;
	var tlv = 0;
	var prev = this.getCookie(cookie_name1);
	if (prev == "") {
		this.setCookie(cookie_name1, today.getTime(), 365 * 24 * 60 * 60 * 1000);
		this.setCookie(cookie_name2, tfv, 365 * 24 * 60 * 60 * 1000);
		this.setCookie(cookie_name3, tlv, 365 * 24 * 60 * 60 * 1000);
	} else {
		if (prev < today.getTime()) {
			this.setCookie(cookie_name1, today.getTime(), 365 * 24 * 60 * 60 * 1000);

			tfv = parseInt(this.getCookie(cookie_name2)) + 1;
			this.setCookie(cookie_name2, tfv, 365 * 24 * 60 * 60 * 1000);

			tlv = (today.getTime() - prev) / (24 * 60 * 60 * 1000);
			this.setCookie(cookie_name3, tlv, 365 * 24 * 60 * 60 * 1000);
		} else {
			tfv = parseInt(this.getCookie(cookie_name2));
		}
	}
	return tfv;
}

Misty.Analysis.prototype.getTlv = function() {
	var cookie_name = "Misty" + this.id + "TLV";
	var tlv = this.getCookie(cookie_name);
	if (tlv == "") {
		tlv = 0;
	}
	return tlv;
}

Misty.Analysis.prototype.checkFlash = function() {
	try {
		if (Misty.Analysis.Browser.IE) {
			var flashVersion = new ActiveXObject("ShockwaveFlash.ShockwaveFlash").FlashVersion();
			var version = Math.floor(flashVersion / 0x10000);
			return version;
		} else {
			var version = null;
			for (var i = 0; i < navigator.plugins.length; i++) {
				var str = navigator.plugins[i].description;
				var ptr = str.indexOf("Flash");
				if (ptr >= 0) {
					version = eval(str.substring(ptr + 6, ptr + 9));
				}
			}
			return version;
		}
	} catch (e) {
		return null;
	}
}

Misty.Analysis.prototype.getPeriod = function() {
	if (this.startTime && this.lastTime) {
		return this.lastTime - this.startTime;
	}
	return null;
}

Misty.Analysis.prototype.getStartMousePosition = function() {
	if (this.startMousePosition) {
		return "(" + this.startMousePosition.x + "," + this.startMousePosition.y + ")";
	}
	return null;
}

Misty.Analysis.prototype.getMousePositions = function() {
	if (this.mousePositionRecord) {
		var arr = new Array();
		for (var i = 0; i < this.mousePositionRecord.length; i++) {
			var h = this.mousePositionRecord[i];
			arr.push(h.x + "," + h.y + "," + h.t);
		}
		var str = arr.join('|');
		if (0 < arr.length) {
			str += "|";
		}
		return str;
	}
	return null;
}

Misty.Analysis.prototype.getDynMousePositions = function() {
	if (this.dynMousePositionRecord) {
		var arr = new Array();
		for (var i = 0; i < this.dynMousePositionRecord.length; i++) {
			var h = this.dynMousePositionRecord[i];
			arr.push(h.x + "," + h.y + "," + h.t);
		}
		var str = arr.join('|');
		if (0 < arr.length) {
			str += "|";
		}
		return str;
	}
	return null;
}

Misty.Analysis.prototype.searchNodes = function(nodeName, elem, arr) {
	var cn = elem.childNodes;
	if (cn && cn.length) {
		for (var i = 0; i < cn.length; i++) {
			var c = cn[i];
			if (c.nodeType == 1) {
				if (c.nodeName.toUpperCase() == nodeName) {
					arr[arr.length] = c;
				} else if (c.hasChildNodes()) {
					this.searchNodes(nodeName, c, arr);
				}
			}
		}
	}
}

Misty.Analysis.prototype.setFilters = function(tag, func) {
	var self=this;
	var lFunc = func;
	var arr = new Array();
	if (document.body) {
		this.searchNodes(tag, document.body, arr);
		for (var i = 0; i < arr.length; i++) {
			var elem = arr[i];
			var prev_onclick = elem.getAttribute('onclick');
			if (prev_onclick) {
				(function(act, lFunc2){
					elem.onclick = function(ev){
						var res = eval(" var misty_dummy_function = function() { " + act + "}; misty_dummy_function();");
						if (res) {
							lFunc2(this, ev);
							var myself = this;
							setTimeout(function() {
								location.href = myself.href
							}, self.safariSupportDelayTime);
						}
						return false;
					};
				})(prev_onclick, lFunc);
			}
			else {
				(function(lFunc2){
					elem.onclick = function(ev){
						lFunc2(this, ev);
						var myself = this;
						setTimeout(function(){
							location.href = myself.href
						}, self.safariSupportDelayTime);
						return false;
					}
				})(lFunc);
			}
		}
	}
}

Misty.Analysis.prototype.end = function(ev) {
	var im = new Image(1,1);
	this.lastTime = (new Date()).getTime();
	var params = new Array();
	params.push("mode=end");
	params.push("id=" + this.id);
	params.push("stt=" + Math.floor((this.startTime) / 100));
	params.push("rand=" + this.randomNumber);
	params.push("lhn=" + encodeURIComponent(this.lastClickHref));  
	params.push("smp=" + this.getStartMousePosition());
	params.push("mt=" + this.mouseTimes);
	params.push("mwu=" + this.mouseWheelUp);
	params.push("mwd=" + this.mouseWheelDown);
	params.push("m=" + this.getMousePositions());
	params.push("mp=" + this.getDynMousePositions());
	params.push("paramend=1");
	im.onload = function() {}
	im.src = this.img_url2 + "?" + params.join('&');
}

Misty.Analysis.prototype.start = function() {
	var im = document.getElementById(this.beacon_id);
	this.startTime = (new Date()).getTime();
	this.mouseWheelUp = 0;
	this.mouseWheelDown = 0;
	var win_size = this.getWinSize();
	var scr_size = this.getScrSize();
	var params = new Array();
	params.push("mode=start");
	params.push("id=" + this.id);
	params.push("stt=" + Math.floor((this.startTime) / 100));
	params.push("rand=" + this.randomNumber);
	params.push("ref=" + encodeURIComponent(document.referrer));
	params.push("url=" + encodeURIComponent(location.href));
	params.push(this.checkCookie() ? "cookie=1" : "cookie=0");
	params.push("uid=" + this.getUid(Math.floor((this.startTime) / 100), this.randomNumber));	
	params.push("tfv=" + this.getTfv());	
	params.push("tlv=" + this.getTlv());	
	params.push("flash=" + this.checkFlash());	
	params.push("title=" + encodeURIComponent(document.title));
	params.push("ww=" + win_size.width);
	params.push("wh=" + win_size.height);
	params.push("sw=" + scr_size.width);
	params.push("sh=" + scr_size.height);
	params.push("cd=" + scr_size.colorDepth);
	params.push("paramend=1");
	im.onload = function() {}
	im.src = this.img_url1 + "?" + params.join('&');
}

Misty.Analysis.prototype.init = function() {
	var self = this;
	self.randomNumber = Math.floor(Math.random() * 100000);

	if (!Misty.Analysis.Browser.Safari) {
		Misty.Analysis.addEventListener(window,"load", function() {
			self.start();
		});
		Misty.Analysis.addEventListener(window, "unload", function() {
			self.end();
			Misty.Analysis.removeAllEventListeners();
		});
//		if (document.body) {
//			Misty.Analysis.addEventListener(document.body, "click", function(ev) {
//				self.mouseClick(ev);
//			});
//			Misty.Analysis.addEventListener(document.body, "DOMMouseScroll", function(ev) {
//				self.mouseScroll(ev);
//			});
//			Misty.Analysis.addEventListener(document.body, "mousemove" , function(ev) { 
//				self.mouseMove(ev);
//			});
//		}
	} else {
		Misty.Analysis.addEventListener(window,"load", function() {
			self.start();
			self.setFilters("A", function(elem, ev) {
				self.setMouseClick(elem, ev);
				self.end();
			});
			Misty.Analysis.addEventListener(window, "unload", function() {
				Misty.Analysis.removeAllEventListeners();
			})
//			if (document.body) {
//				Misty.Analysis.addEventListener(document.body, "click", function(ev) {
//					self.mouseClick(ev);
//				});
//				Misty.Analysis.addEventListener(document.body, "mousewheel", function(ev) {
//					self.mouseScroll(ev);
//				});
//				Misty.Analysis.addEventListener(document.body, "mousemove" , function(ev) { 
//					self.mouseMove(ev);
//				});
//			}
		});
	}
	document.write('<img id="' + this.beacon_id + '" width="1" height="1" />');
}

