/* 
Twisted Griddr
Version: 0.1
Author: Simon de Turck

The Twisted Griddr makes a .... grid! repositions it's tiles when browser resizes and more....

Needs to be a real jQuery plugin some day  .........
*/ 

//Global variables
var _visableColumns = 0;
var _visableRows = 0;
var _hiddenTiles = [];
var _activeTile = null;
var _needsGridUpdate = false;
var _animated = false;
var _nextTile = null;

//Patterns
var p1 = [	[0,0],[1,0],[2,0],
			[0,1],[1,1],[2,1] ];
			
var p2 = [  [-1,0],[0,0],[1,0],
		    [-1,1],[0,1],[1,1]];

var p3 = [  [-2,0],[-1,0],[0,0],
		    [-2,1],[-1,1],[0,1]];
		
var p4 = [  [0,-1],[1,-1],[2,-1],
		    [0,0],[1,0],[2,0]];
		
var p5 = [  [-1,-1],[0,-1],[1,-1],
		    [-1,0],[0,0],[1,0]];
		
var p6 = [  [-2,-1],[-1,-1],[0,-1],
		    [-2,0],[-1,0],[0,0]];


$(function(){
	
	//Create, Name, Index and Init the Tiles
	var i = 0;
	/*for(i=0; i<25; i++){
		var tile = $(".tile","#assets").clone();
		
		$(tile).attr("id","tile_" + i);
		$(tile).attr("idx", i);
		$(tile).attr("row", i);
		$(tile).attr("col", i);
		$(tile).attr("left",i);
		$(tile).attr("top",i);
		
		$(tile).prepend($(".closebutton","#assets").clone());
		$("#canvas").append(tile);
	}*/
	
	
	$(".tile","#canvas").each(function(){
		//if(i>0) {
			$(this).attr("id","tile_" + i);
			$(this).attr("idx", i);
			$(this).attr("row", i);
			$(this).attr("col", i);
			$(this).attr("left",i);
			$(this).attr("top",i);
			
			//$(this).prepend($(".closebutton","#assets").clone());
		//}
		if(!$(this).hasClass("ignore")){
			i++
		}
	});
	
	
	// Tile Events
	$(".tile>.small>.tile-content").each(function(){ 
		$(this).hover(function(){
		
			//Rollover :: Show details
 			$("div.overlay", this).stop().animate({bottom: 0}, 400, "easeOutQuint");
 			
 		}, function(){
 		
 			//Rollout :: Hide details
 			$("div.overlay", this).stop().animate({bottom: -136}, 200, "swing");
 			
 		}).click(function(){
 		
 			//Click :: Show Big tile
 			if(_activeTile != null){
 				// Or do we ..... NO there can be only 1 BIG tile?
				_nextTile = this;				
				// $(".closebutton", $(tile)).click();
				showTiles();
				setTimeout("showNextTile()", 250);
				return;
			}
			// Get the properties
			var tile = $(this).parent().parent();
			var _id	 = tile.attr('id');
			var _idx = tile.attr('idx');
			var _row = tile.attr('row');
			var _col = tile.attr('col');
			var tiles = [];
			var firsttile = null;
			
			// Get the tiles that need to go and hide!
			if(_col == _visableColumns-1){
				if(_row == _visableRows){
					tiles = getTiles(_col,_row,p6);
				}else{
					tiles = getTiles(_col,_row,p3);
				}
			}else if(_col == _visableColumns-2){
				if(_row == _visableRows){
					tiles = getTiles(_col,_row,p5);
				}else{
					tiles = getTiles(_col,_row,p2);
				}
			}else{
				if(_row == _visableRows){
					tiles = getTiles(_col,_row,p4);
				}else{
					tiles = getTiles(_col,_row,p1);
				}
			}
			
			_hiddenTiles = tiles;
			_activeTile = tile;
			firsttile = $("#" + tiles[0]);
			
			//Hide, Widen, Position and fadein the selected tile
			$(tile).css('display', 'none')
			$(tile).addClass('widetile');
			$(tile).css('left',		$(firsttile).attr('xpos') + "px");
			$(tile).css('top',  	$(firsttile).attr('ypos') + "px");
			$(tile).fadeIn('slow');
			
			//Make the closebutton do something
			$(".closebutton, .bigImage img",$(tile)).bind('click', function(){
				showTiles();
			})
			
			// Make the popupbutton do something
			$("a.info", $(tile)).click(showPopup);
			
			//Hide the surrounding tiles
			hideTiles();
			
			// Load slideshow:
			images = [];			
			$(".images var", tile).each(function(){				
				images.push($(this).text());
			});
			
			currentImage = 0;
			loadImage(currentImage);
			
			// Bind the previous and next buttons:
			$("a.prev", tile).click(function(){
				currentImage--;
				if(currentImage < 0) { currentImage = images.length-1; }
				loadImage(currentImage);
				return false;
			});
			
			$("a.next", tile).click(function(){
				currentImage++;
				if(currentImage >= images.length) { currentImage = 0; }
				loadImage(currentImage);
				return false;
			});
 		
 		})
	
	});
	
	//TwistedWindowResizingRoutine (tm)
	var resizeTimer = null;
	$(window).bind('resize',function(){
		if(resizeTimer) clearTimeout(resizeTimer)
		resizeTimer = setTimeout(updateGrid,100);
	});

    $("#popup form").submit(function(){
        var ok = true;
        $("input.required", this).each(function(){
            if($(this).val() == '')
            {
                ok = false;
                $(this).addClass("error");
            } else {
                $(this).removeClass("error");
            }
        });
        if(!ok)
        {
            alert('U heeft niet alle verplichte velden ingevuld');
            return false;
        }
    });

	//First time grid update!
	updateGrid();


});

