// Cadbury colors	
var lightRed = "#f0a0b8";
var darkRed = "#a00000";
var pureWhite = "#ffffff";
var darkWhite = "#d6d6d6";
var pureBlack = "#000000";
var lightBlue = "#7888d8";
var darkBlue = "#1020b0";
var theYellow = "#ffffd0";
var lightGray = "#cccccc";
var pureBlack = "#000000";

function Board (model)
{
	var i;
	this.pattern = Array (9);
    this.symbol;
    this.order;
	this.playerIndex = 1;
	this.first = "player";
    this.sym = Array (" ", "x", "o");
	this.img = Array ("/images/nada.bmp", "/images/x.bmp", "/images/o.bmp");
	this.clear = function () {for (i = 0; i < 9; i++) this.pattern [i] = 0;}
	if (model) this.pattern = model;
	else this.clear ();
	//alert ("constructing: " + this.pattern);
	this.compare = function (b){if (this.pattern != b.pattern) return false; else return true;}
    this.setSymbols = function ()
    {
        if ((board.symbol == 'x' && board.first == "player") ||
			 (board.symbol == 'o' && board.first == "machine"))
        {
            board.sym [1] = 'x';
            board.sym [2] = 'o';
            board.img [1] = '/images/x.bmp';
            board.img [2] = '/images/o.bmp';
        }else{
            board.sym [1] = 'o';
            board.sym [2] = 'x';
            board.img [1] = '/images/o.bmp';
            board.img [2] = '/images/x.bmp';
        }
    }
    
	this.show = function ()
	{
		for (var i = 0; i < 9; i++)
		{
			this.theSpace = document.getElementById ("" + i);
			this.theImage = this.img [this.pattern [i]]
			this.theSpace.style.backgroundImage = "url('" + this.theImage + "')";
			this.theSpace.style.backgroundPosition = "center";
			this.theSpace.style.backgroundRepeat = "no-repeat";
		}
	}
	
    this.pString = function (pattern)
    {
        var s = "";
        for (i = 0; i < 9; i++) s += pattern [i];
        return s;
    }
            
	this.place = function (player, sq)
	{
		this.o = document.getElementById (this.name).sq;
		this.theImage = this.img [sym];
		this.pattern [sq] = sym;
	}
}

function initSession ()
{
	document.getElementById ("wins").value = "0";
	document.getElementById ("draws").value = "0";
	document.getElementById ("losses").value = "0";
	document.forms ["user"].order [0].checked = true;
	document.forms ["user"].symbol [0].checked = true;
	document.forms ["user"].diff [4].selected = true;
	document.forms ["user"].agg [0].selected = true;
}
function xmlhttpChange ()
{
    var raw;
	var results = "";
	var parts;
    var patt;
    var ends;
    var res = new Array ();
	var parts = new Array ();
    res ["response"] = "";
	res ["ordinal"] = "";
	res ["message"] = "";
	res ["end"] = "";
	res ["error"] = "";
	// if xmlhttp shows "loaded"
	if (xmlhttp.readyState == 4)
	{
		if (xmlhttp.status == 200)
		{
			done = true;
			document.getElementById ("board").style.backgroundColor = "transparent";
			raw = xmlhttp.responseText;
            for (var i = 0; i < raw.length; i++)
            {
                if ((raw.charCodeAt (i) == 10) || (raw.charCodeAt (i) == 13)) continue;
                results += raw.charAt (i);
            }
			parts = results.split ('&');
			for (i = 0; i < parts.length; i++)
			{
				pair = parts [i].split ('=');
				res [pair [0]] = pair [1];
			}
            if (res ['error'] != "none")
			{
				document.getElementById ("board").style.backgroundColor = "transparent";
				document.getElementById ("announcement").innerHTML = "Error";
				alert ("Error: " + results);
				return;
			}
            board.winner = res ['end'];
			if (res ['response'] != "none") 
            {
                sPattern = res ['response'];
                for (var i = 0; i < 9; i++) 
                    board.pattern [i] = sPattern.charAt (i);
                board.show ();
                document.getElementById ("announcement").innerHTML = "Your play";
                //alert ("Pattern: " + board.pattern);
            }
            if (board.winner != "none") 
            {
                //alert ("End of game");
                gamePlay = false;
                if (board.winner == "draw") 
                {   
                    announce ("draw", player);
                    document.getElementById ("draws").value = 
                        parseInt (document.getElementById ("draws").value) + 1;
                }else{
                    announce ("win", board.winner);
                    if (board.winner == "player")
                        document.getElementById ("wins").value = 
                            parseInt (document.getElementById ("wins").value) + 1;
                    else
                        document.getElementById ("losses").value = 
                            parseInt (document.getElementById ("losses").value) + 1;
                }
    
            }
             playerResponse = false;
            getMove ();
		}
		else 
		{
			document.getElementById ("board").style.backgroundColor = "transparent";
			document.getElementById ("announcement").innerHTML = "Error";
			alert ("Problem retrieving data")
		}
	}
}
var xmlhttp;

