var color = new Array(2);
color[0] = '#000000';
color[1] = '#ffffff';
var zoom = 4;
var maxZoom = 10;
var minZoom = 1;

var initialized = false;

var activeTool = 'pencil';

var colorNum = 0;
var theKey;
var NS = (navigator.appName.indexOf("Netscape") != -1);

function SetShift(dObject)
{
	theKey = (NS) ? dObject.which : dObject.keyCode;

	if (theKey == 16 && colorNum == 0)
	{
		colorNum = 1;
	}
}

function RelShift(dObject)
{
	theKey = (NS) ? dObject.which : dObject.keyCode;

	if (theKey == 16 && colorNum == 1)
	{
		colorNum = 0;
	}
}

function ZoomIn()
{
	if(zoom != maxZoom)
	{
		zoom++;
		document.getElementById('workerTable').className = 'Zoom' + zoom;
	}
}

function ZoomOut()
{
	if(zoom != minZoom)
	{
		zoom--;
		document.getElementById('workerTable').className = 'Zoom' + zoom;
	}	
}

function ZoomTo100()
{
		zoom = minZoom;
		document.getElementById('workerTable').className = 'Zoom' + zoom;	
}

function ChangeColor(dObject)
{
	var dElement = GetElement(dObject);

	if(dElement != false)
	{
		color[colorNum] = dElement.title;

		var dObj = document.getElementById('color' + colorNum);
		dObj.style.backgroundColor = dElement.title;
		dObj.title = dElement.title;
		
		document.getElementById('customColorInput').value = color[colorNum].substring(1);
	}
}

function PaintIt(dObject)	// Funtion that switches the colors
{
	var dElement = GetElement(dObject);
	if(dElement != false && dElement.id.indexOf('cell') == 0)
	{
		dElement.style.backgroundColor = color[colorNum];
		dElement.title = color[colorNum];
	}
}

function Fill()
{
	for(var i = 0; i < 2500; i++)
	{
		document.getElementById('cell'+i).style.backgroundColor = color[colorNum];
		document.getElementById('cell'+i).title = color[colorNum];
	}
}

function CloseCustomColor()
{
	var obj = document.getElementById('customColor');
	obj.style.top = 0;
	obj.style.left = 0;
	obj.style.display = 'none';
	
	colorNum = 0;
	
	UnsetListener(document.getElementById('customColorBtn'), 'click', SetCustomColor);
	UnsetListener(document.getElementById('customColorCloseBtn'), 'click', CloseCustomColor);	
}

function SetCustomColor()
{
	var obj = document.getElementById('customColorInput');
	
	if(obj.value.length == 3 || obj.value.length == 6)
	{
		var str = obj.value;
		if(obj.value.length == 3)
		{
			str	 = (obj.value.substr(0, 1) + obj.value.substr(0, 1));
			str	+= (obj.value.substr(1, 1) + obj.value.substr(1, 1));
			str	+= (obj.value.substr(2, 1) + obj.value.substr(2, 1));
			obj.value = str;
		}
		
		var dObj = document.getElementById('color' + colorNum);
		color[colorNum] = '#' + str;
		dObj.style.backgroundColor = color[colorNum];
		dObj.title = color[colorNum];			
	}
	
	CloseCustomColor();	
}

function CustomColor(dObject)
{
	dElement = GetElement(dObject);
	colorNum = dElement.id.substring(5);
	var obj = document.getElementById('customColor');
	
	obj.style.top = dObject.clientY + "px";
	obj.style.left = dObject.clientX + "px";
	obj.style.display = 'block';
	
	document.getElementById('customColorInput').value = color[colorNum].substring(1);
	document.getElementById('customColorInput').focus();
	document.getElementById('customColorInput').select();
	
	SetListener(document.getElementById('customColorBtn'), 'click', SetCustomColor);
	SetListener(document.getElementById('customColorCloseBtn'), 'click', CloseCustomColor);
}

function ChangeTool(dObject)
{
	var dElement = GetElement(dObject);
	
	if(dElement != false)
	{
		if(dElement.parentNode.id == activeTool)
		{
			return;	
		}
		else
		{
			document.getElementById(activeTool).className = 'controlBtn inactiveTool';
			activeTool = dElement.parentNode.id;
			document.getElementById(activeTool).className = 'controlBtn activeTool';
			
			ReverseListeners();
		}
	}	
}

function ReverseListeners()
{
	switch(activeTool)
	{
		case 'pipett':
			UnsetListener(document, 'mousedown', AttachPaintListeners);
			UnsetListener(document, 'mouseup', DetachPaintListeners);
			UnsetListener(document, 'mousedown', PaintIt);
			
			SetListener(document.getElementById('workerTable'), 'click', GrabTheColor);
		break;
		
		case 'pencil':
			SetListener(document, 'mousedown', AttachPaintListeners);
			SetListener(document, 'mouseup', DetachPaintListeners);
			SetListener(document, 'mousedown', PaintIt);
			
			UnsetListener(document.getElementById('workerTable'), 'click', GrabTheColor);
		break;
		
		default:
			alert('Something went really wrong! Refresh the page!');
	}
}

