	var totalCards = 52,
		force00=0,
		rotation = 360 / totalCards;
		radius = 110,
		rotationOffset = 0,
		ruleDragOffset = 0,
		scrollingRules = false,
		hasScrolled = false,
		swipeEdit = false,
		editingRules = false,
		buffer = Array(),
		imageReady = new Image(),
		cardRule = Array(),
		cardValues = Array(
			"c_A","d_A","h_A","s_A",						   
   		"c_2","d_2","h_2","s_2",
			"c_3","d_3","h_3","s_3",
			"c_4","d_4","h_4","s_4",
			"c_5","d_5","h_5","s_5",
			"c_6","d_6","h_6","s_6",
			"c_7","d_7","h_7","s_7",
			"c_8","d_8","h_8","s_8",
			"c_9","d_9","h_9","s_9",
			"c_10","d_10","h_10","s_10",
			"c_J","d_J","h_J","s_J",
			"c_Q","d_Q","h_Q","s_Q",
			"c_K","d_K","h_K","s_K"			
		);
	
	
	var has3d = ('m11' in new WebKitCSSMatrix()),
	isIphone = navigator.appVersion.match(/iphone/gi) ? true : false,
	isIpad = navigator.appVersion.match(/ipad/gi) ? true : false,
	isIpod = navigator.appVersion.match(/ipod/gi) ? true : false,	
	isAndroid = navigator.appVersion.match(/android/gi) ? true : false,
	isTouch = isIphone || isIpad || isIpod || isAndroid,
	triggerOn = isTouch ? 'touchstart' : 'mousedown',
	triggerOff = isTouch ? 'touchmove' : 'mousemove',
	triggerMove = isTouch ? 'touchend' : 'mouseup';
