var curr = null;
var maxz = 0;
var dx = 0;
var dy = 0;
var cw = 0;
var ch = 0;
var progress = null;
var totalimgs = 0;
var imgs = 0;
var wait = false;
var moving = false;
var stack = new Array();
var updating = false;

var request = null;
var requestst = null;
var requestou = null;

var loop_period = 9000;
var move_period = 30;

var last_update = 0;

function createRequest() {
    try{
        request = new XMLHttpRequest();
    }catch (trymicrosoft){
        try{
            request = new ActiveXObject("Msxml2.XMLHTTP");
        }catch (othermicrosoft){
            try{
                request = new ActiveXObject("Microsoft.XMLHTTP");
            }catch (failed){
                request = null;
            }
        }
    }
    if (request == null){
        alert("Error creating request object!");
    }
}

function createRequestst() {
    try{
        requestst = new XMLHttpRequest();
    }catch (trymicrosoft){
        try{
            requestst = new ActiveXObject("Msxml2.XMLHTTP");
        }catch (othermicrosoft){
            try{
                requestst = new ActiveXObject("Microsoft.XMLHTTP");
            }catch (failed){
                requestst = null;
            }
        }
    }
    if (requestst == null){
        alert("Error creating requestst object!");
    }
}

function createRequestou() {
    try{
        requestou = new XMLHttpRequest();
    }catch (trymicrosoft){
        try{
            requestou = new ActiveXObject("Msxml2.XMLHTTP");
        }catch (othermicrosoft){
            try{
                requestou = new ActiveXObject("Microsoft.XMLHTTP");
            }catch (failed){
                requestou = null;
            }
        }
    }
    if (requestou == null){
        alert("Error creating requestou object!");
    }
}

function join(g1, gid2, ox, oy) {
	var g2 = document.getElementById('grp' + gid2);
	var nodes = g1.childNodes;
	var n = nodes.length;
	for (var i = n - 1; i >= 0; i --) {
		var c = nodes[i];
		if (!c.id) continue;
		c.style.left = (c.offsetLeft + parseInt(ox)) + 'px';
		c.style.top = (c.offsetTop + parseInt(oy)) + 'px';
		g1.removeChild(c);
		g2.appendChild(c);
		if (gid2 == 1) {
			c.style.cursor = 'default';
		}
	}
	if (gid2 != 1) {
		g2.style.zIndex = g1.style.zIndex;
	}
}

var reloading = false;

function rand(n) {
	return Math.round(Math.random() * n);
}

function rel() {
	window.location.reload();
}

function reload() {
	reloading = true;
	setTimeout('rel()', rand(60) * 1000);
}

function updated() {
	if (reloading) return;
	if (request.readyState == 4) {
		if (request.status == 200) {
			var s = request.responseText;
			if (s != '') process(s, true);
		} else {
			alert('Connection lost');
			window.location.reload();
		}
		showwait(false);
		updating = false;
	}
}

function update(el, x, y, z) {
	if (reloading) return;
	updating = true;
	showwait(true);
	createRequest();
	var url = 'update.php?v=' + ver + '&el=' + el + '&x=' + x + '&y=' + y + '&z=' + z + '&time=' + new Date().getTime();
	request.open('GET', url, true);
	request.onreadystatechange = updated;
	request.send(null);
}

function select(el, event) {
	if (reloading) return;
	
	if (curr != null) return;
	
	if (el.id == 'grp1') return;
	
	last_update = new Date().getTime();
	
	curr = el;
	maxz ++;
	curr.style.zIndex = maxz;
	
	var cx = curr.offsetLeft;
	var cy = curr.offsetTop;
	var tx = -100;
	var ty = -100;
	if (event.pageX) tx = event.pageX;
	else if (event.x) tx = event.x;
	if (event.pageY) ty = event.pageY;
	else if (event.y) ty = event.y;
	if ((tx == -100) || (ty == -100)) return;
	dx = cx - tx;
	dy = cy - ty;
	cw = curr.offsetWidth;
	ch = curr.offsetHeight;

    if (event.stopPropagation) event.stopPropagation();
	else event.cancelBubble = true; 

	if (event.preventDefault) event.preventDefault();
    else event.returnValue = false;
	
	if (document.addEventListener) {
        document.addEventListener("mousemove", move, true);
        document.addEventListener("mouseup", release, true);
    }
    else if (document.attachEvent) {
        document.attachEvent("onmousemove", move);
        document.attachEvent("onmouseup", release);
    }
}

