/********************************
* touch support
*********************************/
(function($) {
	var supportTouch = ("createTouch" in document),
		supportsOrientationChange = "onorientationchange" in window,
		scrollEvent = "touchmove scroll",
		touchStartEvent = supportTouch ? "touchstart" : "mousedown",
		touchStopEvent = supportTouch ? "touchend" : "mouseup",
		touchMoveEvent = supportTouch ? "touchmove" : "mousemove",
		orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

	$.isTouchDevice = function() {
		return supportTouch ? true : false;
	}

	$.supportsOrientationChange = function() {
		return supportsOrientationChange ? true : false;
	}

	$.getOrientationChangeAction = function() {
		return supportsOrientationChange ? "orientationchange" : "resize";
	}

	$.orientation = function() {
		if ($.supportsOrientationChange()) {
			return window.orientation;	
		} else {
			var $w = $(window);
			return $w.width() > $w.height() ? 'landscape' : 'portrait';
		}
	}

	// also handles swipeleft, swiperight
	$.event.special.swipe = {
		setup: function() {
			var thisObject = this,
				$this = $( thisObject );

			$this
				.bind( touchStartEvent, function( event ) {
					var data = event.originalEvent.touches ?
							event.originalEvent.touches[ 0 ] :
							event,
						start = {
							time: (new Date).getTime(),
							coords: [ data.pageX, data.pageY ],
							origin: $( event.target )
						},
						stop;
					
					function moveHandler( event ) {
						if ( !start ) {
							return;
						}
						
						var data = event.originalEvent.touches ?
								event.originalEvent.touches[ 0 ] :
								event;
						stop = {
								time: (new Date).getTime(),
								coords: [ data.pageX, data.pageY ]
						};
						
						// prevent scrolling
						if ( Math.abs( start.coords[0] - stop.coords[0] ) > 10 ) {
							event.preventDefault();
						}
					}
					
					$this
						.bind( touchMoveEvent, moveHandler )
						.one( touchStopEvent, function( event ) {
							$this.unbind( touchMoveEvent, moveHandler );
							if ( start && stop ) {
								if ( stop.time - start.time < 1000 && 
										Math.abs( start.coords[0] - stop.coords[0]) > 30 &&
										Math.abs( start.coords[1] - stop.coords[1]) < 75 ) {
									start.origin
									.trigger( "swipe" )
	
									.trigger( start.coords[0] > stop.coords[0] ? "swipeleft" : "swiperight" );
								}
							}
							start = stop = undefined;
						});
				});
		}
	};

	// add new event shortcuts
	$.each( "swipe swipeleft swiperight".split( " " ), function( i, name ) {
		$.fn[ name ] = function( fn ) {
			return fn ? this.bind( name, fn ) : this.trigger( name );
		};
		$.attrFn[ name ] = true;
	});

	//Adds the events to the jQuery events special collection
	$.each({
		swipeleft: "swipe",
		swiperight: "swipe"
	}, function( event, sourceEvent ) {
		$.event.special[ event ] = {
			setup: function() {
				$( this ).bind( sourceEvent, $.noop );
			}
		};
	});

})(jQuery);
