(function($){
    $.jfancytile = function(el, options){
         var base = this;
         
         base.$el = $(el);
         base.el = el;
         
         base.$el.data("jfancytile", base);
         
         base.init = function(){
         base.options = $.extend({},$.jfancytile.defaultOptions, options);
            
			if (jQuery.browser.safari && document.readyState != "complete"){
				setTimeout( arguments.callee, 100 );
				return;
			}
			
			var imageData = { };
			var container = { width : 0, height : 0 };
			
			base.imageCounter = 0;
			$("ul li img", base.$el).each(function() {
				imageData[base.imageCounter] = {
					src : $(this).attr("src"),
					title : $(this).attr("alt"),
					width : $(this).width(),
					height : $(this).height()
				};
				base.imageCounter++;

				if( $(this).width() > container.width ) {
					container.width = $(this).width();
				}
				
				if( $(this).height() > container.height ) {
					container.height = $(this).height();
				}
			});
			
			// Remove all list items
			$("ul", base.$el).remove();
         
			// Create backwards navigation
			/*var navBack = $("<div />")
								.attr("class", "jfancytilenav jfancytileBack")
								.css({
									height : container.height
								})
								.click(function(){
									navTo(2);
								})
								.appendTo(base.$el);
				*/
			// Create forwards navigation
			/*var navForward = $("<div />")
								.attr("class", "jfancytilenav jfancytileForward")
								.css({
									"height" : container.height,
									"margin-left" : container.width - 50,
								})
								.click(function(){
									navigate("forward");
								})
								.appendTo(base.$el);
			*/
			// Create host container
			var hostContainer = $("<div/>")
										.attr("class", "jfancytileContainer")
										.css({
											width : container.width,
											height : container.height
										})
										.appendTo(base.$el);
			var totalNrOfTiles = base.options.rowCount * base.options.columnCount;
			var first = true;
			for(var img in imageData) {
				var imageContainer = $("<div />")
											.css({
												"width" : imageData[img].width,
												"height" : imageData[img].height,
												"position" : "absolute",
                                    "z-index" : -321
											});
				if(imageData[img].width < container.width) {
					var margin = Math.floor((container.width - imageData[img].width) / 2);
					imageContainer.css({ "margin-left" : margin + "px" });
				}				
				if(imageData[img].height < container.height) {
					var margin = Math.floor((container.height - imageData[img].height) / 2);
					imageContainer.css({ "margin-top" : margin + "px" });			
				}
				if(first) {
					imageContainer.attr("class", "jfancyfirst");
					first = false;
				}
				imageContainer.appendTo($(hostContainer));
				/*var titleContainer = $("<h3 />")
											.html(imageData[img].title)
											.attr("class", "jfancytileTitle")
											.appendTo($(imageContainer));
				*/
            
				var tileDimension = { width : Math.floor((imageData[img].width / base.options.columnCount)), height : Math.floor((imageData[img].height / base.options.rowCount)) };
				var tilePosition = { x : 0, y : 0 };
				for(var i = 0; i < totalNrOfTiles; i++) {
					var tile = $("<div />")
									.css({
										"float" : "left",
										"position" : "relative",
										"width" : tileDimension.width,
										"height" : tileDimension.height,
										"background-image" : "url(" + imageData[img].src + ")",
										"background-position" : "-" + (tilePosition.x * tileDimension.width) + "px -" + (tilePosition.y * tileDimension.height) + "px"
									})
									.appendTo($(imageContainer));
		
					tilePosition.x++;
					if(tilePosition.x > base.options.columnCount - 1) { // Minus one, since tilePosition is zero based
						tilePosition.x = 0;
						tilePosition.y++;
					}
				}
			};
			base.$el.children().not("div.jfancytilenav").children().not(".jfancyfirst").children().not("div").fadeOut(0);
        };
        
      var currentZindex = -321;
		var currentImageIndex = 0;
        
		var navigate = function(direction){
  			if(direction == "back") {
				if(currentImageIndex != 0) {
					currentImageIndex--;
				} else {
					currentImageIndex = base.imageCounter -1;
				}
			} else if (direction == "forward") {
				if(currentImageIndex != base.imageCounter - 1) { // Minus one, zero based
					currentImageIndex++;
				} else {
					currentImageIndex = 0;
				}
			}
         refreshImgs();
      };
      
      var navTo = function(newidx) {
         currentImageIndex = newidx;
         refreshImgs();
      };

      var refreshImgs = function() {
			base.$el.children().not("div.jfancytilenav").children().eq(currentImageIndex).children().not("h3").each(function() {				
            $(this).animate({ left: '+=' + Math.floor(Math.random() * 33.0 - 17.0), top: '+=' + Math.floor(Math.random() * 33.0 - 17.0), opacity:0 }, 0, base.options.outEasing);            
			});
			currentZindex++;
			base.$el.children().not("div.jfancytilenav").children().eq(currentImageIndex).css({ "z-index" : currentZindex });
			base.$el.children().not("div.jfancytilenav").children().eq(currentImageIndex).children().not("h3").each(function() {
				$(this).animate({ top : 0, left:0, opacity:1 }, base.options.inSpeed, base.options.outEasing);
			});			         
			base.$el.children().not("div.jfancytilenav").children().eq(currentImageIndex).children().not("div").fadeIn(base.options.inSpeed);
		};

      $.fn.switchTo = function(opts) {
         currentImageIndex=opts;
         refreshImgs();
      };

      base.init();
    };
    
    $.jfancytile.defaultOptions = {
    	inEasing: "swing",
    	outEasing: "swing",
      inSpeed: 1500,
      outSpeed: 1500,
      rowCount: 4,
      columnCount: 8,
      maxTileShift: 1
    };

    $.fn.jfancytile = function(options){
        return this.each(function(){
            (new $.jfancytile(this, options));
        });
    };
})(jQuery);

