//2009 Bizmosis
//20090307 Added Livequery for auto binding ontap and ondoubletap

$.fn.tap = function(fn) {
	var maxTapTime = 200;
	this.each(function(i,val) {
		

		$(val).touchstart(function(e) {
			e = e.originalEvent;

			this.startTime = e.timeStamp;
			this.startY = e.touches[0].clientY;
			this.startX = e.touches[0].clientX;
			this.didMove = false;


			
		});
		$(val).touchmove(function(e) {
			this.didMove = true;
			
		});
		$(val).touchend(function(e) {
			e = e.originalEvent;
			
			this.endTime = e.timeStamp;
			this.endY = e.changedTouches[0].clientY;
			this.endX = e.changedTouches[0].clientX;
			
			this.distanceX = Math.abs(this.startX - this.endX);
			this.distanceY = Math.abs(this.startY - this.endY);
			this.tapTime = this.endTime - this.startTime;
			
			//alert(this.distanceX + ":" + this.distanceY + ":" + this.touchTime);
			
			if(this.distanceX < 10 && this.distanceY<10  && this.tapTime<maxTapTime)
			{
				if (fn) {
					fn.call(this);
				}
				
			}
			this.resetTouch();
			
		});
		
		this.resetTouch = function()
		{
			/*
			 this.startTime = null;
			this.startY = null;
			this.startX = null;
			this.endX = null;
			this.endY = null;
			*/
			
			
		}
		
		
	});
	return $(this);
};

$.fn.doubletap = function(fn) {
	this.each(function(i,val) {
		
		//this wires events but doesnt do anything
		$(val).tap(null);

		$(val).touchstart(function(e) {
			e = e.originalEvent;

			if(this.endTime)
			{
				var timeSinceLastTap = e.timeStamp - this.endTime;
				if(timeSinceLastTap<100 && timeSinceLastTap>0)
				{
					if (fn) {
						fn.call(this);
					}
					
				}
				
			}
			
		});
		
		
		
	});
	return $(this);
};
