SG.namespace("SG.cal.touch");

SG.cal.touch = {

	start : null,
	end : null,
	moving : false,
	timeoutId : null,
	contextmenuTimeout : 400,
	prevType : null,
	preventDefault : false,

	touchHandler : function(event) {
		var changedTouches = event.changedTouches, first = changedTouches ? changedTouches[0] : event, type = "";
		if (event.touches && event.touches.length > 1) {
			return;
		}

		switch (event.type) {
		case "touchstart":
			type = "mousedown";
			SG.cal.touch.start = new Date().getTime();
			SG.cal.touch.moving = false;
			SG.cal.touch.timeoutId = setTimeout(function() {
				SG.cal.touch.simulateEvent(event, "contextmenu", 2, first, true);
			}, SG.cal.touch.contextmenuTimeout);
			break;
		case "touchmove":
			type = "mousemove";
			SG.cal.touch.moving = true;
			clearTimeout(SG.cal.touch.timeoutId);
			break;
		case "touchend":
			clearTimeout(SG.cal.touch.timeoutId);
			/* if no contextmenu or dragDrog prevent event */
			if (SG.cal.touch.prevType == "contextmenu" || (SG.cal.touch.moving && SG.cal.touch.preventDefault == false)) {
				event.preventDefault();
				return;
			}
			SG.cal.touch.simulateEvent(event, "mouseup", 0, first);
			if (SG.cal.touch.moving == false) {
				type = "tap";
			}
			SG.cal.touch.end = new Date().getTime();
			break;
		default:
			SG.cal.touch.prevType = type;
			return;
		}

		if (type != '') {
			SG.cal.touch.simulateEvent(event, type, 0, first);
		}
	},

	simulateEvent : function(event, type, button, first) {
		SG.cal.touch.prevType = type;

		var x = 0;
		if (type == "contextmenu") {
			x = (type == "contextmenu" ? 40 : 0);
		}
		x -= window.scrollX;

		var simulatedEvent = document.createEvent("MouseEvent");
		simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX + x,
				first.clientY, false, false, false, false, button, null);

		first.target.dispatchEvent(simulatedEvent);

		if (SG.cal.touch.preventDefault) {
			event.preventDefault();
		}
	},

	isTouchDevice : function() {
		var agent = navigator.userAgent;
		return agent.match(/ipad/i) != null || agent.match(/iphone/i) != null || agent.match(/android/i) != null || window.Touch;
	},
	
	init : function() {
		if (SG.cal.touch.isTouchDevice()) {
			document.addEventListener("touchstart", this.touchHandler, true);
			document.addEventListener("touchmove", this.touchHandler, true);
			document.addEventListener("touchend", this.touchHandler, true);
			document.addEventListener("touchcancel", this.touchHandler, true);
		}
	}

};

SG.cal.touch.init();