function move(event) {
	if (curr == null) return;
	
	var tx = -100;
	var ty = -100;
	if (event.pageX) tx = event.pageX;
	else if (event.x) tx = event.x;
	if (event.pageY) ty = event.pageY;
	else if (event.y) ty = event.y;
	if ((tx == -100) || (ty == -100)) return;
	
	var cx = dx + tx;
	var cy = dy + ty;
	
	if (cx < 0) cx = 0;
	else if (cx > (980 - cw)) cx = 980 - cw;
	if (cy < 0) cy = 0;
	else if (cy > 1000 - ch) cy = 1000 - ch;
	
	
	curr.style.left = cx + 'px';
	curr.style.top = cy + 'px';
	
	if (event.stopPropagation) event.stopPropagation();
	else event.cancelBubble = true; 

	if (event.preventDefault) event.preventDefault();
    else event.returnValue = false;
}

function release(event) {
	if (document.removeEventListener) {
		document.removeEventListener("mouseup", release, true);
		document.removeEventListener("mousemove", move, true);
	}
	else if (document.detachEvent) {
		document.detachEvent("onmouseup", release);
		document.detachEvent("onmousemove", move);
	}
	
	if (event.stopPropagation) event.stopPropagation();
	else event.cancelBubble = true; 
	
	last_update = new Date().getTime();
	update(curr.id, curr.offsetLeft, curr.offsetTop, curr.style.zIndex);
	
	curr = null;
}

var prefix = '';

function preload(n) {
	if (n > totalimgs) return;
	img_loaded(n);
	setTimeout('preload(' + (n+1) + ')', 1);
}

function changebck(el, src) {
	if (el.filters) {
		el.filters[0].src = src;
	} else {
		el.style.background = "url('" + src + "')";
	}
}

function img_loaded(n) {
	imgs ++;
	if (totalimgs == 0) return;
	changebck(document.getElementById('p' + n), prefix + '' + n + '.png');
}

function tostack(op, el, p2, p3, p4, twait) {
	/* for (var i = 0; i < stack.length; i++) {
		if (stack[i].el == el) {
			if ((stack[i].op == 'm') && (op == 'm')) {
				stack[i].x = p2;
				stack[i].y = p3;
				stack[i].z = p4;
				stack[i].wait = twait;
			}
			if (op == 'j') {
				stack[i].op = op;
				stack[i].gid2 = p2;
				stack[i].ox = p3;
				stack[i].oy = p4;
				stack[i].wait = twait;
			}
			return;
		}
	} */
	
	
	
	if (op == 'j') {
		/* var t = new Object();
		t.op = op;
		t.el = el;
		t.gid2 = p2;
		t.ox = p3;
		t.oy = p4;
		t.wait = twait;
		stack.push(t); */
	} else if (op == 'm') {
		var t = new Object();
		t.op = op;
		t.el = el;
		t.x = p2;
		t.y = p3;
		t.z = p4;
		t.wait = twait;
		stack.push(t);
	}
	
	if (!moving) {
		moving = true;
		setTimeout("stacktmr()", move_period + 100);
	}
}

function stacktmr() {
	var i = 0;
	var n = stack.length;
	while (i < n) {		
		var t = stack[i];
		if (t.wait > 0) {
			t.wait --;
			
			if (t.wait == 0) {
				var j = 0;
				while (j < i) {
					if (t.el == stack[j].el) {
						stack.splice(j, 1);
						j--;
						i--;
						n--;
					}
					j++;
				}
			}
			
			i++;
			continue;
		}
		
		if (t.op == 'm') {
			if (t.z != -1) {
				t.el.style.zIndex = t.z;
				t.z = -1;
				t.cx = t.el.offsetLeft;
				t.cy = t.el.offsetTop;
			}
			
			var dx = t.cx - t.x;
			var dy = t.cy - t.y;
			if ((t.el == curr) || ((dx == 0) && (dy == 0))) {
				stack.splice(i, 1);
				n--;
				i--;
			} else {
				mx = Math.round(dx / 4);
				my = Math.round(dy / 4);
				if ((mx == 0) && (dx != 0)) {
					if (dx < 0) mx = -1; else mx = 1;
				}
				if ((my == 0) && (dy != 0)) {
					if (dy < 0) my = -1; else my = 1;
				}
				t.cx = t.cx - mx;
				t.cy = t.cy - my;
				t.el.style.left = t.cx + 'px';
				t.el.style.top = t.cy + 'px';
			}
		} else if (t.op == 'j') {			
			join(t.el, t.gid2, t.ox, t.oy);
			stack.splice(i, 1);
			n--;
			i--;
		}
		
		i++;
	}
	
	if (stack.length > 0) {
		setTimeout("stacktmr()", move_period);
	}
	else moving = false;
}

