/**
 * jq-tapswipe
 * @version 1.0 (2010/9/2)
 */
(function($) {
	
	var ua = navigator.userAgent;
	var isTouchable = false;
	var touchDevices = ["iPhone", "iPod", "iPad"];
	for (var d = 0; d < touchDevices.length; d++) {
		var device = touchDevices[d];
		if(ua.match(new RegExp(device, "i"))){	isTouchable=true;break;}
	};
	
	 $.fn.touchwipe = function(settings) {
     var config = {
    		min_move: 20,
 			wipeLeft: function() { console.log("left"); },
 			wipeRight: function() { console.log("right"); },
			wipeUp:function(){console.log("up"); },
			wipeDown:function(){console.log("down"); },
			preventDefaultEvents: true
	 };
     
     if (settings) $.extend(config, settings);
 
     this.each(function() {
    	 var startX;
		 var startY;
		 var isMoving = false;

    	 function cancelTouch() {
    		 this.removeEventListener('touchmove', onTouchMove);
    		 startX = null;
    		 startY = null;
    		 isMoving = false;
    	 }	
    	 
    	 function onTouchMove(e) {
    		 if(config.preventDefaultEvents)e.preventDefault();
			 
    		 if(isMoving) {
	    		 var x = e.touches[0].pageX;
	    		 var y = e.touches[0].pageY;
	    		 var dx = startX - x;
	    		 var dy = startY - y;
	    		
				 if(Math.abs(dx) >= config.min_move) {
	    			cancelTouch();
	    			if(dx > 0)config.wipeLeft();
	    			else config.wipeRight();
	    		 } else if(Math.abs(dy) >= config.min_move){
				 	cancelTouch();
	    			if(dy > 0)config.wipeUp();
	    			else config.wipeDown();
				 };
    		 }
    	 }
    	 function onTouchStart(e)
    	 {
    		 if (e.touches.length == 1) {
    			 startX = e.touches[0].pageX;
    			 startY = e.touches[0].pageY;
    			 isMoving = true;
    			 this.addEventListener('touchmove', onTouchMove, false);
    		 }
    	 }
		 if(isTouchable)this.addEventListener('touchstart', onTouchStart, false);
     });
   };
 
 
   $.fn.tap = function(settings) {

     var config = {
 			press: function() { /*console.log("down");*/ },
 			release: function() { /*console.log("up");*/ },
			preventDefaultEvents: true
	 };
     
     if (settings) $.extend(config, settings);
 
     this.each(function() {
    	 
		 function onTouchEnd(e) {
			 config.release(e);
    	 };
    	 
    	 function onTouchStart(e){
			 config.press(e);
    	 };
		 if(isTouchable){
			 this.addEventListener('touchstart', onTouchStart, false);
			 this.addEventListener('touchend', onTouchEnd, false);
		 } else {
			 $(this).mousedown(onTouchStart);
			 $(this).mouseup(onTouchEnd);
		 }
		 
     });
 
     return this;
   };
 })(jQuery);

