var spacesLeft;
var top;
var canReplace;
var gameInProgress;
var deck;
var timeAllowed;
var currentCard;
var cardArray;
var startTime;
var displayTime;
var connector;

function initialize()
{
	connector = new Connector();
	spacesLeft = 25;
	top = 0;
	canReplace = false;
	gameInProgress = false;
	changeBackground( "nextCard", "bgRed" );
	deck = new Deck();
	timeAllowed = 60;
	cardArray = new Array( 5 );
	for( var i = 0; i < 5; i++ )
	{
		cardArray[ i ] = new Array( 5 );
		for( var j = 0; j < 5; j++ )
		{
			gEBI( "grid" + i + j ).onclick = clickSlot;
		}
	}
	resetCardGrid();
	gEBI( "newGameButton" ).onclick = startGame;
	getScores();
}
function getScores()
{
	say( "highScoresWrapper", "<table id='highScoresTable' class='clearBoth' border='1'><tr>" +
		"<td class='tableColumn'>Name</td><td class='tableColumn'>Score</td><td class='tableColumn'>Date</td></tr></table>" );
	if( connector.makeCall( "xml", "getScores", "/projects/Rush/ajax/getScores", "" ) )
	{
		var results = connector.results[ "getScores" ];
		var root = results.documentElement;
		events = root.getElementsByTagName( "score" );
		for( var i = 0; i < events.length; i++)
		{
			var name = events[ i ].getAttribute( "name" );
			var score = events[ i ].getAttribute( "score" );
			var date = events[ i ].getAttribute( "date" );
			addRowToScoresTable( name, score, date );
		}
	}
	else
	{
		alert( "Error Getting Scores -01" );
	}
}
function addScore( name, score, date )
{
	if( connector.makeCall( "text", "addScore", "/projects/Rush/ajax/addScore", "" +
		"&name=" + escape( name ) +
		"&score=" + escape( score ) +
		"&date=" + escape( date ) )
	)
	{
		var results = connector.results[ "addScore" ];
		if( results[ 0 ].replace( /\s/g, '' ) == "success" )
		{
			getScores();
		}
		else
			alert( "Error Adding Score -02" + connector.results[ "addScore" ] + "\n" +
				"name: " + name +
				"\nscore: " + score +
				"\ndate: " + date );
	}
	else
	{
		alert( "Error Adding Score -03" + connector.results[ "addScore" ] );
	}
}
function addRowToScoresTable( name, date, score )
{
	var highScoresTable = gEBI( "highScoresTable" );
	var lastRow = highScoresTable.rows.length;
	var row = highScoresTable.insertRow( lastRow );
	
	var dataCell = row.insertCell( 0 ); //dataCell.className = "borderedTableCell";
	var textNode = document.createTextNode( name );
	dataCell.appendChild( textNode );
	
	var dataCell = row.insertCell( 1 ); //dataCell.className = "borderedTableCell";
	var textNode = document.createTextNode( date );
	dataCell.appendChild( textNode );
	
	var dataCell = row.insertCell( 2 ); //dataCell.className = "borderedTableCell";
	var textNode = document.createTextNode( score );
	dataCell.appendChild( textNode );
}
function clickSlot()
{
	if( gameInProgress )
	{
		var doChanges = false;
		//If they try to replace a card
		if( this.className.indexOf( "bgBlank" ) < 0 )
		{
			if( canReplace )
			{
				canReplace = false;
				doChanges = true;
			}
			else
			{
				say( "textArea", "You cannot replace any more cards.<br />" );
			}
		}
		else
		{
			spacesLeft--;
			doChanges = true;
		}
		if( doChanges )
		{
			changeBackground( this.id, "bg" + currentCard.toString().replace( /\s/gi, "" ) );
			cardArray[ this.id.substring( 4, 5 ) ][ this.id.substring( 5, 6 ) ] = currentCard;
			changeCard();
		}
	}
	else
		alert( "To begin, click the \"New Game\" button." );
}
function startGame()
{
	say( "textArea", "" );
	changeBackground( "timer", "bgSafe" );
	canReplace = true;
	resetCardGrid();
	date = new Date();
	startTime = date.getTime();
	//timerBar.setForeground( new Color( 163, 184, 204 ) );
	deck.shuffle();
	spacesLeft = 25;
	top = 0;
	changeCard();
	gameInProgress = true;
	startClock();
}
var timeout;
function startClock()
{
	if( gameInProgress )
	{
		timeout = setTimeout( startClock, 100 );
		var date = new Date();
		var timeElapsed = Math.floor( ( date.getTime() - startTime ) / 1000 );
		displayTime = timeAllowed - timeElapsed;
		say( "timer", displayTime );
		//timePercentage = Math.floor( displayTime / timeAllowed * 100 );
		//gEBI( "timerDot" ).width = timePercentage + "%";
		//say( "timer", timePercentage + "%" );
		//say( "output", gEBI( "timer" ).className );
		if( displayTime < 10 )
		{
			changeBackground( "timer", "bgDanger" );
		}
		if( displayTime < 1 )
			addUpPoints();
	}
}
function changeCard()
{
	if( top < 52 )
	{
		currentCard = deck.getCard( top++ );
		changeBackground( "nextCard", "bg" + currentCard.toString().replace( /\s/gi, "" ) );
	}
	if( spacesLeft == 0 )
		addUpPoints();
}
function resetCardGrid()
{
	for( var i = 0; i < 5; i++ )
	{
		for( var j = 0; j < 5; j++ )
		{
			changeBackground( "grid" + i + j, " bgBlank" );
			cardArray[ i ][ j ] = new Card( "", "" );
		}
	}
}
function changeBackground( id, newBg )
{
	var element = gEBI( id );
	element.className = element.className.replace( /(\s|\b)bg.*(\s|\b)/gi, "" );
	element.className += " " + newBg;
}
function addUpPoints()
{
	clearTimeout( timeout );
	gameInProgress = false;
	
	var pointsForHand = 0;
	var totalPoints = 0;
	var handText = "";
	say( "textArea", "" );
	
	for( var i = 0; i < 5; i++ )
	{
		handText = findHighestHand( cardArray[ i ] );
		pointsForHand = getPointsForHand( handText );
		totalPoints += pointsForHand;
		
		sayMore( "textArea", "Row " + (i+1) + ":  " + handText + "  " + pointsForHand + "<br />" );
	}
	sayMore( "textArea", "<br />" );
	var tempCardArray = new Array( 5 );
	for( var j = 0; j < 5; j++ )
	{
	
		for( var k = 0; k < 5; k++ )
		{
			tempCardArray[ k ] = cardArray[ k ][ j ];
		}
		handText = findHighestHand( tempCardArray );
		pointsForHand = getPointsForHand( handText );
		totalPoints += pointsForHand;
		
		sayMore( "textArea", "Column " + (j+1) + ":  " + handText + "  " + pointsForHand + "<br />" );
	}
	sayMore( "textArea", "<br />" );
	for( var m = 0; m < 5; m++ )
	{
		tempCardArray[ m ] = cardArray[ m ][ m ];
	}
	handText = findHighestHand( tempCardArray );
	pointsForHand = getPointsForHand( handText );
	totalPoints += pointsForHand;
	
	sayMore( "textArea", "Diagonal 1:  " + handText + "  " + pointsForHand + "<br />" );
	
	for( var m = 0; m < 5; m++ )
	{
		tempCardArray[ m ] = cardArray[ m ][ 4 - m ];
	}
	handText = findHighestHand( tempCardArray );
	pointsForHand = getPointsForHand( handText );
	totalPoints += pointsForHand;
	
	sayMore( "textArea", "Diagonal 2:  " + handText + "  " + pointsForHand + "<br />" );
	sayMore( "textArea", "<br />" );
	
	sayMore( "textArea", "Points: " + totalPoints + "<br />" );
	
	sayMore( "textArea", "Time bonus: " + displayTime + "<br />" );
	
	var grandTotal = totalPoints + displayTime;
	
	sayMore( "textArea", "Final Score: " + grandTotal + "<br />" );
	
	var name = prompt( "What is your name?" );
	var date = getDate();
	addScore( name, grandTotal, date );
	/*if( list.canAdd( grandTotal ) )
	{
		String userName = JOptionPane.showInputDialog( "Enter your name for the high scores list.", lastenteredName );
		lastenteredName = userName;
		Score s = new Score( userName, grandTotal );
		int highLightrow = list.add( s );
		try
		{
			connection.setAutoCommit( false );
			pstmtInsert.setString( 1, userName );
			pstmtInsert.setString( 2, "" + grandTotal );
			pstmtInsert.setString( 3, s.getDate() );
			pstmtInsert.executeUpdate();
			connection.commit();
			connection.setAutoCommit( true );
		}
		catch( SQLException sqlE )
		{
			JOptionPane.showMessageDialog( null, "SQLException 5" );
			sqlE.printStackTrace();
		}
		catch( Exception e )
		{
			JOptionPane.showMessageDialog( null, "General Error 4" );
			JOptionPane.showMessageDialog( null, e.getLocalizedMessage() );
			JOptionPane.showMessageDialog( null, e.getMessage() );
			JOptionPane.showMessageDialog( null, e.toString() );
			//System.err.println( "General Error 4" );
			e.printStackTrace();
		}
		updateTable( highLightrow );
	}*/
}
function findHighestHand( cardsReal )
{
	var cards = new Array();
	for( var i = 0; i < 5; i++ )
	{
		cards[ i ] = cardsReal[ i ];
		if( cards[ i ].getNumValue() == 0 )
			return "No Hand";
	}
	for( var i = 0; i < 5; i++ )
	{
		if( cards[ 0 ].getNumValue() > cards[ 1 ].getNumValue() )
		{
			var temp = cards[ 0 ];
			cards[ 0 ] = cards[ 1 ];
			cards[ 1 ] = temp;
		}
		if( cards[ 1 ].getNumValue() > cards[ 2 ].getNumValue() )
		{
			var temp = cards[ 1 ];
			cards[ 1 ] = cards[ 2 ];
			cards[ 2 ] = temp;
		}
		if( cards[ 2 ].getNumValue() > cards[ 3 ].getNumValue() )
		{
			var temp = cards[ 2 ];
			cards[ 2 ] = cards[ 3 ];
			cards[ 3 ] = temp;
		}
		if( cards[ 3 ].getNumValue() > cards[ 4 ].getNumValue() )
		{
			var temp = cards[ 3 ];
			cards[ 3 ] = cards[ 4 ];
			cards[ 4 ] = temp;
		}
	}
	
	var canBeFlush = false;
	var canBeStraight = false;
	
	var card1Suit = cards[ 0 ].getSuit();
	if( card1Suit == cards[ 1 ].getSuit() &&
		card1Suit == cards[ 2 ].getSuit() &&
		card1Suit == cards[ 3 ].getSuit() &&
		card1Suit == cards[ 4 ].getSuit()
	)//hand can be a flush
	{
		canBeFlush = true;
	}
	
	if( after( cards[ 0 ].getFace() ) == cards[ 1 ].getFace() &&
			after( cards[ 1 ].getFace() ) == cards[ 2 ].getFace() &&
			after( cards[ 2 ].getFace() ) == cards[ 3 ].getFace() &&
			(
				( after( cards[ 3 ].getFace() ) == cards[ 4 ].getFace() ) ||
				(
					cards[ 0 ].getFace() == "deuce" && cards[ 4 ].getFace() == "ace"
				)
			)
	)
	{
		canBeStraight = true;
	}
	
	if( canBeFlush && canBeStraight )
	{
		if( cards[ 0 ].getFace() == "ten" )
			return "Royal Flush";
		else
			return "Straight Flush";
	}
	
	if( cards[ 1 ].getFace() == cards[ 2 ].getFace() &&
		cards[ 2 ].getFace() == cards[ 3 ].getFace() &&
		(
			cards[ 1 ].getFace() == cards[ 0 ].getFace() ||
			cards[ 1 ].getFace() == cards[ 4 ].getFace()
		)
	)
		return "Four of a Kind";
		
	if( cards[ 0 ].getFace() == cards[ 1 ].getFace() &&
		cards[ 3 ].getFace() == cards[ 4 ].getFace() &&
		(
			cards[ 2 ].getFace() == cards[ 1 ].getFace() ||
			cards[ 2 ].getFace() == cards[ 3 ].getFace()
		)
	)
		return "Full House";
	
	if( canBeFlush )
		return "Flush";
	if( canBeStraight )
		return "Straight";
	
	if( ( cards[ 0 ].getFace() == cards[ 1 ].getFace() &&
			cards[ 1 ].getFace() == cards[ 2 ].getFace()
		) ||
		( cards[ 1 ].getFace() == cards[ 2 ].getFace() &&
			cards[ 2 ].getFace() == cards[ 3 ].getFace()
		) ||
		( cards[ 2 ].getFace() == cards[ 3 ].getFace() &&
			cards[ 3 ].getFace() == cards[ 4 ].getFace()
		)
	)
		return "Three of a Kind";
	if(
		( cards[ 0 ].getFace() == cards[ 1 ].getFace() &&
			cards[ 2 ].getFace() == cards[ 3 ].getFace()
		) ||
		( cards[ 0 ].getFace() == cards[ 1 ].getFace() &&
			cards[ 3 ].getFace() == cards[ 4 ].getFace()
		) ||
		( cards[ 1 ].getFace() == cards[ 2 ].getFace() &&
			cards[ 3 ].getFace() == cards[ 4 ].getFace()
		)
	)
		return "Two Pairs";
	if(
		cards[ 0 ].getFace() == cards[ 1 ].getFace() ||
		cards[ 1 ].getFace() == cards[ 2 ].getFace() ||
		cards[ 2 ].getFace() == cards[ 3 ].getFace() ||
		cards[ 3 ].getFace() == cards[ 4 ].getFace()
	)
		return "One Pair";
	
	return "No Hand";
	
}
function after( first )
{
	if( first == "deuce" )
		return "three";
	else if( first == "three" )
		return "four";
	else if( first == "four" )
		return "five";
	else if( first == "five" )
		return "six";
	else if( first == "six" )
		return "seven";
	else if( first == "seven" )
		return "eight";
	else if( first == "eight" )
		return "nine";
	else if( first == "nine" )
		return "ten";
	else if( first == "ten" )
		return "jack";
	else if( first == "jack" )
		return "queen";
	else if( first == "queen" )
		return "king";
	else if( first == "king" )
		return "ace";
	else
		return "None";
}
function getPointsForHand( hand )
{
	if( hand == "Royal Flush" )
		return 500;
	else if( hand == "Straight Flush" )
		return 400;
	else if( hand == "Four of a Kind" )
		return 300;
	else if( hand == "Full House" )
		return 200;
	else if( hand == "Flush" )
		return 100;
	else if( hand == "Straight" )
		return 90;
	else if( hand == "Three of a Kind" )
		return 80;
	else if( hand == "Two Pairs" )
		return 70;
	else if( hand == "One Pair" )
		return 60;
	else if( hand == "No Hand" )
		return 0;
	else
		return -999;
}