function process(s, zerotime) {
	if (reloading) return;
	
	/* for (var i = 0; i < stack.length; i++) {
		stack[i].wait = 0;
	} */
	
	var data = s.split(',');
	if (ver > data[0]) return;
	ver = parseInt(data[0]);
	var i = 1;
	var n = data.length;
	
	var w = 0;
	var incw = 0;
	if ((!zerotime) && (n > 1)) {
		incw = loop_period / (move_period * (n - 1) / 5);
	}
	
	while (i < n) {
		var act = data[i];
		if (act == 'm') {
			var tmp = document.getElementById('grp' + data[i + 1]);
			if (tmp == null) {
				return;
			}
			var x = data[i + 2];
			var y = data[i + 3];
			var z = data[i + 4];
			
			if (z > maxz) maxz = z;
			
			if (tmp != curr) {
				tostack(act, tmp, x, y, z, Math.floor(w));
			}
			w += incw;
		} else if (act == 'j') {
			var tmp = document.getElementById('grp' + data[i + 1]);
			if (tmp == null) {
				return;
			}
			//tostack(act, tmp, data[i + 2], data[i + 3], data[i + 4], Math.floor(w));
			join(tmp, data[i + 2], data[i + 3], data[i + 4]);
			w += incw;
		} else if (act == 'n') {
			reload();
			return;
		} else {
			window.location.reload();
			return;
		}
		
		i += 5;
	}
}

function state() {
	if (reloading) return;
	if (requestst.readyState == 4) {
		if (!updating) {
			if (requestst.status == 200) {
				var s = requestst.responseText;
			
				if (s == '') {
					wait = false;
					return;
				}
			
				process(s, false);
				wait = false;
			} else {
				alert('Connection lost');
				window.location.reload();
			}
		}
		wait = false;
	}
}

function getState() {	
	if (reloading) return;
	createRequestst();
	var url = 'state.php?v=' + ver + '&time=' + new Date().getTime();
	requestst.open('GET', url, true);
	requestst.onreadystatechange = state;
	requestst.send(null);
}

var waiti = 0;

function loop() {
	if (last_update == 0) {
		last_update = new Date().getTime();
	} else {
		if ((new Date().getTime() - last_update) > 600000) {
			reloading = true;
			position_ina();
		}
	}
	
	
	if (reloading) return;
	setTimeout("loop()", loop_period);
	if (!wait) {
		waiti = 0;
		wait = true;
		getState();
	} else {
		waiti++;
		if (waiti > 10) {
			requestst.abort();
			wait = false;
		}
	}
}

function check() {
	if (imgs == 0) {
		document.getElementById('progress_d').style.display = 'none';
		document.getElementById('over').style.display = 'none';
		document.getElementById('arena').style.zIndex = '0';
	}
}

var elwait = null;

function showwait(show) {
	if (elwait == null)
		elwait = document.getElementById('wait');
	if (show) {
		elwait.style.top = (document.body.scrollTop + 10) + 'px';
		elwait.style.left = (document.body.scrollLeft + 10) + 'px';
		elwait.style.display = 'block';
	} else {
		elwait.style.display = 'none';
	}
}

function showthumb(w, h) {
	w += 15;
	h += 15;
	var nl = (window.screen.width - w) / 2;
	var nt = (window.screen.height - h) / 2;
	newwin = window.open('thumb.php?time=' + new Date().getTime(), 'Thumbnail', 'left='+nl+',top='+nt+',height='+h+',width='+w);
	return false;
}

