//dec 2 hex
var hD="0123456789ABCDEF";
function d2h(d) {
	var h = hD.substr(d&15,1);
	while(d>15) {d>>=4;h=hD.substr(d&15,1)+h;}
	if (h.length == 1) 
		h = "0"+h
	return h;
}

//used for the text
function randomColor() {
	var red;
	var green;
	var blue;

	var mindiff = 230
	var maxbright = 400	
	do {
		red   = Math.round(Math.random()*256);
		green = Math.round(Math.random()*256);
		blue  = Math.round(Math.random()*256);
	} while ( (Math.abs(red - green) < mindiff &&  Math.abs(green - blue) < mindiff && Math.abs(blue - red) < mindiff) && red + green + blue > maxbright )		
	var pepe = d2h(red)+d2h(green)+d2h(blue);
	return pepe
}

function randomInt(x) {
var r = Math.round(x*Math.random())
return r
}

function randomSpeed() {
return Math.random()*6 - 3
}


//lazy way to verify an img is moving fast enough
function tooSlow(a, b) {
	if (Math.abs(a) + Math.abs(b) < 1) {
		return 1;
	}else {
		return 0;
	}
}




//do nothing functon handles event after a sendMsg call  
function getmsg(){};


var myargs = new Array();
function sendMsg() {
	var text = document.message.msg.value;
	if (whatIsIt(text) == 'txt') {
		text = text.substring(0,50);
	}
	addMsg(text); /*lo agrego a la pantalla*/
	myargs['newmsg']=text;
	document.message.msg.value = '';
	bajax.call('/cgi-bin/addmessage.pl', getmsg,  myargs); /* lo mando al servidor */
}

// se fija si un mensaje ya existe
function exists(msg) {
	var n = 0;
	for (n=0; n<maxdots; n++) {
		/*
		   if (imgs[n].firstChild.data.match(/polaca/)){
			alert("["+imgs[n].firstChild.data+"] ["+msg+"]");
			}
		*/
		try{
		if (imgs[n].firstChild.data.replace("http://","")==msg.replace("http://","")) {
			return 1;
		}
		}catch(err){
		}
		if (imgs[n].src && imgs[n].src==msg) {
			return 1;
		}
	}
	return 0
}



// va a buscar nuevos mensaje al servidor
function getnewmessages() {
	bajax.call("/cgi-bin/getlastmessage.pl", addMsgFromServer,  myargs);
}

//coloca un elemento en el medio y le da velocidad randomica
function resetPosition(i){
	var posx = startx + randomInt(40) - 20 - imgs[i].offsetWidth/2;
	var posy = starty + randomInt(40) - 20 - imgs[i].offsetHeight/2;
	if (esBox2D) {
		try {
		  imgs[i].style.left = posx
		  imgs[i].style.top = posy;
		}catch(err){
		}
	}else{
		x[i] = posx;
		y[i] = posy;
		do {
			yy[i] = randomSpeed();
			xx[i] = randomSpeed();
		} while (tooSlow(yy[i], xx[i]));
	}
}

//maneja lo recibido de una llamada al servidor
function addMsgFromServer(text) {
	var campos = text.split("|");
	addMsg(campos[2]);
}

