// vars
var xhr;
var vcXHR;
var preloadimg = new Image(800,600);
var mashes = new Array('mash2','mash4','mash6','mash8','mash10');
var pix = document.createElement('SPAN');
var coords = "";
var timestamp = 0;
var mouseButtonPressed = false;
var pixels = new Array();
var remotePainter = new Array();
//

var preloaded = new Array();
function preload_images() {
	for (var i = 0; i < arguments.length; i++){
		preloaded[i] = document.createElement('img');
		preloaded[i].setAttribute('src',arguments[i]);
	};
};

preload_images(
	'/images/cp_horizontal_picker.png',
	'/images/bojanka_popup.gif',
	'/images/paleta.png',
	'/images/olovka.gif',
	'/images/button.gif',
	'/images/bojanka_bg-1.png',
	'/images/wood69-1.jpg',
	'/images/paleta.png',
	'/images/paleta_pressed.gif',
	'/images/button_pressed.gif',
	'/images/pomoc_paleta.jpg'
);

pix.style.position = "absolute";
pix.style.height = "4px";
pix.style.width = "4px";
pix.style.backgroundColor = "rgb(0,0,0)";
pix.style.fontSize = "1px";
pix.style.zIndex = "100";


function pad(number,length) {
    var str = '' + number;
    while (str.length < length)
    str = '0' + str;
    return str;
}

function removeChildNodes(element){
	while (element.childNodes[0]){
		element.removeChild(element.childNodes[0]);
	}
}


function getRGB(rgb){
	var return_array;
	if (0 <= rgb.indexOf("#"))
	{
		return new Array(parseInt("0x" + rgb.substr(1, 2)).toString(10), 
					 parseInt("0x" + rgb.substr(3, 2)).toString(10),
					 parseInt("0x" + rgb.substr(5, 2)).toString(10)
					);
	}
	return rgb.replace(/rgb.*\(|\)|\s/g,'').split(',');
}


function init() {
	var imgdiv = $('imgdiv');
	var cpdiv = $('color');
	var coords = new Object();
	coords.x = findPosX(cpdiv);
	coords.y = findPosY(cpdiv);
	if(cpdiv) attachColorPicker(cpdiv,coords);
	addEvent(imgdiv,'mousedown', divMouseDown);
	addEvent(imgdiv,'mousemove', divMouseMove);
	addEvent(imgdiv,'mouseup', divMouseUp);
	for(m in mashes) {
		addEvent($(mashes[m]),'click', prepareMash);
	}
	updater();
}

function prepareMash(e) {
	clickedEl = getEventTarget(e);
	if(clickedEl.nodeName != 'LI')	clickedEl = clickedEl.parentNode;
	for(m in mashes) {
		try {$(mashes[m]).style.backgroundColor = "rgb(255,255,255)";} catch (e) {}
	}
	clickedEl.style.backgroundColor = "rgb(200,200,200)";
	size = clickedEl.id.replace(/mash/,'');
	pix.style.width = size +'px';
	pix.style.height = size +'px';
}

function divMouseDown (e) {
	writePixel(getEventTarget(e),(getMouseX(e)) - findPosX($('imgdiv')),(getMouseY(e) - findPosY($('imgdiv')) ));
	mouseButtonPressed = true;
}

function divMouseMove (e) {
	if(mouseButtonPressed)
		writePixel(getEventTarget(e),(getMouseX(e)) - findPosX($('imgdiv')),(getMouseY(e) - findPosY($('imgdiv')) ));
}


function divMouseUp (e) {
	if(mouseButtonPressed != false) {
		if(xhr = getXHR()) {
			xhr.onreadystatechange = function() 
			{
				if (xhr.readyState == 4 ) 
				{
					var isok = new RegExp(/^OK/);
					if(isok.exec(xhr.responseText) != null)
					{
						x = xhr.responseText.split(':');
						timestamp = x[1].split(',')[0];
						updater(true);
						coords = "";
					}
				}
			}
		} else {
			alert('failed to get XHR object!!!!');
		}
		rgb = getRGB($('color').style.backgroundColor);
		xhr.open('POST', url,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		try{
			xhr.send('action=update&coords=' + pix.style.width.replace(/px/,'') + ',' + pad(rgb[0],3) + ':' +pad(rgb[1],3) + ':' + pad(rgb[2],3)  +  ',' + coords)
		} catch(e) {
			console.log(e.message + "\npuklo ko zvecka...");
		}
		coords = "";
		mouseButtonPressed = false;
	}
}

function writePixel(where,x,y) {
	if(where.nodeName != 'SPAN') {
		mashpixel = pix.cloneNode(false);
		mashpixel.style.left = (x - (pix.style.height.replace(/px/,'')/2)) + 'px';
		mashpixel.style.top  = (y - (pix.style.width.replace(/px/,'')/2)) + 'px';
		mashpixel.style.backgroundColor = $('color').style.backgroundColor;
		where.appendChild(mashpixel);
		coords += '|' + x + ',' + y ;
	}
}

function updater(cleaner) {
	d = new Date();
	preloadimg.src = 'current.png?currtime=' + (((d.getTime() - d.getMilliseconds()) / 1000) + d.getTimezoneOffset() );
	preloadimg.onload = function () { 
		$('imgdiv').style.backgroundImage = 'url(' + preloadimg.src + ')' ;
		if(cleaner) {
			removeChildNodes($('imgdiv'));
		}
	}
}

function versionChecker() {
	if(vcXHR = getXHR()) {
		vcXHR.onreadystatechange = function() 
		{
			if (vcXHR.readyState == 4 ) 
			{
				x = vcXHR.responseText.split(',');
				if (timestamp != x[0]) {
					updater(false);
				}
				timestamp = x[0];
				//remotePainter = x[1];
			}
		}
	}
	vcXHR.open('POST',url,true);
	vcXHR.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	vcXHR.send('action=loadcheck');
}
var popups = new Array('help','about','chat');
for(p in popups) {try {$(popups[p]).style.display = 'none';} catch (e) {}}

function showPopUp(winname) {
	if(($(winname).style.display == 'none') || (typeof $(winname).style.display == 'undefined') || ($(winname).style.display == '')) {
		$(winname).style.left = findPosX($('imgdiv')) + 20 +'px';
		$(winname).style.top = findPosY($('imgdiv')) + 20 +'px';
		for(p in popups) {try {$(popups[p]).style.display = 'none';} catch (e) {}} // "unshow" them all and then show only correct one :)
		$(winname).style.display= 'block';
	} else {
		$(winname).style.display = 'none';
	}
}

window.onload = init;

setInterval('versionChecker()', 2000);
