var colors = ["#FF2520", "#FFC920", "#433CEF", "#1EF42C", "#ff8605" ];
var gameInterval = 500;
var gameTicks = 0;

var tweets = new Array();

var blocksizeWidth=40;
var blocksizeHeight=16;

function windowWidth(){
	return document.body.clientWidth;
}

function windowHeight(){
	return getInnerHeight();
}

function block(){
	this.gone = false;
	this.height; //= Math.floor(Math.random()*4)+1;
	this.width; //= Math.round( ((tweets[ (twetris.blocks.length % 20) ]).length/ (this.height*2)) /3 );
	this.top = 0;
	this.bottom;
	this.left;
	this.right;
	
	this.div; 
	
	this.drop = function(){
		while( this.move("down") ){
			twetris.score+=50;
		}
		twetris.update();
		return;
	}
	
	this.move = function( direction ) {
		switch( direction ) {
			case "left":
				if( this.left-1 < 1 ){
					return false;
				} else if( twetris.areBlocksOpen(this.left-1, this.right-1, this.top, this.bottom ) ) {
					this.left--;
					this.right--;
					this.update();
					return true;
				} else {
					return false;
				}
				break;
			case "right":
				if( this.right+1 > twetris.width+1 ){
					return false;
				} else if( twetris.areBlocksOpen( this.left+1, this.right+1, this.top, this.bottom ) ) {
					this.left++;
					this.right++;
					this.update();
					return true;
				} else {
					return false;
				}
				break;
			case "down":
				if( this.bottom+1 > twetris.height ){
					return false;
				} else {
					if( twetris.areBlocksOpen( this.left, this.right, this.top+1,  this.bottom+1) ){
						this.top++;
						this.bottom++;
						this.update();
						return true;
					} else {
						return false;
					}
				}
				break;
			case "shift":
				var tempWidth = this.height/2;
				var tempHeight = this.width*2;
				
				var tempTop = this.bottom - tempHeight;
				var tempBottom = this.bottom;
				var tempLeft = this.left - Math.floor( (tempWidth - this.width) /2 );
				var tempRight = this.right + Math.ceil( (tempWidth - this.width) /2 );
				//alert( "left: " + tempLeft + " right: " + tempRight + " top: " + tempTop + " bottom: " + tempBottom);
				
				if(tempLeft-1<1){
					tempLeft=1;
					tempRight = tempLeft+tempWidth;
				} else if( tempRight+1 > twetris.width+1){
					tempRight = twetris.width;
					tempLeft = tempRight - tempWidth;
				}
				if( twetris.areBlocksOpen( tempLeft, tempRight, tempTop,  tempBottom) ){
					this.top = tempTop;
					this.bottom = tempBottom;
					this.left = tempLeft;
					this.right = tempRight;
					this.width = tempWidth;
					this.height = tempHeight;

					this.update;
					return true
				} else {
					return false;
				}
				break;
				
			default:
				alert('move error');
				return false;
				break; 
		}
	}
	
	this.update = function(){
		
		if(this.height <= 0){
			this.div.style.display = 'none';  
			this.top = twetris.height+2;
			this.bottom = twetris.height+2;
			this.width = 0;
			this.height= 0;
			this.gone == true;
		}
		this.div.style.width = String(this.width*blocksizeWidth) + "px";
		this.div.style.height = String(this.height*blocksizeHeight) + "px";
		this.div.style.marginTop = String( (this.top+4)*blocksizeHeight) + "px";
		this.div.style.marginLeft = String(this.left*blocksizeWidth) + "px";
	};
	
	this.draw = function(){
		if( (twetris.blocks.length % 20) == 10) {
			twetris.getTimeline();
		}
		this.tweet = (tweets[ (twetris.blocks.length) ]);
		this.tweetWords = this.tweet.split(' ').length;

		this.height = 2*(Math.ceil(Math.random()*3));
		while( this.tweetWords < this.height/2 && this.height > 1){
			this.height= this.height-2;
		}
		this.width= Math.ceil( (this.tweet.length/ (this.height*5)) /2 );
		while( this.tweetWords < this.width && this.width > 1 ){
			this.width--;
		}
		
		this.bottom = this.top+this.height;
		this.left = Math.round( twetris.width/2 - this.width/2 );
		this.right = this.left + this.width;
		
		
		this.div = document.createElement('div');
		this.div.className = 'block';
		this.div.style.marginTop = String( (this.top+4)*blocksizeHeight) + "px";
		this.div.style.marginLeft = String(this.left*blocksizeWidth) + "px";
		this.div.style.display = "block";
		this.div.style.width = this.width*blocksizeWidth;
		this.div.style.height = this.height*blocksizeHeight;
		this.div.innerHTML = tweets[ (twetris.blocks.length) ];
		
		
		randomColor = colors[Math.floor( Math.random()*5 )];
		this.div.style.color = randomColor;
		//this.div.style.border = "1px solid " + randomColor;
		
		document.body.appendChild(this.div);
		document.getElementById('nextTweet').innerHTML = "Next Tweet - " + tweets[twetris.blocks.length+1];
	};
	
}

