/**
* @Copyright Copyright (C) 2010 - JoniJnm.es
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
**/

var kide = {
	$: function(id) {
		return document.getElementById(id);
	},
	css: function(id, param, value) {
		if (typeof(value)!="undefined") this.$(id).style[param] = value;
		else return this.$(id).style[param];
	},
	val: function(id, v) {
		if (typeof(v)!="undefined") this.$(id).value = v;
		else return this.$(id).value;
	},
	html: function(id, value) {
		if (typeof(value)!="undefined") this.$(id).innerHTML = value;
		else return this.$(id).innerHTML;
	},
	show: function(id,s) {
		if (typeof(s)!="undefined") s = s ? "" : "none";
		else s = this.css(id,"display") == "none" ? "" : "none";
		this.css(id,"display",s);
	},
	visible: function(id,s) {
		if (typeof(s)!="undefined") s = s ? "" : "hidden";
		else s = this.css(id,"visibility") == "hidden" ? "" : "hidden";
		this.css(id,"visibility",s);
	},
	nuevoAjax: function() {
		var xmlhttp=false;
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp = false;
			}
		}
		if (!xmlhttp && typeof XMLHttpRequest!='undefined')
			xmlhttp = new XMLHttpRequest();
		return xmlhttp;
	},
	form: function(param, v) {
		if (typeof(v) == "undefined") return document.forms.kideForm[param].value;
		else document.forms.kideForm[param].value = v;
	},
	iniciar: function() {
		this.encendido = 2;
		this.$("encendido").src = this.img_encendido[2];
		if (this.recargar_parado) {
			this.recargar_parado = false;
			this.recargar();
		}
		if (this.sesiones_parado) {
			this.sesiones_parado = false;
			this.sesiones();
		}
		if (this.privados_parado && this.privados_encontrado && this.site=="com") {
			this.privados_parado = false;
			this.privados_recargar();
		}
	},
	open_popup: function() {
		if (this.popup)
			this.popup.close();
		this.popup=window.open(this.popup_url, 'kide', 'toolbar=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1,width=800,height=600');
	},
	text: function(row) {
		var n = navigator.userAgent.toString();
		if (n.indexOf("MSIE") != -1)
			return row.text;
		return row.textContent;
	},
	recargar: function() {
		if (this.encendido == 2) {
			this.ajax("reload");
			setTimeout("kide.recargar()", this.refresh_time);
		}
		else
			this.recargar_parado = true;
	},
	sesiones: function() {
		if (this.encendido == 2) {
			this.ajax("sesiones");
			setTimeout("kide.sesiones()", this.refresh_time_sesion);
		}
		else
			this.sesiones_parado = true;
	},
	privados_recargar: function() {
		if (this.encendido == 2) {
			this.ajax("privados_reload");
			setTimeout("kide.privados_recargar()", this.refresh_time_privates);
		}
		else
			this.privados_parado = true;
	},
	apagar_encender: function() {
		if (this.encendido == 0)
			this.encendido++;
		else if (this.encendido == 1) 
			this.iniciar();
		else 
			this.encendido = 0;
			
		this.save_config("encendido", this.encendido);
		this.$('encendido').src = this.img_encendido[this.encendido];
	},
	sonido: function() {
		if (this.sound != -1) {
			if (this.$('sound').src == this.sound_on) {
				this.sound = 0;
				this.$('sound').src = this.sound_off;
			}
			else {
				this.sound = 1;
				this.$('sound').src = this.sound_on;
				this.play_msg_sound();
			}
			this.save_config("sound", this.sound);
		}
	},
	save_config: function(param, value) {
		var ajax = this.nuevoAjax();
		var config = document.cookie.match(/kide_config=([^;]*)/);
		config = decodeURIComponent(config[1]);
		if (config.search(eval('/'+param+'=/')) > -1)
			config = config.replace(eval('/'+param+'=[^;]*/'), param+'='+value);
		else
			config += ';'+param+'='+value;
		document.cookie = 'kide_config='+encodeURIComponent(config)+'; path=/';
	},
	ahora: function() {
		var ya = new Date();
		var m = ya.getMonth() + 1;
		ya = ya.getDate()+"-"+(m < 10 ? "0" : "")+m+" "+ya.getHours()+":"+(ya.getMinutes() < 10 ? "0" : "")+ya.getMinutes()+":"+(ya.getSeconds() < 10 ? "0" : "")+ya.getSeconds();
		return ya;
	},
	in_array: function(e, a) {
		for (var i=0; i<a.length; i++)
			if (a[i] == e) return true;
		return false;
	},
	insertAfter: function(newElement,targetElement) {
		var parent = targetElement.parentNode;
		if (parent.lastchild == targetElement) 
			parent.appendChild(newElement);
		else 
			parent.insertBefore(newElement, targetElement.nextSibling);
	},
	htmlspecialchars_decode: function(string, quote_style) {
		//http://phpjs.org/functions/htmlspecialchars_decode:427
		var optTemp = 0, i = 0, noquotes= false;
		if (typeof quote_style === 'undefined') {
			quote_style = 2;
		}
		string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
		var OPTS = {
			'ENT_NOQUOTES': 0,
			'ENT_HTML_QUOTE_SINGLE' : 1,
			'ENT_HTML_QUOTE_DOUBLE' : 2,
			'ENT_COMPAT': 2,
			'ENT_QUOTES': 3,
			'ENT_IGNORE' : 4
		};
		if (quote_style === 0)
			noquotes = true;
		if (typeof quote_style !== 'number') {
			quote_style = [].concat(quote_style);
			for (i=0; i < quote_style.length; i++) {
				if (OPTS[quote_style[i]] === 0) 
					noquotes = true;
				else if (OPTS[quote_style[i]])
					optTemp = optTemp | OPTS[quote_style[i]];
			}
			quote_style = optTemp;
		}
		if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE)
			string = string.replace(/&#0*39;/g, "'");
		if (!noquotes)
			string = string.replace(/&quot;/g, '"');
		string = string.replace(/&amp;/g, '&');
		return string;
	},
	check_shift: function(event, up, priv) {
		var theCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (up) {
			if (theCode == 16) {
				if (priv)
					this.shift_priv_pressed = false;
				else
					this.shift_pressed = false;
			}
		}
		else if (theCode != 13) {
			if (priv)
				this.shift_priv_pressed = theCode == 16;
			else
				this.shift_pressed = theCode == 16;
		}
	},
	pressEnter_stop: function(event) {
		var theCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		return theCode != 13;
	},
	pressedEnter: function(event, priv) {
		var theCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (theCode == 13) {
			if ((!priv && this.shift_pressed) || (priv && this.shift_priv_pressed))
				return true;
			else if (priv) 
				this.ajax("privados_insertar");
			else
				this.sm();
			return false;
		} 
		else
			return true;
	},
	tiempo: function(t) {
		t = Number(t) - this.retardo;
		var time = new Date();
		time = time.getTime();
		t = Math.floor((time/1000) - t);
		if (t < 0) t = 1;
		
		var out = "";
		var i;
		var salir = false;
		var datos = new Array();
		
		datos[0] = new Array();
		datos[0][0] = Math.floor(t/2592000);
		datos[0][1] = Math.floor((t - datos[0][0]*2592000)/86400); 
		datos[0][2] = Math.floor((t - datos[0][0]*2592000 - datos[0][1]*86400)/3600);
		datos[0][3] = Math.floor((t - datos[0][0]*2592000 - datos[0][1]*86400 - datos[0][2]*3600)/60);
		datos[0][4] = Math.floor(t - datos[0][0]*62592000 - datos[0][1]*86400 - datos[0][2]*3600 - datos[0][3]*60);
		
		datos[1] = [1, 3, 7, 10];
		
		for (i=0;i<=4 && !salir;i++) {
			if (datos[0][i]) {
				salir = true;
				out += datos[0][i]+" "+this.lang[datos[0][i]!=1 ? i*2+1 : i*2];
				if (i < 4 && datos[0][i] <= datos[1][i] && datos[0][i+1]) 
					out += " "+datos[0][i+1]+" "+this.lang[datos[0][i+1]!=1 ? (i+1)*2+1 : (i+1)*2];
			}
		}
		if (!out) out = '1 '+this.lang[8];
		kide.html('KIDE_tiempoK', out); 
	},
	insertSmile: function(text) {
		var textarea = document.forms.kideForm.txt;
		textarea.value += " "+text;
		textarea.focus(textarea.value.length - 1);
	},
	filter_smilies: function(s) {
		s = " "+s+" ";
		for (var i = 0; i < this.smilies.length; i++) {
			s = s.replace(" "+this.smilies[i][0], '<img alt="' + this.smilies[i][0] + '" title="' + this.smilies[i][0] + '" src="' + this.smilies[i][1] + '" class="KIDE_icono" />');
			s = s.replace(" "+this.smilies[i][0].toLowerCase(), '<img alt="' + this.smilies[i][0] + '" title="' + this.smilies[i][0] + '" src="' + this.smilies[i][1] + '" class=KIDE_icono" />')
		}
		return s;
	},
	privado_cerrado: function(alias) {
		return !this.privados[alias].opened;
	},
	privado_getAlias: function(sid) {
		for (var i=0; i<this.privados.length; i++) {
			if (this.privados[i].sid == sid) return i;
		}
		return -1;
	},
	tohtml: function(s) {
		s = s.replace(/&/g, "&amp;");
		s = s.replace(/</g, "&lt;");
		s = s.replace(/>/g, "&gt;");
		s = s.replace(/'/g, "&#39;");
		s = s.replace(/"/g, "&quot;");
		return s;
	},
	sm: function() {
		this.ajax("insertar");
		
		if (this.rango == 3) 
			this.anti_flood_spam();
		if (this.encendido == 1) 
			this.iniciar();
	},
	anti_flood_spam: function() {
		if (this.ban[0] != 5) {
			this.ban[0]++;
			var time = new Date();
			time = time.getTime();
			this.ban[this.ban[1]] = time;
			this.ban[1]++;
		}
		else {
			var i;
			for (i=2;i<6;i++)
				this.ban[i] = this.ban[i+1];
			var time = new Date();
			time = time.getTime();
			this.ban[6] = time;
			var aux = this.ban[6] - this.ban[2];
			if (aux < 10*1000) {
				this.val('KIDE_txt', '');
				this.$('KIDE_txt').disabled = true;
				this.ajax("baneado");
			}
		}
	},
	retardo_input: function() {
		this.retardo_avisar = true;
		this.ajax("retardo");
	},
	mostrar_iconos: function() {
		if (this.$('KIDE_iconos')) {
			this.save_config('icons_hidden', this.css('KIDE_iconos', 'display') == 'none' ? 0 : 1);
			this.show('KIDE_iconos');
		}
	},
	play_msg_sound: function() {
		if (navigator.userAgent.toString().indexOf("MSIE") != -1)
			this.html('KIDE_msg_sound', '<object name="msg_sound" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#3,0,0,0" width="0" height="0"><param name="src" value="'+this.sound_src+'"><param name="loop" value="false"></object>');
		else
			this.html('KIDE_msg_sound', '<embed name="msg_sound" src="'+this.sound_src+'" width="0" height="0" loop="false" />');
	},
	privado_abrir_cerrar: function(alias) {
		if (this.privado_cerrado(alias)) {
			mostrar = true;
			d = true;
		}
		else {
			mostrar = false;
			d = false;
			if (this.privado_abierto == alias) 
				this.privado_minimizar(alias);
		}
		this.show("privados_mini_"+alias, mostrar);
		this.privados[alias].opened = d;
	},
	privado_parar: function(sid) {
		var alias = this.privado_getAlias(sid);
		this.privados[alias].stoped = true;
		this.privado_insertar(sid, "JoniJnm", this.privados_usuario_cerrado, "", 0, false);
		if (alias == this.privado_abierto)
			this.$("privados_txt").disabled = true;
	},
	privado_nuevo: function(sid, name, rango, img) {
		if (this.solo_registrado)
			alert(this.privados_need_login);
		else {
			var alias = this.privado_getAlias(sid);
			if (alias == -1) {
				this.privado_crear(sid, name, rango, img);
				alias = this.privado_getAlias(sid);
			}
			this.show("KIDE_usuario", false);
			if (this.privado_cerrado(alias))
				this.privado_abrir_cerrar(alias);
			this.privado_minimizar(alias);
		}
	},
	mostrar_opciones: function() {
		if (!this.mostrar_colores_iniciado) {
			this.mostrar_colores_iniciado = true;
			this.ajax('colores');
		}
		this.show('KIDE_opciones');
	},
	save_options: function() {
		this.show('KIDE_opciones', false);
		if (this.color)
			this.save_config("color", this.color);
		kide.save_config("ocultar_sesion", kide.$('ocultar_sesion').checked?1:0);
		if (this.rango==3 && this.form('KIDE_nuevo_nick') && this.form('KIDE_nuevo_nick')!=this.name) {
			this.name = this.form('KIDE_nuevo_nick');
			this.html('KIDE_my_name', this.tohtml(this.name));
			kide.save_config("name", kide.name);
		}
		if (kide.form("KIDE_template") != kide.template) {
			kide.save_config("template", kide.form("KIDE_template"));
			location.reload();
		}
	},
	set_color: function(c) {
		if (this.works) {
			this.color = c;
			this.css('KIDE_txt', 'color', "#"+c);
			if (this.$('privados_txt'))
				this.css('privados_txt', 'color', "#"+c);
		}
	},
	borrar: function(id) {
		if (id > 0) {
			this.show("KIDE_id_"+id, false);
			this.show("KIDE_mensaje", false)
			this.ajax("borrar", id);
		}
		else
			alert(this.mensaje_borrar);
	},
	banear: function(sid, tipo) {
		var dias = this.form('kide_'+tipo+'_banear_dias');
		var horas = this.form('kide_'+tipo+'_banear_horas');
		var minutos = this.form('kide_'+tipo+'_banear_minutos');
		if (dias>0 || horas>0 || minutos>0)
			this.ajax("banear", [sid, tipo]);
	},
	ajax: function(tipo, tmp) {
		var ajax = this.nuevoAjax();
		if (tipo == "reload") { 
			ajax.onreadystatechange = function() {
				if (ajax.readyState == 4 && ajax.status == 200) {
					var xml = ajax.responseXML.documentElement;
					if (xml.getElementsByTagName('mensaje').length > 0) {
						var row;
						kide.n = kide.text(xml.getElementsByTagName('last_id')[0]);
						kide.last_time = kide.text(xml.getElementsByTagName('last_time')[0]);
						for (var i=0; i<xml.getElementsByTagName('mensaje').length; i++) {
							row = xml.getElementsByTagName('mensaje')[i];
							kide.insertNewContent(row.getAttribute("name"),kide.htmlspecialchars_decode(kide.text(row)),row.getAttribute("url"),row.getAttribute("date"),row.getAttribute("color"),row.getAttribute("rango"),row.getAttribute("id"),row.getAttribute("sesion"),row.getAttribute("sesion")==kide.sesion,row.getAttribute("hora"),row.getAttribute("img"));
						}
					}
					if (!kide.privados_encontrado && kide.text(xml.getElementsByTagName('privados')[0]) > 0) {
						if (kide.site == "mod") {
							kide.privados_encontrado = true;
							kide.html("KIDE_privados_mod", kide.privados_nuevos);
							kide.show("KIDE_privados_mod", true);
						}
						else {
							if (kide.encendido == 1) {
								kide.privados_encontrado = true;
								kide.iniciar();
							}
							else if (kide.encendido == 2 && kide.privados_parado) {
								kide.privados_encontrado = true;
								kide.privados_parado = false;
								kide.privados_recargar();
							}
						}
					}
					kide.tiempo(kide.last_time);
				}
			};
			if (this.direct) {
				ajax.open('POST', this.direct_url+'reload.php', true);
				ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				ajax.send("id="+this.n+"&token="+this.token+"&order="+this.order+"&gmt="+kide.gmt+"&formato_hora="+encodeURIComponent(kide.formato_hora)+"&formato_fecha="+encodeURIComponent(kide.formato_fecha));
			}
			else {
				ajax.open('POST',  this.ajax_url+"&task=reload", true);
				ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				ajax.send("id="+this.n+"&token="+this.token);
			}
		}
		else if (tipo == "insertar") {
			var txt = this.val('KIDE_txt');
			this.show('KIDE_img_ajax', false);
			ajax.onreadystatechange = function() {
				if (ajax.readyState == 4 && ajax.status == 200) {
					var xml = ajax.responseXML.documentElement;
					if (xml.getAttribute('banned') == 1) {
						location.reload();
					}
					else {
						var texto = kide.text(xml.getElementsByTagName('txt')[0]);
						kide.insertNewContent(kide.name,texto.length?texto:txt,kide.url,kide.ahora(),kide.color,kide.rango,xml.getAttribute('id'),kide.sesion,true,xml.getAttribute('hora'),xml.getAttribute('img')); 
						kide.val('KIDE_txt', '');
						kide.last_time = xml.getAttribute('tiempo');
						kide.tiempo(kide.last_time);
						kide.show('KIDE_img_ajax', false);
					}
				}
			};
			ajax.open('POST', this.ajax_url+"&task=insertar", true);
			ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			ajax.send("txt="+encodeURIComponent(txt.replace(/~/g, ""))+"&token="+this.token);
		}
		else if (tipo == "baneado") {
			ajax.onreadystatechange = function() {
				if (ajax.readyState == 4)
					location.reload();
			};
			ajax.open('POST', this.ajax_url+"&task=insertar", true);
			ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			ajax.send("banear=1");
		}
		else if (tipo == "colores") {
			ajax.onreadystatechange = function() {
				if (ajax.readyState == 4 && ajax.status == 200) 
					kide.html('KIDE_opciones_colores', ajax.responseText);
			};
			ajax.open('POST', this.ajax_url+"&task=colores", true);
			ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			ajax.send(null);
		}
		else if (tipo == "borrar") {
			ajax.open('POST', this.ajax_url+"&task=borrar", true);
			ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			ajax.send("id="+tmp);
		}
		else if (tipo == "sesiones") {
			if (kide.site == "com") {
				ajax.onreadystatechange = function() {
					if (ajax.readyState == 4 && ajax.status == 200) {
						var xml = ajax.responseXML.documentElement;
						kide.sids = [];
						kide.html('KIDE_usuarios', '');
						var alias, name;
						for (var i=0; i<xml.getElementsByTagName('user').length; i++) {
							row = xml.getElementsByTagName('user')[i];
							alias = kide.privado_getAlias(row.getAttribute("sesion"));
							if (alias != -1) {
								name = row.getAttribute('name');
								if (name != kide.privados[alias].name) {
									kide.privados[alias].name = row.getAttribute('name');
									if (kide.privados[alias].opened)
										kide.privado_update_name_opened(kide.privados[alias].name);
									kide.privado_update_name_mini(alias, name);
								}
							}
							kide.sids[kide.sids.length] = row.getAttribute("sesion");
							kide.insert_sesion(row);
						}
					}
				};
			}
			ajax.open('POST', this.ajax_url+"&task=sesiones&site="+kide.site, true);
			ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			ajax.send("token="+this.token);
		}
		else if (tipo == "retardo") {
			ajax.onreadystatechange = function() {
				if (ajax.readyState == 4 && ajax.status == 200) {
					var out = ajax.responseText.split("|");
					out = out[0];
					if (out > 0) {
						var time = new Date();
						time = time.getTime();
						out = out - Math.floor((time/1000));
						kide.retardo = out;
						kide.save_config("retardo", kide.retardo);
						if (kide.retardo_avisar) {
							alert(kide.retardo_frase.replace("%s", out));
						}
					}
				}
			};
			ajax.open('POST', this.ajax_url+"&task=retardo", true);
			ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			ajax.send(null);
		}
		else if (tipo == "banear") {
			var dias = this.form('kide_'+tmp[1]+'_banear_dias');
			var horas = this.form('kide_'+tmp[1]+'_banear_horas');
			var minutos = this.form('kide_'+tmp[1]+'_banear_minutos');
			ajax.onreadystatechange = function() {
				if (ajax.readyState == 4 && ajax.status == 200) {
					var out = ajax.responseText;
					alert(out);
					kide.show('KIDE_'+tmp[1]+'_banear_span', false);
					kide.form('kide_'+tmp[1]+'_banear_dias', 0);
					kide.form('kide_'+tmp[1]+'_banear_horas', 0);
					kide.form('kide_'+tmp[1]+'_banear_minutos', 0);
				}
			};
			ajax.open('POST', this.ajax_url+"&task=banear", true);
			ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			ajax.send("sesion="+tmp[0]+"&dias="+dias+"&horas="+horas+"&minutos="+minutos);
		}
		else if (tipo == "privados_reload") {
			ajax.onreadystatechange = function() {
				if (ajax.readyState == 4 && ajax.status == 200) {
					var xml = ajax.responseXML.documentElement;
					if (xml.getElementsByTagName('mensaje').length > 0) {
						var row;
						var sid;
						for (var i=0; i<xml.getElementsByTagName('mensaje').length; i++) {
							row = xml.getElementsByTagName('mensaje')[i];
							sid = row.getAttribute("sesion");
							if (kide.privado_getAlias(sid) == -1) 
								kide.privado_crear(sid, row.getAttribute("from"), row.getAttribute("rango"), row.getAttribute("img"));
							kide.privado_insertar(sid, row.getAttribute("from"), kide.htmlspecialchars_decode(kide.text(row)), row.getAttribute("color"), row.getAttribute("rango"), false);
						}
					}
				}
			};
			if (kide.direct) {
				ajax.open('POST', this.direct_url+"privados_reload.php", true);
				ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				ajax.send("order="+this.order);
			}
			else {
				ajax.open('POST', this.ajax_url+"&task=privados_reload", true);
				ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				ajax.send(null);
			}
		}
		else if (tipo == "privados_insertar") {
			if (this.encendido == 1) {
				this.privados_encontrado = true;
				this.iniciar();
			}
			else if (this.encendido == 2 && this.privados_parado) {
				this.privados_encontrado = true;
				this.privados_parado = false;
				this.privados_recargar();
			}
			this.visible("privados_full_img_ajax", true);
			var txt = this.val('privados_txt');
			ajax.onreadystatechange = function() {
				if (ajax.readyState == 4 && ajax.status == 200) {
					kide.visible("privados_full_img_ajax", false);
					var out = ajax.responseText;
					out = out.split("~");
					if (out[0] == -1)
						kide.privado_parar(out[1]);
					else 
						kide.privado_insertar(out[0], out[1], out[2], kide.color, kide.rango, true);
					kide.val('privados_txt', '');
				}
			};
			ajax.open('POST', this.ajax_url+"&task=privados_insertar", true);
			ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			ajax.send("sesion="+this.privados[this.privado_abierto].sid+"&txt="+encodeURIComponent(txt.replace(/~/g, "")));
		}
	}
};