function GrabTheColor(dObject)	// Funtion that switches the colors
{
	var dElement = GetElement(dObject);
	if(dElement != false && dElement.id.indexOf('cell') == 0)
	{
		color[colorNum] = dElement.title;
		var dObj = document.getElementById('color' + colorNum);
		dObj.style.backgroundColor = color[colorNum];
		dObj.title = color[colorNum];	
	}
}

function AttachPaintListeners(dObject)
{
	var dElement = GetElement(dObject);
	if(dElement.id != 'imgView')		// to get rid of a weird bug in IE
		SetListener(document, 'mousemove', PaintIt);
}

function DetachPaintListeners()
{
	UnsetListener(document, 'mousemove', PaintIt);
}

function WorkWithIt(dObject)
{
	var dElement = GetElement(dObject);
	
	if(dElement != false)
	{
		var str = dElement.className.substring(14);
		GrabTable(str);
	}	
	
}


function SetImgViews()
{
	for(var i = 0; i < 15; i++)
	{
		SetListener(document.getElementById('img'+i), 'click', WorkWithIt);
	}
}

function UnsetImgViews()
{
	for(var i = 0; i < 15; i++)
	{
		UnsetListener(document.getElementById('img'+i), 'click', WorkWithIt);
	}
}

var dWidth = 50;
var dHeight = 50;

function AttachListeners()
{
	SetListener(document.getElementById('paintBox'), 'selectstart', StopDefault);
	SetListener(document.getElementById('paintBox'), 'mousedown', StopDefault);

	SetListener(document, 'mousedown', PaintIt);
	SetListener(document, 'mousedown', AttachPaintListeners);
	SetListener(document, 'mouseup', DetachPaintListeners);		
		
	SetListener(document, 'keydown', SetShift);
	SetListener(document, 'keyup', RelShift);
	
	SetListener(document.getElementById('color0'), 'click', CustomColor);
	SetListener(document.getElementById('color1'), 'click', CustomColor);

	SetListener(document.getElementById('plus'), 'click', ZoomIn);
	SetListener(document.getElementById('minus'), 'click', ZoomOut);
	SetListener(document.getElementById('equal'), 'click', ZoomTo100);
	
	SetListener(document.getElementById('pencil'), 'click', ChangeTool);
	SetListener(document.getElementById('pipett'), 'click', ChangeTool);
	
	SetListener(document.getElementById('saver'), 'click', PrintImage);
	SetListener(document.getElementById('fill'), 'click', Fill);
	
	for(var i = 0; i <= 15; i++)
	{
		SetListener(document.getElementById('c' + i), 'mousedown', ChangeColor);
	}

	//GrabImages();
	initialized = true;
	//var GI = self.setInterval("GrabImages()", 10000);
	GrabTable('empty');
}
SetListener(window, 'load', AttachListeners);


/* AJAX */
function PrintImage()
{	
	var xmlhttp = GetXMLHttpRequest();
	var serverPage = '/php/pimpy/imageGenerator.php';
	var queryString = GetPimpyQueryString();
	
	xmlhttp.open('post', serverPage, true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
			if(xmlhttp.responseText != 'failure' && xmlhttp.responseText != '')
			{
				//GrabImages();
				window.location = '/php/pimpy/imageGrabber.php?type=download&id=' + xmlhttp.responseText;
			}
		}
	}
	xmlhttp.send(queryString);
}

function GrabTable(dID)
{
	var xmlhttp = GetXMLHttpRequest();
	var querystring = 'id=' + encodeURIComponent(dID) + '&zoom=' + encodeURIComponent(zoom);
	
	var serverPage = '/php/pimpy/tableGenerator.php';

	xmlhttp.open('post', serverPage, true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
			document.getElementById('paintBox').innerHTML = xmlhttp.responseText;
			ReverseListeners();
		}
	}
	xmlhttp.send(querystring);		
}

function GrabImages()
{
	if(initialized == true)
		UnsetImgViews();

	var xmlhttp = GetXMLHttpRequest();
	var serverPage = '/php/pimpy/imageView.php';

	xmlhttp.open('post', serverPage, true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
			document.getElementById('imgView').innerHTML = xmlhttp.responseText;
			setTimeout('SetImgViews()', 150);
		}
	}
	xmlhttp.send(null);	
}

function GetPimpyQueryString(dForm)
{ 
	var qStr = "width="+dWidth+"&height="+dHeight+"&"; 
	var dCount = dWidth * dHeight;
	var obj = "";
	
	for(var i = 0; i < (dCount - 1); i++) 
	{ 
		obj = document.getElementById('cell' + i);
		qStr += obj.id + '=' + encodeURIComponent(obj.title.substr(1, obj.title.length-1))+'&';
	}
	obj = document.getElementById('cell' + (dCount - 1));
	qStr += obj.id + '=' + encodeURIComponent(obj.title.substr(1, obj.title.length-1));
	return qStr;
}