var numberOfColumns = 7; 
var numberOfRows = 7; 

var grid = [];
var selected = [];
var dirty = [];
var allowClicks = true;

var curtainState = false;

function curtain ()
{
	if (!curtainState) {
	
		pageTracker._trackPageview("/ipopper/cleared.html"); 
		document.getElementById('poppercurtain').style.display = ""; 
		curtainState = true;		
	} else {
	
		document.getElementById('poppercurtain').style.display = "none";
		curtainState = false;
	}
}

function removeAllChildren (parent)
{
	while (parent.hasChildNodes()) {
		parent.removeChild(parent.firstChild);
	}
}

function resetGrid()
{

	if (curtainState) curtain();
	grid = new Array(numberOfColumns);
	selected = new Array(numberOfColumns);
	dirty = new Array(numberOfColumns);
	
	for( var x = 0; x < numberOfColumns; x++ ) {
		grid[x] = new Array(numberOfRows);
		selected[x] = new Array(numberOfRows);
		dirty[x] = new Array(numberOfRows);
		
		for( var y = 0; y < numberOfRows; y++ ) {
			grid[x][y] = 1 + Math.floor(Math.random() * 5);
			selected[x][y] = false;
			dirty[x][y] = false;
		}
	}
}

function popper ()
{
	resetGrid();
	
	var gridTable = document.getElementById('grid');
	removeAllChildren(gridTable);
	for( var y = 0; y < numberOfRows; y++ ) {
		var row = gridTable.insertRow(-1);
		for( var x = 0; x < numberOfColumns; x++ ) {
			
			var col = row.insertCell(-1);
			var img = document.createElement('img');
			
			img.setAttribute("src", "http://www.officeevil.com/wp-content/themes/Office_Evil/images/popper/popper-"+grid[x][y]+".png");
			img.setAttribute("id", x+"_"+y);
			img.setAttribute("numberOfColumns", 32);
			img.setAttribute("numberOfRows", 32);
			img.setAttribute("width", 44);
			img.setAttribute("height", 44);
			img.onclick = function() {
			
				var str = this.id;
				var split = str.split("_")
				click(parseInt(split[0]),parseInt(split[1]));
			}
			
			//img.setAttribute("onClick", "click("+x+","+y+");");
			col.appendChild(img);
		}
	}            
                  
}

function updateCell(x, y)
{
    var newSrc;
	if( selected[x][y] ){
        newSrc = "http://www.officeevil.com/wp-content/themes/Office_Evil/images/popper/popper-sel.png";
    }    
    else {
        newSrc = "http://www.officeevil.com/wp-content/themes/Office_Evil/images/popper/popper-"+grid[x][y]+".png"
    }    
    
    var img = document.getElementById(x+"_"+y);
    img.src = newSrc;
	//document.images[x+"_"+y].src = newSrc;
}

function checkScore()
{
	var win = true;
	
	for( var y = 0; y < numberOfRows; y++ ) {
		for( var x = 0; x < numberOfColumns; x++ ) {
			var img = document.getElementById(x+"_"+y);
    		
    		if (img.src != 'http://www.officeevil.com/wp-content/themes/Office_Evil/images/popper/popper-0.png') win = false;
		}
	}
	
	if (win) {
	
		curtain();
		//alert('win = ' + win);	
	}
}

function updateAllCells()
{
	for( var y = 0; y < numberOfRows; y++ ) {
		for( var x = 0; x < numberOfColumns; x++ ) {
			updateCell(x, y);
		}
	}
}

function updateAllDirtyCells()
{
	for( var y = 0; y < numberOfRows; y++ ) {
		for( var x = 0; x < numberOfColumns; x++ ) {
			if( dirty[x][y] ) {
				updateCell(x, y);
				dirty[x][y] = false;
			}
		}
	}
}

function removeSelectedCells()
{
	for( var y = 0; y < numberOfRows; y++ ) {
		for( var x = 0; x < numberOfColumns; x++ ) {
			if( selected[x][y] ) {
				grid[x][y] = 0;
				selected[x][y] = false;
				dirty[x][y] = true;
			}
		}
	}
}

function fallDown()
{
    var fallTo,foundGap;
	for( var x = numberOfColumns-1; x >= 0; x-- ) {
		foundGap = false;
		for( var y = numberOfRows-1; y >= 0; y-- ) {
			if( grid[x][y] == 0 ) {
				if( ! foundGap ) {
					fallTo = y;
					foundGap = true;
				}
			}
			else { // grid occupied
				if( foundGap ) {
					grid[x][fallTo] = grid[x][y];
					grid[x][y] = 0;
					dirty[x][fallTo] = true;
					dirty[x][y] = true;
					fallTo -= 1;
				}
			}
		}
	}
}

function fallRight()
{
     var fallTo,foundGap;
	for( var y = numberOfRows-1; y >= 0; y-- ) {
	    foundGap = false;
		for( var x = numberOfColumns-1; x >= 0; x-- ) {
			if( grid[x][y] == 0 ) {
				if( ! foundGap ) {
					fallTo = x;
					foundGap = true;
				}
			}
			else { // grid occupied
				if( foundGap ) {
					grid[fallTo][y] = grid[x][y];
					grid[x][y] = 0;
					dirty[fallTo][y] = true;
					dirty[x][y] = true;
					fallTo -= 1;
				}
			}
		}
	}
}

function deselectAllCells()
{
	for( var y = 0; y < numberOfRows; y++ ) {
		for( var x = 0; x < numberOfColumns; x++ ) {
			if( selected[x][y] ) {
				selected[x][y] = false;
				dirty[x][y] = true;
			}
		}
	}
}

function cellHasIdenticalNeighbour(x, y)
{
	var cell = grid[x][y];
	if( ( x+1 < numberOfColumns  && cell == grid[x+1][y] )
	 || ( x-1 >= 0     && cell == grid[x-1][y] )
	 || ( y+1 < numberOfRows && cell == grid[x][y+1] )
	 || ( y-1 >= 0     && cell == grid[x][y-1] ) ) {
		return true;
	}
	else {
		return false;
	}
}

function selectCellAndContiguousCells(cell, x, y)
{
	if( x >= 0 && x < numberOfColumns && y >= 0 && y < numberOfRows ) {
		if( cell == grid[x][y] && ! selected[x][y] ) {
			selected[x][y] = true;
			dirty[x][y] = true;
			selectCellAndContiguousCells( cell, x+1, y );
			selectCellAndContiguousCells( cell, x-1, y );
			selectCellAndContiguousCells( cell, x, y+1 );
			selectCellAndContiguousCells( cell, x, y-1 );
		}
	}
}

function fallRightAndAllowClicks()
{
	fallRight();
	updateAllDirtyCells();
	allowClicks = true;
}

function fallDownThenFallRightAndAllowClicks()
{
	fallDown();
	updateAllDirtyCells();
    fallRightAndAllowClicks();
}

function click(x, y)
{
	//alert('click x:' + x + ' y:' + y);
	if( ! allowClicks ){
		return;
	}	
	
	if( grid[x][y] != 0 ) {
		deselectAllCells();
		if( cellHasIdenticalNeighbour( x, y ) ){
			selectCellAndContiguousCells( grid[x][y], x, y );
		}	
		updateAllDirtyCells();		
		removeSelectedCells();
		updateAllDirtyCells();

		checkScore();
		allowClicks = false;
		setTimeout("fallDownThenFallRightAndAllowClicks();", 100);
	}
}