// agrega un mensaje al documento 
function addMsg(text) {
	text = text.replace("\n","");
	if (text == '')
		return 0;
	var n = 0;
	if (exists(text))
		return 0;
	
	var elem
	if (text.match(/\.(jpg)|(jpeg)|(png)|(gif)|(svg)|(bmp)$/i)) {
		elem = document.createElement("IMG");
		if (!text.match(/http:\/\//i)) {
			elem.src = "http://"+text
		}
		else {
			elem.src = text 
		}
		elem.width=imgWidth;
		elem.height=imgHeight;
		elem.left = 0;
		elem.top = 0;
		text = ''
	}
	else if (text.match(/^http:\/\//) || text.match(/\.\w{2,4}\/?$/i))  { 
		elem = document.createElement("A");
		if (!text.match(/^http:\/\//i)) {
			elem.href = "http://"+text
		}
		else {
			elem.href = text 
		}
		elem.width=10;
		elem.height=10;
	}
	else {
	   elem	= document.createElement("DIV");
		elem.width=10;
		elem.height=10;
	}
	elem.style.position = "absolute";
	var newnode = document.createTextNode(text.replace("http://",""));
	elem.appendChild(newnode);
	elem.style.color = randomColor();
	var body = document.getElementById('elbody');
	body.replaceChild(elem, imgs[current]);
	imgs[current] = elem;
	resetPosition(current);
	if (esBox2D) {
		replaceThisOne(current, elem);  // para box2d
	}

	current++;
	if (current >= maxdots) 
		current = 0;
	
	return 1
}

function whatIsIt(text) {
	if (text.match(/\.(jpg)|(jpeg)|(png)|(gif)|(svg)|(bmp)$/i)) {
		return('img');
	}
	else if (text.match(/^http:\/\//) || text.match(/\.\w{2,4}\/?$/i))  { 
		return('url');
	}
	else {
		return('txt');
	}
}

var maxdots = 10;

var sw = document.body.clientWidth - 15;
var sh = document.body.clientHeight - 15;

document.getElementById('box').style.position = 'absolute';
document.getElementById('box').style.top = sh/2-15;
document.getElementById('box').style.left = sw/2-60;


var imgs = new Array(maxdots);
var txts = new Array(maxdots);
var xx   = new Array(maxdots);
var yy   = new Array(maxdots);
var x    = new Array(maxdots);
var y    = new Array(maxdots);

/* centro de la pantalla */
var startx = sw/2;
var starty = sh/2;

/* tamaño default de una imagen */
var imgHeight = 100;
var imgWidth = 100;

var current = 0;

function mensajes(x) {
	var tmp = x.split("\n");
	var j;
	for(j=0; j<tmp.length && j<maxdots; j++) {
		tmp[2].length--;
			
		var campos = tmp[j].split("|");
		if (!tmp[0].match(/\d+/)) { continue; } /* si la linea no comienza en numero salteo */
		if (campos[1] == "img") {
			imgs[j] = document.createElement("IMG");
			imgs[j].src = campos[2];
			imgs[j].width=imgWidth;
			imgs[j].height=imgHeight;
		}
		else if (campos[1]== "url") {
			imgs[j] = document.createElement("A");
			imgs[j].href = campos[2]
			//imgs[j].width=10;
			//imgs[j].height=10;
		}
		else {
			imgs[j] = document.createElement("DIV");
			//imgs[j].width=10;
			//imgs[j].height=10;
		}
		try{
		txts[j] = document.createTextNode(campos[2].replace("http://",""));
		}catch(err){
		}
		imgs[j].style.position = "absolute";
		imgs[j].style.zindex = -1;
		if (imgs[j] != undefined && txts[j] != undefined && campos[1] != "img") {
		  try {
		    imgs[j].appendChild(txts[j]);
		  }catch(err){
		  }
		}
		document.body.appendChild(imgs[j]);
		resetPosition(j);
		var color = randomColor();
		imgs[j].style.color = color;
		if(esBox2D) {
			addNewOne(imgs[j]);  // box2d ?
		}
	}
}




function move() {
	for(i = 0; i < maxdots; i++) {	
		try {	
		if (y[i]>=(sh-imgs[i].offsetHeight- 5)){
			yy[i] = -yy[i];
		}
		else if (y[i]<=1) {
			yy[i] = -yy[i];
		}
		
		if (x[i]>=(sw-imgs[i].offsetWidth- 5)){
			xx[i] = -xx[i];
		}
		else if (x[i]<=1) {
			xx[i] = -xx[i];
		}
		x[i] = x[i] + xx[i];
		y[i] = y[i] + yy[i];
		
		imgs[i].style.left = Math.round(x[i]);
		imgs[i].style.top = Math.round(y[i]);
		}catch(err){
		}
	}
}

function myOnLoad() {
	document.message.msg.focus();
}


var myargs = new Array();
bajax.call('/cgi-bin/getmessages.pl', mensajes, myargs);
if (!esBox2D) {
	setInterval('move()', 30);
}
setInterval('getnewmessages()',6000);