//	touchSupport = (navigator.userAgent.toLowerCase().indexOf('iphone')!=-1);
//	triggerOn  = touchSupport ? "touchstart" : "mousedown",
//	triggerOff = touchSupport ? "touchend" : "mouseup";
//	triggerMove = touchSupport ? "touchmove" : "mousemove";
	
	function shuffle(oldArray) {
		var newArray = oldArray.slice();
	 	var len = newArray.length;
		var i = len;
		 while (i--) {
		 	var p = parseInt(Math.random()*len);
			var t = newArray[i];
	  		newArray[i] = newArray[p];
		  	newArray[p] = t;
	 	}
		return newArray; 
	};

	cardRule["K"] = "King is rule. Add a rule to the game";
	cardRule["Q"] = "Queen is questions. Ask the person to your left a question. If they answer, they drink. To keep the round going that person must ask the person to their left.";
	cardRule["J"] = "Jack is categories. Pick a category, then start by saying something in that category. Continue around the table";
	cardRule["10"]= "Social. Everyone drinks.";
	cardRule["9"] = "Rhyme. Phrases are so much cooler than single words. Start the round by saying a word, the person to the left must say another to keep going";	
	cardRule["8"] = "Mate. Pick someone to drink with";	
	cardRule["7"] = "Heaven. Last person to point up drinks.";	
	cardRule["6"] = "Chicks. All the girls at the table, drink.";	
	cardRule["5"] = "Guys. All the guys at the table, drink.";	
	cardRule["4"] = "Floor. Last person to point down drinks.";	
	cardRule["3"] = "Me. bottoms up, buddy.";
	cardRule["2"] = "You. Pick someone and they'll have to drink alone.";	
	cardRule["A"] = "Waterfall. Start drinking, the person to your left should start right after you and so on... this keeps going until you stop.";	
	
	$(function() {			   		
		////////// GENERAL FUNCTIONS
		$("body").bind(triggerOn,function(e){e.preventDefault()});
		$("body").bind("orientationchange",function() {
			if($(window).width()>$(window).height()) { // landscape
				$("body").css({background:"url(images/tableLandscape.jpg)"});
			} else {
				$("body").css({background:"url(images/table.jpg)"});				
			}
			$("#container, #titlebar").css({width:$(window).width(), backgroundPosition:"center"});	
			window.scrollTo(0,0);													
		});
		
		////////// BUTTON FUNCTIONS
		$(".play").live(triggerOn,function(e) {
			hideInfo();	
			play();
		});
		$(".edit").live(triggerOn,function(e) {
			hideInfo();										   
			edit();
		});			
		$(".editClose").live(triggerOn,function(e) {
			play();		
			$(this).remove();
		});
		////////// END BUTTON FUNCTIONS
		
		function hideInfo() {
			$("#info").hide();
		}				
		////////// END GENERAL FUNCTIONS

		////////// GAME FUNCTIONS
		function deal() {
			rotationOffset = 0;
			cards = shuffle(cardValues);
			imageReady.src = "images/cards/" + cards.pop() + ".jpg";
			for(c=0;c<totalCards;c++) {
				rotationOffset = rotationOffset + Math.PI * (360 / totalCards) / 180;
				$("#cards").append("<div id='card_" + c + "' class='card ontable'></div>");	
				$("#card_" + c).data("cardNum",c).css({zIndex:c,"-webkit-transform": "rotateZ(" + (((rotation*c)+90)-rotation) + "deg) scale(.2)",left:Math.round(radius * Math.cos(rotationOffset))+40,top:Math.round(radius * Math.sin(rotationOffset))});			
			}	
		}
		$(".ontable").live(triggerOn,function(e) {	
			e.preventDefault();
			if(editingRules) {
				play();
			}
				cardID = $(this).data("cardNum");
				if($(".flipping").length==0 && $(".finishedFlipping").length==0) {	
					value = imageReady.src.split("_")[1].replace(".jpg","");
					$(this).css({zIndex:53,opacity:1,background:"none"}).html("<div class='f' style='background:url(" + imageReady.src + ")'><div class='rule'>" + cardRule[value] + "</div></div><div class='b'></div>");
					cX = Math.round($(this).css("left").replace("px",""))*-1; 
					cY = Math.round($(this).css("top").replace("px",""))*-1;
					$(this).find(".rule").css({top:($(this).height()/2)-($(this).find(".rule").height()/2)});		
					translate = has3d ? 'scale(1) rotateY(0deg) translate3d(' + (cX + 45) + 'px,' + cY + 'px,0px)' : 'scale(1) rotateY(0deg) translate(' + (cX + 45) + 'px,' + (cY+35) + 'px)'
					$(this).transition({'-webkit-transform': translate,}, { speed: '750ms'}).addClass("flipping");
					
					//buffer a new image while we show this one
					imageReady.src = "images/cards/" + cards.pop() + ".jpg";	
					
					// flip it over
					$(".flipping .f").transition({'-webkit-transform': 'rotateY(0deg)'}, { speed: '750ms'});
					$(".flipping .b").transition({'-webkit-transform': 'rotateY(-180deg)'}, { speed: '750ms' ,callback:function() {
						$(".flipping").addClass("finishedFlipping").removeClass("flipping").removeClass("ontable"); 
						if(isTouch) {
							addSwipeListener($(".finishedFlipping")[0], function(e) {
								removeCard(e)
							 });																															
						} else {
							$(".finishedFlipping").live("click",function() { 
								removeCard(e)
							});
						}
					}});										
				}
			//}
		});
		
		function removeCard(e) {
			offX = e.directionX=="right" ? 500 : -500;
			offY = e.directionY=="down" ? 500 : -500;			
			offRotation = Math.round((Math.random()*7))+14;
			translate = has3d ? 'scale(1) rotateZ(' + offRotation + 'deg) translate3d(' + offX + 'px,' + offY + 'px,0px)':'scale(1) rotateZ(' + offRotation + 'deg) translate(' + offX + 'px,' + offY + 'px)';
			$(".finishedFlipping").transition({'-webkit-transform': translate}, { speed: '750ms', callback: function() { 
				$(".finishedFlipping").remove(); 
				if($(".ontable").length==0) {
					again = confirm("Deal again?")
					if(again) {
						deal();	
					} else {
						alert("done");	
					}
				}
			} });		
		}
		
		function play() {			
			editingRules = false;
			setupPlayField = function() {
				translate = has3d ? 'translate3d(0px,0px,0px)': 'translate(0px,0px)';
				$("#cards").transition({'-webkit-transform':translate},{speed:'500ms'});
				translate = has3d ? 'translate3d(0px,80px,0px)' : 'translate(0px,80px)';
				$("#ruleStrip").transition({'-webkit-transform':translate},{speed:'500ms'});			
			}
			if($(".editing").length>0) {
				editDone($(".editing .editCancel")[0]);
				setTimeout(setupPlayField,600);
			} else {
				setupPlayField();
			}
			$("#titlebar").empty();
			$("#titlebar").append("<a class='edit right button'>Edit Rules</a>");
		}

		
		////////// END GAME FUNCTIONS
		
		////////// EDITING FUNCTIONS

		function edit() {
			editingRules = true;
			$("#titlebar").append("<a class='editClose right button'>Done</a>");
			removeCard({directionX:"left",directionY:"up"});
			translate = has3d ? 'translate3d(0px,-50px,0px)': 'translate(0px,-50px)';
			$("#cards").transition({'-webkit-transform':translate},{speed:'500ms'});
			translate = has3d ? 'translate3d(0px,-120px,0px)' : 'translate(0px,-120px)';
			$("#ruleStrip").transition({'-webkit-transform':translate},{speed:'500ms'});
		}
		
		function renderEditCards() {
			if($(".ruleCard").length<=0) {
				for(r=0;r<cardValues.length;r+=4) {
					buffer.push((new Image()).src="images/cards/" + cardValues[r] + ".jpg")
					offsetX = (r*15)-90;
					//image = "cards/" + cardValues[r].split("_")[0] + '_' + cardValues[r].split("_")[1] + ".jpg";
					$("#ruleStripContent").append("<div class='ruleCard' style='left:" + offsetX + "px;' id='edit-" + cardValues[r] + "'><div class='f' style='background:url(images/card.png)'><div class='value'>" + cardValues[r].split("_")[1].toUpperCase() + "</div></div></div>");
				}
			}
		}

		$(".ruleCard:not(.editing)").live("click",function(e) {
			e.preventDefault();	
			card = this;
			if($(".editing").length<=0) {
				if(!hasScrolled) { // initially the scrollOffset will be 0 and this helps the click delay 
					scrollOffset =0;
				} else {
					if(isTouch) {
						scrollOffset = $("#ruleStripContent").css('-webkit-transform').split("(")[1].split("px")[0];		
					} else {
						scrollOffset =-90;						
					}
				}
				editRule(this);
			}
		});
							
		function editRule(card) {
			//force00 = setInterval(function() { window.scrollTo(0,0); },100);
			duration = "500ms";
			cardOffset = $(card).position().left;
			//console.log("val: " + $(card));	
			cv = $(card).attr("id").split("-")[1].split("_")[1];				
			cardImage = "url(images/cards/" + $(card).attr("id").replace("edit-","") + ".jpg)" ;//$(card).find(".f").css('background');
			$(card).addClass("editing");
			$(card).parents("div:not(#container)").css({overflow:"visible"});
			$(card).data("undo",$(card).css('-webkit-transform'));
			translate = has3d ? 'translate3d(' + (35-cardOffset+(scrollOffset*-1)) + 'px,-255px,0px) scale(1)' : 'translate(' + (35-cardOffset+(scrollOffset*-1)) + 'px,-255px) scale(1)'
			$(card).transition({'-webkit-transform':translate,zIndex:90},{speed:duration});								
			$(card).append("<div class='b' style='background:" + cardImage + "; overflow:hidden'><a class='editComplete button'>Save</a><a class='editCancel button'>Cancel</a><textarea></textarea></div>");									
			$(card).find(".f").transition({'-webkit-transform':'rotateY(-180deg)'},{speed:duration});				
			$(card).find(".b").transition({'-webkit-transform':'rotateY(0deg)'},{speed:duration});	
			$(card).find("textarea").val(cardRule[cv]);
			translate = has3d ? 'translate3d(0px,-40px,0px)' : 'translate(0px,-40px)';
			$("#ruleStrip").transition({'-webkit-transform':translate},{speed:duration});
			myScroll.disable();	
			
		}
		
		$(".editing textarea").live("blur",function() {	window.scrollTo(0,0); });
		
		
		
		
		// this seems to have no effect 
		$(".editing textarea").live("touchmove",function(e) { e.preventDefault(); window.scrollTo(0,0); })
		
		
		
		

		$(".editComplete").live("click",function() {
			window.scrollTo(0,0);
			cv = $(this).parents(".ruleCard").attr("id").split("-")[1].split("_")[1];
			cardRule[cv] = $(this).parent().find("textarea").val();
			editDone(this);
			
		});
		$(".editCancel").live("click",function() {
			editDone(this);
		});
			
		function editDone(b) {
			clearInterval(force00);
			window.scrollTo(0,0);
			card = $(b).parents(".ruleCard");
			translate = has3d ? 'translate3d(0px,-120px,0px)' : 'translate(0px,-120px)';
			$("#ruleStrip").transition({'-webkit-transform':translate},{speed:'500ms'});				
			$(card).removeClass("editing").transition({'-webkit-transform':$(card).data("undo")},{speed:'500ms'});		
			$(card).find(".f").transition({'-webkit-transform':'rotateY(0deg)'},{speed:'500ms'});				
			$(card).find(".b").transition({'-webkit-transform':'rotateY(-180deg)'},{speed:'500ms',callback:function() {
				$(card).find(".b").remove();																																		  
			}});								
			myScroll.enable();		
		}

		if(isTouch) {
			document.addEventListener('touchmove', function(e){ e.preventDefault(); });
			myScroll = new iScroll('ruleStripContent');
			$("#ruleStripContent").live(triggerMove,function() {hasScrolled = true;});			
		} else {
			hasScrolled = true;	
		}

		
		////////// END EDITING FUNCTIONS
		
		// run functions
		
		deal();
		setTimeout(renderEditCards,1500);
		
		if(!isTouch) {
			window.resizeTo(320,480);	
		}
					
  });
		