// fifteen puzzle for iPhone
// (c) 2007 stephan.com
// v1.1 for jquery

jQuery.fn.fifteen = function(){
	
	// set up global variables and utility functions
	jQuery.fifteen = {
		// We start with position 15 open.
		// It would be nicer to prescramble the pieces
		// but that introduces a parity issue
		emptyPosition: 15,
		topOf: function(pos) {
			return Math.floor(pos/4)*75
		},
		leftOf: function(pos) {
			return pos%4*75;			
		}
	}
	

	// put a div inside the main block
	$("#fifteen").append("<div/>");
	
	// throw fifteen div's into that inner block
	for(i=0;i<15;i++) {
		$("#fifteen > div").append("<div/>");
	}
	
	// Tag them as tiles
	$("#fifteen > div > div").addClass("Tile");
	
	// Tag evens and odds
	$("div.Tile:even").addClass("even");
	$("div.Tile:odd").addClass("odd");
	
	// Set the ID's and initial positions
	$("div.Tile").each(function(i){
		$(this).
			attr({id: "Tile"+(i+1), position: i}).
			css({top: jQuery.fifteen.topOf(i), left: jQuery.fifteen.leftOf(i)}).
			append(i+1);
	})
	// Attach a click handler to each tile
	$("div.Tile").click(function(){
		var from = $(this).attr("position");
		var to = $.fifteen.emptyPosition;
		// if we're immediately above or below, move stuff
		// sneaky because we use mod 4 for the up/down case - kinda cheating
		// For big fun, take out this line
		if((Math.abs(from-to)==1 && Math.floor(from/4)==Math.floor(to/4)) || Math.abs(from-to)==4) {
			$(this).animate({top: jQuery.fifteen.topOf(to), left: jQuery.fifteen.leftOf(to)})
			// swap the recorded positions
			$(this).attr("position",to);
			$.fifteen.emptyPosition = from;
		}
		
	});	
}