function showNextTile()
{
	if(_nextTile!=null) {
		$(_nextTile).click();
		_nextTile = null;
	}
}


function loadImage(nr)
{
	
	// Laad de ajaxloader zien:
	$("img.ajaxloader", _activeTile).fadeIn("fast");
	// Verwijder de huidige onload()-event handler:
	$(".bigImage img", _activeTile).unbind("load");
	$(".bigImage img", _activeTile).load(function(){		
		// Verberg de ajaxloader:
		$("img.ajaxloader", _activeTile).fadeOut("fast");
		// Toon de afbeelding
		$(".bigImage img", _activeTile).fadeIn("fast");
	})
	// Verberg de afbeelding:
	$(".bigImage img", _activeTile).fadeOut("fast", function(){
		// Pas de href aan:
		$(".bigImage img", _activeTile).attr("src", images[nr]);
	});
}

// Hide tiles that need hiding.
function hideTiles(){
	jQuery.each(_hiddenTiles,function(){
		if(_activeTile.attr('id') != this){
			// Hide instantaneous, the big tile will fade in (snappy huh) 
			$("#" + this).css('display','none');			
		}
	});
}

// Gimme back my tiles!
function showTiles(){
	var d = 0; //delay multiplier
	jQuery.each(_hiddenTiles,function(){
		if(_activeTile.attr('id') != this){
			// If and only if this tile is not the active one...
			// show with a longer delay for each tile .. TwistedTileWavedAppear (tm)
			// Dirty trick since jQuery has no "real" delay
			$("#" + this).animate({delay: 0.0}, 15*d).fadeIn(300);
			//$("#" + this).fadeIn(300 + (200*d));
			d++;
		}else{
			// This is the active tile, it's big now, make small again!
			//Hide, Shrink, Position and fadein the active tile			
			$(_activeTile).css('display','none');
			$(_activeTile).removeClass('widetile');
			$(_activeTile).css('left', $(_activeTile).attr('xpos') + "px");
			$(_activeTile).css('top',  $(_activeTile).attr('ypos') + "px");
			$(_activeTile).animate({delay: 0}, 15*d).fadeIn(300);
			//$(_activeTile).fadeIn(300 + (200*d));
			d++;
		}
	});
	
	// $(".bigImage img", _activeTile).hide();
	
	// No active tiles so reset stuff
	_activeTile=null;
	_hiddenTiles=null;
	
	// And if the browser resized during the time there was a big tile open, update the grid now cuz we can!
	if(_needsGridUpdate){
		updateGrid();
	}
}

// Get the tiles that need hiding using one of the patterns
function getTiles(col,row,pattern){
	var i = 0;
	var r = [];
	for(i=0; i<pattern.length; i++){
		var itm = pattern[i];
		var nc = Number(col) + itm[0];
		var nr = Number(row) + itm[1];
		if(nr<0) { nr=0; }
		r.push(nc + "-" + nr);
	}
	return r;
}

// Update that grid!
function updateGrid(){
	
	if(_activeTile != null){
		// But wait, there is a Big tile ... remember to update later then...
		_needsGridUpdate = true;
		return;
	}
	
	// need to get this from css... but don't feel like it right now...
	var tileWidth = 267;
	var tileHeight = 248;
	
	// How many columns fit in the Canvas width?
	// _visableColumns = Math.floor(($("#canvas").innerWidth()) / tileWidth);
    _visableColumns = Math.floor(($(window).width() - 150) / tileWidth);
    // console.log(_visableColumns);
	var row = 0;
	
	// Update each tile
	$(".tile", "#canvas").each(function(){
		
		// need to check wetter the id and idx is undefined, can happen because of the empty first tile.
		var id = $(this).attr('id') == undefined?0:$(this).attr('id');
		var idx = $(this).attr('idx') == undefined?0:$(this).attr('idx');
		row = Math.floor(idx / _visableColumns);
		var col = idx%_visableColumns;
		var xPos = col*tileWidth;
		var yPos = row*tileHeight;
		
		$(this).attr("col",col);
		$(this).attr("row",row);
		$(this).attr('id',col + "-" + row);
		$(this).attr("xpos",xPos);
		$(this).attr("ypos",yPos);
		
		$(this).css("position","absolute");
	
		//alert(idx);
		
		$(this).css('left',xPos + 'px');
		$(this).css('top',yPos + 'px');
		
		
		
	});
	
	//Store number of rows in this useless va-ri-able.
	_visableRows = row;
	
	//Make #content as heigh as the canvas .... don't ask .... positioning stuff
	$("#right.gallery #content").height((_visableRows*tileHeight) + tileHeight + 60); // +60 is voor een margin
    
    // Minimum height, zodat de 'terug naar boven'-knop niet ergens in het midden zweeft bij weinig items:
    $("#right.gallery").css({minHeight: $(window).height() - 200});

	
	// no need to remember to update since .... we just did!!!! (duh)
	_needsGridUpdate = false;
}

function showPopup()
{
	var ScrollTop = document.body.scrollTop;
	if (ScrollTop == 0) {
		if (window.pageYOffset) {
			ScrollTop = window.pageYOffset;
		} else {
			ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
		}
	}
	
	$("#black").css({height: $(document).height()}).fadeIn();
	$("#popup").css({top: ScrollTop + 50}).fadeIn();
	
	$("#popup strong.name").text($(".overlay span.titel", _activeTile).text());
	$("#popup strong.manufacturer").text($(".overlay span.merk", _activeTile).text());
	$("#popup input[name=name]").val($("#popup strong.name").text());
	$("#popup input[name=manufacturer]").val($("#popup strong.manufacturer").text());
	
	return false;
}
