﻿var jpc;

function initJPC(grid, color)
{
	jpc = new JPC(grid, color);
}



function JPC(grid, color)
{
	this.rownum = grid.length;
	this.colnum = grid[0].length;

	this.origgrid = grid;

	this.grid = new Array();
	for(var i = 0; i < this.rownum; i++)
	{
		this.grid[i] = new Array();
		for(var j = 0; j < this.colnum; j++)
			this.grid[i][j] = 0;
	}
	this.current = 0;
	this.currentColor = 0;
	this.state = 0;

	var monochrome = (color.length == 2);
	this.color = color;

	if(monochrome)
		this.setColor(1);
}

JPC.prototype.getDiv = function(id)
{
	return document.getElementById(id);
}

JPC.prototype.getCell = function(i, j)
{
	return this.getDiv("jpcell_" + i + "_" + j);
}

JPC.prototype.onnummousedown = function(id, colornum, reverse)
{
	if(event.button == 2)
	{
		var cls = " jpstrike";
		if(reverse) cls += "rev";
		var td = this.getDiv(id);
		if(td.className.indexOf(cls) > 0)
			td.className = td.className.substring(0, td.className.indexOf(cls));
		else
			td.className += cls;
	}
	else
		this.setColor(colornum);
}

JPC.prototype.setColor = function(colornum)
{
	this.currentColor = colornum;
	document.getElementById("jpcolor").style.backgroundColor = this.color[colornum];
}

JPC.prototype.onmousedown = function(i, j)
{
	this.state = (event.button == 2 ? -1 : 1);
	if(this.state == -1 && this.grid[i][j] != -1)
		this.current = -1;
	else if(this.state == 1 && this.grid[i][j] != this.currentColor)
		this.current = this.currentColor;
	else
		this.current = 0;
	this.onmouseover(i, j);
}

JPC.prototype.onmouseover = function(i, j)
{
	if(this.state != 0)
	{
		this.grid[i][j] = this.current;
		if(this.current == -1)
		{
			this.getCell(i, j).style.backgroundColor = this.color[0];
			this.getCell(i, j).innerHTML = "x";
		}
		else
		{
			this.getCell(i, j).style.backgroundColor = this.color[this.current];
			this.getCell(i, j).innerHTML = "";
		}
	}
}

JPC.prototype.onmouseup = function()
{
	this.state = 0;
}

JPC.prototype.check = function()
{
	for(var i = 0; i < this.rownum; i++)
		for(var j = 0; j < this.colnum; j++)
			if(this.grid[i][j] <= 0 && this.origgrid[i][j] > 0 || this.grid[i][j] > 0 && this.grid[i][j] != this.origgrid[i][j])
				return false;
	return true;
}