function sendPlay (pattern, diff, agg)
{
	if (window.XMLHttpRequest)
	{
		//alert ("Not IE");
		xmlhttp = new XMLHttpRequest ();
		xmlhttp.onreadystatechange = xmlhttpChange;
	}
	// code for IE
	else if (window.ActiveXObject)
	{
		//alert ("IE");
		xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP");
		xmlhttp.onreadystatechange = xmlhttpChange;
	}
	done = false;
	postString = "pyTacWeb.py";
	postString += "?pattern="+ pattern;
	postString += "&diff="+ diff;
	postString += "&agg="+ agg;
	postString = encodeURI (postString);
	//alert (postString); 
	xmlhttp.open ("GET", postString, true);
	xmlhttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send ("");
	document.getElementById ("board").style.backgroundColor = "#ff8080";
    document.getElementById ("announcement").innerHTML = "Wait...";
	
	
	
}

function setOrder ()
{
    o = document.forms ["user"].order;
    if (o[0].checked) board.order = board.first = "player";
    else if (o[1].checked) board.order = board.first = "machine";
    else if (o[2].checked) board.order = "alternate";
    board.setSymbols ();
}
function setSymbol ()
{
	o = document.forms ["user"].symbol;
	if (o[0].checked) board.symbol = 'x'; else board.symbol = 'o';
    board.setSymbols ();
}

function markBoard (o)
{
    var index = parseInt (o.id);
	if (board.pattern [index] != 0) return false;
    theImage = board.img [board.playerIndex];    
    board.pattern [index] = board.playerIndex;
	o.style.backgroundImage = "url('" + theImage + "')";
	o.style.backgroundPosition = "center";
	o.style.backgroundRepeat = "no-repeat";
	theMove = o.id;
	return true;
}
var playerResponse = false;
var gamePlay = false;
var player;
function placeSymbol (o)
{
	if (playerResponse || !gamePlay || !markBoard (o)) return;
	playerResponse = true;
}
function getMove ()
{
	var move;
	while (!playerResponse) 
	{
		setTimeout (getMove, 100);
		return;
	}
	sendPlay (board.pString (board.pattern), 
			  document.forms ["user"].diff.value, 
			  document.forms ["user"].agg.value);
}

function startGame ()
{
	gamePlay = true;
	setOrder ();
	setSymbol ();
    board.clear ();
    board.show ();
    if (board.first == "player") 
    {
        board.playerIndex = 1; 
        setTimeout (getMove, 100);
        document.getElementById ("announcement").innerHTML = "Choose Your Play";
    } else {
        board.playerIndex = 2;
        sendPlay (board.pString (board.pattern),
			  	  document.forms ["user"].diff.value, 
			      document.forms ["user"].agg.value);
    }
	if (board.order == "alternate")
	{
		if (board.first == "player") board.first = "machine";
		else board.first = "player";
	}
	else if (board.order == "machine") board.first = "machine";
	else board.first = "player";

}
function announce (status, player)
{
	var an = "The game is a ";
	if (status == "draw") an += "draw";
	else an += "win for the " + player;
	document.getElementById ("announcement").innerHTML = an;
}
function changeDifficulty ()
{
	;
}
function changeAggression ()
{
	;
}