function gamespace(){
	this.blocks = new Array();
	//this.tweets = new Array();
	this.playing = true;
	this.currentBlock;
	this.nextBlock;
	this.width = Math.floor(windowWidth()/blocksizeWidth) -2;
	this.height = Math.floor(windowHeight()/blocksizeHeight)-6; 
	this.score = 0;
	this.ingame = true;
	this.div;
	this.newPlace=0;
	
	this.spots = new Array( this.height +1 );

	
	this.saveScore = function() {
		if( this.playing ){
			return false;
		}
		document.getElementById('savingBlock').style.display = 'block';
		var name = document.getElementById('nameInput').value;
		var score = this.score;
		var place = this.newPlace;
		
		$.post("storeScore.php", { name: name, score: score, place:place },
		  function(data){
			if( place > 0 ){
		    	document.getElementById('newName').innerHTML = name + "&nbsp;&nbsp<a class=\"retweet\" href=\"http://twitter.com/home?status=RT%20@twetris%20New%20High%20Score:%20(" + 
		        place + ") " + name + " with a score of " + score + "\" >Retweet your high score</a>";
			} else {
				document.getElementById('newName').innerHTML = name + "&nbsp;&nbsp<a class=\"retweet\" href=\"http://twitter.com/home?status=My%20score%20on%20TWETRIS:%20" + 
		        score + "%20-%20play%20at%20http://brett.wejrowski.com/twetris/\" >Tweet your score</a>";
			}
		
			if(!readCookie('savedName')){
				createCookie('savedName',name,30);
			}
			if(!readCookie('highScore') || Number(readCookie('highScore')) < score ){
					createCookie('highScore',score,30);
			}
		
		
		  });
		//document.getElementById('savingBlock').style.display = 'none';
	}
	
	
	this.pause = function() {
		if(this.playing == false){
			this.playing = true;
			this.pauseDiv.innerHTML = "pause";
			document.getElementById('helper').style.display = 'none';
		} else {
			document.getElementById('helpLink').innerHTML = 'close';
			document.getElementById('helpTitle').innerHTML = '*PAUSED*';
			
			this.playing = false;
			this.pauseDiv.innerHTML = "resume";
			document.getElementById('helpIntro').style.display= "none";
			
			document.getElementById('helper').style.display = 'block';
		}
		return true;
		
	}
	
	
	this.playedBefore = function(){
		if( !readCookie('playedBefore') ){
			createCookie('playedBefore','true',30);
			return false;
		} else {
			return true;
		}
	}
	
	this.getTimeline = function(){
		document.getElementById('loading').style.display = 'block';
		$.ajax({
				type: 'GET',
				url: "public_timeline.php",
				dataType: 'json',
				jsonp:'jsonp_callback',
				success: function(json) {
					for(var x=0;x<json.length; x++){
						var newTweet = json[x].user.screen_name + ": " + json[x].text;
						tweets.push(newTweet);
					}
					document.getElementById('loading').style.display = 'none';
				}
			});
		
		
	}
	this.tick = function() {
		if(this.playing){
			gameTicks++;
		}
		if( gameTicks > 100 ){
			gameTicks = 0;
			if( gameInterval > 50) {
				gameInterval = Math.round(gameInterval*0.93);
			}
		}
		this.update();
		this.scoreDiv.innerHTML = "score: " + this.score;
		setTimeout("twetris.tick()",gameInterval);
	}
	
	this.initialize = function(){
	
	
		this.getTimeline();	
		
		for(var k=0;k<this.height+1;k++){
			this.spots[k] = 0;
		}
		
		this.div = document.getElementById('gameblock');
		this.div.style.width = (this.width)*blocksizeWidth;
		this.div.style.height = (this.height)*blocksizeHeight;
		this.div.style.marginTop = blocksizeHeight*4;
		this.div.style.marginLeft = blocksizeWidth*1;
		this.div.style.border = "1px solid #333";
		
		//document.getElementById('tagLine').style.marginTop = ((this.height +4)*blocksizeHeight + 35 ) + 'px';
		
		
		this.nextBlock = new block( );
		

		this.scoreDiv = document.getElementById('scoreDiv');
		this.pauseDiv = document.getElementById('pauseButton');
		
		this.playing = true;
		this.tick();
		if(!this.playedBefore()){
			this.pause();
			
			document.getElementById('helpLink').innerHTML = 'Let\'s Play!';
			document.getElementById('helpTitle').innerHTML = 'Welcome to Twetris';
			document.getElementById('helpIntro').style.display= "block";
		}
	}
	
	this.update = function(){
		this.linesCleared = 0;
		if( !this.playing || !tweets[0] ){
		} else if( !this.currentBlock ){
			
			this.currentBlock = this.nextBlock;
			if( this.areBlocksOpen( this.left, this.right, this.top, this.bottom ) ){
				this.currentBlock.draw();
				this.nextBlock = new block( );
			} else {
				twetris.gameover();
				
			}
			
			
		} else if( !this.currentBlock.move("down") || this.currentBlock.gone){
			if( this.currentBlock.top <= 0 ){
				this.gameover();
				
			} else {
				this.blocks.push( this.currentBlock );
			
				if( this.blocks.length == 0 ){
					this.score = 0;
				} else {
					var gameSize = 900/(this.width*this.height);
					this.score = Math.round(this.score + gameSize*this.blocks.length*this.width + (this.currentBlock.width*this.currentBlock.height*this.blocks.length));
				}
				
				this.scoreDiv.innerHTML = "score: " + this.score;
				for(var j=this.currentBlock.bottom; j> this.currentBlock.top;j--){
					
					this.spots[j] += this.currentBlock.width;
					
				}
				
				this.checkblocks();
				
				
				this.currentBlock = this.nextBlock;
				if( this.areBlocksOpen( this.left, this.right, this.top, this.bottom ) ){
					this.currentBlock.draw();
					this.nextBlock = new block();
				} else {
					twetris.gameover();
					
				}
			}
		} 
	}
	
	
	this.checkblocks = function(){
		
		var fullLines = new Array();
		
		for(var i=0; i<this.height+1;i++){
			if( this.spots[i] >= this.width ){
				this.clearLine(i);
			}
		}
		
	}
	
	this.clearLine = function(line){
		this.linesCleared++;
		this.score= Math.round(this.score + this.linesCleared*(this.width/5));
		//TODO: highlight that ish.
		for( var x=0; x<this.blocks.length;x++ ){
			var tempBlock = this.blocks[x];
			if( tempBlock.top < line ){
				if( tempBlock.bottom >= line ){
					tempBlock.height--;
				} else {
					tempBlock.bottom++;
				}
				tempBlock.top++;
				tempBlock.update();	
			}
		}
		for( var j=line; j>0; j--){
			this.spots[j] = this.spots[j-1];
		}
		
	}
	
	this.areBlocksOpen = function( newleft, newright, newtop, newbottom ){
		for(var x=0; x<this.blocks.length;x++){
			var tempBlock = this.blocks[x];
			if(!tempBlock.done){
				if( ( (newleft < tempBlock.right && newleft >= tempBlock.left) ||
				  	(newright > tempBlock.left && newright <= tempBlock.right) ) &&
					( (newtop < tempBlock.bottom && newtop >= tempBlock.top) ||
				  	(newbottom > tempBlock.top && newbottom <= tempBlock.bottom) ) ) 
				{
					return false;
				} else if(
					( (tempBlock.left < newright && tempBlock.left >= newleft) ||
				  	  (tempBlock.right > newleft && tempBlock.right <= newright) ) &&
					( (tempBlock.top < newbottom && tempBlock.top >= newtop) ||
				  	  (tempBlock.bottom > newtop && tempBlock.bottom <= newbottom) ) )
				{ 
					return false;
				}
			}
		}	
		return true;	
	}
	
	
	this.gameover = function(){
		this.playing = false;
		this.newPlace= 0;
		$.ajax({
				type: 'GET',
				url: "getScores.php",
				success: function(json) {
					var eachItem = json.split("##");
					var newOut = false;
					var y=0;
					for(var x=0;x<eachItem.length-1 && x < 10; x++){
						var info = eachItem[y].split('&&');
					
						if( !newOut && twetris.score > Number(info[1]) ){
							twetris.newPlace = x+1;
							document.getElementById('name' + (x+1) ).innerHTML =  '<span style="float:left;" >' + (x + 1) + ".&nbsp;</span>" +
									'<span id="newName"><input type="text" id="nameInput" value="@yourname" />' + 
									'<input type="button" value="submit" onclick="twetris.saveScore(); return false;" />' + 
									'<img src="saving_block.gif" style="display:none;" id="savingBlock" /></span>';
							document.getElementById('score' + (x+1) ).innerHTML = twetris.score;
							document.getElementById('top' + (x+1)).style.color = '#900';
							document.getElementById('newScore').style.display = 'none';
							x++;
							newOut = true;
						}
						
						document.getElementById('top' + (x+1)).style.color = '#333';
						document.getElementById('name' + (x+1) ).innerHTML = (x + 1) + ". " + info[0];
						document.getElementById('score' + (x+1) ).innerHTML = info[1];
						y++;
					}
					
					if( !newOut ){
						document.getElementById('name11').innerHTML =  '<span id="newName"><input type="text" id="nameInput" value="@yourname" />' + 
								'<input type="button" value="submit" onclick="twetris.saveScore(); return false;" />' + 
								'<img src="saving_block.gif" style="display:none;" id="savingBlock" /></span>';
						document.getElementById('score11').innerHTML = twetris.score;
						document.getElementById('newScore').style.display = 'block';
						
					}
					
					if(!!readCookie('savedName')){
						document.getElementById('nameInput').value = readCookie('savedName');
					}
				}
			});
		
		document.getElementById('topScores').style.display = 'block';
	}
	
}