function onlineusers() {
	if (reloading) return;
	if (requestou.readyState == 4) {
		if (requestou.status == 200) {
			var s = requestou.responseText;
			document.getElementById('users').innerHTML = s;
		} else {
			alert('Connection lost');
			window.location.reload();
		}
	}
}

function getOu() {
	if (reloading) return;
	createRequestou();
	var url = 'online.php?time=' + new Date().getTime();
	requestou.open('GET', url, true);
	requestou.onreadystatechange = onlineusers;
	requestou.send(null);
}

var secs = 0;

function updateTime() {
	setTimeout('updateTime()', 30000);
	secs += 30;
	var mins = Math.floor(secs / 60);
	var hrs = Math.floor(mins / 60);
	mins = mins % 60;
	
	var str = ((hrs > 0) ? (hrs + ' h, ') : '') + mins + ' min';
	document.getElementById('time').innerHTML = str;
	
	getOu();	
}

var bckcolor = '#E3E3E3';
var cancelHide = false;
function hidePicker() {
	if (cancelHide) return;
	document.getElementById('colorPicker').style.display = 'none';
	document.getElementById('arena').style.background = bckcolor;
	document.getElementById('colorBox').style.background = bckcolor;
}
function selectColor(col) {
	bckcolor = col;
	cancelHide = false;
	hidePicker();
}
function changeColor(col) {
	cancelHide = true;
	//document.getElementById('arena').style.background = el.style.background;
	document.getElementById('colorBox').style.background = col;
}
function doHide() {
	cancelHide = false;
	setTimeout('hidePicker()', 1000);
}
function getAbsolutePos(el) {
	var r = { x: el.offsetLeft, y: el.offsetTop };
	if (el.offsetParent) {
		var tmp = getAbsolutePos(el.offsetParent);		
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
}
function showPicker() {
	var r = getAbsolutePos(document.getElementById('colorBox'));
	var cp = document.getElementById('colorPicker');
	cp.style.left = r.x + 'px';
	cp.style.top = (r.y + 20) + 'px';
	cp.style.display = 'block';
	cancelHide = true;
}
function populatePicker() {
	var cp = document.getElementById('colorPicker');
	var colors = new Array(
"#FFFFFF", "#EFEFEF", "#DFDFDF", "#CFCFCF", "#BFBFBF", "#AFAFAF", "#9f9f9f", "#8f8f8f",
"#7f7f7f", "#6f6f6f", "#5f5f5f", "#4f4f4f", "#3f3f3f", "#2f2f2f", "#1f1f1f", "#0f0f0f",
"#F69679", "#F9AD81", "#FDC689", "#FFF799", "#C4DF9B", "#A3D39C", "#82CA9C", "#7ACCC8",
"#6DCFF6", "#7DA7D9", "#8393CA", "#8781BD", "#A186BE", "#BD8CBF", "#F49AC1", "#F5989D",
"#F26C4F", "#F68E56", "#FBAF5D", "#FFF568", "#ACD373", "#7CC576", "#3CB878", "#1CBBB4",
"#00BFF3", "#448CCB", "#5674B9", "#605CA8", "#8560A8", "#A864A8", "#F06EAA", "#F26D7D"
	);
	var total = colors.length;
	var s = '';
	for (var i = 0; i < total; i++) {
		s += '<div class="color" style="background-color:' + colors[i] + '" onclick="selectColor(\'' + colors[i] + '\')" onmouseover="changeColor(\'' + colors[i] + '\');" onmouseout="doHide();"></div>';
	}
	cp.innerHTML = s;
}

var ina = null;
var blend = null;
var blend_top = -100;
function position_ina() {
	if (ina == null) {
		ina = document.getElementById('message_ina');
		blend = document.getElementById('blend');
		//blend.style.display = 'block';
		ina.style.display = 'block';
	}
	if (blend_top != (document.documentElement.scrollTop)) {
		blend_top = document.documentElement.scrollTop;
		ina.style.top = blend_top + 200 + 'px';
		//blend.style.top = blend_top + 'px';
	}
	setTimeout('position_ina()', 10);
}