function createGame(){
	twetris = new gamespace();
	twetris.initialize();
	return;
}
window.onload = createGame;


if (document.layers) { document.captureEvents(Event.KEYDOWN); }
document.onkeydown = getKey;
function getKey(keyStroke) {

   var keyCode = window.event ? window.event.keyCode : keyStroke.keyCode;
   switch(keyCode){
		case 16:
			if( !twetris.playing ){
				return;
			}
			twetris.currentBlock.drop();
			break;
		case 37:
			if( !twetris.playing ){
				return;
			}
			twetris.currentBlock.move("left");
			break;
		case 39:
			if( !twetris.playing ){
				return;
			}
			twetris.currentBlock.move("right");
			break;
		case 38:
			if( !twetris.playing ){
				return;
			}
			twetris.currentBlock.move("shift");
			break;
		case 40:
			if( !twetris.playing ){
				return;
			}
			twetris.score+=10;
			twetris.update();
			break;
			
		case 32:
		case 19:
		case 80:
			if( !twetris.playing ){
				return;
			}
			twetris.pause();
			break;
		default:
			break;
	}
	return true;
}



function getScreenCenterY() 
 {  
 	var y = 0;  
   	y = getScrollOffset()+(getInnerHeight()/2);  
 	return(y);  
 }  
   
 function getScreenCenterX() 
 {  
 	return(document.body.clientWidth/2);  
 }  
   
 function getInnerHeight() 
 {  
 	var y;  
 	if (self.innerHeight) // all except Explorer  
 	{  
 		y = self.innerHeight;  
 	}  
 	else if (document.documentElement &&  document.documentElement.clientHeight)  
 	// Explorer 6 Strict Mode  
 	{  
 		y = document.documentElement.clientHeight;  
 	}  
 	else if (document.body) // other Explorers  
 	{  
 		y = document.body.clientHeight;  
 	}  
 	return(y);  
 	}  
 	   
 function getScrollOffset() 
 {  
 	var y;  
 	if (self.pageYOffset) // all except Explorer  
 	{  
 		y = self.pageYOffset;  
 	}  
 	else if (document.documentElement && document.documentElement.scrollTop)  
 	// Explorer 6 Strict  
 	{  
 		y = document.documentElement.scrollTop;  
 	}  
 	else if (document.body) // all other Explorers  
 	{  
 		y = document.body.scrollTop;  
 	}  
 	return(y);  
 }


//*************************************************************************************************
// Thanks to Peter-Paul Koch for these cookie functions! (http://www.quirksmode.org/js/cookies.html)
//*************************************************************************************************
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
